From b458744d00b8c695c5643d6a736d7726beb11805 Mon Sep 17 00:00:00 2001 From: Wiwi Kuan Date: Wed, 29 Mar 2023 01:16:08 +0800 Subject: [PATCH] Add files via upload First upload. --- globals.js | 122 ++ index.html | 46 + p5.min.js | 2 + piano-visualizer.js | 222 +++ style.css | 547 ++++++ webmidi.js | 4427 +++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 5366 insertions(+) create mode 100644 globals.js create mode 100644 index.html create mode 100644 p5.min.js create mode 100644 piano-visualizer.js create mode 100644 style.css create mode 100644 webmidi.js diff --git a/globals.js b/globals.js new file mode 100644 index 0000000..46ee49a --- /dev/null +++ b/globals.js @@ -0,0 +1,122 @@ +let midiSelectSlider; + +// for piano visualizer +let nowPedaling = false; // is it pedaling?(不要動) +let isKeyOn = []; // what notes are being pressed (1 or 0)(不要動) +let isPedaled = []; // what notes are pedaled (1 or 0)(不要動) +let keyOnColor // set it in setup() +let pedaledColor // set it in setup() +let isBlack = [0, 11, 0, 13, 0, 0, 11, 0, 12, 0, 13, 0]; // 是黑鍵嗎?是的話,相對左方的白鍵位移多少?(default: {0, 11, 0, 13, 0, 0, 11, 0, 12, 0, 13, 0}) +let border = 3; // 左方留空幾個畫素?(default: 3) +let whiteKeyWidth = 20; // 白鍵多寬?(default: 20) +let whiteKeySpace = 1; // 白鍵間的縫隙多寬?(default: 1) +let blackKeyWidth = 17; // 黑鍵多寬?(default: 17) +let blackKeyHeight = 45; // 黑鍵多高?(default: 45) +let radius = 5; // 白鍵圓角(default: 5) +let bRadius = 4; // 黑鍵圓角(default: 4) +let keyAreaY = 3; // 白鍵從 Y 軸座標多少開始?(default: 3) +let keyAreaHeight = 70; // 白鍵多高?(default: 70) +let rainbowMode = false; // 彩虹模式 (default: false) +let cc64now = 0; // 現在的踏板狀態 +let cc67now = 0; + +let sessionStartTime = new Date(); +let sessionTotalSeconds = 0; + +// note counter +let notesThisFrame = 0; +let totalNotesPlayed = 0; +let shortTermTotal = new Array(60).fill(0); +let legatoHistory = new Array(60).fill(0); +let totalIntensityScore = 0; + +// for key pressed counter +let notePressedCount = 0; +let notePressedCountHistory = []; + +WebMidi.enable(function (err) { //check if WebMidi.js is enabled + if (err) { + console.log("WebMidi could not be enabled.", err); + } else { + console.log("WebMidi enabled!"); + } + + //name our visible MIDI input and output ports + console.log("---"); + console.log("Inputs Ports: "); + for (i = 0; i < WebMidi.inputs.length; i++) { + console.log(i + ": " + WebMidi.inputs[i].name); + } + + console.log("---"); + console.log("Output Ports: "); + for (i = 0; i < WebMidi.outputs.length; i++) { + console.log(i + ": " + WebMidi.outputs[i].name); + } + midiSelectSlider = select("#slider"); + midiSelectSlider.attribute("max", WebMidi.inputs.length - 1); + midiSelectSlider.changed(inputChanged); + midiIn = WebMidi.inputs[midiSelectSlider.value()] + inputChanged(); +}); + +function inputChanged() { + midiIn.removeListener(); + midiIn = WebMidi.inputs[midiSelectSlider.value()]; + midiIn.addListener('noteon', "all", function (e) { + console.log("Received 'noteon' message (" + e.note.number + ", " + e.velocity + ")."); + noteOn(e.note.number, e.velocity); + }); + midiIn.addListener('noteoff', "all", function (e) { + console.log("Received 'noteoff' message (" + e.note.number + ", " + e.velocity + ")."); + noteOff(e.note.number, e.velocity); + }) + midiIn.addListener('controlchange', 'all', function(e) { + console.log("Received control change message:", e.controller.number, e.value); + controllerChange(e.controller.number, e.value) + }); + console.log(midiIn.name); + select("#device").html(midiIn.name); +}; + +function noteOn(pitch, velocity) { + totalNotesPlayed++; + notesThisFrame++; + totalIntensityScore += velocity; + + // piano visualizer + isKeyOn[pitch] = 1; + if (nowPedaling) { + isPedaled[pitch] = 1; + } +} + +function noteOff(pitch, velocity) { + isKeyOn[pitch] = 0; +} + +function controllerChange(number, value) { + // Receive a controllerChange + if (number == 64) { + cc64now = value; + + if (value >= 64) { + nowPedaling = true; + for (let i = 0; i < 128; i++) { + // copy key on to pedal + isPedaled[i] = isKeyOn[i]; + } + } else if (value < 64) { + nowPedaling = false; + for (let i = 0; i < 128; i++) { + // reset isPedaled + isPedaled[i] = 0; + } + } + } + + if (number == 67) { + cc67now = value; + + } +} \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..8bb7dae --- /dev/null +++ b/index.html @@ -0,0 +1,46 @@ + + + + + 好和弦的鋼琴鍵盤顯示器 + + + + + + + + +
+
+
+

鋼琴鍵盤顯示器 by NiceChord

+
選擇 MIDI 裝置
+ +
Select Input:
+
+
+ +
+
+ +
+ +
+ +
+ + TIME:使用時間 | NOTE COUNT:總彈奏音符數 | NOTES/S:最近一秒鐘彈奏音符數 | LEGATO:圓滑指數(最近一秒鐘平均來說有幾個鍵被同時按住)
+ CALORIES:消耗熱量(估計值,好玩就好)| KEYS:現在正在被按住或被踏板留住的音 | PEDALS:左右踏板深度顯示
+ (密技:點鍵盤最左上角的角落,可以儲存截圖)

+
+ + + 覺得好用嗎?到 NiceChord.com 逛逛支持我! +
+ + + + + + \ No newline at end of file diff --git a/p5.min.js b/p5.min.js new file mode 100644 index 0000000..7a5b827 --- /dev/null +++ b/p5.min.js @@ -0,0 +1,2 @@ +/*! p5.js v1.6.0 February 22, 2023 */ +!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).p5=e()}(function(){var s,t,r;return function o(n,s,i){function a(t,e){if(!s[t]){if(!n[t]){var r="function"==typeof require&&require;if(!e&&r)return r(t,!0);if(l)return l(t,!0);throw(e=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",e}r=s[t]={exports:{}},n[t][0].call(r.exports,function(e){return a(n[t][1][e]||e)},r,r.exports,o,n,s,i)}return s[t].exports}for(var l="function"==typeof require&&require,e=0;e>16&255,s[i++]=t>>8&255,s[i++]=255&t;2===o&&(t=l[e.charCodeAt(r)]<<2|l[e.charCodeAt(r+1)]>>4,s[i++]=255&t);1===o&&(t=l[e.charCodeAt(r)]<<10|l[e.charCodeAt(r+1)]<<4|l[e.charCodeAt(r+2)]>>2,s[i++]=t>>8&255,s[i++]=255&t);return s},r.fromByteArray=function(e){for(var t,r=e.length,o=r%3,n=[],s=0,i=r-o;s>18&63]+a[e>>12&63]+a[e>>6&63]+a[63&e]}(o));return n.join("")}(e,s,i>2]+a[t<<4&63]+"==")):2==o&&(t=(e[r-2]<<8)+e[r-1],n.push(a[t>>10]+a[t>>4&63]+a[t<<2&63]+"="));return n.join("")};for(var a=[],l=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=0,s=o.length;n>>1;case"base64":return T(e).length;default:if(n)return o?-1:E(e).length;t=(""+t).toLowerCase(),n=!0}}function r(e,t,r){var o,n=!1;if((t=void 0===t||t<0?0:t)>this.length)return"";if((r=void 0===r||r>this.length?this.length:r)<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e=e||"utf8";;)switch(e){case"hex":var s=this,i=t,a=r,l=s.length;(!a||a<0||l=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=d.from(t,o)),d.isBuffer(t))return 0===t.length?-1:p(e,t,r,o,n);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?(n?Uint8Array.prototype.indexOf:Uint8Array.prototype.lastIndexOf).call(e,t,r):p(e,[t],r,o,n);throw new TypeError("val must be string, number or Buffer")}function p(e,t,r,o,n){var s=1,i=e.length,a=t.length;if(void 0!==o&&("ucs2"===(o=String(o).toLowerCase())||"ucs-2"===o||"utf16le"===o||"utf-16le"===o)){if(e.length<2||t.length<2)return-1;i/=s=2,a/=2,r/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(n)for(var u=-1,c=r;c>8,o=o%256,n.push(o),n.push(r);return n}(t,e.length-r),e,r,o)}function M(e,t,r){r=Math.min(e.length,r);for(var o=[],n=t;n>>10&1023|55296),c=56320|1023&c),o.push(c),n+=d}var f=o,h=f.length;if(h<=v)return String.fromCharCode.apply(String,f);for(var p="",m=0;mt&&(e+=" ... "),""},e&&(d.prototype[e]=d.prototype.inspect),d.prototype.compare=function(e,t,r,o,n){if(O(e,Uint8Array)&&(e=d.from(e,e.offset,e.byteLength)),!d.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===r&&(r=e?e.length:0),void 0===o&&(o=0),void 0===n&&(n=this.length),(t=void 0===t?0:t)<0||r>e.length||o<0||n>this.length)throw new RangeError("out of range index");if(n<=o&&r<=t)return 0;if(n<=o)return-1;if(r<=t)return 1;if(this===e)return 0;for(var s=(n>>>=0)-(o>>>=0),i=(r>>>=0)-(t>>>=0),a=Math.min(s,i),l=this.slice(o,n),u=e.slice(t,r),c=0;c>>=0,isFinite(r)?(r>>>=0,void 0===o&&(o="utf8")):(o=r,r=void 0)}var n=this.length-t;if((void 0===r||nthis.length)throw new RangeError("Attempt to write outside buffer bounds");o=o||"utf8";for(var s,i,a,l=!1;;)switch(o){case"hex":var u=this,c=e,d=t,f=r,h=(d=Number(d)||0,u.length-d);(!f||h<(f=Number(f)))&&(f=h),(h=c.length)/2e.length)throw new RangeError("Index out of range")}function j(e,t,r,o){if(r+o>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function _(e,t,r,o,n){return t=+t,r>>>=0,n||j(e,0,r,4),s.write(e,t,r,o,23,4),r+4}function x(e,t,r,o,n){return t=+t,r>>>=0,n||j(e,0,r,8),s.write(e,t,r,o,52,8),r+8}d.prototype.slice=function(e,t){var r=this.length,r=((e=~~e)<0?(e+=r)<0&&(e=0):r>>=0,t>>>=0,r||m(e,t,this.length);for(var o=this[e],n=1,s=0;++s>>=0,t>>>=0,r||m(e,t,this.length);for(var o=this[e+--t],n=1;0>>=0,t||m(e,1,this.length),this[e]},d.prototype.readUInt16LE=function(e,t){return e>>>=0,t||m(e,2,this.length),this[e]|this[e+1]<<8},d.prototype.readUInt16BE=function(e,t){return e>>>=0,t||m(e,2,this.length),this[e]<<8|this[e+1]},d.prototype.readUInt32LE=function(e,t){return e>>>=0,t||m(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},d.prototype.readUInt32BE=function(e,t){return e>>>=0,t||m(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},d.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||m(e,t,this.length);for(var o=this[e],n=1,s=0;++s>>=0,t>>>=0,r||m(e,t,this.length);for(var o=t,n=1,s=this[e+--o];0>>=0,t||m(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},d.prototype.readInt16LE=function(e,t){e>>>=0,t||m(e,2,this.length);t=this[e]|this[e+1]<<8;return 32768&t?4294901760|t:t},d.prototype.readInt16BE=function(e,t){e>>>=0,t||m(e,2,this.length);t=this[e+1]|this[e]<<8;return 32768&t?4294901760|t:t},d.prototype.readInt32LE=function(e,t){return e>>>=0,t||m(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},d.prototype.readInt32BE=function(e,t){return e>>>=0,t||m(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},d.prototype.readFloatLE=function(e,t){return e>>>=0,t||m(e,4,this.length),s.read(this,e,!0,23,4)},d.prototype.readFloatBE=function(e,t){return e>>>=0,t||m(e,4,this.length),s.read(this,e,!1,23,4)},d.prototype.readDoubleLE=function(e,t){return e>>>=0,t||m(e,8,this.length),s.read(this,e,!0,52,8)},d.prototype.readDoubleBE=function(e,t){return e>>>=0,t||m(e,8,this.length),s.read(this,e,!1,52,8)},d.prototype.writeUIntLE=function(e,t,r,o){e=+e,t>>>=0,r>>>=0,o||b(this,e,t,r,Math.pow(2,8*r)-1,0);var n=1,s=0;for(this[t]=255&e;++s>>=0,r>>>=0,o||b(this,e,t,r,Math.pow(2,8*r)-1,0);var n=r-1,s=1;for(this[t+n]=255&e;0<=--n&&(s*=256);)this[t+n]=e/s&255;return t+r},d.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,1,255,0),this[t]=255&e,t+1},d.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},d.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},d.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||b(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},d.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||b(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},d.prototype.writeIntLE=function(e,t,r,o){e=+e,t>>>=0,o||b(this,e,t,r,(o=Math.pow(2,8*r-1))-1,-o);var n=0,s=1,i=0;for(this[t]=255&e;++n>0)-i&255;return t+r},d.prototype.writeIntBE=function(e,t,r,o){e=+e,t>>>=0,o||b(this,e,t,r,(o=Math.pow(2,8*r-1))-1,-o);var n=r-1,s=1,i=0;for(this[t+n]=255&e;0<=--n&&(s*=256);)e<0&&0===i&&0!==this[t+n+1]&&(i=1),this[t+n]=(e/s>>0)-i&255;return t+r},d.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,1,127,-128),this[t]=255&(e=e<0?255+e+1:e),t+1},d.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},d.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},d.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||b(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},d.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,4,2147483647,-2147483648),this[t]=(e=e<0?4294967295+e+1:e)>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},d.prototype.writeFloatLE=function(e,t,r){return _(this,e,t,!0,r)},d.prototype.writeFloatBE=function(e,t,r){return _(this,e,t,!1,r)},d.prototype.writeDoubleLE=function(e,t,r){return x(this,e,t,!0,r)},d.prototype.writeDoubleBE=function(e,t,r){return x(this,e,t,!1,r)},d.prototype.copy=function(e,t,r,o){if(!d.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r=r||0,o||0===o||(o=this.length),t>=e.length&&(t=e.length),(o=0=this.length)throw new RangeError("Index out of range");if(o<0)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length);var n=(o=e.length-t>>=0,r=void 0===r?this.length:r>>>0,"number"==typeof(e=e||0))for(s=t;s>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.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;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function T(e){return S.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(w,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function C(e,t,r,o){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 k(e){return e!=e}var L=function(){for(var e="0123456789abcdef",t=new Array(256),r=0;r<16;++r)for(var o=16*r,n=0;n<16;++n)t[o+n]=e[r]+e[n];return t}()}.call(this,P("buffer").Buffer)},{"base64-js":1,buffer:4,ieee754:238}],5:[function(e,t,r){t.exports=function(e){if("function"!=typeof e)throw TypeError(String(e)+" is not a function");return e}},{}],6:[function(e,t,r){var o=e("../internals/is-object");t.exports=function(e){if(o(e)||null===e)return e;throw TypeError("Can't set "+String(e)+" as a prototype")}},{"../internals/is-object":74}],7:[function(e,t,r){var o=e("../internals/well-known-symbol"),n=e("../internals/object-create"),e=e("../internals/object-define-property"),s=o("unscopables"),i=Array.prototype;null==i[s]&&e.f(i,s,{configurable:!0,value:n(null)}),t.exports=function(e){i[s][e]=!0}},{"../internals/object-create":90,"../internals/object-define-property":92,"../internals/well-known-symbol":146}],8:[function(e,t,r){"use strict";var o=e("../internals/string-multibyte").charAt;t.exports=function(e,t,r){return t+(r?o(e,t).length:1)}},{"../internals/string-multibyte":123}],9:[function(e,t,r){t.exports=function(e,t,r){if(e instanceof t)return e;throw TypeError("Incorrect "+(r?r+" ":"")+"invocation")}},{}],10:[function(e,t,r){var o=e("../internals/is-object");t.exports=function(e){if(o(e))return e;throw TypeError(String(e)+" is not an object")}},{"../internals/is-object":74}],11:[function(e,t,r){t.exports="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView},{}],12:[function(e,t,r){"use strict";function o(e){return l(e)&&u(E,c(e))}var n,s=e("../internals/array-buffer-native"),i=e("../internals/descriptors"),a=e("../internals/global"),l=e("../internals/is-object"),u=e("../internals/has"),c=e("../internals/classof"),d=e("../internals/create-non-enumerable-property"),f=e("../internals/redefine"),h=e("../internals/object-define-property").f,p=e("../internals/object-get-prototype-of"),m=e("../internals/object-set-prototype-of"),y=e("../internals/well-known-symbol"),e=e("../internals/uid"),g=a.Int8Array,v=g&&g.prototype,b=a.Uint8ClampedArray,b=b&&b.prototype,j=g&&p(g),_=v&&p(v),x=Object.prototype,w=x.isPrototypeOf,y=y("toStringTag"),S=e("TYPED_ARRAY_TAG"),M=s&&!!m&&"Opera"!==c(a.opera),e=!1,E={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8};for(n in E)a[n]||(M=!1);if((!M||"function"!=typeof j||j===Function.prototype)&&(j=function(){throw TypeError("Incorrect invocation")},M))for(n in E)a[n]&&m(a[n],j);if((!M||!_||_===x)&&(_=j.prototype,M))for(n in E)a[n]&&m(a[n].prototype,_);if(M&&p(b)!==_&&m(b,_),i&&!u(_,y))for(n in e=!0,h(_,y,{get:function(){return l(this)?this[S]:void 0}}),E)a[n]&&d(a[n],S,n);t.exports={NATIVE_ARRAY_BUFFER_VIEWS:M,TYPED_ARRAY_TAG:e&&S,aTypedArray:function(e){if(o(e))return e;throw TypeError("Target is not a typed array")},aTypedArrayConstructor:function(e){if(m){if(w.call(j,e))return e}else for(var t in E)if(u(E,n)){t=a[t];if(t&&(e===t||w.call(t,e)))return e}throw TypeError("Target is not a typed array constructor")},exportTypedArrayMethod:function(e,t,r){if(i){if(r)for(var o in E){o=a[o];o&&u(o.prototype,e)&&delete o.prototype[e]}_[e]&&!r||f(_,e,!r&&M&&v[e]||t)}},exportTypedArrayStaticMethod:function(e,t,r){var o,n;if(i){if(m){if(r)for(o in E)(n=a[o])&&u(n,e)&&delete n[e];if(j[e]&&!r)return;try{return f(j,e,!r&&M&&g[e]||t)}catch(e){}}for(o in E)!(n=a[o])||n[e]&&!r||f(n,e,t)}},isView:function(e){e=c(e);return"DataView"===e||u(E,e)},isTypedArray:o,TypedArray:j,TypedArrayPrototype:_}},{"../internals/array-buffer-native":11,"../internals/classof":29,"../internals/create-non-enumerable-property":38,"../internals/descriptors":43,"../internals/global":59,"../internals/has":60,"../internals/is-object":74,"../internals/object-define-property":92,"../internals/object-get-prototype-of":97,"../internals/object-set-prototype-of":101,"../internals/redefine":108,"../internals/uid":143,"../internals/well-known-symbol":146}],13:[function(e,t,D){"use strict";function r(e){return[255&e]}function o(e){return[255&e,e>>8&255]}function n(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]}function s(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]}function i(e){return k(e,23,4)}function U(e){return k(e,52,8)}function a(e,t){H(e[w],t,{get:function(){return b(this)[t]}})}function l(e,t,r,o){if(r=m(r),e=b(e),r+t>e.byteLength)throw O(S);var n=b(e.buffer).bytes,r=r+e.byteOffset,e=n.slice(r,r+t);return o?e:e.reverse()}function u(e,t,r,o,n,s){if(r=m(r),e=b(e),r+t>e.byteLength)throw O(S);for(var i=b(e.buffer).bytes,a=r+e.byteOffset,l=o(+n),u=0;uR;)(P=A[R++])in E||F(E,P,M[P]);c.constructor=E}g&&V(e)!==C&&g(e,C);var y=new T(new E(2)),I=e.setInt8;y.setInt8(0,2147483648),y.setInt8(1,2147483649),!y.getInt8(0)&&y.getInt8(1)||f(e,{setInt8:function(e,t){I.call(this,e,t<<24>>24)},setUint8:function(e,t){I.call(this,e,t<<24>>24)}},{unsafe:!0})}else E=function(e){p(this,E,_);e=m(e);j(this,{bytes:W.call(new Array(e),0),byteLength:e}),d||(this.byteLength=e)},T=function(e,t,r){p(this,T,x),p(e,E,x);var o=b(e).byteLength,t=B(t);if(t<0||o>24},getUint8:function(e){return l(this,1,e)[0]},getInt16:function(e){e=l(this,2,e,1>16},getUint16:function(e){e=l(this,2,e,1>>0},getFloat32:function(e){return L(l(this,4,e,1"+e+""}},{"../internals/require-object-coercible":113}],37:[function(e,t,r){"use strict";function o(){return this}var n=e("../internals/iterators-core").IteratorPrototype,s=e("../internals/object-create"),i=e("../internals/create-property-descriptor"),a=e("../internals/set-to-string-tag"),l=e("../internals/iterators");t.exports=function(e,t,r){t+=" Iterator";return e.prototype=s(n,{next:i(1,r)}),a(e,t,!1,!0),l[t]=o,e}},{"../internals/create-property-descriptor":39,"../internals/iterators":79,"../internals/iterators-core":78,"../internals/object-create":90,"../internals/set-to-string-tag":117}],38:[function(e,t,r){var o=e("../internals/descriptors"),n=e("../internals/object-define-property"),s=e("../internals/create-property-descriptor");t.exports=o?function(e,t,r){return n.f(e,t,s(1,r))}:function(e,t,r){return e[t]=r,e}},{"../internals/create-property-descriptor":39,"../internals/descriptors":43,"../internals/object-define-property":92}],39:[function(e,t,r){t.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},{}],40:[function(e,t,r){"use strict";var o=e("../internals/to-primitive"),n=e("../internals/object-define-property"),s=e("../internals/create-property-descriptor");t.exports=function(e,t,r){t=o(t);t in e?n.f(e,t,s(0,r)):e[t]=r}},{"../internals/create-property-descriptor":39,"../internals/object-define-property":92,"../internals/to-primitive":138}],41:[function(e,t,r){"use strict";function m(){return this}var y=e("../internals/export"),g=e("../internals/create-iterator-constructor"),v=e("../internals/object-get-prototype-of"),b=e("../internals/object-set-prototype-of"),j=e("../internals/set-to-string-tag"),_=e("../internals/create-non-enumerable-property"),x=e("../internals/redefine"),o=e("../internals/well-known-symbol"),w=e("../internals/is-pure"),S=e("../internals/iterators"),e=e("../internals/iterators-core"),M=e.IteratorPrototype,E=e.BUGGY_SAFARI_ITERATORS,T=o("iterator"),C="values",O="entries";t.exports=function(e,t,r,o,n,s,i){g(r,t,o);function a(e){if(e===n&&h)return h;if(!E&&e in d)return d[e];switch(e){case"keys":case C:case O:return function(){return new r(this,e)}}return function(){return new r(this)}}var l,u,o=t+" Iterator",c=!1,d=e.prototype,f=d[T]||d["@@iterator"]||n&&d[n],h=!E&&f||a(n),p="Array"==t&&d.entries||f;if(p&&(p=v(p.call(new e)),M!==Object.prototype&&p.next&&(w||v(p)===M||(b?b(p,M):"function"!=typeof p[T]&&_(p,T,m)),j(p,o,!0,!0),w&&(S[o]=m))),n==C&&f&&f.name!==C&&(c=!0,h=function(){return f.call(this)}),w&&!i||d[T]===h||_(d,T,h),S[t]=h,n)if(l={values:a(C),keys:s?h:a("keys"),entries:a(O)},i)for(u in l)!E&&!c&&u in d||x(d,u,l[u]);else y({target:t,proto:!0,forced:E||c},l);return l}},{"../internals/create-iterator-constructor":37,"../internals/create-non-enumerable-property":38,"../internals/export":50,"../internals/is-pure":75,"../internals/iterators":79,"../internals/iterators-core":78,"../internals/object-get-prototype-of":97,"../internals/object-set-prototype-of":101,"../internals/redefine":108,"../internals/set-to-string-tag":117,"../internals/well-known-symbol":146}],42:[function(e,t,r){var o=e("../internals/path"),n=e("../internals/has"),s=e("../internals/well-known-symbol-wrapped"),i=e("../internals/object-define-property").f;t.exports=function(e){var t=o.Symbol||(o.Symbol={});n(t,e)||i(t,e,{value:s.f(e)})}},{"../internals/has":60,"../internals/object-define-property":92,"../internals/path":104,"../internals/well-known-symbol-wrapped":145}],43:[function(e,t,r){e=e("../internals/fails");t.exports=!e(function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})},{"../internals/fails":51}],44:[function(e,t,r){var o=e("../internals/global"),e=e("../internals/is-object"),n=o.document,s=e(n)&&e(n.createElement);t.exports=function(e){return s?n.createElement(e):{}}},{"../internals/global":59,"../internals/is-object":74}],45:[function(e,t,r){t.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},{}],46:[function(e,t,r){e=e("../internals/engine-user-agent");t.exports=/(iphone|ipod|ipad).*applewebkit/i.test(e)},{"../internals/engine-user-agent":47}],47:[function(e,t,r){e=e("../internals/get-built-in");t.exports=e("navigator","userAgent")||""},{"../internals/get-built-in":56}],48:[function(e,t,r){var o,n,s=e("../internals/global"),e=e("../internals/engine-user-agent"),s=s.process,s=s&&s.versions,s=s&&s.v8;s?n=(o=s.split("."))[0]+o[1]:e&&(!(o=e.match(/Edge\/(\d+)/))||74<=o[1])&&(o=e.match(/Chrome\/(\d+)/))&&(n=o[1]),t.exports=n&&+n},{"../internals/engine-user-agent":47,"../internals/global":59}],49:[function(e,t,r){t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},{}],50:[function(e,t,r){var u=e("../internals/global"),c=e("../internals/object-get-own-property-descriptor").f,d=e("../internals/create-non-enumerable-property"),f=e("../internals/redefine"),h=e("../internals/set-global"),p=e("../internals/copy-constructor-properties"),m=e("../internals/is-forced");t.exports=function(e,t){var r,o,n,s=e.target,i=e.global,a=e.stat,l=i?u:a?u[s]||h(s,{}):(u[s]||{}).prototype;if(l)for(r in t){if(o=t[r],n=e.noTargetGet?(n=c(l,r))&&n.value:l[r],!m(i?r:s+(a?".":"#")+r,e.forced)&&void 0!==n){if(typeof o==typeof n)continue;p(o,n)}(e.sham||n&&n.sham)&&d(o,"sham",!0),f(l,r,o,e)}}},{"../internals/copy-constructor-properties":33,"../internals/create-non-enumerable-property":38,"../internals/global":59,"../internals/is-forced":73,"../internals/object-get-own-property-descriptor":93,"../internals/redefine":108,"../internals/set-global":115}],51:[function(e,t,r){t.exports=function(e){try{return!!e()}catch(e){return!0}}},{}],52:[function(e,t,r){"use strict";e("../modules/es.regexp.exec");var u=e("../internals/redefine"),c=e("../internals/fails"),d=e("../internals/well-known-symbol"),f=e("../internals/regexp-exec"),h=e("../internals/create-non-enumerable-property"),p=d("species"),m=!c(function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$")}),y="$0"==="a".replace(/./,"$0"),e=d("replace"),g=!!/./[e]&&""===/./[e]("a","$0"),v=!c(function(){var e=/(?:)/,t=e.exec,e=(e.exec=function(){return t.apply(this,arguments)},"ab".split(e));return 2!==e.length||"a"!==e[0]||"b"!==e[1]});t.exports=function(r,e,t,o){var s,n,i=d(r),a=!c(function(){var e={};return e[i]=function(){return 7},7!=""[r](e)}),l=a&&!c(function(){var e=!1,t=/a/;return"split"===r&&((t={constructor:{}}).constructor[p]=function(){return t},t.flags="",t[i]=/./[i]),t.exec=function(){return e=!0,null},t[i](""),!e});a&&l&&("replace"!==r||m&&y&&!g)&&("split"!==r||v)||(s=/./[i],t=(l=t(i,""[r],function(e,t,r,o,n){return t.exec===f?a&&!n?{done:!0,value:s.call(t,r,o)}:{done:!0,value:e.call(r,t,o)}:{done:!1}},{REPLACE_KEEPS_$0:y,REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE:g}))[0],n=l[1],u(String.prototype,r,t),u(RegExp.prototype,i,2==e?function(e,t){return n.call(e,this,t)}:function(e){return n.call(e,this)})),o&&h(RegExp.prototype[i],"sham",!0)}},{"../internals/create-non-enumerable-property":38,"../internals/fails":51,"../internals/redefine":108,"../internals/regexp-exec":110,"../internals/well-known-symbol":146,"../modules/es.regexp.exec":181}],53:[function(e,t,r){e=e("../internals/fails");t.exports=!e(function(){return Object.isExtensible(Object.preventExtensions({}))})},{"../internals/fails":51}],54:[function(e,t,r){var s=e("../internals/a-function");t.exports=function(o,n,e){if(s(o),void 0===n)return o;switch(e){case 0:return function(){return o.call(n)};case 1:return function(e){return o.call(n,e)};case 2:return function(e,t){return o.call(n,e,t)};case 3:return function(e,t,r){return o.call(n,e,t,r)}}return function(){return o.apply(n,arguments)}}},{"../internals/a-function":5}],55:[function(e,t,r){"use strict";var o=e("../internals/a-function"),n=e("../internals/is-object"),c=[].slice,d={};t.exports=Function.bind||function(i){var a=o(this),l=c.call(arguments,1),u=function(){var e=l.concat(c.call(arguments));if(this instanceof u){var t=a,r=e.length,o=e;if(!(r in d)){for(var n=[],s=0;s>1,u=23===t?h(2,-24)-h(2,-77):0,c=e<0||0===e&&1/e<0?1:0,d=0;for((e=f(e))!=e||e===1/0?(n=e!=e?1:0,o=r):(o=p(m(e)/y),e*(s=h(2,-o))<1&&(o--,s*=2),2<=(e+=1<=o+l?u/s:u*h(2,1-l))*s&&(o++,s/=2),r<=o+l?(n=0,o=r):1<=o+l?(n=(e*s-1)*h(2,t),o+=l):(n=e*h(2,l-1)*h(2,t),o=0));8<=t;i[d++]=255&n,n/=256,t-=8);for(o=o<>1,a=n-7,l=o-1,n=e[l--],u=127&n;for(n>>=7;0>=-a,a+=t;0"+e+""},m=function(){try{n=document.domain&&new ActiveXObject("htmlfile")}catch(e){}m=n?((e=n).write(p("")),e.close(),t=e.parentWindow.Object,e=null,t):(e=c("iframe"),t="java"+f+":",e.style.display="none",u.appendChild(e),e.src=String(t),(t=e.contentWindow.document).open(),t.write(p("document.F=Object")),t.close(),t.F);for(var e,t,r=a.length;r--;)delete m[d][a[r]];return m()};l[h]=!0,t.exports=Object.create||function(e,t){var r;return null!==e?(o[d]=s(e),r=new o,o[d]=null,r[h]=e):r=m(),void 0===t?r:i(r,t)}},{"../internals/an-object":10,"../internals/document-create-element":44,"../internals/enum-bug-keys":49,"../internals/hidden-keys":61,"../internals/html":63,"../internals/object-define-properties":91,"../internals/shared-key":118}],91:[function(e,t,r){var o=e("../internals/descriptors"),i=e("../internals/object-define-property"),a=e("../internals/an-object"),l=e("../internals/object-keys");t.exports=o?Object.defineProperties:function(e,t){a(e);for(var r,o=l(t),n=o.length,s=0;sn;)!i(o,r=t[n++])||~l(s,r)||s.push(r);return s}},{"../internals/array-includes":18,"../internals/has":60,"../internals/hidden-keys":61,"../internals/to-indexed-object":132}],99:[function(e,t,r){var o=e("../internals/object-keys-internal"),n=e("../internals/enum-bug-keys");t.exports=Object.keys||function(e){return o(e,n)}},{"../internals/enum-bug-keys":49,"../internals/object-keys-internal":98}],100:[function(e,t,r){"use strict";var o={}.propertyIsEnumerable,n=Object.getOwnPropertyDescriptor,s=n&&!o.call({1:2},1);r.f=s?function(e){e=n(this,e);return!!e&&e.enumerable}:o},{}],101:[function(e,t,r){var n=e("../internals/an-object"),s=e("../internals/a-possible-prototype");t.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var r,o=!1,e={};try{(r=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(e,[]),o=e instanceof Array}catch(e){}return function(e,t){return n(e),s(t),o?r.call(e,t):e.__proto__=t,e}}():void 0)},{"../internals/a-possible-prototype":6,"../internals/an-object":10}],102:[function(e,t,r){"use strict";var o=e("../internals/to-string-tag-support"),n=e("../internals/classof");t.exports=o?{}.toString:function(){return"[object "+n(this)+"]"}},{"../internals/classof":29,"../internals/to-string-tag-support":139}],103:[function(e,t,r){var o=e("../internals/get-built-in"),n=e("../internals/object-get-own-property-names"),s=e("../internals/object-get-own-property-symbols"),i=e("../internals/an-object");t.exports=o("Reflect","ownKeys")||function(e){var t=n.f(i(e)),r=s.f;return r?t.concat(r(e)):t}},{"../internals/an-object":10,"../internals/get-built-in":56,"../internals/object-get-own-property-names":95,"../internals/object-get-own-property-symbols":96}],104:[function(e,t,r){e=e("../internals/global");t.exports=e},{"../internals/global":59}],105:[function(e,t,r){t.exports=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}}},{}],106:[function(e,t,r){var o=e("../internals/an-object"),n=e("../internals/is-object"),s=e("../internals/new-promise-capability");t.exports=function(e,t){return o(e),n(t)&&t.constructor===e?t:((0,(e=s.f(e)).resolve)(t),e.promise)}},{"../internals/an-object":10,"../internals/is-object":74,"../internals/new-promise-capability":86}],107:[function(e,t,r){var n=e("../internals/redefine");t.exports=function(e,t,r){for(var o in t)n(e,o,t[o],r);return e}},{"../internals/redefine":108}],108:[function(e,t,r){var i=e("../internals/global"),a=e("../internals/create-non-enumerable-property"),l=e("../internals/has"),u=e("../internals/set-global"),o=e("../internals/inspect-source"),e=e("../internals/internal-state"),n=e.get,c=e.enforce,d=String(String).split("String");(t.exports=function(e,t,r,o){var n=!!o&&!!o.unsafe,s=!!o&&!!o.enumerable,o=!!o&&!!o.noTargetGet;"function"==typeof r&&("string"!=typeof t||l(r,"name")||a(r,"name",t),c(r).source=d.join("string"==typeof t?t:"")),e===i?s?e[t]=r:u(t,r):(n?!o&&e[t]&&(s=!0):delete e[t],s?e[t]=r:a(e,t,r))})(Function.prototype,"toString",function(){return"function"==typeof this&&n(this).source||o(this)})},{"../internals/create-non-enumerable-property":38,"../internals/global":59,"../internals/has":60,"../internals/inspect-source":68,"../internals/internal-state":70,"../internals/set-global":115}],109:[function(e,t,r){var o=e("./classof-raw"),n=e("./regexp-exec");t.exports=function(e,t){var r=e.exec;if("function"==typeof r){r=r.call(e,t);if("object"!=typeof r)throw TypeError("RegExp exec method returned something other than an Object or null");return r}if("RegExp"!==o(e))throw TypeError("RegExp#exec called on incompatible receiver");return n.call(e,t)}},{"./classof-raw":28,"./regexp-exec":110}],110:[function(e,t,r){"use strict";var o,n,d=e("./regexp-flags"),e=e("./regexp-sticky-helpers"),f=RegExp.prototype.exec,h=String.prototype.replace,s=f,p=(o=/a/,n=/b*/g,f.call(o,"a"),f.call(n,"a"),0!==o.lastIndex||0!==n.lastIndex),m=e.UNSUPPORTED_Y||e.BROKEN_CARET,y=void 0!==/()??/.exec("")[1];t.exports=s=p||y||m?function(e){var t,r,o,n,s=this,i=m&&s.sticky,a=d.call(s),l=s.source,u=0,c=e;return i&&(-1===(a=a.replace("y","")).indexOf("g")&&(a+="g"),c=String(e).slice(s.lastIndex),0M((v-s)/d))throw RangeError(w);for(s+=(u-n)*d,n=u,c=0;cv)throw RangeError(w);if(t==n){for(var f=s,h=b;;h+=b){var p=h<=i?1:i+j<=h?j:h-i;if(f>1,e+=M(e/t);S*j>>1>>=1)&&(t+=t))1&o&&(r+=t);return r}},{"../internals/require-object-coercible":113,"../internals/to-integer":133}],126:[function(e,t,r){var o=e("../internals/fails"),n=e("../internals/whitespaces");t.exports=function(e){return o(function(){return!!n[e]()||"​…᠎"!="​…᠎"[e]()||n[e].name!==e})}},{"../internals/fails":51,"../internals/whitespaces":147}],127:[function(e,t,r){function o(t){return function(e){e=String(n(e));return 1&t&&(e=e.replace(s,"")),e=2&t?e.replace(i,""):e}}var n=e("../internals/require-object-coercible"),e="["+e("../internals/whitespaces")+"]",s=RegExp("^"+e+e+"*"),i=RegExp(e+e+"*$");t.exports={start:o(1),end:o(2),trim:o(3)}},{"../internals/require-object-coercible":113,"../internals/whitespaces":147}],128:[function(e,t,r){function o(e){return function(){x(e)}}function n(e){x(e.data)}function s(e){a.postMessage(e+"",h.protocol+"//"+h.host)}var i,a=e("../internals/global"),l=e("../internals/fails"),u=e("../internals/classof-raw"),c=e("../internals/function-bind-context"),d=e("../internals/html"),f=e("../internals/document-create-element"),e=e("../internals/engine-is-ios"),h=a.location,p=a.setImmediate,m=a.clearImmediate,y=a.process,g=a.MessageChannel,v=a.Dispatch,b=0,j={},_="onreadystatechange",x=function(e){var t;j.hasOwnProperty(e)&&(t=j[e],delete j[e],t())};p&&m||(p=function(e){for(var t=[],r=1;r=t.length?{value:e.target=void 0,done:!0}:"keys"==r?{value:o,done:!1}:"values"==r?{value:t[o],done:!1}:{value:[o,t[o]],done:!1}},"values"),s.Arguments=s.Array,n("keys"),n("values"),n("entries")},{"../internals/add-to-unscopables":7,"../internals/define-iterator":41,"../internals/internal-state":70,"../internals/iterators":79,"../internals/to-indexed-object":132}],159:[function(e,t,r){"use strict";var o=e("../internals/export"),n=e("../internals/indexed-object"),s=e("../internals/to-indexed-object"),e=e("../internals/array-method-is-strict"),i=[].join,n=n!=Object,e=e("join",",");o({target:"Array",proto:!0,forced:n||!e},{join:function(e){return i.call(s(this),void 0===e?",":e)}})},{"../internals/array-method-is-strict":22,"../internals/export":50,"../internals/indexed-object":66,"../internals/to-indexed-object":132}],160:[function(e,t,r){var o=e("../internals/export"),e=e("../internals/array-last-index-of");o({target:"Array",proto:!0,forced:e!==[].lastIndexOf},{lastIndexOf:e})},{"../internals/array-last-index-of":20,"../internals/export":50}],161:[function(e,t,r){"use strict";var o=e("../internals/export"),n=e("../internals/array-iteration").map,s=e("../internals/array-method-has-species-support"),e=e("../internals/array-method-uses-to-length"),s=s("map"),e=e("map");o({target:"Array",proto:!0,forced:!s||!e},{map:function(e){return n(this,e,1M;M++)l(b,x=S[M])&&!l(w,x)&&y(w,x,m(b,x));(w.prototype=j).constructor=w,a(s,v,w)}},{"../internals/classof-raw":28,"../internals/descriptors":43,"../internals/fails":51,"../internals/global":59,"../internals/has":60,"../internals/inherit-if-required":67,"../internals/is-forced":73,"../internals/object-create":90,"../internals/object-define-property":92,"../internals/object-get-own-property-descriptor":93,"../internals/object-get-own-property-names":95,"../internals/redefine":108,"../internals/string-trim":127,"../internals/to-primitive":138}],170:[function(e,t,r){e("../internals/export")({target:"Number",stat:!0},{isFinite:e("../internals/number-is-finite")})},{"../internals/export":50,"../internals/number-is-finite":88}],171:[function(e,t,r){"use strict";function c(e,t,r){return 0===t?r:t%2==1?c(e,t-1,r*e):c(e*e,t/2,r)}var o=e("../internals/export"),d=e("../internals/to-integer"),f=e("../internals/this-number-value"),h=e("../internals/string-repeat"),e=e("../internals/fails"),n=1..toFixed,p=Math.floor;o({target:"Number",proto:!0,forced:n&&("0.000"!==8e-5.toFixed(3)||"1"!==.9.toFixed(0)||"1.25"!==1.255.toFixed(2)||"1000000000000000128"!==0xde0b6b3a7640080.toFixed(0))||!e(function(){n.call({})})},{toFixed:function(e){function t(e,t){for(var r=-1,o=t;++r<6;)o+=e*a[r],a[r]=o%1e7,o=p(o/1e7)}function r(e){for(var t=6,r=0;0<=--t;)r+=a[t],a[t]=p(r/e),r=r%e*1e7}function o(){for(var e,t=6,r="";0<=--t;)""===r&&0!==t&&0===a[t]||(e=String(a[t]),r=""===r?e:r+h.call("0",7-e.length)+e);return r}var n,s,i=f(this),e=d(e),a=[0,0,0,0,0,0],l="",u="0";if(e<0||20n;){var s,i,a,l=y[n++],u=t?l.ok:l.fail,c=l.resolve,d=l.reject,f=l.domain;try{u?(t||(p.rejection===oe&&function(e,t){v.call(g,function(){if(C)M.emit("rejectionHandled",e);else se(te,e,t.value)})}(h,p),p.rejection=L),!0===u?s=e:(f&&f.enter(),s=u(e),f&&(f.exit(),a=!0)),s===l.promise?d(w("Promise-chain cycle")):(i=ne(s))?i.call(s,c,d):c(s)):d(e)}catch(e){f&&!a&&f.exit(),d(e)}}p.reactions=[],p.notified=!1,m&&!p.rejection&&(r=h,o=p,v.call(g,function(){var e=o.value,t=ie(o);if(t&&(t=b(function(){C?M.emit("unhandledRejection",e,r):se(O,r,e)}),o.rejection=C||ie(o)?oe:L,t.error))throw t.value}))}))},se=function(e,t,r){var o;ee?((o=S.createEvent("Event")).promise=t,o.reason=r,o.initEvent(e,!1,!0),g.dispatchEvent(o)):o={promise:t,reason:r},(t=g["on"+e])?t(o):e===O&&Y("Unhandled promise rejection",r)},ie=function(e){return e.rejection!==L&&!e.parent},A=function(t,r,o,n){return function(e){t(r,o,e,n)}},R=function(e,t,r,o){t.done||(t.done=!0,(t=o?o:t).value=r,t.state=re,P(e,t,!0))},I=function(r,o,e,t){if(!o.done){o.done=!0,t&&(o=t);try{if(r===e)throw w("Promise can't be resolved itself");var n=ne(e);n?u(function(){var t={done:!1};try{n.call(e,A(I,r,t,o),A(R,r,t,o))}catch(e){R(r,t,e,o)}}):(o.value=e,o.state=k,P(r,o,!1))}catch(e){R(r,{done:!1},e,o)}}};e&&(x=function(e){z(this,x,j),c(e),r.call(this);var t=_(this);try{e(A(I,this,t),A(R,this,t))}catch(e){R(this,t,e)}},(r=function(e){J(this,{type:j,done:!1,notified:!1,parent:!1,reactions:[],rejection:!1,state:0,value:void 0})}).prototype=F(x.prototype,{then:function(e,t){var r=K(this),o=T(X(this,x));return o.ok="function"!=typeof e||e,o.fail="function"==typeof t&&t,o.domain=C?M.domain:void 0,r.parent=!0,r.reactions.push(o),0!=r.state&&P(this,r,!1),o.promise},catch:function(e){return this.then(void 0,e)}}),t=function(){var e=new r,t=_(e);this.promise=e,this.resolve=A(I,e,t),this.reject=A(R,e,t)},h.f=T=function(e){return e===x||e===o?new t:$(e)},i||"function"!=typeof l||(n=l.prototype.then,N(l.prototype,"then",function(e,t){var r=this;return new x(function(e,t){n.call(r,e,t)}).then(e,t)},{unsafe:!0}),"function"==typeof E&&s({global:!0,enumerable:!0,forced:!0},{fetch:function(e){return f(x,E.apply(g,arguments))}}))),s({global:!0,wrap:!0,forced:e},{Promise:x}),B(x,j,!1,!0),G(j),o=a(j),s({target:j,stat:!0,forced:e},{reject:function(e){var t=T(this);return t.reject.call(void 0,e),t.promise}}),s({target:j,stat:!0,forced:i||e},{resolve:function(e){return f(i&&this===o?x:this,e)}}),s({target:j,stat:!0,forced:m},{all:function(e){var a=this,t=T(a),l=t.resolve,u=t.reject,r=b(function(){var o=c(a.resolve),n=[],s=0,i=1;d(e,function(e){var t=s++,r=!1;n.push(void 0),i++,o.call(a,e).then(function(e){r||(r=!0,n[t]=e,--i||l(n))},u)}),--i||l(n)});return r.error&&u(r.value),t.promise},race:function(e){var r=this,o=T(r),n=o.reject,t=b(function(){var t=c(r.resolve);d(e,function(e){t.call(r,e).then(o.resolve,n)})});return t.error&&n(t.value),o.promise}})},{"../internals/a-function":5,"../internals/an-instance":9,"../internals/check-correctness-of-iteration":27,"../internals/classof-raw":28,"../internals/engine-v8-version":48,"../internals/export":50,"../internals/get-built-in":56,"../internals/global":59,"../internals/host-report-errors":62,"../internals/inspect-source":68,"../internals/internal-state":70,"../internals/is-forced":73,"../internals/is-object":74,"../internals/is-pure":75,"../internals/iterate":77,"../internals/microtask":81,"../internals/native-promise-constructor":82,"../internals/new-promise-capability":86,"../internals/perform":105,"../internals/promise-resolve":106,"../internals/redefine":108,"../internals/redefine-all":107,"../internals/set-species":116,"../internals/set-to-string-tag":117,"../internals/species-constructor":121,"../internals/task":128,"../internals/well-known-symbol":146}],179:[function(e,t,r){var o=e("../internals/export"),n=e("../internals/get-built-in"),s=e("../internals/a-function"),i=e("../internals/an-object"),a=e("../internals/is-object"),l=e("../internals/object-create"),u=e("../internals/function-bind"),e=e("../internals/fails"),c=n("Reflect","construct"),d=e(function(){function e(){}return!(c(function(){},[],e)instanceof e)}),f=!e(function(){c(function(){})}),n=d||f;o({target:"Reflect",stat:!0,forced:n,sham:n},{construct:function(e,t){s(e),i(t);var r=arguments.length<3?e:s(arguments[2]);if(f&&!d)return c(e,t,r);if(e==r){switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3])}var o=[null];return o.push.apply(o,t),new(u.apply(e,o))}o=r.prototype,r=l(a(o)?o:Object.prototype),o=Function.apply.call(e,r,t);return a(o)?o:r}})},{"../internals/a-function":5,"../internals/an-object":10,"../internals/export":50,"../internals/fails":51,"../internals/function-bind":55,"../internals/get-built-in":56,"../internals/is-object":74,"../internals/object-create":90}],180:[function(e,t,r){var o=e("../internals/descriptors"),n=e("../internals/global"),s=e("../internals/is-forced"),i=e("../internals/inherit-if-required"),a=e("../internals/object-define-property").f,l=e("../internals/object-get-own-property-names").f,u=e("../internals/is-regexp"),c=e("../internals/regexp-flags"),d=e("../internals/regexp-sticky-helpers"),f=e("../internals/redefine"),h=e("../internals/fails"),p=e("../internals/internal-state").set,m=e("../internals/set-species"),y=e("../internals/well-known-symbol")("match"),g=n.RegExp,v=g.prototype,b=/a/g,j=/a/g,_=new g(b)!==b,x=d.UNSUPPORTED_Y;if(o&&s("RegExp",!_||x||h(function(){return j[y]=!1,g(b)!=b||g(j)==j||"/a/i"!=g(b,"i")}))){for(var w=function(e,t){var r,o=this instanceof w,n=u(e),s=void 0===t;if(!o&&n&&e.constructor===w&&s)return e;_?n&&!s&&(e=e.source):e instanceof w&&(s&&(t=c.call(e)),e=e.source),x&&(r=!!t&&-1M;)!function(t){t in w||a(w,t,{configurable:!0,get:function(){return g[t]},set:function(e){g[t]=e}})}(S[M++]);(v.constructor=w).prototype=v,f(n,"RegExp",w)}m("RegExp")},{"../internals/descriptors":43,"../internals/fails":51,"../internals/global":59,"../internals/inherit-if-required":67,"../internals/internal-state":70,"../internals/is-forced":73,"../internals/is-regexp":76,"../internals/object-define-property":92,"../internals/object-get-own-property-names":95,"../internals/redefine":108,"../internals/regexp-flags":111,"../internals/regexp-sticky-helpers":112,"../internals/set-species":116,"../internals/well-known-symbol":146}],181:[function(e,t,r){"use strict";var o=e("../internals/export"),e=e("../internals/regexp-exec");o({target:"RegExp",proto:!0,forced:/./.exec!==e},{exec:e})},{"../internals/export":50,"../internals/regexp-exec":110}],182:[function(e,t,r){"use strict";var o=e("../internals/redefine"),n=e("../internals/an-object"),s=e("../internals/fails"),i=e("../internals/regexp-flags"),e="toString",a=RegExp.prototype,l=a[e],s=s(function(){return"/a/b"!=l.call({source:"a",flags:"b"})}),u=l.name!=e;(s||u)&&o(RegExp.prototype,e,function(){var e=n(this),t=String(e.source),r=e.flags;return"/"+t+"/"+String(void 0===r&&e instanceof RegExp&&!("flags"in a)?i.call(e):r)},{unsafe:!0})},{"../internals/an-object":10,"../internals/fails":51,"../internals/redefine":108,"../internals/regexp-flags":111}],183:[function(e,t,r){"use strict";var o=e("../internals/collection"),e=e("../internals/collection-strong");t.exports=o("Set",function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},e)},{"../internals/collection":32,"../internals/collection-strong":30}],184:[function(e,t,r){"use strict";var o=e("../internals/export"),n=e("../internals/object-get-own-property-descriptor").f,s=e("../internals/to-length"),i=e("../internals/not-a-regexp"),a=e("../internals/require-object-coercible"),l=e("../internals/correct-is-regexp-logic"),e=e("../internals/is-pure"),u="".endsWith,c=Math.min,l=l("endsWith");o({target:"String",proto:!0,forced:!!(e||l||(!(o=n(String.prototype,"endsWith"))||o.writable))&&!l},{endsWith:function(e){var t=String(a(this)),r=(i(e),1=t.length?{value:void 0,done:!0}:(t=o(t,r),e.index+=t.length,{value:t,done:!1})})},{"../internals/define-iterator":41,"../internals/internal-state":70,"../internals/string-multibyte":123}],187:[function(e,t,r){"use strict";var o=e("../internals/fix-regexp-well-known-symbol-logic"),c=e("../internals/an-object"),d=e("../internals/to-length"),n=e("../internals/require-object-coercible"),f=e("../internals/advance-string-index"),h=e("../internals/regexp-exec-abstract");o("match",1,function(o,l,u){return[function(e){var t=n(this),r=null==e?void 0:e[o];return void 0!==r?r.call(e,t):new RegExp(e)[o](String(t))},function(e){var t=u(l,e,this);if(t.done)return t.value;var r=c(e),o=String(this);if(!r.global)return h(r,o);for(var n=r.unicode,s=[],i=r.lastIndex=0;null!==(a=h(r,o));){var a=String(a[0]);""===(s[i]=a)&&(r.lastIndex=f(o,d(r.lastIndex),n)),i++}return 0===i?null:s}]})},{"../internals/advance-string-index":8,"../internals/an-object":10,"../internals/fix-regexp-well-known-symbol-logic":52,"../internals/regexp-exec-abstract":109,"../internals/require-object-coercible":113,"../internals/to-length":134}],188:[function(e,t,r){e("../internals/export")({target:"String",proto:!0},{repeat:e("../internals/string-repeat")})},{"../internals/export":50,"../internals/string-repeat":125}],189:[function(e,t,r){"use strict";var o=e("../internals/fix-regexp-well-known-symbol-logic"),M=e("../internals/an-object"),E=e("../internals/to-object"),T=e("../internals/to-length"),C=e("../internals/to-integer"),s=e("../internals/require-object-coercible"),O=e("../internals/advance-string-index"),k=e("../internals/regexp-exec-abstract"),L=Math.max,P=Math.min,A=Math.floor,R=/\$([$&'`]|\d\d?|<[^>]*>)/g,I=/\$([$&'`]|\d\d?)/g;o("replace",2,function(n,j,_,e){var x=e.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE,w=e.REPLACE_KEEPS_$0,S=x?"$":"$0";return[function(e,t){var r=s(this),o=null==e?void 0:e[n];return void 0!==o?o.call(e,r,t):j.call(String(r),e,t)},function(e,t){if(!x&&w||"string"==typeof t&&-1===t.indexOf(S)){var r=_(j,e,this,t);if(r.done)return r.value}for(var o,n=M(e),s=String(this),i="function"==typeof t,a=(i||(t=String(t)),n.global),l=(a&&(o=n.unicode,n.lastIndex=0),[]);null!==(h=k(n,s))&&(l.push(h),a);)""===String(h[0])&&(n.lastIndex=O(s,T(n.lastIndex),o));for(var u,c="",d=0,f=0;f>>0;if(0==o)return[];if(void 0===e)return[r];if(!c(e))return p.call(r,e,o);for(var n,s,i,a=[],t=(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.unicode?"u":"")+(e.sticky?"y":""),l=0,u=new RegExp(e.source,t+"g");(n=f.call(u,r))&&!(l<(s=u.lastIndex)&&(a.push(r.slice(l,n.index)),1=o));)u.lastIndex===n.index&&u.lastIndex++;return l===r.length?!i&&u.test("")||a.push(""):a.push(r.slice(l)),a.length>o?a.slice(0,o):a}:"0".split(void 0,0).length?function(e,t){return void 0===e&&0===t?[]:p.call(this,e,t)}:p;return[function(e,t){var r=d(this),o=null==e?void 0:e[n];return void 0!==o?o.call(e,r,t):y.call(String(r),e,t)},function(e,t){var r=m(y,e,this,t,y!==p);if(r.done)return r.value;var r=g(e),o=String(this),e=v(r,RegExp),n=r.unicode,s=(r.ignoreCase?"i":"")+(r.multiline?"m":"")+(r.unicode?"u":"")+(S?"y":"g"),i=new e(S?r:"^(?:"+r.source+")",s),a=void 0===t?w:t>>>0;if(0==a)return[];if(0===o.length)return null===_(i,o)?[o]:[];for(var l=0,u=0,c=[];ue.key){o.splice(t,0,e);break}t===s&&o.push(e)}r.updateURL()},forEach:function(e){for(var t,r=L(this).entries,o=v(e,16)return;a=0;while(f()){l=null;if(a>0)if(f()=="."&&a<4)n++;else return;if(!x.test(f()))return;while(x.test(f())){u=parseInt(f(),10);if(l===null)l=u;else if(l==0)return;else l=l*10+u;if(l>255)return;n++}t[r]=t[r]*256+l;a++;if(a==2||a==4)r++}if(a!=4)return;break}else if(f()==":"){n++;if(!f())return}else if(f())return;t[r++]=s}if(o!==null){c=r-o;r=7;while(r!=0&&c>0){d=t[r];t[r--]=t[o+c-1];t[o+--c]=d}}else if(r!=8)return;return t}(t.slice(1,-1)))?void(e.host=r):_;if(C(e))return t=z(t),ne.test(t)||null===(r=function(e){var t=e.split("."),r,o,n,s,i,a,l;if(t.length&&t[t.length-1]=="")t.pop();if((r=t.length)>4)return e;for(o=[],n=0;n1&&s.charAt(0)=="0"){i=ee.test(s)?16:8;s=s.slice(i==8?1:2)}if(s==="")a=0;else{if(!(i==10?re:i==8?te:oe).test(s))return e;a=parseInt(s,i)}o.push(a)}for(n=0;n=Z(256,5-r))return null}else if(a>255)return null}for(l=o.pop(),n=0;n":1,"`":1}),ce=d({},ue,{"#":1,"?":1,"{":1,"}":1}),M=d({},ce,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),E=function(e,t){var r=V(e,0);return 32f,applyPalette:()=>function(e,t,r="rgb565"){if(!e||!e.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(e instanceof Uint8Array||e instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");if(256>24&255,c=l>>16&255,d=l>>8&255,l=255&l,f=L(l,d,c,u),f=f in a?a[f]:a[f]=function(t,r,o,n,s){let i=0,a=1e100;for(let e=0;ea||(l=u[0],(c+=v(l-t))>a||(l=u[1],(c+=v(l-r))>a||(l=u[2],(c+=v(l-o))>a||(a=c,i=e))))}return i}(l,d,c,u,t);i[e]=f}else{const g="rgb444"===r?P:k;for(let e=0;e>16&255,m=h>>8&255,h=255&h,y=g(h,m,p),y=y in a?a[y]:a[y]=function(t,r,o,n){let s=0,i=1e100;for(let e=0;ei||(a=l[1],(u+=v(a-r))>i||(a=l[2],(u+=v(a-o))>i||(i=u,s=e)))}return s}(h,m,p,t);i[e]=y}}return i},default:()=>h,nearestColor:()=>function(e,t,r=u){return e[l(e,t,r)]},nearestColorIndex:()=>l,nearestColorIndexWithDistance:()=>d,prequantize:()=>function(e,{roundRGB:r=5,roundAlpha:o=10,oneBitAlpha:n=null}={}){const s=new Uint32Array(e.buffer);for(let t=0;t>24&255;var a,l=i>>16&255,u=i>>8&255,i=255&i;e=c(e,o),n&&(a="number"==typeof n?n:127,e=e<=a?0:255),i=c(i,r),u=c(u,r),l=c(l,r),s[t]=e<<24|l<<16|u<<8|i<<0}},quantize:()=>function(e,t,r={}){var{format:o="rgb565",clearAlpha:n=!0,clearAlphaColor:s=0,clearAlphaThreshold:i=0,oneBitAlpha:a=!1}=r;if(!e||!e.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(e instanceof Uint8Array||e instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");e=new Uint32Array(e.buffer);let l=!1!==r.useSqrt;const u="rgba4444"===o,c=function(r,e){const t="rgb444"===e?4096:65536,o=new Array(t),n=r.length;if("rgba4444"===e)for(let t=0;t>24&255,a=s>>16&255,l=s>>8&255,s=255&s,u=L(s,l,a,i);let e=u in o?o[u]:o[u]=D();e.rc+=s,e.gc+=l,e.bc+=a,e.ac+=i,e.cnt++}else if("rgb444"===e)for(let t=0;t>16&255,f=c>>8&255,c=255&c,h=P(c,f,d);let e=h in o?o[h]:o[h]=D();e.rc+=c,e.gc+=f,e.bc+=d,e.cnt++}else for(let t=0;t>16&255,y=p>>8&255,p=255&p,g=k(p,y,m);let e=g in o?o[g]:o[g]=D();e.rc+=p,e.gc+=y,e.bc+=m,e.cnt++}return o}(e,o),d=c.length,f=d-1,h=new Uint32Array(d+1);for(var p=0,m=0;m>1,!(c[y=h[v]].err<=b));g=v)h[g]=y;h[g]=m}var j,_=p-t;for(m=0;m<_;){for(;;){var x=h[1];if((j=c[x]).tm>=j.mtm&&c[j.nn].mtm<=j.tm)break;j.mtm==f?x=h[1]=h[h[0]--]:(I(c,x,!1),j.tm=m);b=c[x].err;for(g=1;(v=g+g)<=h[0]&&(vc[h[v+1]].err&&v++,!(b<=c[y=h[v]].err));g=v)h[g]=y;h[g]=x}var w=c[j.nn],S=j.cnt,M=w.cnt,E=1/(S+M);u&&(j.ac=E*(S*j.ac+M*w.ac)),j.rc=E*(S*j.rc+M*w.rc),j.gc=E*(S*j.gc+M*w.gc),j.bc=E*(S*j.bc+M*w.bc),j.cnt+=w.cnt,j.mtm=++m,c[w.bk].fw=w.fw,c[w.fw].bk=w.bk,w.mtm=f}let T=[];for(m=0;;0){let e=A(Math.round(c[m].rc),0,255),t=A(Math.round(c[m].gc),0,255),r=A(Math.round(c[m].bc),0,255),o=255;u&&(o=A(Math.round(c[m].ac),0,255),a&&(C="number"==typeof a?a:127,o=o<=C?0:255),n&&o<=i&&(e=t=r=s,o=0));var C=u?[e,t,r,o]:[e,t,r];if(function(t,r){for(let e=0;efunction(r,o,e=5){if(r.length&&o.length){var n=r.map(e=>e.slice(0,3)),s=e*e,i=r[0].length;for(let t=0;ti?e.slice(0,3):e.slice();var a=d(n,e.slice(0,3),u),l=a[0],a=a[1];0>>0),0!=t&&(e=Math.max(e,256));const r=s;s=new Uint8Array(e),0>=8,c-=8;if((v>m||h)&&(h?(p=f,m=(1<>=8,c-=8;0>3}function L(e,t,r,o){return e>>4|240&t|(240&r)<<4|(240&o)<<8}function P(e,t,r){return e>>4<<8|240&t|r>>4}function A(e,t,r){return e>8&255)}function O(e,t){for(var r=0;r>1,c=-7,d=r?n-1:0,f=r?-1:1,n=e[t+d];for(d+=f,s=n&(1<<-c)-1,n>>=-c,c+=a;0>=-c,c+=o;0>1,d=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,f=o?0:s-1,h=o?1:-1,s=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,i=u):(i=Math.floor(Math.log(t)/Math.LN2),t*(o=Math.pow(2,-i))<1&&(i--,o*=2),2<=(t+=1<=i+c?d/o:d*Math.pow(2,1-c))*o&&(i++,o/=2),u<=i+c?(a=0,i=u):1<=i+c?(a=(t*o-1)*Math.pow(2,n),i+=c):(a=t*Math.pow(2,c-1)*Math.pow(2,n),i=0));8<=n;e[r+f]=255&a,f+=h,a/=256,n-=8);for(i=i<Math.abs(e[0])&&(t=1),t=Math.abs(e[2])>Math.abs(e[t])?2:t}function T(e,t){e.f+=t.f,e.b.f+=t.b.f}function f(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=v(t.b.a,e,t.a),(e=v(r.b.a,e,r.a))<=t)}function C(e){e.a.i=null;var t=e.e;t.a.c=t.c,t.c.a=t.a,e.e=null}function O(e,t){m(e.a),e.c=!1,(e.a=t).i=e}function k(e){for(var t=e.a.a;(e=G(e)).a.a===t;);return e.c&&(O(e,t=S(B(e).a.b,e.a.e)),e=G(e)),e}function q(e,t,r){var o=new F;return o.a=r,o.e=p(e.f,t.e,o),r.i=o}function X(e,t){switch(e.s){case 100130:return 0!=(1&t);case 100131:return 0!==t;case 100132:return 0>1]],a[i[u]])?N:ue)(r,u),a[s]=null,l[s]=r.b,r.b=s}else for(r.c[-(s+1)]=null;0Math.max(i.a,l.a))){if(g(s,i)){if(0r.f&&(r.f*=2,r.c=ae(r.c,r.f+1)),0===r.b?n=o:(n=r.b,r.b=r.c[r.b]),r.e[n]=t,r.c[n]=o,r.d[o]=n,r.h&&ue(r,o),n):(r=e.a++,e.c[r]=t,-(r+1))}function se(e){if(0===e.a)return le(e.b);var t=e.c[e.d[e.a-1]];if(0!==e.b.a&&g(U(e.b),t))return le(e.b);for(;--e.a,0e.a||g(o[i],o[l])){n[r[s]=i]=s;break}n[r[s]=l]=s,s=a}}function ue(e,t){for(var r=e.d,o=e.e,n=e.c,s=t,i=r[s];;){var a=s>>1,l=r[a];if(0==a||g(o[l],o[i])){n[r[s]=i]=s;break}n[r[s]=l]=s,s=a}}function F(){this.e=this.a=null,this.f=0,this.c=this.b=this.h=this.d=!1}function B(e){return e.e.c.b}function G(e){return e.e.a.b}(t=r.prototype).x=function(){I(this,0)},t.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 l(this,100900)}l(this,100901)},t.y=function(e){switch(e){case 100142:return 0;case 100140:return this.s;case 100141:return this.m;default:l(this,100900)}return!1},t.A=function(e,t,r){this.j[0]=e,this.j[1]=t,this.j[2]=r},t.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:l(this,100900)}},t.C=function(e,t){var r=!1,o=[0,0,0];I(this,2);for(var n=0;n<3;++n){var s=e[n];s<-1e150&&(s=-1e150,r=!0),1e150o[u]&&(o[u]=c,n[u]=r)}if(o[1]-a[1]>o[r=0]-a[0]&&(r=1),a[r=o[2]-a[2]>o[r]-a[r]?2:r]>=o[r])i[0]=0,i[1]=0,i[2]=1;else{for(a=l[r],n=n[r],l=[o=0,0,0],a=[a.g[0]-n.g[0],a.g[1]-n.g[1],a.g[2]-n.g[2]],u=[0,0,0],r=s.e;r!==s;r=r.e)u[0]=r.g[0]-n.g[0],u[1]=r.g[1]-n.g[1],u[2]=r.g[2]-n.g[2],l[0]=a[1]*u[2]-a[2]*u[1],l[1]=a[2]*u[0]-a[0]*u[2],l[2]=a[0]*u[1]-a[1]*u[0],o<(c=l[0]*l[0]+l[1]*l[1]+l[2]*l[2])&&(o=c,i[0]=l[0],i[1]=l[1],i[2]=l[2]);o<=0&&(i[0]=i[1]=i[2]=0,i[W(a)]=1)}s=!0}for(l=W(i),r=this.b.c,o=(l+1)%3,n=(l+2)%3,l=0>=1;)++n;if(i=1<>8&255,g[v++]=255&t,g[v++]=t>>8&255,g[v++]=(null!==b?128:0)|n,g[v++]=s,g[v++]=0,null!==b)for(var a=0,l=b.length;a>16&255,g[v++]=u>>8&255,g[v++]=255&u}if(null!==o){if(o<0||65535>8&255,g[v++]=0}var _=!1;this.addFrame=function(e,t,r,o,n,s){if(!0===_&&(--v,_=!1),s=void 0===s?{}:s,e<0||t<0||65535>=1;)++u;var l=1<>8&255,g[v++]=h,g[v++]=0),g[v++]=44,g[v++]=255&e,g[v++]=e>>8&255,g[v++]=255&t,g[v++]=t>>8&255,g[v++]=255&r,g[v++]=r>>8&255,g[v++]=255&o,g[v++]=o>>8&255,g[v++]=!0===i?128|u-1:0,!0===i)for(var p=0,m=a.length;p>16&255,g[v++]=y>>8&255,g[v++]=255&y}return v=function(t,r,e,o){t[r++]=e;var n=r++,s=1<>=8,c-=8,r===n+256&&(t[n]=255,n=r++)}function h(e){d|=e<>=8,c-=8,r===n+256&&(t[n]=255,n=r++);4096===l?(h(s),l=1+a,u=e+1,m={}):(1<>=l,c-=l,y==s)a=1+i,u=(1<<(l=n+1))-1,m=null;else{if(y==i)break;for(var g=y>8,++v;var j=b;if(o>=8;null!==m&&a<4096&&(p[a++]=m<<8|j,u+1<=a&&l<12&&(++l,u=u<<1|1)),m=y}}f!==o&&console.log("Warning, gif stream shorter than expected.")}try{r.GifWriter=o,r.GifReader=function(b){var e=0;if(71!==b[e++]||73!==b[e++]||70!==b[e++]||56!==b[e++]||56!=(b[e++]+1&253)||97!==b[e++])throw new Error("Invalid GIF 87a/89a header.");var j=b[e++]|b[e++]<<8,t=b[e++]|b[e++]<<8,r=b[e++],o=1<<1+(7&r),n=(b[e++],b[e++],null),s=null,i=(r>>7&&(n=e,e+=3*(s=o)),!0),a=[],l=0,u=null,c=0,d=null;for(this.width=j,this.height=t;i&&e>2&7,e++;break;case 254:for(;;){if(!(0<=(h=b[e++])))throw Error("Invalid block size");if(0===h)break;e+=h}break;default:throw new Error("Unknown graphic control label: 0x"+b[e-1].toString(16))}break;case 44:var h,p=b[e++]|b[e++]<<8,m=b[e++]|b[e++]<<8,y=b[e++]|b[e++]<<8,g=b[e++]|b[e++]<<8,v=b[e++],_=v>>6&1,x=1<<1+(7&v),w=n,S=s,M=!1,v=(v>>7&&(M=!0,w=e,e+=3*(S=x)),e);for(e++;;){if(!(0<=(h=b[e++])))throw Error("Invalid block size");if(0===h)break;e+=h}a.push({x:p,y:m,width:y,height:g,has_local_palette:M,palette_offset:w,palette_size:S,data_offset:v,data_length:e-v,transparent_index:u,interlaced:!!_,delay:l,disposal:c});break;case 59:i=!1;break;default:throw new Error("Unknown gif block: 0x"+b[e-1].toString(16))}this.numFrames=function(){return a.length},this.loopCount=function(){return d},this.frameInfo=function(e){if(e<0||e>=a.length)throw new Error("Frame index out of range.");return a[e]},this.decodeAndBlitFrameBGRA=function(e,t){for(var e=this.frameInfo(e),r=e.width*e.height,o=new Uint8Array(r),n=(E(b,e.data_offset,o,r),e.palette_offset),s=e.transparent_index,i=(null===s&&(s=256),e.width),a=j-i,l=i,u=4*(e.y*j+e.x),c=4*((e.y+e.height)*j+e.x),d=u,f=4*a,h=(!0===e.interlaced&&(f+=4*j*7),8),p=0,m=o.length;p>=1)),v===s?d+=4:(y=b[n+3*v],g=b[n+3*v+1],v=b[n+3*v+2],t[d++]=v,t[d++]=g,t[d++]=y,t[d++]=255),--l}},this.decodeAndBlitFrameRGBA=function(e,t){for(var e=this.frameInfo(e),r=e.width*e.height,o=new Uint8Array(r),n=(E(b,e.data_offset,o,r),e.palette_offset),s=e.transparent_index,i=(null===s&&(s=256),e.width),a=j-i,l=i,u=4*(e.y*j+e.x),c=4*((e.y+e.height)*j+e.x),d=u,f=4*a,h=(!0===e.interlaced&&(f+=4*j*7),8),p=0,m=o.length;p>=1)),v===s?d+=4:(y=b[n+3*v],g=b[n+3*v+1],v=b[n+3*v+2],t[d++]=y,t[d++]=g,t[d++]=v,t[d++]=255),--l}}}}catch(e){}},{}],241:[function(Pr,r,o){!function(Lr){var e,t;e=this,t=function(j){"use strict";function D(e){if(null==this)throw TypeError();var t,r=String(this),o=r.length,e=e?Number(e):0;if(!((e=e!=e?0:e)<0||o<=e))return 55296<=(t=r.charCodeAt(e))&&t<=56319&&e+1>>16-t;return e.tag>>>=t,e.bitcount-=t,o+r}function $(e,t){for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>=1,r+=t.table[++n],0<=(o-=t.table[n]););return e.tag=s,e.bitcount-=n,t.trans[r+o]}function ee(e,t,r){for(;;){var o=$(e,t);if(256===o)return N;if(o<256)e.dest[e.destLen++]=o;else for(var n,s=b(e,H[o-=257],W[o]),o=$(e,r),i=n=e.destLen-b(e,q[o],X[o]);i>>=1,o=n,b(s,2,0)){case 0:r=function(e){for(var t,r;8this.x2&&(this.x2=e)),"number"==typeof t&&((isNaN(this.y1)||isNaN(this.y2))&&(this.y1=t,this.y2=t),tthis.y2&&(this.y2=t))},a.prototype.addX=function(e){this.addPoint(e,null)},a.prototype.addY=function(e){this.addPoint(null,e)},a.prototype.addBezier=function(e,t,r,o,n,s,i,a){var l=[e,t],u=[r,o],c=[n,s],d=[i,a];this.addPoint(e,t),this.addPoint(i,a);for(var f=0;f<=1;f++){var h,p=6*l[f]-12*u[f]+6*c[f],m=-3*l[f]+9*u[f]-9*c[f]+3*d[f],y=3*u[f]-3*l[f];0==m?0==p||0<(h=-y/p)&&h<1&&(0===f&&this.addX(g(l[f],u[f],c[f],d[f],h)),1===f&&this.addY(g(l[f],u[f],c[f],d[f],h))):(h=Math.pow(p,2)-4*y*m)<0||(0<(y=(-p+Math.sqrt(h))/(2*m))&&y<1&&(0===f&&this.addX(g(l[f],u[f],c[f],d[f],y)),1===f&&this.addY(g(l[f],u[f],c[f],d[f],y))),0<(y=(-p-Math.sqrt(h))/(2*m))&&y<1&&(0===f&&this.addX(g(l[f],u[f],c[f],d[f],y)),1===f&&this.addY(g(l[f],u[f],c[f],d[f],y))))}},a.prototype.addQuad=function(e,t,r,o,n,s){r=e+2/3*(r-e),o=t+2/3*(o-t);this.addBezier(e,t,r,o,r+1/3*(n-e),o+1/3*(s-t),n,s)},f.prototype.moveTo=function(e,t){this.commands.push({type:"M",x:e,y:t})},f.prototype.lineTo=function(e,t){this.commands.push({type:"L",x:e,y:t})},f.prototype.curveTo=f.prototype.bezierCurveTo=function(e,t,r,o,n,s){this.commands.push({type:"C",x1:e,y1:t,x2:r,y2:o,x:n,y:s})},f.prototype.quadTo=f.prototype.quadraticCurveTo=function(e,t,r,o){this.commands.push({type:"Q",x1:e,y1:t,x:r,y:o})},f.prototype.close=f.prototype.closePath=function(){this.commands.push({type:"Z"})},f.prototype.extend=function(e){var t;if(e.commands)e=e.commands;else if(e instanceof a)return t=e,this.moveTo(t.x1,t.y1),this.lineTo(t.x2,t.y1),this.lineTo(t.x2,t.y2),this.lineTo(t.x1,t.y2),void this.close();Array.prototype.push.apply(this.commands,e)},f.prototype.getBoundingBox=function(){for(var e=new a,t=0,r=0,o=0,n=0,s=0;s>8&255,255&e]},l.USHORT=r(2),w.SHORT=function(e){return[(e=32768<=e?-(65536-e):e)>>8&255,255&e]},l.SHORT=r(2),w.UINT24=function(e){return[e>>16&255,e>>8&255,255&e]},l.UINT24=r(3),w.ULONG=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]},l.ULONG=r(4),w.LONG=function(e){return[(e=2147483648<=e?-(4294967296-e):e)>>24&255,e>>16&255,e>>8&255,255&e]},l.LONG=r(4),w.FIXED=w.ULONG,l.FIXED=l.ULONG,w.FWORD=w.SHORT,l.FWORD=l.SHORT,w.UFWORD=w.USHORT,l.UFWORD=l.USHORT,w.LONGDATETIME=function(e){return[0,0,0,0,e>>24&255,e>>16&255,e>>8&255,255&e]},l.LONGDATETIME=r(8),w.TAG=function(e){return A.argument(4===e.length,"Tag should be exactly 4 ASCII characters."),[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]},l.TAG=r(4),w.Card8=w.BYTE,l.Card8=l.BYTE,w.Card16=w.USHORT,l.Card16=l.USHORT,w.OffSize=w.BYTE,l.OffSize=l.BYTE,w.SID=w.USHORT,l.SID=l.USHORT,w.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?w.NUMBER16(e):w.NUMBER32(e)},l.NUMBER=function(e){return w.NUMBER(e).length},w.NUMBER16=function(e){return[28,e>>8&255,255&e]},l.NUMBER16=r(3),w.NUMBER32=function(e){return[29,e>>24&255,e>>16&255,e>>8&255,255&e]},l.NUMBER32=r(5),w.REAL=function(e){for(var t=e.toString(),r=/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(t),o=(r&&(r=parseFloat("1e"+((r[2]?+r[2]:0)+r[1].length)),t=(Math.round(e*r)/r).toString()),""),n=0,s=t.length;n>8&255,t[t.length]=255&o}return t},l.UTF16=function(e){return 2*e.length};var se,ie={"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":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"},ae=(m.MACSTRING=function(e,t,r,o){var n=ie[o];if(void 0!==n){for(var s="",i=0;i>8&255,l+256&255)}return s})(e,t,r);return r},w.INDEX=function(e){for(var t=1,r=[t],o=[],n=0;n>8,t[c+1]=255&d,t=t.concat(o[u])}return t},l.TABLE=function(e){for(var t=0,r=e.fields.length,o=0;o>1,a.skip("uShort",3),y.glyphIndexMap={};for(var j,_=new R.Parser(g,v+b+14),x=new R.Parser(g,v+b+16+2*j),w=new R.Parser(g,v+b+16+4*j),S=new R.Parser(g,v+b+16+6*j),M=v+b+16+8*j,E=0;E>4,s=15&s;if(15==i)break;if(o+=n[i],15==s)break;o+=n[s]}return parseFloat(o)}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 Ie(e,t,r){var o=new R.Parser(e,t=void 0!==t?t:0),n=[],s=[];for(r=void 0!==r?r:e.length;o.relativeOffset>1,E.length=0,C=!0}return function e(t){for(var r,o,n,s,i,a,l,u,c,d,f,h,p=0;pMath.abs(h-L)?k=f+E.shift():L=h+E.shift(),M.curveTo(v,b,j,_,l,u),M.curveTo(c,d,f,h,k,L);break;default:console.log("Glyph "+g.index+": unknown operator 1200"+m),E.length=0}break;case 14:0>3;break;case 21:2>16),p+=2;break;case 29:i=E.pop()+y.gsubrsBias,(a=y.gsubrs[i])&&e(a);break;case 30:for(;0=r.begin&&e=c.length&&(s=o.parseChar(),r.names.push(o.parseString(s)));break;case 2.5:r.numberOfGlyphs=o.parseUShort(),r.offset=new Array(r.numberOfGlyphs);for(var a=0;at.value.tag?1:-1}),t.fields=t.fields.concat(o),t.fields=t.fields.concat(n),t}function xt(e,t,r){for(var o=0;o 123 are reserved for internal usage");h|=1<>>1,s=e[n].tag;if(s===t)return n;s>>1,s=e[n];if(s===t)return n;s>>1,i=(n=e[s]).start;if(i===t)return n;i(n=e[r-1]).end?0:n}function Tt(e,t){this.font=e,this.tableName=t}function Ct(e){Tt.call(this,e,"gpos")}function i(e){Tt.call(this,e,"gsub")}function Ot(e,t,r){for(var o=e.subtables,n=0;nt.points.length-1||o.matchedPoints[1]>n.points.length-1)throw Error("Matched points out of range in "+t.name);var i=t.points[o.matchedPoints[0]],a=n.points[o.matchedPoints[1]],o={xScale:o.xScale,scale01:o.scale01,scale10:o.scale10,yScale:o.yScale,dx:0,dy:0},a=At([a],o)[0];o.dx=i.x-a.x,o.dy=i.y-a.y,s=At(n.points,o)}t.points=t.points.concat(s)}}return Rt(t.points)}(Ct.prototype=Tt.prototype={searchTag:St,binSearch:Mt,getTable:function(e){var t=this.font.tables[this.tableName];return t=!t&&e?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=i[t-1].tag,"Features must be added in alphabetical order."),i.push(n={tag:r,feature:{params:0,lookupListIndexes:[]}}),s.push(t),n.feature}},getLookupTables:function(e,t,r,o,n){var e=this.getFeatureTable(e,t,r,n),s=[];if(e){for(var i,a=e.lookupListIndexes,l=this.font.tables[this.tableName].lookups,u=0;u",s),t.stack.push(Math.round(64*s))}function fr(e,t){var r=t.stack,o=r.pop(),n=t.fv,s=t.pv,i=t.ppem,a=t.deltaBase+16*(e-1),l=t.deltaShift,u=t.z0;j.DEBUG&&console.log(t.step,"DELTAP["+e+"]",o,r);for(var c=0;c>4)===i&&(0<=(f=(15&f)-8)&&f++,j.DEBUG&&console.log(t.step,"DELTAPFIX",d,"by",f*l),d=u[d],n.setRelative(d,d,f*l,s))}}function hr(e,t){var r=t.stack,o=r.pop();j.DEBUG&&console.log(t.step,"ROUND[]"),r.push(64*t.round(o/64))}function pr(e,t){var r=t.stack,o=r.pop(),n=t.ppem,s=t.deltaBase+16*(e-1),i=t.deltaShift;j.DEBUG&&console.log(t.step,"DELTAC["+e+"]",o,r);for(var a=0;a>4)===n&&(0<=(u=(15&u)-8)&&u++,u=u*i,j.DEBUG&&console.log(t.step,"DELTACFIX",l,"by",u),t.cvt[l]+=u)}}function mr(e,t){var r,o=t.stack,n=o.pop(),o=o.pop(),s=t.z2[n],i=t.z1[o];j.DEBUG&&console.log(t.step,"SDPVTL["+e+"]",n,o),n=e?(r=s.y-i.y,i.x-s.x):(r=i.x-s.x,i.y-s.y),t.dpv=qt(r,n)}function C(e,t){var r=t.stack,o=t.prog,n=t.ip;j.DEBUG&&console.log(t.step,"PUSHB["+e+"]");for(var s=0;s":"_")+(o?"R":"_")+(0===n?"Gr":1===n?"Bl":2===n?"Wh":"")+"]",e?u+"("+s.cvt[u]+","+a+")":"",l,"(d =",i,"->",y*m,")"),s.rp1=s.rp0,s.rp2=l,t&&(s.rp0=l)}Ut.prototype.exec=function(e,t){if("number"!=typeof t)throw new Error("Point size is not a number!");if(!(2",o),a.interpolate(d,s,i,l),a.touch(d)}e.loop=1},lr.bind(void 0,0),lr.bind(void 0,1),function(e){for(var t=e.stack,r=e.rp0,o=e.z0[r],n=e.loop,s=e.fv,i=e.pv,a=e.z1;n--;){var l=t.pop(),u=a[l];j.DEBUG&&console.log(e.step,(1'.concat(n,"").concat(t,""),this.dummyDOM||(this.dummyDOM=document.getElementById(o).parentNode),this.descriptions?this.descriptions.fallbackElements||(this.descriptions.fallbackElements={}):this.descriptions={fallbackElements:{}},this.descriptions.fallbackElements[e]?this.descriptions.fallbackElements[e].innerHTML!==n&&(this.descriptions.fallbackElements[e].innerHTML=n):this._describeElementHTML("fallback",e,n),r===this.LABEL&&(this.descriptions.labelElements||(this.descriptions.labelElements={}),this.descriptions.labelElements[e]?this.descriptions.labelElements[e].innerHTML!==n&&(this.descriptions.labelElements[e].innerHTML=n):this._describeElementHTML("label",e,n)))},s.default.prototype._describeHTML=function(e,t){var r,o=this.canvas.id;"fallback"===e?(this.dummyDOM.querySelector("#".concat(o+i))?this.dummyDOM.querySelector("#"+o+l).insertAdjacentHTML("beforebegin",'

')):(r='

'),this.dummyDOM.querySelector("#".concat(o,"accessibleOutput"))?this.dummyDOM.querySelector("#".concat(o,"accessibleOutput")).insertAdjacentHTML("beforebegin",r):this.dummyDOM.querySelector("#".concat(o)).innerHTML=r),this.descriptions.fallback=this.dummyDOM.querySelector("#".concat(o).concat(a)),this.descriptions.fallback.innerHTML=t):"label"===e&&(this.dummyDOM.querySelector("#".concat(o+u))?this.dummyDOM.querySelector("#".concat(o+d))&&this.dummyDOM.querySelector("#".concat(o+d)).insertAdjacentHTML("beforebegin",'

')):(r='

'),this.dummyDOM.querySelector("#".concat(o,"accessibleOutputLabel"))?this.dummyDOM.querySelector("#".concat(o,"accessibleOutputLabel")).insertAdjacentHTML("beforebegin",r):this.dummyDOM.querySelector("#"+o).insertAdjacentHTML("afterend",r)),this.descriptions.label=this.dummyDOM.querySelector("#"+o+c),this.descriptions.label.innerHTML=t)},s.default.prototype._describeElementHTML=function(e,t,r){var o,n=this.canvas.id;"fallback"===e?(this.dummyDOM.querySelector("#".concat(n+i))?this.dummyDOM.querySelector("#"+n+l)||this.dummyDOM.querySelector("#"+n+a).insertAdjacentHTML("afterend",'
Canvas elements and their descriptions
')):(o='
Canvas elements and their descriptions
'),this.dummyDOM.querySelector("#".concat(n,"accessibleOutput"))?this.dummyDOM.querySelector("#".concat(n,"accessibleOutput")).insertAdjacentHTML("beforebegin",o):this.dummyDOM.querySelector("#"+n).innerHTML=o),(o=document.createElement("tr")).id=n+"_fte_"+t,this.dummyDOM.querySelector("#"+n+l).appendChild(o),this.descriptions.fallbackElements[t]=this.dummyDOM.querySelector("#".concat(n).concat("_fte_").concat(t)),this.descriptions.fallbackElements[t].innerHTML=r):"label"===e&&(this.dummyDOM.querySelector("#".concat(n+u))?this.dummyDOM.querySelector("#".concat(n+d))||this.dummyDOM.querySelector("#"+n+c).insertAdjacentHTML("afterend",'
')):(o='
'),this.dummyDOM.querySelector("#".concat(n,"accessibleOutputLabel"))?this.dummyDOM.querySelector("#".concat(n,"accessibleOutputLabel")).insertAdjacentHTML("beforebegin",o):this.dummyDOM.querySelector("#"+n).insertAdjacentHTML("afterend",o)),(e=document.createElement("tr")).id=n+"_lte_"+t,this.dummyDOM.querySelector("#"+n+d).appendChild(e),this.descriptions.labelElements[t]=this.dummyDOM.querySelector("#".concat(n).concat("_lte_").concat(t)),this.descriptions.labelElements[t].innerHTML=r)};e=s.default;r.default=e},{"../core/main":267,"core-js/modules/es.array.concat":149,"core-js/modules/es.regexp.exec":181,"core-js/modules/es.string.ends-with":184,"core-js/modules/es.string.replace":189}],248:[function(e,t,r){"use strict";e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.map"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.map"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;e=(e=e("../core/main"))&&e.__esModule?e:{default:e};e.default.prototype._updateGridOutput=function(e){var t,r,o,n;this.dummyDOM.querySelector("#".concat(e,"_summary"))&&(t=this._accessibleOutputs[e],o=function(e,t,r,o){t="".concat(t," canvas, ").concat(r," by ").concat(o," pixels, contains ").concat(e[0]);t=(1===e[0]?"".concat(t," shape: "):"".concat(t," shapes: ")).concat(e[1]);return t}((r=function(e,t){var r,o="",n="",s=0;for(r in t){var i,a=0;for(i in t[r]){var l='
  • ').concat(t[r][i].color," ").concat(r,",");"line"===r?l+=" location = ".concat(t[r][i].pos,", length = ").concat(t[r][i].length," pixels"):(l+=" location = ".concat(t[r][i].pos),"point"!==r&&(l+=", area = ".concat(t[r][i].area," %")),l+="
  • "),o+=l,a++,s++}n=1').concat(t[o][l].color," ").concat(o,"
    "):'').concat(t[o][l].color," ").concat(o," midpoint"),a[t[o][l].loc.locY][t[o][l].loc.locX]?a[t[o][l].loc.locY][t[o][l].loc.locX]=a[t[o][l].loc.locY][t[o][l].loc.locX]+" "+u:a[t[o][l].loc.locY][t[o][l].loc.locX]=u,s++}for(n in a){var c,d="";for(c in a[n])d+="",void 0!==a[n][c]&&(d+=a[n][c]),d+="";i=i+d+""}return i}(e,this.ingredients.shapes),o!==t.summary.innerHTML&&(t.summary.innerHTML=o),n!==t.map.innerHTML&&(t.map.innerHTML=n),r.details!==t.shapeDetails.innerHTML&&(t.shapeDetails.innerHTML=r.details),this._accessibleOutputs[e]=t)};e=e.default;r.default=e},{"../core/main":267,"core-js/modules/es.array.concat":149,"core-js/modules/es.array.map":161}],249:[function(e,t,r){"use strict";e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.fill"),e("core-js/modules/es.array.map"),e("core-js/modules/es.number.to-fixed"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.fill"),e("core-js/modules/es.array.map"),e("core-js/modules/es.number.to-fixed"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var o=(e=e("../core/main"))&&e.__esModule?e:{default:e};function l(e,t,r){return e[0]<.4*t?e[1]<.4*r?"top left":e[1]>.6*r?"bottom left":"mid left":e[0]>.6*t?e[1]<.4*r?"top right":e[1]>.6*r?"bottom right":"mid right":e[1]<.4*r?"top middle":e[1]>.6*r?"bottom middle":"middle"}function u(e,t,r){t=Math.floor(e[0]/t*10),e=Math.floor(e[1]/r*10);return 10===t&&(t-=1),10===e&&(e-=1),{locX:t,locY:e}}o.default.prototype.textOutput=function(e){o.default._validateParameters("textOutput",arguments),this._accessibleOutputs.text||(this._accessibleOutputs.text=!0,this._createOutput("textOutput","Fallback"),e===this.LABEL&&(this._accessibleOutputs.textLabel=!0,this._createOutput("textOutput","Label")))},o.default.prototype.gridOutput=function(e){o.default._validateParameters("gridOutput",arguments),this._accessibleOutputs.grid||(this._accessibleOutputs.grid=!0,this._createOutput("gridOutput","Fallback"),e===this.LABEL&&(this._accessibleOutputs.gridLabel=!0,this._createOutput("gridOutput","Label")))},o.default.prototype._addAccsOutput=function(){return this._accessibleOutputs||(this._accessibleOutputs={text:!1,grid:!1,textLabel:!1,gridLabel:!1}),this._accessibleOutputs.grid||this._accessibleOutputs.text},o.default.prototype._createOutput=function(e,t){var r,o,n,s=this.canvas.id,i=(this.ingredients||(this.ingredients={shapes:{},colors:{background:"white",fill:"white",stroke:"black"},pShapes:""}),this.dummyDOM||(this.dummyDOM=document.getElementById(s).parentNode),"");"Fallback"===t?(r=s+e,this.dummyDOM.querySelector("#".concat(o=s+"accessibleOutput"))||(this.dummyDOM.querySelector("#".concat(s,"_Description"))?this.dummyDOM.querySelector("#".concat(s,"_Description")).insertAdjacentHTML("afterend",'
    ')):this.dummyDOM.querySelector("#".concat(s)).innerHTML='
    '))):"Label"===t&&(r=s+e+(i=t),this.dummyDOM.querySelector("#".concat(o=s+"accessibleOutput"+t))||(this.dummyDOM.querySelector("#".concat(s,"_Label"))?this.dummyDOM.querySelector("#".concat(s,"_Label")):this.dummyDOM.querySelector("#".concat(s))).insertAdjacentHTML("afterend",'
    '))),this._accessibleOutputs[r]={},"textOutput"===e?(i="#".concat(s,"gridOutput").concat(i),n='
    Text Output

      '),this.dummyDOM.querySelector(i)?this.dummyDOM.querySelector(i).insertAdjacentHTML("beforebegin",n):this.dummyDOM.querySelector("#".concat(o)).innerHTML=n,this._accessibleOutputs[r].list=this.dummyDOM.querySelector("#".concat(r,"_list"))):"gridOutput"===e&&(i="#".concat(s,"textOutput").concat(i),n='
      Grid Output

        '),this.dummyDOM.querySelector(i)?this.dummyDOM.querySelector(i).insertAdjacentHTML("afterend",n):this.dummyDOM.querySelector("#".concat(o)).innerHTML=n,this._accessibleOutputs[r].map=this.dummyDOM.querySelector("#".concat(r,"_map"))),this._accessibleOutputs[r].shapeDetails=this.dummyDOM.querySelector("#".concat(r,"_shapeDetails")),this._accessibleOutputs[r].summary=this.dummyDOM.querySelector("#".concat(r,"_summary"))},o.default.prototype._updateAccsOutput=function(){var e=this.canvas.id;JSON.stringify(this.ingredients.shapes)!==this.ingredients.pShapes&&(this.ingredients.pShapes=JSON.stringify(this.ingredients.shapes),this._accessibleOutputs.text&&this._updateTextOutput(e+"textOutput"),this._accessibleOutputs.grid&&this._updateGridOutput(e+"gridOutput"),this._accessibleOutputs.textLabel&&this._updateTextOutput(e+"textOutputLabel"),this._accessibleOutputs.gridLabel&&this._updateGridOutput(e+"gridOutputLabel"))},o.default.prototype._accsBackground=function(e){this.ingredients.pShapes=JSON.stringify(this.ingredients.shapes),this.ingredients.shapes={},this.ingredients.colors.backgroundRGBA!==e&&(this.ingredients.colors.backgroundRGBA=e,this.ingredients.colors.background=this._rgbColorName(e))},o.default.prototype._accsCanvasColors=function(e,t){"fill"===e?this.ingredients.colors.fillRGBA!==t&&(this.ingredients.colors.fillRGBA=t,this.ingredients.colors.fill=this._rgbColorName(t)):"stroke"===e&&this.ingredients.colors.strokeRGBA!==t&&(this.ingredients.colors.strokeRGBA=t,this.ingredients.colors.stroke=this._rgbColorName(t))},o.default.prototype._accsOutput=function(e,t){"ellipse"===e&&t[2]===t[3]?e="circle":"rectangle"===e&&t[2]===t[3]&&(e="square");var r,o,n={},s=!0,i=function(e,t){var r;e="rectangle"===e||"ellipse"===e||"arc"===e||"circle"===e||"square"===e?(r=Math.round(t[0]+t[2]/2),Math.round(t[1]+t[3]/2)):"triangle"===e?(r=(t[0]+t[2]+t[4])/3,(t[1]+t[3]+t[5])/3):"quadrilateral"===e?(r=(t[0]+t[2]+t[4]+t[6])/4,(t[1]+t[3]+t[5]+t[7])/4):"line"===e?(r=(t[0]+t[2])/2,(t[1]+t[3])/2):(r=t[0],t[1]);return[r,e]}(e,t);if("line"===e?(n.color=this.ingredients.colors.stroke,n.length=Math.round(this.dist(t[0],t[1],t[2],t[3])),r=l([t[0],[1]],this.width,this.height),o=l([t[2],[3]],this.width,this.height),n.loc=u(i,this.width,this.height),n.pos=r===o?"at ".concat(r):"from ".concat(r," to ").concat(o)):("point"===e?n.color=this.ingredients.colors.stroke:(n.color=this.ingredients.colors.fill,n.area=function(e,t,r,o){var n=0;{var s,i,a,l,u,c,d;"arc"===e?(s=((t[5]-t[4])%(2*Math.PI)+2*Math.PI)%(2*Math.PI),n=s*t[2]*t[3]/8,"open"!==t[6]&&"chord"!==t[6]||(d=t[0],i=t[1],a=t[0]+t[2]/2*Math.cos(t[4]).toFixed(2),l=t[1]+t[3]/2*Math.sin(t[4]).toFixed(2),u=t[0]+t[2]/2*Math.cos(t[5]).toFixed(2),c=t[1]+t[3]/2*Math.sin(t[5]).toFixed(2),d=Math.abs(d*(l-c)+a*(c-i)+u*(i-l))/2,s>Math.PI?n+=d:n-=d)):"ellipse"===e||"circle"===e?n=3.14*t[2]/2*t[3]/2:"line"===e||"point"===e?n=0:"quadrilateral"===e?n=Math.abs((t[6]+t[0])*(t[7]-t[1])+(t[0]+t[2])*(t[1]-t[3])+(t[2]+t[4])*(t[3]-t[5])+(t[4]+t[6])*(t[5]-t[7]))/2:"rectangle"===e||"square"===e?n=t[2]*t[3]:"triangle"===e&&(n=Math.abs(t[0]*(t[3]-t[5])+t[2]*(t[5]-t[1])+t[4]*(t[1]-t[3]))/2)}return Math.round(100*n/(r*o))}(e,t,this.width,this.height)),n.pos=l(i,this.width,this.height),n.loc=u(i,this.width,this.height)),this.ingredients.shapes[e]){if(this.ingredients.shapes[e]!==[n]){for(var a in this.ingredients.shapes[e])JSON.stringify(this.ingredients.shapes[e][a])===JSON.stringify(n)&&(s=!1);!0===s&&this.ingredients.shapes[e].push(n)}}else this.ingredients.shapes[e]=[n]};e=o.default;r.default=e},{"../core/main":267,"core-js/modules/es.array.concat":149,"core-js/modules/es.array.fill":152,"core-js/modules/es.array.map":161,"core-js/modules/es.number.to-fixed":171}],250:[function(e,t,r){"use strict";e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.concat"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;e=(e=e("../core/main"))&&e.__esModule?e:{default:e};e.default.prototype._updateTextOutput=function(e){var t,r,o,n;this.dummyDOM.querySelector("#".concat(e,"_summary"))&&(t=this._accessibleOutputs[e],o=function(e,t,r,o){r="Your output is a, ".concat(r," by ").concat(o," pixels, ").concat(t," canvas containing the following");r=1===e?"".concat(r," shape:"):"".concat(r," ").concat(e," shapes:");return r}((r=function(e,t){var r,o="",n=0;for(r in t)for(var s in t[r]){var i='
      • ').concat(t[r][s].color," ").concat(r,"");"line"===r?i+=", ".concat(t[r][s].pos,", ").concat(t[r][s].length," pixels long.
      • "):(i+=", at ".concat(t[r][s].pos),"point"!==r&&(i+=", covering ".concat(t[r][s].area,"% of the canvas")),i+="."),o+=i,n++}return{numShapes:n,listShapes:o}}(e,this.ingredients.shapes)).numShapes,this.ingredients.colors.background,this.width,this.height),n=function(e,t){var r,o="",n=0;for(r in t)for(var s in t[r]){var i='').concat(t[r][s].color," ").concat(r,"");"line"===r?i+="location = ".concat(t[r][s].pos,"length = ").concat(t[r][s].length," pixels"):(i+="location = ".concat(t[r][s].pos,""),"point"!==r&&(i+=" area = ".concat(t[r][s].area,"%")),i+=""),o+=i,n++}return o}(e,this.ingredients.shapes),o!==t.summary.innerHTML&&(t.summary.innerHTML=o),r.listShapes!==t.list.innerHTML&&(t.list.innerHTML=r.listShapes),n!==t.shapeDetails.innerHTML&&(t.shapeDetails.innerHTML=n),this._accessibleOutputs[e]=t)};e=e.default;r.default=e},{"../core/main":267,"core-js/modules/es.array.concat":149}],251:[function(e,t,r){"use strict";var o=(o=e("./core/main"))&&o.__esModule?o:{default:o};e("./core/constants"),e("./core/environment"),e("./core/friendly_errors/stacktrace"),e("./core/friendly_errors/validate_params"),e("./core/friendly_errors/file_errors"),e("./core/friendly_errors/fes_core"),e("./core/friendly_errors/sketch_reader"),e("./core/helpers"),e("./core/legacy"),e("./core/preload"),e("./core/p5.Element"),e("./core/p5.Graphics"),e("./core/p5.Renderer"),e("./core/p5.Renderer2D"),e("./core/rendering"),e("./core/shim"),e("./core/structure"),e("./core/transform"),e("./core/shape/2d_primitives"),e("./core/shape/attributes"),e("./core/shape/curves"),e("./core/shape/vertex"),e("./accessibility/outputs"),e("./accessibility/textOutput"),e("./accessibility/gridOutput"),e("./accessibility/color_namer"),e("./color/color_conversion"),e("./color/creating_reading"),e("./color/p5.Color"),e("./color/setting"),e("./data/p5.TypedDict"),e("./data/local_storage.js"),e("./dom/dom"),e("./accessibility/describe"),e("./events/acceleration"),e("./events/keyboard"),e("./events/mouse"),e("./events/touch"),e("./image/filters"),e("./image/image"),e("./image/loading_displaying"),e("./image/p5.Image"),e("./image/pixels"),e("./io/files"),e("./io/p5.Table"),e("./io/p5.TableRow"),e("./io/p5.XML"),e("./math/calculation"),e("./math/math"),e("./math/noise"),e("./math/p5.Vector"),e("./math/random"),e("./math/trigonometry"),e("./typography/attributes"),e("./typography/loading_displaying"),e("./typography/p5.Font"),e("./utilities/array_functions"),e("./utilities/conversion"),e("./utilities/string_functions"),e("./utilities/time_date"),e("./webgl/3d_primitives"),e("./webgl/interaction"),e("./webgl/light"),e("./webgl/loading"),e("./webgl/material"),e("./webgl/p5.Camera"),e("./webgl/p5.Geometry"),e("./webgl/p5.Matrix"),e("./webgl/p5.RendererGL.Immediate"),e("./webgl/p5.RendererGL"),e("./webgl/p5.RendererGL.Retained"),e("./webgl/p5.Shader"),e("./webgl/p5.RenderBuffer"),e("./webgl/p5.Texture"),e("./webgl/text"),e("./core/init"),t.exports=o.default},{"./accessibility/color_namer":246,"./accessibility/describe":247,"./accessibility/gridOutput":248,"./accessibility/outputs":249,"./accessibility/textOutput":250,"./color/color_conversion":252,"./color/creating_reading":253,"./color/p5.Color":254,"./color/setting":255,"./core/constants":256,"./core/environment":257,"./core/friendly_errors/fes_core":258,"./core/friendly_errors/file_errors":259,"./core/friendly_errors/sketch_reader":260,"./core/friendly_errors/stacktrace":261,"./core/friendly_errors/validate_params":262,"./core/helpers":263,"./core/init":264,"./core/legacy":266,"./core/main":267,"./core/p5.Element":268,"./core/p5.Graphics":269,"./core/p5.Renderer":270,"./core/p5.Renderer2D":271,"./core/preload":272,"./core/rendering":273,"./core/shape/2d_primitives":274,"./core/shape/attributes":275,"./core/shape/curves":276,"./core/shape/vertex":277,"./core/shim":278,"./core/structure":279,"./core/transform":280,"./data/local_storage.js":281,"./data/p5.TypedDict":282,"./dom/dom":283,"./events/acceleration":284,"./events/keyboard":285,"./events/mouse":286,"./events/touch":287,"./image/filters":288,"./image/image":289,"./image/loading_displaying":290,"./image/p5.Image":291,"./image/pixels":292,"./io/files":293,"./io/p5.Table":294,"./io/p5.TableRow":295,"./io/p5.XML":296,"./math/calculation":297,"./math/math":298,"./math/noise":299,"./math/p5.Vector":300,"./math/random":301,"./math/trigonometry":302,"./typography/attributes":303,"./typography/loading_displaying":304,"./typography/p5.Font":305,"./utilities/array_functions":306,"./utilities/conversion":307,"./utilities/string_functions":308,"./utilities/time_date":309,"./webgl/3d_primitives":310,"./webgl/interaction":311,"./webgl/light":312,"./webgl/loading":313,"./webgl/material":314,"./webgl/p5.Camera":315,"./webgl/p5.Geometry":316,"./webgl/p5.Matrix":317,"./webgl/p5.RenderBuffer":318,"./webgl/p5.RendererGL":321,"./webgl/p5.RendererGL.Immediate":319,"./webgl/p5.RendererGL.Retained":320,"./webgl/p5.Shader":322,"./webgl/p5.Texture":323,"./webgl/text":324}],252:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;e=(e=e("../core/main"))&&e.__esModule?e:{default:e};e.default.ColorConversion={},e.default.ColorConversion._hsbaToHSLA=function(e){var t=e[0],r=e[1],o=e[2],n=(2-r)*o/2;return 0!=n&&(1==n?r=0:n<.5?r/=2-r:r=r*o/(2-2*n)),[t,r,n,e[3]]},e.default.ColorConversion._hsbaToRGBA=function(e){var t,r,o,n,s,i=6*e[0],a=e[1],l=e[2];return 0===a?[l,l,l,e[3]]:(r=l*(1-a),o=l*(1-a*(i-(t=Math.floor(i)))),a=l*(1-a*(1+t-i)),i=1===t?(n=o,s=l,r):2===t?(n=r,s=l,a):3===t?(n=r,s=o,l):4===t?(n=a,s=r,l):5===t?(n=l,s=r,o):(n=l,s=a,r),[n,s,i,e[3]])},e.default.ColorConversion._hslaToHSBA=function(e){var t=e[0],r=e[1],o=e[2],n=o<.5?(1+r)*o:o+r-o*r;return[t,r=2*(n-o)/n,n,e[3]]},e.default.ColorConversion._hslaToRGBA=function(e){var t,r=6*e[0],o=e[1],n=e[2];return 0===o?[n,n,n,e[3]]:[(t=function(e,t,r){return e<0?e+=6:6<=e&&(e-=6),e<1?t+(r-t)*e:e<3?r:e<4?t+(r-t)*(4-e):t})(2+r,o=2*n-(n=n<.5?(1+o)*n:n+o-n*o),n),t(r,o,n),t(r-2,o,n),e[3]]},e.default.ColorConversion._rgbaToHSBA=function(e){var t,r,o=e[0],n=e[1],s=e[2],i=Math.max(o,n,s),a=i-Math.min(o,n,s);return 0==a?r=t=0:(r=a/i,o===i?t=(n-s)/a:n===i?t=2+(s-o)/a:s===i&&(t=4+(o-n)/a),t<0?t+=6:6<=t&&(t-=6)),[t/6,r,i,e[3]]},e.default.ColorConversion._rgbaToHSLA=function(e){var t,r,o=e[0],n=e[1],s=e[2],i=Math.max(o,n,s),a=Math.min(o,n,s),l=i+a,a=i-a;return 0==a?r=t=0:(r=l<1?a/l:a/(2-l),o===i?t=(n-s)/a:n===i?t=2+(s-o)/a:s===i&&(t=4+(o-n)/a),t<0?t+=6:6<=t&&(t-=6)),[t/6,r,l/2,e[3]]};e=e.default.ColorConversion;r.default=e},{"../core/main":267}],253:[function(e,t,r){"use strict";function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e){return(i="function"==typeof Symbol&&"symbol"===o(Symbol.iterator)?function(e){return o(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":o(e)})(e)}e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.map"),e("core-js/modules/es.object.get-own-property-descriptor"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.weak-map"),e("core-js/modules/web.dom-collections.iterator"),e("core-js/modules/es.array.map"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var l=(n=e("../core/main"))&&n.__esModule?n:{default:n},u=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==i(e)&&"function"!=typeof e)return{default:e};var t=a();if(t&&t.has(e))return t.get(e);var r,o={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(r in e){var s;Object.prototype.hasOwnProperty.call(e,r)&&((s=n?Object.getOwnPropertyDescriptor(e,r):null)&&(s.get||s.set)?Object.defineProperty(o,r,s):o[r]=e[r])}o.default=e,t&&t.set(e,o);return o}(e("../core/constants"));function a(){var e;return"function"!=typeof WeakMap?null:(e=new WeakMap,a=function(){return e},e)}e("./p5.Color"),e("../core/friendly_errors/validate_params"),e("../core/friendly_errors/file_errors"),e("../core/friendly_errors/fes_core"),l.default.prototype.alpha=function(e){return l.default._validateParameters("alpha",arguments),this.color(e)._getAlpha()},l.default.prototype.blue=function(e){return l.default._validateParameters("blue",arguments),this.color(e)._getBlue()},l.default.prototype.brightness=function(e){return l.default._validateParameters("brightness",arguments),this.color(e)._getBrightness()},l.default.prototype.color=function(){var e;return l.default._validateParameters("color",arguments),arguments[0]instanceof l.default.Color?arguments[0]:(e=arguments[0]instanceof Array?arguments[0]:arguments,new l.default.Color(this,e))},l.default.prototype.green=function(e){return l.default._validateParameters("green",arguments),this.color(e)._getGreen()},l.default.prototype.hue=function(e){return l.default._validateParameters("hue",arguments),this.color(e)._getHue()},l.default.prototype.lerpColor=function(e,t,r){l.default._validateParameters("lerpColor",arguments);var o,n,s,i=this._colorMode,a=this._colorMaxes;if(i===u.RGB)n=e.levels.map(function(e){return e/255}),s=t.levels.map(function(e){return e/255});else if(i===u.HSB)e._getBrightness(),t._getBrightness(),n=e.hsba,s=t.hsba;else{if(i!==u.HSL)throw new Error("".concat(i,"cannot be used for interpolation."));e._getLightness(),t._getLightness(),n=e.hsla,s=t.hsla}return r=Math.max(Math.min(r,1),0),void 0===this.lerp&&(this.lerp=function(e,t,r){return r*(t-e)+e}),e=this.lerp(n[0],s[0],r),t=this.lerp(n[1],s[1],r),o=this.lerp(n[2],s[2],r),n=this.lerp(n[3],s[3],r),e*=a[i][0],t*=a[i][1],o*=a[i][2],n*=a[i][3],this.color(e,t,o,n)},l.default.prototype.lightness=function(e){return l.default._validateParameters("lightness",arguments),this.color(e)._getLightness()},l.default.prototype.red=function(e){return l.default._validateParameters("red",arguments),this.color(e)._getRed()},l.default.prototype.saturation=function(e){return l.default._validateParameters("saturation",arguments),this.color(e)._getSaturation()};var n=l.default;r.default=n},{"../core/constants":256,"../core/friendly_errors/fes_core":258,"../core/friendly_errors/file_errors":259,"../core/friendly_errors/validate_params":262,"../core/main":267,"./p5.Color":254,"core-js/modules/es.array.iterator":158,"core-js/modules/es.array.map":161,"core-js/modules/es.object.get-own-property-descriptor":173,"core-js/modules/es.object.to-string":177,"core-js/modules/es.string.iterator":186,"core-js/modules/es.symbol":196,"core-js/modules/es.symbol.description":194,"core-js/modules/es.symbol.iterator":195,"core-js/modules/es.weak-map":228,"core-js/modules/web.dom-collections.iterator":230}],254:[function(e,t,r){"use strict";function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e){return(i="function"==typeof Symbol&&"symbol"===o(Symbol.iterator)?function(e){return o(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":o(e)})(e)}e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.map"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.object.get-own-property-descriptor"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.regexp.constructor"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.string.trim"),e("core-js/modules/es.weak-map"),e("core-js/modules/web.dom-collections.iterator"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.map"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.regexp.constructor"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.string.trim"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var c=n(e("../core/main")),d=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==i(e)&&"function"!=typeof e)return{default:e};var t=a();if(t&&t.has(e))return t.get(e);var r,o={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(r in e){var s;Object.prototype.hasOwnProperty.call(e,r)&&((s=n?Object.getOwnPropertyDescriptor(e,r):null)&&(s.get||s.set)?Object.defineProperty(o,r,s):o[r]=e[r])}o.default=e,t&&t.set(e,o);return o}(e("../core/constants")),f=n(e("./color_conversion"));function a(){var e;return"function"!=typeof WeakMap?null:(e=new WeakMap,a=function(){return e},e)}function n(e){return e&&e.__esModule?e:{default:e}}c.default.Color=function(e,t){if(this._storeModeAndMaxes(e._colorMode,e._colorMaxes),this.mode!==d.RGB&&this.mode!==d.HSL&&this.mode!==d.HSB)throw new Error("".concat(this.mode," is an invalid colorMode."));return this._array=c.default.Color._parseInputs.apply(this,t),this._calculateLevels(),this},c.default.Color.prototype.toString=function(e){var t=this.levels,r=this._array,o=r[3];switch(e){case"#rrggbb":return"#".concat(t[0]<16?"0".concat(t[0].toString(16)):t[0].toString(16),t[1]<16?"0".concat(t[1].toString(16)):t[1].toString(16),t[2]<16?"0".concat(t[2].toString(16)):t[2].toString(16));case"#rrggbbaa":return"#".concat(t[0]<16?"0".concat(t[0].toString(16)):t[0].toString(16),t[1]<16?"0".concat(t[1].toString(16)):t[1].toString(16),t[2]<16?"0".concat(t[2].toString(16)):t[2].toString(16),t[3]<16?"0".concat(t[3].toString(16)):t[3].toString(16));case"#rgb":return"#".concat(Math.round(15*r[0]).toString(16),Math.round(15*r[1]).toString(16),Math.round(15*r[2]).toString(16));case"#rgba":return"#".concat(Math.round(15*r[0]).toString(16),Math.round(15*r[1]).toString(16),Math.round(15*r[2]).toString(16),Math.round(15*r[3]).toString(16));case"rgb":return"rgb(".concat(t[0],", ",t[1],", ",t[2],")");case"rgb%":return"rgb(".concat((100*r[0]).toPrecision(3),"%, ",(100*r[1]).toPrecision(3),"%, ",(100*r[2]).toPrecision(3),"%)");case"rgba%":return"rgba(".concat((100*r[0]).toPrecision(3),"%, ",(100*r[1]).toPrecision(3),"%, ",(100*r[2]).toPrecision(3),"%, ",(100*r[3]).toPrecision(3),"%)");case"hsb":case"hsv":return this.hsba||(this.hsba=f.default._rgbaToHSBA(this._array)),"hsb(".concat(this.hsba[0]*this.maxes[d.HSB][0],", ",this.hsba[1]*this.maxes[d.HSB][1],", ",this.hsba[2]*this.maxes[d.HSB][2],")");case"hsb%":case"hsv%":return this.hsba||(this.hsba=f.default._rgbaToHSBA(this._array)),"hsb(".concat((100*this.hsba[0]).toPrecision(3),"%, ",(100*this.hsba[1]).toPrecision(3),"%, ",(100*this.hsba[2]).toPrecision(3),"%)");case"hsba":case"hsva":return this.hsba||(this.hsba=f.default._rgbaToHSBA(this._array)),"hsba(".concat(this.hsba[0]*this.maxes[d.HSB][0],", ",this.hsba[1]*this.maxes[d.HSB][1],", ",this.hsba[2]*this.maxes[d.HSB][2],", ",o,")");case"hsba%":case"hsva%":return this.hsba||(this.hsba=f.default._rgbaToHSBA(this._array)),"hsba(".concat((100*this.hsba[0]).toPrecision(3),"%, ",(100*this.hsba[1]).toPrecision(3),"%, ",(100*this.hsba[2]).toPrecision(3),"%, ",(100*o).toPrecision(3),"%)");case"hsl":return this.hsla||(this.hsla=f.default._rgbaToHSLA(this._array)),"hsl(".concat(this.hsla[0]*this.maxes[d.HSL][0],", ",this.hsla[1]*this.maxes[d.HSL][1],", ",this.hsla[2]*this.maxes[d.HSL][2],")");case"hsl%":return this.hsla||(this.hsla=f.default._rgbaToHSLA(this._array)),"hsl(".concat((100*this.hsla[0]).toPrecision(3),"%, ",(100*this.hsla[1]).toPrecision(3),"%, ",(100*this.hsla[2]).toPrecision(3),"%)");case"hsla":return this.hsla||(this.hsla=f.default._rgbaToHSLA(this._array)),"hsla(".concat(this.hsla[0]*this.maxes[d.HSL][0],", ",this.hsla[1]*this.maxes[d.HSL][1],", ",this.hsla[2]*this.maxes[d.HSL][2],", ",o,")");case"hsla%":return this.hsla||(this.hsla=f.default._rgbaToHSLA(this._array)),"hsl(".concat((100*this.hsla[0]).toPrecision(3),"%, ",(100*this.hsla[1]).toPrecision(3),"%, ",(100*this.hsla[2]).toPrecision(3),"%, ",(100*o).toPrecision(3),"%)");default:return"rgba(".concat(t[0],",",t[1],",",t[2],",",o,")")}},c.default.Color.prototype.setRed=function(e){this._array[0]=e/this.maxes[d.RGB][0],this._calculateLevels()},c.default.Color.prototype.setGreen=function(e){this._array[1]=e/this.maxes[d.RGB][1],this._calculateLevels()},c.default.Color.prototype.setBlue=function(e){this._array[2]=e/this.maxes[d.RGB][2],this._calculateLevels()},c.default.Color.prototype.setAlpha=function(e){this._array[3]=e/this.maxes[this.mode][3],this._calculateLevels()},c.default.Color.prototype._calculateLevels=function(){for(var e=this._array,t=this.levels=new Array(e.length),r=e.length-1;0<=r;--r)t[r]=Math.round(255*e[r]);this.hsla=null,this.hsba=null},c.default.Color.prototype._getAlpha=function(){return this._array[3]*this.maxes[this.mode][3]},c.default.Color.prototype._storeModeAndMaxes=function(e,t){this.mode=e,this.maxes=t},c.default.Color.prototype._getMode=function(){return this.mode},c.default.Color.prototype._getMaxes=function(){return this.maxes},c.default.Color.prototype._getBlue=function(){return this._array[2]*this.maxes[d.RGB][2]},c.default.Color.prototype._getBrightness=function(){return this.hsba||(this.hsba=f.default._rgbaToHSBA(this._array)),this.hsba[2]*this.maxes[d.HSB][2]},c.default.Color.prototype._getGreen=function(){return this._array[1]*this.maxes[d.RGB][1]},c.default.Color.prototype._getHue=function(){return this.mode===d.HSB?(this.hsba||(this.hsba=f.default._rgbaToHSBA(this._array)),this.hsba[0]*this.maxes[d.HSB][0]):(this.hsla||(this.hsla=f.default._rgbaToHSLA(this._array)),this.hsla[0]*this.maxes[d.HSL][0])},c.default.Color.prototype._getLightness=function(){return this.hsla||(this.hsla=f.default._rgbaToHSLA(this._array)),this.hsla[2]*this.maxes[d.HSL][2]},c.default.Color.prototype._getRed=function(){return this._array[0]*this.maxes[d.RGB][0]},c.default.Color.prototype._getSaturation=function(){return this.mode===d.HSB?(this.hsba||(this.hsba=f.default._rgbaToHSBA(this._array)),this.hsba[1]*this.maxes[d.HSB][1]):(this.hsla||(this.hsla=f.default._rgbaToHSLA(this._array)),this.hsla[1]*this.maxes[d.HSL][1])};var h={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},e=/\s*/,s=/(\d{1,3})/,l=/((?:\d+(?:\.\d+)?)|(?:\.\d+))/,u=new RegExp("".concat(l.source,"%")),p={HEX3:/^#([a-f0-9])([a-f0-9])([a-f0-9])$/i,HEX4:/^#([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])$/i,HEX6:/^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i,HEX8:/^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i,RGB:new RegExp(["^rgb\\(",s.source,",",s.source,",",s.source,"\\)$"].join(e.source),"i"),RGB_PERCENT:new RegExp(["^rgb\\(",u.source,",",u.source,",",u.source,"\\)$"].join(e.source),"i"),RGBA:new RegExp(["^rgba\\(",s.source,",",s.source,",",s.source,",",l.source,"\\)$"].join(e.source),"i"),RGBA_PERCENT:new RegExp(["^rgba\\(",u.source,",",u.source,",",u.source,",",l.source,"\\)$"].join(e.source),"i"),HSL:new RegExp(["^hsl\\(",s.source,",",u.source,",",u.source,"\\)$"].join(e.source),"i"),HSLA:new RegExp(["^hsla\\(",s.source,",",u.source,",",u.source,",",l.source,"\\)$"].join(e.source),"i"),HSB:new RegExp(["^hsb\\(",s.source,",",u.source,",",u.source,"\\)$"].join(e.source),"i"),HSBA:new RegExp(["^hsba\\(",s.source,",",u.source,",",u.source,",",l.source,"\\)$"].join(e.source),"i")},s=(c.default.Color._parseInputs=function(e,t,r,o){var n,s=arguments.length,i=this.mode,a=this.maxes[i],l=[];if(3<=s){for(l[0]=e/a[0],l[1]=t/a[1],l[2]=r/a[2],l[3]="number"==typeof o?o/a[3]:1,n=l.length-1;0<=n;--n){var u=l[n];u<0?l[n]=0:1"].indexOf(r[0])?void 0:r[0],lineNumber:r[1],columnNumber:r[2],source:e}},this)},parseFFOrSafari:function(e){return e.stack.split("\n").filter(function(e){return!e.match(o)},this).map(function(e){var t,r;return-1===(e=-1 eval")?e.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1"):e).indexOf("@")&&-1===e.indexOf(":")?{functionName:e}:{functionName:(r=e.match(t=/((.*".+"[^@]*)?[^@]*)(?:@)/))&&r[1]?r[1]:void 0,fileName:(r=this.extractLocation(e.replace(t,"")))[0],lineNumber:r[1],columnNumber:r[2],source:e}},this)},parseOpera:function(e){return!e.stacktrace||-1e.stacktrace.split("\n").length?this.parseOpera9(e):e.stack?this.parseOpera11(e):this.parseOpera10(e)},parseOpera9:function(e){for(var t=/Line (\d+).*script (?:in )?(\S+)/i,r=e.message.split("\n"),o=[],n=2,s=r.length;n/,"$2").replace(/\([^)]*\)/g,"")||void 0,args:void 0===(t=r.match(/\(([^)]*)\)/)?r.replace(/^[^(]+\(([^)]*)\)$/,"$1"):t)||"[arguments not available]"===t?void 0:t.split(","),fileName:o[0],lineNumber:o[1],columnNumber:o[2],source:e}},this)}}}e.default._getErrorStackParser=function(){return new o};e=e.default;r.default=e},{"../main":267,"core-js/modules/es.array.filter":153,"core-js/modules/es.array.index-of":157,"core-js/modules/es.array.join":159,"core-js/modules/es.array.map":161,"core-js/modules/es.array.slice":162,"core-js/modules/es.regexp.exec":181,"core-js/modules/es.string.match":187,"core-js/modules/es.string.replace":189,"core-js/modules/es.string.split":191}],262:[function(e,t,r){"use strict";function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.for-each"),e("core-js/modules/es.array.includes"),e("core-js/modules/es.array.index-of"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.last-index-of"),e("core-js/modules/es.array.map"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.function.name"),e("core-js/modules/es.map"),e("core-js/modules/es.number.constructor"),e("core-js/modules/es.object.get-own-property-descriptor"),e("core-js/modules/es.object.get-prototype-of"),e("core-js/modules/es.object.keys"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.reflect.construct"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.set"),e("core-js/modules/es.string.includes"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.string.split"),e("core-js/modules/es.weak-map"),e("core-js/modules/web.dom-collections.for-each"),e("core-js/modules/web.dom-collections.iterator"),e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.for-each"),e("core-js/modules/es.array.includes"),e("core-js/modules/es.array.index-of"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.last-index-of"),e("core-js/modules/es.array.map"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.function.name"),e("core-js/modules/es.map"),e("core-js/modules/es.number.constructor"),e("core-js/modules/es.object.get-prototype-of"),e("core-js/modules/es.object.keys"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.reflect.construct"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.set"),e("core-js/modules/es.string.includes"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.string.split"),e("core-js/modules/web.dom-collections.for-each"),e("core-js/modules/web.dom-collections.iterator"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n=(n=e("../main"))&&n.__esModule?n:{default:n};(function(e){if(e&&e.__esModule)return;if(null===e||"object"!==a(e)&&"function"!=typeof e)return;var t=i();if(t&&t.has(e))return t.get(e);var r,o={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(r in e){var s;Object.prototype.hasOwnProperty.call(e,r)&&((s=n?Object.getOwnPropertyDescriptor(e,r):null)&&(s.get||s.set)?Object.defineProperty(o,r,s):o[r]=e[r])}o.default=e,t&&t.set(e,o)})(e("../constants")),e("../internationalization");function i(){var e;return"function"!=typeof WeakMap?null:(e=new WeakMap,i=function(){return e},e)}function a(e){return(a="function"==typeof Symbol&&"symbol"===o(Symbol.iterator)?function(e){return o(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":o(e)})(e)}n.default._validateParameters=n.default._clearValidateParamsCache=function(){};e=n.default;r.default=e},{"../../../docs/parameterData.json":void 0,"../constants":256,"../internationalization":265,"../main":267,"core-js/modules/es.array.concat":149,"core-js/modules/es.array.for-each":154,"core-js/modules/es.array.includes":156,"core-js/modules/es.array.index-of":157,"core-js/modules/es.array.iterator":158,"core-js/modules/es.array.join":159,"core-js/modules/es.array.last-index-of":160,"core-js/modules/es.array.map":161,"core-js/modules/es.array.slice":162,"core-js/modules/es.function.name":165,"core-js/modules/es.map":166,"core-js/modules/es.number.constructor":169,"core-js/modules/es.object.get-own-property-descriptor":173,"core-js/modules/es.object.get-prototype-of":175,"core-js/modules/es.object.keys":176,"core-js/modules/es.object.to-string":177,"core-js/modules/es.reflect.construct":179,"core-js/modules/es.regexp.exec":181,"core-js/modules/es.regexp.to-string":182,"core-js/modules/es.set":183,"core-js/modules/es.string.includes":185,"core-js/modules/es.string.iterator":186,"core-js/modules/es.string.split":191,"core-js/modules/es.symbol":196,"core-js/modules/es.symbol.description":194,"core-js/modules/es.symbol.iterator":195,"core-js/modules/es.weak-map":228,"core-js/modules/web.dom-collections.for-each":229,"core-js/modules/web.dom-collections.iterator":230}],263:[function(e,t,r){"use strict";function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e){return(i="function"==typeof Symbol&&"symbol"===o(Symbol.iterator)?function(e){return o(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":o(e)})(e)}e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.object.get-own-property-descriptor"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.weak-map"),e("core-js/modules/web.dom-collections.iterator"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var s=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==i(e)&&"function"!=typeof e)return{default:e};var t=a();if(t&&t.has(e))return t.get(e);var r,o={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(r in e){var s;Object.prototype.hasOwnProperty.call(e,r)&&((s=n?Object.getOwnPropertyDescriptor(e,r):null)&&(s.get||s.set)?Object.defineProperty(o,r,s):o[r]=e[r])}o.default=e,t&&t.set(e,o);return o}(e("./constants"));function a(){var e;return"function"!=typeof WeakMap?null:(e=new WeakMap,a=function(){return e},e)}r.default={modeAdjust:function(e,t,r,o,n){return n===s.CORNER?{x:e,y:t,w:r,h:o}:n===s.CORNERS?{x:e,y:t,w:r-e,h:o-t}:n===s.RADIUS?{x:e-r,y:t-o,w:2*r,h:2*o}:n===s.CENTER?{x:e-.5*r,y:t-.5*o,w:r,h:o}:void 0}}},{"./constants":256,"core-js/modules/es.array.iterator":158,"core-js/modules/es.object.get-own-property-descriptor":173,"core-js/modules/es.object.to-string":177,"core-js/modules/es.string.iterator":186,"core-js/modules/es.symbol":196,"core-js/modules/es.symbol.description":194,"core-js/modules/es.symbol.iterator":195,"core-js/modules/es.weak-map":228,"core-js/modules/web.dom-collections.iterator":230}],264:[function(e,t,r){"use strict";e("core-js/modules/es.array.iterator"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.promise"),e("core-js/modules/es.string.iterator"),e("core-js/modules/web.dom-collections.iterator"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.promise"),e("core-js/modules/es.string.iterator"),e("core-js/modules/web.dom-collections.iterator");var o=(n=e("../core/main"))&&n.__esModule?n:{default:n};e("./internationalization");var n=Promise.resolve();Promise.all([new Promise(function(e,t){"complete"===document.readyState?e():window.addEventListener("load",e,!1)}),n]).then(function(){void 0!==window._setupDone?console.warn("p5.js seems to have been imported multiple times. Please remove the duplicate import"):window.mocha||(window.setup&&"function"==typeof window.setup||window.draw&&"function"==typeof window.draw)&&!o.default.instance&&new o.default})},{"../core/main":267,"./internationalization":265,"core-js/modules/es.array.iterator":158,"core-js/modules/es.object.to-string":177,"core-js/modules/es.promise":178,"core-js/modules/es.string.iterator":186,"core-js/modules/web.dom-collections.iterator":230}],265:[function(e,t,r){"use strict";e("core-js/modules/es.array.includes"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.object.keys"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.promise"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.string.includes"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.string.split"),e("core-js/modules/web.dom-collections.iterator"),e("core-js/modules/es.array.includes"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.object.keys"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.promise"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.string.includes"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.string.split"),e("core-js/modules/web.dom-collections.iterator"),Object.defineProperty(r,"__esModule",{value:!0}),r.setTranslatorLanguage=r.currentTranslatorLanguage=r.availableTranslatorLanguages=r.initialize=r.translator=void 0;var n,s,o=a(e("i18next")),i=a(e("i18next-browser-languagedetector"));function a(e){return e&&e.__esModule?e:{default:e}}function l(e,t){for(var r=0;r=i.width||t>=i.height?[0,0,0,0]:this._getPixel(e,t);n=new a.default.Image(r,o);return n.canvas.getContext("2d").drawImage(i,e,t,r*s,o*s,0,0,r,o),n},a.default.Renderer.prototype.textLeading=function(e){return"number"==typeof e?(this._setProperty("_leadingSet",!0),this._setProperty("_textLeading",e),this._pInst):this._textLeading},a.default.Renderer.prototype.textSize=function(e){return"number"==typeof e?(this._setProperty("_textSize",e),this._leadingSet||this._setProperty("_textLeading",e*L._DEFAULT_LEADMULT),this._applyTextProperties()):this._textSize},a.default.Renderer.prototype.textStyle=function(e){return e?(e!==L.NORMAL&&e!==L.ITALIC&&e!==L.BOLD&&e!==L.BOLDITALIC||this._setProperty("_textStyle",e),this._applyTextProperties()):this._textStyle},a.default.Renderer.prototype.textAscent=function(){return null===this._textAscent&&this._updateTextMetrics(),this._textAscent},a.default.Renderer.prototype.textDescent=function(){return null===this._textDescent&&this._updateTextMetrics(),this._textDescent},a.default.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}},a.default.Renderer.prototype.textWrap=function(e){return this._setProperty("_textWrap",e),this._textWrap},a.default.Renderer.prototype.text=function(e,t,r,o,n){var s,i,a,l,u=this._pInst,c=this._textWrap,d=Number.MAX_VALUE,f=r;if((this._doFill||this._doStroke)&&void 0!==e){if(s=(e=(e="string"!=typeof e?e.toString():e).replace(/(\t)/g," ")).split("\n"),void 0!==o){switch(this._rectMode===L.CENTER&&(t-=o/2),this._textAlign){case L.CENTER:t+=o/2;break;case L.RIGHT:t+=o}if(void 0!==n){this._rectMode===L.CENTER&&(r-=n/2,f-=n/2);var e=r,h=u.textAscent();switch(this._textBaseline){case L.BOTTOM:l=r+n,r=Math.max(l,r),f+=h;break;case L.CENTER:l=r+n/2,r=Math.max(l,r),f+=h/2}d=r+n-h,this._textBaseline===L.CENTER&&(d=e+n-h/2)}else{if(this._textBaseline===L.BOTTOM)return console.warn("textAlign(*, BOTTOM) requires x, y, width and height");if(this._textBaseline===L.CENTER)return console.warn("textAlign(*, CENTER) requires x, y, width and height")}if(c===L.WORD){for(var p=[],m=0;ma.HALF_PI&&e<=3*a.HALF_PI?Math.atan(r/o*Math.tan(e))+a.PI:Math.atan(r/o*Math.tan(e))+a.TWO_PI,t=t<=a.HALF_PI?Math.atan(r/o*Math.tan(t)):t>a.HALF_PI&&t<=3*a.HALF_PI?Math.atan(r/o*Math.tan(t))+a.PI:Math.atan(r/o*Math.tan(t))+a.TWO_PI),tp||Math.abs(this.accelerationY-this.pAccelerationY)>p||Math.abs(this.accelerationZ-this.pAccelerationZ)>p)&&s.deviceMoved(),"function"==typeof s.deviceTurned&&(t=this.rotationX+180,e=this.pRotationX+180,r=l+180,0>>24],r+=R[(16711680&I)>>16],o+=R[(65280&I)>>8],n+=R[255&I],t+=B[b],i++}j[a=S+g]=s/t,_[a]=r/t,x[a]=o/t,w[a]=n/t}S+=f}for(u=(l=-N)*f,v=S=0;v>>16,e[1+r]=(65280&t[o])>>>8,e[2+r]=255&t[o],e[3+r]=(4278190080&t[o])>>>24},V._toImageData=function(e){return e instanceof ImageData?e:e.getContext("2d").getImageData(0,0,e.width,e.height)},V._createImageData=function(e,t){return V._tmpCanvas=document.createElement("canvas"),V._tmpCtx=V._tmpCanvas.getContext("2d"),this._tmpCtx.createImageData(e,t)},V.apply=function(e,t,r){var o=e.getContext("2d"),n=o.getImageData(0,0,e.width,e.height),t=t(n,r);t instanceof ImageData?o.putImageData(t,0,0,0,0,e.width,e.height):o.putImageData(n,0,0,0,0,e.width,e.height)},V.threshold=function(e,t){for(var r=V._toPixels(e),o=(void 0===t&&(t=.5),Math.floor(255*t)),n=0;n>8)/o,r[n+1]=255*(i*t>>8)/o,r[n+2]=255*(a*t>>8)/o}},V.dilate=function(e){for(var t,r,o,n,s,i,a,l,u,c=V._toPixels(e),d=0,f=c.length?c.length/4:0,h=new Int32Array(f);d>16&255)+151*(n>>8&255)+28*(255&n))<(a=77*(u>>16&255)+151*(u>>8&255)+28*(255&u))&&(o=u,n=a),n<(a=77*((u=V._getARGB(c,l))>>16&255)+151*(u>>8&255)+28*(255&u))&&(o=u,n=a),n<(l=77*(s>>16&255)+151*(s>>8&255)+28*(255&s))&&(o=s,n=l),n<(u=77*(i>>16&255)+151*(i>>8&255)+28*(255&i))&&(o=i,n=u),h[d++]=o;V._setPixels(c,h)},V.erode=function(e){for(var t,r,o,n,s,i,a,l,u,c=V._toPixels(e),d=0,f=c.length?c.length/4:0,h=new Int32Array(f);d>16&255)+151*(u>>8&255)+28*(255&u))<(n=77*(n>>16&255)+151*(n>>8&255)+28*(255&n))&&(o=u,n=a),(a=77*((u=V._getARGB(c,l))>>16&255)+151*(u>>8&255)+28*(255&u))>16&255)+151*(s>>8&255)+28*(255&s))>16&255)+151*(i>>8&255)+28*(255&i))"+d.length.toString()+" out of "+a.toString()),e.next=45,new Promise(function(e){return setTimeout(e,0)});e.next=47;break;case 45:e.next=36;break;case 47:f.html("Frames processed, generating color palette..."),this.loop(),this.pixelDensity(c),m=(0,C.GIFEncoder)(),y=function(e){for(var t=new Uint8Array(e.length*e[0].length),r=0;r"+_.toString()+" out of "+a.toString()),e.next=65,new Promise(function(e){return setTimeout(e,0)});case 65:_++,e.next=57;break;case 68:m.finish(),M=m.bytesView(),M=new Blob([M],{type:"image/gif"}),d=[],this._recording=!1,this.loop(),f.html("Done. Downloading your gif!🌸"),T.default.prototype.downloadFile(M,t,"gif");case 77:case"end":return e.stop()}},e,this)});var a,r=function(){var e=this,i=arguments;return new Promise(function(t,r){var o=a.apply(e,i);function n(e){l(o,t,r,n,s,"next",e)}function s(e){l(o,t,r,n,s,"throw",e)}n(void 0)})};return function(e,t){return r.apply(this,arguments)}}(),T.default.prototype.image=function(e,t,r,o,n,s,i,a,l,u,c,d){T.default._validateParameters("image",arguments);var f=e.width,h=e.height,p=(d=d||j.CENTER,c=c||j.CENTER,e.elt&&e.elt.videoWidth&&!e.canvas&&(f=e.elt.videoWidth,h=e.elt.videoHeight),o||f),n=n||h,s=s||0,i=i||0,a=v(a||f,f),f=v(l||h,h),l=1;e.elt&&!e.canvas&&e.elt.style.width&&(l=e.elt.videoWidth&&!o?e.elt.videoWidth:e.elt.width,l/=parseInt(e.elt.style.width,10)),s*=l,i*=l,f*=l,a*=l;h=y(u,c,d,(h=m.default.modeAdjust(t,r,p,n,this._renderer._imageMode)).x,h.y,h.w,h.h,s,i,a,f);this._renderer.image(e,h.sx,h.sy,h.sw,h.sh,h.dx,h.dy,h.dw,h.dh)},T.default.prototype.tint=function(){for(var e=arguments.length,t=new Array(e),r=0;r=t&&(t=Math.floor(r.timeDisplayed/t),r.timeDisplayed=0,r.lastChangeTime=e,r.displayIndex+=t,r.loopCount=Math.floor(r.displayIndex/r.numFrames),null!==r.loopLimit&&r.loopCount>=r.loopLimit?r.playing=!1:(e=r.displayIndex%r.numFrames,this.drawingContext.putImageData(r.frames[e].image,0,0),r.displayIndex=e,this.setModified(!0))))},s.default.Image.prototype._setProperty=function(e,t){this[e]=t,this.setModified(!0)},s.default.Image.prototype.loadPixels=function(){s.default.Renderer2D.prototype.loadPixels.call(this),this.setModified(!0)},s.default.Image.prototype.updatePixels=function(e,t,r,o){s.default.Renderer2D.prototype.updatePixels.call(this,e,t,r,o),this.setModified(!0)},s.default.Image.prototype.get=function(e,t,r,o){return s.default._validateParameters("p5.Image.get",arguments),s.default.Renderer2D.prototype.get.apply(this,arguments)},s.default.Image.prototype._getPixel=s.default.Renderer2D.prototype._getPixel,s.default.Image.prototype.set=function(e,t,r){s.default.Renderer2D.prototype.set.call(this,e,t,r),this.setModified(!0)},s.default.Image.prototype.resize=function(e,t){0===e&&0===t?(e=this.canvas.width,t=this.canvas.height):0===e?e=this.canvas.width*t/this.canvas.height:0===t&&(t=this.canvas.height*e/this.canvas.width),e=Math.floor(e),t=Math.floor(t);var r=document.createElement("canvas");if(r.width=e,r.height=t,this.gifProperties)for(var o=this.gifProperties,n=0;n/g,">").replace(/"/g,""").replace(/'/g,"'")}function i(e,t){t&&!0!==t&&"true"!==t||(t="");var r="";return(e=e||"untitled")&&e.includes(".")&&(r=e.split(".").pop()),t&&r!==t&&(r=t,e="".concat(e,".").concat(r)),[e,r]}e("../core/friendly_errors/validate_params"),e("../core/friendly_errors/file_errors"),e("../core/friendly_errors/fes_core"),v.default.prototype.loadJSON=function(){for(var e=arguments.length,t=new Array(e),r=0;r"),n.print("");if(n.print(' '),n.print(""),n.print(""),n.print(" "),"0"!==s[0]){n.print(" ");for(var c=0;c".concat(d)),n.print(" ")}n.print(" ")}for(var f=0;f");for(var h=0;h".concat(p)),n.print(" ")}n.print(" ")}n.print("
        "),n.print(""),n.print("")}n.close(),n.clear()},v.default.prototype.writeFile=function(e,t,r){var o="application/octet-stream",e=(v.default.prototype._isSafari()&&(o="text/plain"),new Blob(e,{type:o}));v.default.prototype.downloadFile(e,t,r)},v.default.prototype.downloadFile=function(e,t,r){var o,t=i(t,r),r=t[0];e instanceof Blob?n.default.saveAs(e,r):((o=document.createElement("a")).href=e,o.download=r,o.onclick=function(e){document.body.removeChild(e.target),e.stopPropagation()},o.style.display="none",document.body.appendChild(o),v.default.prototype._isSafari()&&(e=(e='Hello, Safari user! To download this file...\n1. Go to File --\x3e Save As.\n2. Choose "Page Source" as the Format.\n')+'3. Name it with this extension: ."'.concat(t[1],'"'),alert(e)),o.click())},v.default.prototype._checkFileExtension=i,v.default.prototype._isSafari=function(){return 0>>0},getSeed:function(){return t},rand:function(){return(r=(1664525*r+1013904223)%o)/o}};n.setSeed(e),j=new Array(4096);for(var s=0;s<4096;s++)j[s]=n.rand()},e.default);r.default=e},{"../core/main":267}],300:[function(e,t,r){"use strict";function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e){return(i="function"==typeof Symbol&&"symbol"===o(Symbol.iterator)?function(e){return o(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":o(e)})(e)}e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.every"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.array.some"),e("core-js/modules/es.math.sign"),e("core-js/modules/es.number.constructor"),e("core-js/modules/es.number.is-finite"),e("core-js/modules/es.object.get-own-property-descriptor"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.string.sub"),e("core-js/modules/es.weak-map"),e("core-js/modules/web.dom-collections.iterator"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.every"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.array.some"),e("core-js/modules/es.math.sign"),e("core-js/modules/es.number.constructor"),e("core-js/modules/es.number.is-finite"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.string.sub"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var a=(s=e("../core/main"))&&s.__esModule?s:{default:s},n=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==i(e)&&"function"!=typeof e)return{default:e};var t=l();if(t&&t.has(e))return t.get(e);var r,o={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(r in e){var s;Object.prototype.hasOwnProperty.call(e,r)&&((s=n?Object.getOwnPropertyDescriptor(e,r):null)&&(s.get||s.set)?Object.defineProperty(o,r,s):o[r]=e[r])}o.default=e,t&&t.set(e,o);return o}(e("../core/constants"));function l(){var e;return"function"!=typeof WeakMap?null:(e=new WeakMap,l=function(){return e},e)}a.default.Vector=function(){var e,t,r="[object Function]"==={}.toString.call(arguments[0])?(this.isPInst=!0,this._fromRadians=arguments[0],this._toRadians=arguments[1],e=arguments[2]||0,t=arguments[3]||0,arguments[4]||0):(e=arguments[0]||0,t=arguments[1]||0,arguments[2]||0);this.x=e,this.y=t,this.z=r},a.default.Vector.prototype.toString=function(){return"p5.Vector Object : [".concat(this.x,", ").concat(this.y,", ").concat(this.z,"]")},a.default.Vector.prototype.set=function(e,t,r){return e instanceof a.default.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},a.default.Vector.prototype.copy=function(){return this.isPInst?new a.default.Vector(this._fromRadians,this._toRadians,this.x,this.y,this.z):new a.default.Vector(this.x,this.y,this.z)},a.default.Vector.prototype.add=function(e,t,r){return e instanceof a.default.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};function u(e,t){return 0!==e&&(this.x=this.x%e),0!==t&&(this.y=this.y%t),this}function c(e,t,r){return 0!==e&&(this.x=this.x%e),0!==t&&(this.y=this.y%t),0!==r&&(this.z=this.z%r),this}a.default.Vector.prototype.rem=function(e,t,r){var o;if(e instanceof a.default.Vector){if(Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.z))return n=parseFloat(e.x),s=parseFloat(e.y),o=parseFloat(e.z),c.call(this,n,s,o)}else if(e instanceof Array){if(e.every(function(e){return Number.isFinite(e)}))return 2===e.length?u.call(this,e[0],e[1]):3===e.length?c.call(this,e[0],e[1],e[2]):void 0}else if(1===arguments.length){if(Number.isFinite(e)&&0!==e)return this.x=this.x%e,this.y=this.y%e,this.z=this.z%e,this}else if(2===arguments.length){var n=Array.prototype.slice.call(arguments);if(n.every(function(e){return Number.isFinite(e)})&&2===n.length)return u.call(this,n[0],n[1])}else if(3===arguments.length){var s=Array.prototype.slice.call(arguments);if(s.every(function(e){return Number.isFinite(e)})&&3===s.length)return c.call(this,s[0],s[1],s[2])}},a.default.Vector.prototype.sub=function(e,t,r){return e instanceof a.default.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},a.default.Vector.prototype.mult=function(e,t,r){var o;return e instanceof a.default.Vector?Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.z)&&"number"==typeof e.x&&"number"==typeof e.y&&"number"==typeof e.z?(this.x*=e.x,this.y*=e.y,this.z*=e.z):console.warn("p5.Vector.prototype.mult:","x contains components that are either undefined or not finite numbers"):e instanceof Array?e.every(function(e){return Number.isFinite(e)})&&e.every(function(e){return"number"==typeof e})?1===e.length?(this.x*=e[0],this.y*=e[0],this.z*=e[0]):2===e.length?(this.x*=e[0],this.y*=e[1]):3===e.length&&(this.x*=e[0],this.y*=e[1],this.z*=e[2]):console.warn("p5.Vector.prototype.mult:","x contains elements that are either undefined or not finite numbers"):(o=Array.prototype.slice.call(arguments)).every(function(e){return Number.isFinite(e)})&&o.every(function(e){return"number"==typeof e})?(1===arguments.length&&(this.x*=e,this.y*=e,this.z*=e),2===arguments.length&&(this.x*=e,this.y*=t),3===arguments.length&&(this.x*=e,this.y*=t,this.z*=r)):console.warn("p5.Vector.prototype.mult:","x, y, or z arguments are either undefined or not a finite number"),this},a.default.Vector.prototype.div=function(e,t,r){if(e instanceof a.default.Vector)if(Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.z)&&"number"==typeof e.x&&"number"==typeof e.y&&"number"==typeof e.z){var o=0===e.z&&0===this.z;if(0===e.x||0===e.y||!o&&0===e.z)return console.warn("p5.Vector.prototype.div:","divide by 0"),this;this.x/=e.x,this.y/=e.y,o||(this.z/=e.z)}else console.warn("p5.Vector.prototype.div:","x contains components that are either undefined or not finite numbers");else if(e instanceof Array)if(e.every(function(e){return Number.isFinite(e)})&&e.every(function(e){return"number"==typeof e})){if(e.some(function(e){return 0===e}))return console.warn("p5.Vector.prototype.div:","divide by 0"),this;1===e.length?(this.x/=e[0],this.y/=e[0],this.z/=e[0]):2===e.length?(this.x/=e[0],this.y/=e[1]):3===e.length&&(this.x/=e[0],this.y/=e[1],this.z/=e[2])}else console.warn("p5.Vector.prototype.div:","x contains components that are either undefined or not finite numbers");else{o=Array.prototype.slice.call(arguments);if(o.every(function(e){return Number.isFinite(e)})&&o.every(function(e){return"number"==typeof e})){if(o.some(function(e){return 0===e}))return console.warn("p5.Vector.prototype.div:","divide by 0"),this;1===arguments.length&&(this.x/=e,this.y/=e,this.z/=e),2===arguments.length&&(this.x/=e,this.y/=t),3===arguments.length&&(this.x/=e,this.y/=t,this.z/=r)}else console.warn("p5.Vector.prototype.div:","x, y, or z arguments are either undefined or not a finite number")}return this},a.default.Vector.prototype.mag=function(){return Math.sqrt(this.magSq())},a.default.Vector.prototype.magSq=function(){var e=this.x,t=this.y,r=this.z;return e*e+t*t+r*r},a.default.Vector.prototype.dot=function(e,t,r){return e instanceof a.default.Vector?this.dot(e.x,e.y,e.z):this.x*(e||0)+this.y*(t||0)+this.z*(r||0)},a.default.Vector.prototype.cross=function(e){var t=this.y*e.z-this.z*e.y,r=this.z*e.x-this.x*e.z,e=this.x*e.y-this.y*e.x;return this.isPInst?new a.default.Vector(this._fromRadians,this._toRadians,t,r,e):new a.default.Vector(t,r,e)},a.default.Vector.prototype.dist=function(e){return e.copy().sub(this).mag()},a.default.Vector.prototype.normalize=function(){var e=this.mag();return 0!==e&&this.mult(1/e),this},a.default.Vector.prototype.limit=function(e){var t=this.magSq();return e*e>>0},n.default.prototype.randomSeed=function(e){this._lcgSetSeed(s,e),this._gaussian_previous=!1},n.default.prototype.random=function(e,t){var r,o;return n.default._validateParameters("random",arguments),r=null!=this[s]?this._lcg(s):Math.random(),void 0===e?r:void 0===t?e instanceof Array?e[Math.floor(r*e.length)]:r*e:(th&&(b=d,v=a,s=l,d=x+h*(i&&x=t?r.substring(r.length-t,r.length):r}},o.default.prototype.unhex=function(e){return e instanceof Array?e.map(o.default.prototype.unhex):parseInt("0x".concat(e),16)};e=o.default;r.default=e},{"../core/main":267,"core-js/modules/es.array.map":161,"core-js/modules/es.number.constructor":169,"core-js/modules/es.object.to-string":177,"core-js/modules/es.regexp.to-string":182,"core-js/modules/es.string.repeat":188}],308:[function(e,t,r){"use strict";e("core-js/modules/es.array.filter"),e("core-js/modules/es.array.index-of"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.map"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.regexp.constructor"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.string.match"),e("core-js/modules/es.string.replace"),e("core-js/modules/es.string.split"),e("core-js/modules/es.string.trim"),e("core-js/modules/es.array.filter"),e("core-js/modules/es.array.index-of"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.map"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.regexp.constructor"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.string.match"),e("core-js/modules/es.string.replace"),e("core-js/modules/es.string.split"),e("core-js/modules/es.string.trim"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var s=(l=e("../core/main"))&&l.__esModule?l:{default:l};function o(e,t,r){var o=e<0,e=o?e.toString().substring(1):e.toString(),n=e.indexOf("."),s=-1!==n?e.substring(0,n):e,i=-1!==n?e.substring(n+1):"",a=o?"-":"";if(void 0!==r){o="";(-1!==n||0r&&(i=i.substring(0,r));for(var l=0;lo.length)for(var n=t-(o+=-1===r?".":"").length+1,s=0;s=_.TWO_PI?"".concat(c="ellipse","|"):"".concat(c="arc","|").concat(s,"|").concat(i,"|").concat(a,"|")).concat(l,"|"),c=(this.geometryInHash(u)||((t=new S.default.Geometry(l,1,function(){if(this.strokeIndices=[],s.toFixed(10)!==i.toFixed(10)){a!==_.PIE&&void 0!==a||(this.vertices.push(new S.default.Vector(.5,.5,0)),this.uvs.push([.5,.5]));for(var e=0;e<=l;e++){var t=(i-s)*(e/l)+s,r=.5+Math.cos(t)/2,t=.5+Math.sin(t)/2;this.vertices.push(new S.default.Vector(r,t,0)),this.uvs.push([r,t]),e>5&31)/31,(p>>10&31)/31):(r=i,o=a,l)),new x.default.Vector(y,g,v)),j=1;j<=3;j++){var _=m+12*j,_=new x.default.Vector(u.getFloat32(_,!0),u.getFloat32(4+_,!0),u.getFloat32(8+_,!0));e.vertices.push(_),e.vertexNormals.push(b),d&&s.push(r,o,n)}e.faces.push([3*h,3*h+1,3*h+2]),e.uvs.push([0,0],[0,0],[0,0])}}(e,t);else{t=new DataView(t);if(!("TextDecoder"in window))return console.warn("Sorry, ASCII STL loading only works in browsers that support TextDecoder (https://caniuse.com/#feat=textencoder)");t=new TextDecoder("utf-8").decode(t).split("\n");!function(e,t){for(var r,o,n="",s=[],i=0;i=Math.PI)&&(n*=-1),(i+=r)<0&&(i=.1),Math.sin(s)*i*Math.sin(o)),t=Math.cos(s)*i,r=Math.sin(s)*i*Math.cos(o);this.camera(e+this.centerX,t+this.centerY,r+this.centerZ,this.centerX,this.centerY,this.centerZ,0,n,0)},f.default.Camera.prototype._isActive=function(){return this===this._renderer._curCamera},f.default.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])};e=f.default.Camera;r.default=e},{"../core/main":267}],316:[function(e,t,r){"use strict";e("core-js/modules/es.array.slice"),e("core-js/modules/es.string.sub"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.string.sub"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var l=(e=e("../core/main"))&&e.__esModule?e:{default:e};l.default.Geometry=function(e,t,r){return this.vertices=[],this.lineVertices=[],this.lineTangentsIn=[],this.lineTangentsOut=[],this.lineSides=[],this.vertexNormals=[],this.faces=[],this.uvs=[],this.edges=[],this.vertexColors=[],this.vertexStrokeColors=[],this.lineVertexColors=[],this.detailX=void 0!==e?e:1,this.detailY=void 0!==t?t:1,this.dirtyFlags={},r instanceof Function&&r.call(this),this},l.default.Geometry.prototype.reset=function(){this.lineVertices.length=0,this.lineTangentsIn.length=0,this.lineTangentsOut.length=0,this.lineSides.length=0,this.vertices.length=0,this.edges.length=0,this.vertexColors.length=0,this.vertexStrokeColors.length=0,this.lineVertexColors.length=0,this.vertexNormals.length=0,this.uvs.length=0,this.dirtyFlags={}},l.default.Geometry.prototype.computeFaces=function(){this.faces.length=0;for(var e,t,r,o=this.detailX+1,n=0;nthis.vertices.length-1-this.detailX;o--)e.add(this.vertexNormals[o]);e=l.default.Vector.div(e,this.detailX);for(var n=this.vertices.length-1;n>this.vertices.length-1-this.detailX;n--)this.vertexNormals[n]=e;return this},l.default.Geometry.prototype._makeTriangleEdges=function(){if(this.edges.length=0,Array.isArray(this.strokeIndices))for(var e=0,t=this.strokeIndices.length;e 65535 triangles. Your web browser does not support the WebGL Extension OES_element_index_uint.");r.drawElements(r.TRIANGLES,t.vertexCount,t.indexBufferType,0)}else r.drawArrays(e||r.TRIANGLES,0,t.vertexCount)},a.default.RendererGL.prototype._drawPoints=function(e,t){var r=this.GL,o=this._getImmediatePointShader();this._setPointUniforms(o),this._bindBuffer(t,r.ARRAY_BUFFER,this._vToNArray(e),Float32Array,r.STATIC_DRAW),o.enableAttrib(o.attributes.aPosition,3),r.drawArrays(r.Points,0,e.length),o.unbindShader()},a.default.RendererGL);r.default=n},{"../core/main":267,"./p5.RenderBuffer":318,"./p5.RendererGL":321,"core-js/modules/es.array.fill":152,"core-js/modules/es.array.iterator":158,"core-js/modules/es.array.some":163,"core-js/modules/es.object.keys":176,"core-js/modules/es.object.to-string":177,"core-js/modules/es.string.iterator":186,"core-js/modules/es.symbol":196,"core-js/modules/es.symbol.description":194,"core-js/modules/es.symbol.iterator":195,"core-js/modules/es.typed-array.copy-within":197,"core-js/modules/es.typed-array.every":198,"core-js/modules/es.typed-array.fill":199,"core-js/modules/es.typed-array.filter":200,"core-js/modules/es.typed-array.find":202,"core-js/modules/es.typed-array.find-index":201,"core-js/modules/es.typed-array.float32-array":203,"core-js/modules/es.typed-array.for-each":205,"core-js/modules/es.typed-array.includes":206,"core-js/modules/es.typed-array.index-of":207,"core-js/modules/es.typed-array.iterator":210,"core-js/modules/es.typed-array.join":211,"core-js/modules/es.typed-array.last-index-of":212,"core-js/modules/es.typed-array.map":213,"core-js/modules/es.typed-array.reduce":215,"core-js/modules/es.typed-array.reduce-right":214,"core-js/modules/es.typed-array.reverse":216,"core-js/modules/es.typed-array.set":217,"core-js/modules/es.typed-array.slice":218,"core-js/modules/es.typed-array.some":219,"core-js/modules/es.typed-array.sort":220,"core-js/modules/es.typed-array.subarray":221,"core-js/modules/es.typed-array.to-locale-string":222,"core-js/modules/es.typed-array.to-string":223,"core-js/modules/es.typed-array.uint16-array":224,"core-js/modules/es.typed-array.uint32-array":225,"core-js/modules/web.dom-collections.iterator":230}],321:[function(e,t,r){"use strict";function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e){return(i="function"==typeof Symbol&&"symbol"===o(Symbol.iterator)?function(e){return o(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":o(e)})(e)}e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.fill"),e("core-js/modules/es.array.filter"),e("core-js/modules/es.array.from"),e("core-js/modules/es.array.includes"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.object.assign"),e("core-js/modules/es.object.get-own-property-descriptor"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.string.includes"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.typed-array.float32-array"),e("core-js/modules/es.typed-array.float64-array"),e("core-js/modules/es.typed-array.int16-array"),e("core-js/modules/es.typed-array.uint8-array"),e("core-js/modules/es.typed-array.uint16-array"),e("core-js/modules/es.typed-array.uint32-array"),e("core-js/modules/es.typed-array.copy-within"),e("core-js/modules/es.typed-array.every"),e("core-js/modules/es.typed-array.fill"),e("core-js/modules/es.typed-array.filter"),e("core-js/modules/es.typed-array.find"),e("core-js/modules/es.typed-array.find-index"),e("core-js/modules/es.typed-array.for-each"),e("core-js/modules/es.typed-array.includes"),e("core-js/modules/es.typed-array.index-of"),e("core-js/modules/es.typed-array.iterator"),e("core-js/modules/es.typed-array.join"),e("core-js/modules/es.typed-array.last-index-of"),e("core-js/modules/es.typed-array.map"),e("core-js/modules/es.typed-array.reduce"),e("core-js/modules/es.typed-array.reduce-right"),e("core-js/modules/es.typed-array.reverse"),e("core-js/modules/es.typed-array.set"),e("core-js/modules/es.typed-array.slice"),e("core-js/modules/es.typed-array.some"),e("core-js/modules/es.typed-array.sort"),e("core-js/modules/es.typed-array.subarray"),e("core-js/modules/es.typed-array.to-locale-string"),e("core-js/modules/es.typed-array.to-string"),e("core-js/modules/es.weak-map"),e("core-js/modules/web.dom-collections.iterator"),e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.fill"),e("core-js/modules/es.array.filter"),e("core-js/modules/es.array.from"),e("core-js/modules/es.array.includes"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.object.assign"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.string.includes"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.typed-array.float32-array"),e("core-js/modules/es.typed-array.float64-array"),e("core-js/modules/es.typed-array.int16-array"),e("core-js/modules/es.typed-array.uint8-array"),e("core-js/modules/es.typed-array.uint16-array"),e("core-js/modules/es.typed-array.uint32-array"),e("core-js/modules/es.typed-array.copy-within"),e("core-js/modules/es.typed-array.every"),e("core-js/modules/es.typed-array.fill"),e("core-js/modules/es.typed-array.filter"),e("core-js/modules/es.typed-array.find"),e("core-js/modules/es.typed-array.find-index"),e("core-js/modules/es.typed-array.for-each"),e("core-js/modules/es.typed-array.includes"),e("core-js/modules/es.typed-array.index-of"),e("core-js/modules/es.typed-array.iterator"),e("core-js/modules/es.typed-array.join"),e("core-js/modules/es.typed-array.last-index-of"),e("core-js/modules/es.typed-array.map"),e("core-js/modules/es.typed-array.reduce"),e("core-js/modules/es.typed-array.reduce-right"),e("core-js/modules/es.typed-array.reverse"),e("core-js/modules/es.typed-array.set"),e("core-js/modules/es.typed-array.slice"),e("core-js/modules/es.typed-array.some"),e("core-js/modules/es.typed-array.sort"),e("core-js/modules/es.typed-array.subarray"),e("core-js/modules/es.typed-array.to-locale-string"),e("core-js/modules/es.typed-array.to-string"),e("core-js/modules/web.dom-collections.iterator"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var p=l(e("../core/main")),s=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==i(e)&&"function"!=typeof e)return{default:e};var t=a();if(t&&t.has(e))return t.get(e);var r,o={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(r in e){var s;Object.prototype.hasOwnProperty.call(e,r)&&((s=n?Object.getOwnPropertyDescriptor(e,r):null)&&(s.get||s.set)?Object.defineProperty(o,r,s):o[r]=e[r])}o.default=e,t&&t.set(e,o);return o}(e("../core/constants")),n=l(e("libtess"));e("./p5.Shader"),e("./p5.Camera"),e("../core/p5.Renderer"),e("./p5.Matrix"),e("path");function a(){var e;return"function"!=typeof WeakMap?null:(e=new WeakMap,a=function(){return e},e)}function l(e){return e&&e.__esModule?e:{default:e}}function u(e){return function(e){if(Array.isArray(e)){for(var t=0,r=new Array(e.length);t vTexCoord.y;\n bool y1 = p1.y > vTexCoord.y;\n bool y2 = p2.y > vTexCoord.y;\n\n // could web be under the curve (after t1)?\n if (y1 ? !y2 : y0) {\n // add the coverage for t1\n coverage.x += saturate(C1.x + 0.5);\n // calculate the anti-aliasing for t1\n weight.x = min(weight.x, abs(C1.x));\n }\n\n // are we outside the curve (after t2)?\n if (y1 ? !y0 : y2) {\n // subtract the coverage for t2\n coverage.x -= saturate(C2.x + 0.5);\n // calculate the anti-aliasing for t2\n weight.x = min(weight.x, abs(C2.x));\n }\n}\n\n// this is essentially the same as coverageX, but with the axes swapped\nvoid coverageY(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n bool x0 = p0.x > vTexCoord.x;\n bool x1 = p1.x > vTexCoord.x;\n bool x2 = p2.x > vTexCoord.x;\n\n if (x1 ? !x2 : x0) {\n coverage.y -= saturate(C1.y + 0.5);\n weight.y = min(weight.y, abs(C1.y));\n }\n\n if (x1 ? !x0 : x2) {\n coverage.y += saturate(C2.y + 0.5);\n weight.y = min(weight.y, abs(C2.y));\n }\n}\n\nvoid main() {\n\n // calculate the pixel scale based on screen-coordinates\n pixelScale = hardness / fwidth(vTexCoord);\n\n // which grid cell is this pixel in?\n ivec2 gridCoord = ifloor(vTexCoord * vec2(uGridSize));\n\n // intersect curves in this row\n {\n // the index into the row info bitmap\n int rowIndex = gridCoord.y + uGridOffset.y;\n // fetch the info texel\n vec4 rowInfo = getTexel(uSamplerRows, rowIndex, uGridImageSize);\n // unpack the rowInfo\n int rowStrokeIndex = getInt16(rowInfo.xy);\n int rowStrokeCount = getInt16(rowInfo.zw);\n\n for (int iRowStroke = INT(0); iRowStroke < N; iRowStroke++) {\n if (iRowStroke >= rowStrokeCount)\n break;\n\n // each stroke is made up of 3 points: the start and control point\n // and the start of the next curve.\n // fetch the indices of this pair of strokes:\n vec4 strokeIndices = getTexel(uSamplerRowStrokes, rowStrokeIndex++, uCellsImageSize);\n\n // unpack the stroke index\n int strokePos = getInt16(strokeIndices.xy);\n\n // fetch the two strokes\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n\n // calculate the coverage\n coverageX(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n // intersect curves in this column\n {\n int colIndex = gridCoord.x + uGridOffset.x;\n vec4 colInfo = getTexel(uSamplerCols, colIndex, uGridImageSize);\n int colStrokeIndex = getInt16(colInfo.xy);\n int colStrokeCount = getInt16(colInfo.zw);\n \n for (int iColStroke = INT(0); iColStroke < N; iColStroke++) {\n if (iColStroke >= colStrokeCount)\n break;\n\n vec4 strokeIndices = getTexel(uSamplerColStrokes, colStrokeIndex++, uCellsImageSize);\n\n int strokePos = getInt16(strokeIndices.xy);\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n coverageY(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n weight = saturate(1.0 - weight * 2.0);\n float distance = max(weight.x + weight.y, minDistance); // manhattan approx.\n float antialias = abs(dot(coverage, weight) / distance);\n float cover = min(abs(coverage.x), abs(coverage.y));\n gl_FragColor = vec4(uMaterialColor.rgb, 1.) * uMaterialColor.a;\n gl_FragColor *= saturate(max(antialias, cover));\n}\n",lineVert:m+"/*\n Part of the Processing project - http://processing.org\n Copyright (c) 2012-15 The Processing Foundation\n Copyright (c) 2004-12 Ben Fry and Casey Reas\n Copyright (c) 2001-04 Massachusetts Institute of Technology\n This library is free software; you can redistribute it and/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation, version 2.1.\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n You should have received a copy of the GNU Lesser General\n Public License along with this library; if not, write to the\n Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n Boston, MA 02111-1307 USA\n*/\n\n#define PROCESSING_LINE_SHADER\n\nprecision mediump float;\nprecision mediump int;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uStrokeWeight;\n\nuniform bool uUseLineColor;\nuniform vec4 uMaterialColor;\n\nuniform vec4 uViewport;\nuniform int uPerspective;\nuniform int uStrokeJoin;\n\nattribute vec4 aPosition;\nattribute vec3 aTangentIn;\nattribute vec3 aTangentOut;\nattribute float aSide;\nattribute vec4 aVertexColor;\n\nvarying vec4 vColor;\nvarying vec2 vTangent;\nvarying vec2 vCenter;\nvarying vec2 vPosition;\nvarying float vMaxDist;\nvarying float vCap;\nvarying float vJoin;\n\nvec2 lineIntersection(vec2 aPoint, vec2 aDir, vec2 bPoint, vec2 bDir) {\n // Rotate and translate so a starts at the origin and goes out to the right\n bPoint -= aPoint;\n vec2 rotatedBFrom = vec2(\n bPoint.x*aDir.x + bPoint.y*aDir.y,\n bPoint.y*aDir.x - bPoint.x*aDir.y\n );\n vec2 bTo = bPoint + bDir;\n vec2 rotatedBTo = vec2(\n bTo.x*aDir.x + bTo.y*aDir.y,\n bTo.y*aDir.x - bTo.x*aDir.y\n );\n float intersectionDistance =\n rotatedBTo.x + (rotatedBFrom.x - rotatedBTo.x) * rotatedBTo.y /\n (rotatedBTo.y - rotatedBFrom.y);\n return aPoint + aDir * intersectionDistance;\n}\n\nvoid main() {\n // using a scale <1 moves the lines towards the camera\n // in order to prevent popping effects due to half of\n // the line disappearing behind the geometry faces.\n vec3 scale = vec3(0.9995);\n\n // Caps have one of either the in or out tangent set to 0\n vCap = (aTangentIn == vec3(0.)) != (aTangentOut == (vec3(0.)))\n ? 1. : 0.;\n\n // Joins have two unique, defined tangents\n vJoin = (\n aTangentIn != vec3(0.) &&\n aTangentOut != vec3(0.) &&\n aTangentIn != aTangentOut\n ) ? 1. : 0.;\n\n vec4 posp = uModelViewMatrix * aPosition;\n vec4 posqIn = uModelViewMatrix * (aPosition + vec4(aTangentIn, 0));\n vec4 posqOut = uModelViewMatrix * (aPosition + vec4(aTangentOut, 0));\n\n // Moving vertices slightly toward the camera\n // to avoid depth-fighting with the fill triangles.\n // Discussed here:\n // http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=252848 \n posp.xyz = posp.xyz * scale;\n posqIn.xyz = posqIn.xyz * scale;\n posqOut.xyz = posqOut.xyz * scale;\n\n vec4 p = uProjectionMatrix * posp;\n vec4 qIn = uProjectionMatrix * posqIn;\n vec4 qOut = uProjectionMatrix * posqOut;\n vCenter = p.xy;\n\n // formula to convert from clip space (range -1..1) to screen space (range 0..[width or height])\n // screen_p = (p.xy/p.w + <1,1>) * 0.5 * uViewport.zw\n\n // prevent division by W by transforming the tangent formula (div by 0 causes\n // the line to disappear, see https://github.com/processing/processing/issues/5183)\n // t = screen_q - screen_p\n //\n // tangent is normalized and we don't care which aDirection it points to (+-)\n // t = +- normalize( screen_q - screen_p )\n // t = +- normalize( (q.xy/q.w+<1,1>)*0.5*uViewport.zw - (p.xy/p.w+<1,1>)*0.5*uViewport.zw )\n //\n // extract common factor, <1,1> - <1,1> cancels out\n // t = +- normalize( (q.xy/q.w - p.xy/p.w) * 0.5 * uViewport.zw )\n //\n // convert to common divisor\n // t = +- normalize( ((q.xy*p.w - p.xy*q.w) / (p.w*q.w)) * 0.5 * uViewport.zw )\n //\n // remove the common scalar divisor/factor, not needed due to normalize and +-\n // (keep uViewport - can't remove because it has different components for x and y\n // and corrects for aspect ratio, see https://github.com/processing/processing/issues/5181)\n // t = +- normalize( (q.xy*p.w - p.xy*q.w) * uViewport.zw )\n\n vec2 tangentIn = normalize((qIn.xy*p.w - p.xy*qIn.w) * uViewport.zw);\n vec2 tangentOut = normalize((qOut.xy*p.w - p.xy*qOut.w) * uViewport.zw);\n\n vec2 curPerspScale;\n if(uPerspective == 1) {\n // Perspective ---\n // convert from world to clip by multiplying with projection scaling factor\n // to get the right thickness (see https://github.com/processing/processing/issues/5182)\n // invert Y, projections in Processing invert Y\n curPerspScale = (uProjectionMatrix * vec4(1, -1, 0, 0)).xy;\n } else {\n // No Perspective ---\n // multiply by W (to cancel out division by W later in the pipeline) and\n // convert from screen to clip (derived from clip to screen above)\n curPerspScale = p.w / (0.5 * uViewport.zw);\n }\n\n vec2 offset;\n if (vJoin == 1.) {\n vTangent = normalize(tangentIn + tangentOut);\n vec2 normalIn = vec2(-tangentIn.y, tangentIn.x);\n vec2 normalOut = vec2(-tangentOut.y, tangentOut.x);\n float side = sign(aSide);\n float sideEnum = abs(aSide);\n\n // We generate vertices for joins on either side of the centerline, but\n // the \"elbow\" side is the only one needing a join. By not setting the\n // offset for the other side, all its vertices will end up in the same\n // spot and not render, effectively discarding it.\n if (sign(dot(tangentOut, vec2(-tangentIn.y, tangentIn.x))) != side) {\n // Side enums:\n // 1: the side going into the join\n // 2: the middle of the join\n // 3: the side going out of the join\n if (sideEnum == 2.) {\n // Calculate the position + tangent on either side of the join, and\n // find where the lines intersect to find the elbow of the join\n vec2 c = (posp.xy/posp.w + vec2(1.,1.)) * 0.5 * uViewport.zw;\n vec2 intersection = lineIntersection(\n c + (side * normalIn * uStrokeWeight / 2.) * curPerspScale,\n tangentIn,\n c + (side * normalOut * uStrokeWeight / 2.) * curPerspScale,\n tangentOut\n );\n offset = (intersection - c);\n\n // When lines are thick and the angle of the join approaches 180, the\n // elbow might be really far from the center. We'll apply a limit to\n // the magnitude to avoid lines going across the whole screen when this\n // happens.\n float mag = length(offset);\n float maxMag = 3. * uStrokeWeight;\n if (mag > maxMag) {\n offset *= maxMag / mag;\n }\n } else if (sideEnum == 1.) {\n offset = side * normalIn * curPerspScale * uStrokeWeight / 2.;\n } else if (sideEnum == 3.) {\n offset = side * normalOut * curPerspScale * uStrokeWeight / 2.;\n }\n }\n if (uStrokeJoin == STROKE_JOIN_BEVEL) {\n vec2 avgNormal = vec2(-vTangent.y, vTangent.x);\n vMaxDist = abs(dot(avgNormal, normalIn * uStrokeWeight / 2.));\n } else {\n vMaxDist = uStrokeWeight / 2.;\n }\n } else {\n vec2 tangent = aTangentIn == vec3(0.) ? tangentOut : tangentIn;\n vTangent = tangent;\n vec2 normal = vec2(-tangent.y, tangent.x);\n\n float normalOffset = sign(aSide);\n // Caps will have side values of -2 or 2 on the edge of the cap that\n // extends out from the line\n float tangentOffset = abs(aSide) - 1.;\n offset = (normal * normalOffset + tangent * tangentOffset) *\n uStrokeWeight * 0.5 * curPerspScale;\n vMaxDist = uStrokeWeight / 2.;\n }\n vPosition = vCenter + offset / curPerspScale;\n\n gl_Position.xy = p.xy + offset.xy;\n gl_Position.zw = p.zw;\n \n vColor = (uUseLineColor ? aVertexColor : uMaterialColor);\n}\n",lineFrag:m+"precision mediump float;\nprecision mediump int;\n\nuniform vec4 uMaterialColor;\nuniform int uStrokeCap;\nuniform int uStrokeJoin;\nuniform float uStrokeWeight;\n\nvarying vec4 vColor;\nvarying vec2 vTangent;\nvarying vec2 vCenter;\nvarying vec2 vPosition;\nvarying float vMaxDist;\nvarying float vCap;\nvarying float vJoin;\n\nfloat distSquared(vec2 a, vec2 b) {\n vec2 aToB = b - a;\n return dot(aToB, aToB);\n}\n\nvoid main() {\n if (vCap > 0.) {\n if (\n uStrokeCap == STROKE_CAP_ROUND &&\n distSquared(vPosition, vCenter) > uStrokeWeight * uStrokeWeight * 0.25\n ) {\n discard;\n } else if (\n uStrokeCap == STROKE_CAP_SQUARE &&\n dot(vPosition - vCenter, vTangent) > 0.\n ) {\n discard;\n }\n // Use full area for PROJECT\n } else if (vJoin > 0.) {\n if (\n uStrokeJoin == STROKE_JOIN_ROUND &&\n distSquared(vPosition, vCenter) > uStrokeWeight * uStrokeWeight * 0.25\n ) {\n discard;\n } else if (uStrokeJoin == STROKE_JOIN_BEVEL) {\n vec2 normal = vec2(-vTangent.y, vTangent.x);\n if (abs(dot(vPosition - vCenter, normal)) > vMaxDist) {\n discard;\n }\n }\n // Use full area for MITER\n }\n gl_FragColor = vec4(vColor.rgb, 1.) * vColor.a;\n}\n",pointVert:"attribute vec3 aPosition;\nuniform float uPointSize;\nvarying float vStrokeWeight;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nvoid main() {\n\tvec4 positionVec4 = vec4(aPosition, 1.0);\n\tgl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n\tgl_PointSize = uPointSize;\n\tvStrokeWeight = uPointSize;\n}",pointFrag:"precision mediump float;\nprecision mediump int;\nuniform vec4 uMaterialColor;\nvarying float vStrokeWeight;\n\nvoid main(){\n float mask = 0.0;\n\n // make a circular mask using the gl_PointCoord (goes from 0 - 1 on a point)\n // might be able to get a nicer edge on big strokeweights with smoothstep but slightly less performant\n\n mask = step(0.98, length(gl_PointCoord * 2.0 - 1.0));\n\n // if strokeWeight is 1 or less lets just draw a square\n // this prevents weird artifacting from carving circles when our points are really small\n // if strokeWeight is larger than 1, we just use it as is\n\n mask = mix(0.0, mask, clamp(floor(vStrokeWeight - 0.5),0.0,1.0));\n\n // throw away the borders of the mask\n // otherwise we get weird alpha blending issues\n\n if(mask > 0.98){\n discard;\n }\n\n gl_FragColor = vec4(uMaterialColor.rgb, 1.) * uMaterialColor.a;\n}\n"},e=(p.default.RendererGL=function(e,t,r,o){return p.default.Renderer.call(this,e,t,r),this._setAttributeDefaults(t),this._initContext(),this.isP3D=!0,this.GL=this.drawingContext,this._pInst._setProperty("drawingContext",this.drawingContext),this._isErasing=!1,this._enableLighting=!1,this.ambientLightColors=[],this.specularColors=[1,1,1],this.directionalLightDirections=[],this.directionalLightDiffuseColors=[],this.directionalLightSpecularColors=[],this.pointLightPositions=[],this.pointLightDiffuseColors=[],this.pointLightSpecularColors=[],this.spotLightPositions=[],this.spotLightDirections=[],this.spotLightDiffuseColors=[],this.spotLightSpecularColors=[],this.spotLightAngle=[],this.spotLightConc=[],this.drawMode=s.FILL,this.curFillColor=this._cachedFillStyle=[1,1,1,1],this.curAmbientColor=this._cachedFillStyle=[1,1,1,1],this.curSpecularColor=this._cachedFillStyle=[0,0,0,0],this.curEmissiveColor=this._cachedFillStyle=[0,0,0,0],this.curStrokeColor=this._cachedStrokeStyle=[0,0,0,1],this.curBlendMode=s.BLEND,this._cachedBlendMode=void 0,this.blendExt=this.GL.getExtension("EXT_blend_minmax"),this._isBlending=!1,this._useSpecularMaterial=!1,this._useEmissiveMaterial=!1,this._useNormalMaterial=!1,this._useShininess=1,this._useLineColor=!1,this._useVertexColor=!1,this.registerEnabled=[],this._tint=[255,255,255,255],this.constantAttenuation=1,this.linearAttenuation=0,this.quadraticAttenuation=0,this.uMVMatrix=new p.default.Matrix,this.uPMatrix=new p.default.Matrix,this.uNMatrix=new p.default.Matrix("mat3"),this._currentNormal=new p.default.Vector(0,0,1),this._curCamera=new p.default.Camera(this),this._curCamera._computeCameraDefaultSettings(),this._curCamera._setDefaultCamera(),this._defaultLightShader=void 0,this._defaultImmediateModeShader=void 0,this._defaultNormalShader=void 0,this._defaultColorShader=void 0,this._defaultPointShader=void 0,this.userFillShader=void 0,this.userStrokeShader=void 0,this.userPointShader=void 0,this.retainedMode={geometry:{},buffers:{stroke:[new p.default.RenderBuffer(4,"lineVertexColors","lineColorBuffer","aVertexColor",this,this._flatten),new p.default.RenderBuffer(3,"lineVertices","lineVerticesBuffer","aPosition",this,this._flatten),new p.default.RenderBuffer(3,"lineTangentsIn","lineTangentsInBuffer","aTangentIn",this,this._flatten),new p.default.RenderBuffer(3,"lineTangentsOut","lineTangentsOutBuffer","aTangentOut",this,this._flatten),new p.default.RenderBuffer(1,"lineSides","lineSidesBuffer","aSide",this)],fill:[new p.default.RenderBuffer(3,"vertices","vertexBuffer","aPosition",this,this._vToNArray),new p.default.RenderBuffer(3,"vertexNormals","normalBuffer","aNormal",this,this._vToNArray),new p.default.RenderBuffer(4,"vertexColors","colorBuffer","aVertexColor",this),new p.default.RenderBuffer(3,"vertexAmbients","ambientBuffer","aAmbientColor",this),new p.default.RenderBuffer(2,"uvs","uvBuffer","aTexCoord",this,this._flatten)],text:[new p.default.RenderBuffer(3,"vertices","vertexBuffer","aPosition",this,this._vToNArray),new p.default.RenderBuffer(2,"uvs","uvBuffer","aTexCoord",this,this._flatten)]}},this.immediateMode={geometry:new p.default.Geometry,shapeMode:s.TRIANGLE_FAN,_bezierVertex:[],_quadraticVertex:[],_curveVertex:[],buffers:{fill:[new p.default.RenderBuffer(3,"vertices","vertexBuffer","aPosition",this,this._vToNArray),new p.default.RenderBuffer(3,"vertexNormals","normalBuffer","aNormal",this,this._vToNArray),new p.default.RenderBuffer(4,"vertexColors","colorBuffer","aVertexColor",this),new p.default.RenderBuffer(3,"vertexAmbients","ambientBuffer","aAmbientColor",this),new p.default.RenderBuffer(2,"uvs","uvBuffer","aTexCoord",this,this._flatten)],stroke:[new p.default.RenderBuffer(4,"lineVertexColors","lineColorBuffer","aVertexColor",this,this._flatten),new p.default.RenderBuffer(3,"lineVertices","lineVerticesBuffer","aPosition",this,this._flatten),new p.default.RenderBuffer(3,"lineTangentsIn","lineTangentsInBuffer","aTangentIn",this,this._flatten),new p.default.RenderBuffer(3,"lineTangentsOut","lineTangentsOutBuffer","aTangentOut",this,this._flatten),new p.default.RenderBuffer(1,"lineSides","lineSidesBuffer","aSide",this)],point:this.GL.createBuffer()}},this.pointSize=5,this.curStrokeWeight=1,this.curStrokeCap=s.ROUND,this.curStrokeJoin=s.ROUND,this.textures=[],this.textureMode=s.IMAGE,this.textureWrapX=s.CLAMP,this.textureWrapY=s.CLAMP,this._tex=null,this._curveTightness=6,this._lookUpTableBezier=[],this._lookUpTableQuadratic=[],this._lutBezierDetail=0,this._lutQuadraticDetail=0,this.isProcessingVertices=!1,this._tessy=this._initTessy(),this.fontInfos={},this._curShader=void 0,this},p.default.RendererGL.prototype=Object.create(p.default.Renderer.prototype),p.default.RendererGL.prototype._setAttributeDefaults=function(e){var t={alpha:!0,depth:!0,stencil:!0,antialias:navigator.userAgent.toLowerCase().includes("safari"),premultipliedAlpha:!0,preserveDrawingBuffer:!0,perPixelLighting:!0};null===e._glAttributes?e._glAttributes=t:e._glAttributes=Object.assign(t,e._glAttributes)},p.default.RendererGL.prototype._initContext=function(){if(this.drawingContext=this.canvas.getContext("webgl",this._pInst._glAttributes)||this.canvas.getContext("experimental-webgl",this._pInst._glAttributes),null===this.drawingContext)throw new Error("Error creating webgl context");var e=this.drawingContext;e.enable(e.DEPTH_TEST),e.depthFunc(e.LEQUAL),e.viewport(0,0,e.drawingBufferWidth,e.drawingBufferHeight),this._viewport=this.drawingContext.getParameter(this.drawingContext.VIEWPORT)},p.default.RendererGL.prototype._resetContext=function(e,t){var r,o=this.width,n=this.height,s=this.canvas.id,i=this._pInst instanceof p.default.Graphics,s=(i?((r=this._pInst).canvas.parentNode.removeChild(r.canvas),r.canvas=document.createElement("canvas"),(r._pInst._userNode||document.body).appendChild(r.canvas),p.default.Element.call(r,r.canvas,r._pInst),r.width=o,r.height=n):((r=this.canvas)&&r.parentNode.removeChild(r),(r=document.createElement("canvas")).id=s,(this._pInst._userNode||document.body).appendChild(r),this._pInst.canvas=r,this.canvas=r),new p.default.RendererGL(this._pInst.canvas,this._pInst,!i));this._pInst._setProperty("_renderer",s),s.resize(o,n),s._applyDefaults(),i||this._pInst._elements.push(s),"function"==typeof t&&setTimeout(function(){t.apply(window._renderer,e)},0)},p.default.prototype.setAttributes=function(e,t){if(void 0===this._glAttributes)console.log("You are trying to use setAttributes on a p5.Graphics object that does not use a WEBGL renderer.");else{var r=!0;if(void 0!==t?(null===this._glAttributes&&(this._glAttributes={}),this._glAttributes[e]!==t&&(this._glAttributes[e]=t,r=!1)):e instanceof Object&&this._glAttributes!==e&&(this._glAttributes=e,r=!1),this._renderer.isP3D&&!r){if(!this._setupDone)for(var o in this._renderer.retainedMode.geometry)if(this._renderer.retainedMode.geometry.hasOwnProperty(o))return void console.error("Sorry, Could not set the attributes, you need to call setAttributes() before calling the other drawing methods in setup()");this.push(),this._renderer._resetContext(),this.pop(),this._renderer._curCamera&&(this._renderer._curCamera._renderer=this._renderer)}}},p.default.RendererGL.prototype._update=function(){this.uMVMatrix.set(this._curCamera.cameraMatrix.mat4[0],this._curCamera.cameraMatrix.mat4[1],this._curCamera.cameraMatrix.mat4[2],this._curCamera.cameraMatrix.mat4[3],this._curCamera.cameraMatrix.mat4[4],this._curCamera.cameraMatrix.mat4[5],this._curCamera.cameraMatrix.mat4[6],this._curCamera.cameraMatrix.mat4[7],this._curCamera.cameraMatrix.mat4[8],this._curCamera.cameraMatrix.mat4[9],this._curCamera.cameraMatrix.mat4[10],this._curCamera.cameraMatrix.mat4[11],this._curCamera.cameraMatrix.mat4[12],this._curCamera.cameraMatrix.mat4[13],this._curCamera.cameraMatrix.mat4[14],this._curCamera.cameraMatrix.mat4[15]),this.ambientLightColors.length=0,this.specularColors=[1,1,1],this.directionalLightDirections.length=0,this.directionalLightDiffuseColors.length=0,this.directionalLightSpecularColors.length=0,this.pointLightPositions.length=0,this.pointLightDiffuseColors.length=0,this.pointLightSpecularColors.length=0,this.spotLightPositions.length=0,this.spotLightDirections.length=0,this.spotLightDiffuseColors.length=0,this.spotLightSpecularColors.length=0,this.spotLightAngle.length=0,this.spotLightConc.length=0,this._enableLighting=!1,this._tint=[255,255,255,255],this.GL.clear(this.GL.DEPTH_BUFFER_BIT)},p.default.RendererGL.prototype.background=function(){var e=(e=this._pInst).color.apply(e,arguments),t=e.levels[0]/255,r=e.levels[1]/255,o=e.levels[2]/255,e=e.levels[3]/255;this.clear(t,r,o,e)},p.default.RendererGL.prototype.fill=function(e,t,r,o){var n=p.default.prototype.color.apply(this._pInst,arguments);this.curFillColor=n._array,this.drawMode=s.FILL,this._useNormalMaterial=!1,this._tex=null},p.default.RendererGL.prototype.stroke=function(e,t,r,o){var n=p.default.prototype.color.apply(this._pInst,arguments);this.curStrokeColor=n._array},p.default.RendererGL.prototype.strokeCap=function(e){this.curStrokeCap=e},p.default.RendererGL.prototype.strokeJoin=function(e){this.curStrokeJoin=e},p.default.RendererGL.prototype.filter=function(e){console.error("filter() does not work in WEBGL mode")},p.default.RendererGL.prototype.blendMode=function(e){e===s.DARKEST||e===s.LIGHTEST||e===s.ADD||e===s.BLEND||e===s.SUBTRACT||e===s.SCREEN||e===s.EXCLUSION||e===s.REPLACE||e===s.MULTIPLY||e===s.REMOVE?this.curBlendMode=e:e!==s.BURN&&e!==s.OVERLAY&&e!==s.HARD_LIGHT&&e!==s.SOFT_LIGHT&&e!==s.DODGE||console.warn("BURN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, and DODGE only work for blendMode in 2D mode.")},p.default.RendererGL.prototype.erase=function(e,t){this._isErasing||(this._applyBlendMode(s.REMOVE),this._isErasing=!0,this._cachedFillStyle=this.curFillColor.slice(),this.curFillColor=[1,1,1,e/255],this._cachedStrokeStyle=this.curStrokeColor.slice(),this.curStrokeColor=[1,1,1,t/255])},p.default.RendererGL.prototype.noErase=function(){this._isErasing&&(this._isErasing=!1,this.curFillColor=this._cachedFillStyle.slice(),this.curStrokeColor=this._cachedStrokeStyle.slice(),this.blendMode(this._cachedBlendMode))},p.default.RendererGL.prototype.strokeWeight=function(e){this.curStrokeWeight!==e&&(this.pointSize=e,this.curStrokeWeight=e)},p.default.RendererGL.prototype._getPixel=function(e,t){var r=new Uint8Array(4);return this.drawingContext.readPixels(e,t,1,1,this.drawingContext.RGBA,this.drawingContext.UNSIGNED_BYTE,r),[r[0],r[1],r[2],r[3]]},p.default.RendererGL.prototype.loadPixels=function(){var e,t=this._pixelsState;!0!==this._pInst._glAttributes.preserveDrawingBuffer?console.log("loadPixels only works in WebGL when preserveDrawingBuffer is true."):(t=t.pixels,e=this.GL.drawingBufferWidth*this.GL.drawingBufferHeight*4,t instanceof Uint8Array&&t.length===e||(t=new Uint8Array(e),this._pixelsState._setProperty("pixels",t)),e=this._pInst._pixelDensity,this.GL.readPixels(0,0,this.width*e,this.height*e,this.GL.RGBA,this.GL.UNSIGNED_BYTE,t))},p.default.RendererGL.prototype.geometryInHash=function(e){return void 0!==this.retainedMode.geometry[e]},p.default.RendererGL.prototype.resize=function(e,t){p.default.Renderer.prototype.resize.call(this,e,t),this.GL.viewport(0,0,this.GL.drawingBufferWidth,this.GL.drawingBufferHeight),this._viewport=this.GL.getParameter(this.GL.VIEWPORT),this._curCamera._resize();e=this._pixelsState;void 0!==e.pixels&&e._setProperty("pixels",new Uint8Array(this.GL.drawingBufferWidth*this.GL.drawingBufferHeight*4))},p.default.RendererGL.prototype.clear=function(){var e=(arguments.length<=0?void 0:arguments[0])||0,t=(arguments.length<=1?void 0:arguments[1])||0,r=(arguments.length<=2?void 0:arguments[2])||0,o=(arguments.length<=3?void 0:arguments[3])||0;this.GL.clearColor(e*o,t*o,r*o,o),this.GL.clearDepth(1),this.GL.clear(this.GL.COLOR_BUFFER_BIT|this.GL.DEPTH_BUFFER_BIT)},p.default.RendererGL.prototype.applyMatrix=function(e,t,r,o,n,s){16===arguments.length?p.default.Matrix.prototype.apply.apply(this.uMVMatrix,arguments):this.uMVMatrix.apply([e,t,0,0,r,o,0,0,0,0,1,0,n,s,0,1])},p.default.RendererGL.prototype.translate=function(e,t,r){return e instanceof p.default.Vector&&(r=e.z,t=e.y,e=e.x),this.uMVMatrix.translate([e,t,r]),this},p.default.RendererGL.prototype.scale=function(e,t,r){return this.uMVMatrix.scale(e,t,r),this},p.default.RendererGL.prototype.rotate=function(e,t){return void 0===t?this.rotateZ(e):(p.default.Matrix.prototype.rotate.apply(this.uMVMatrix,arguments),this)},p.default.RendererGL.prototype.rotateX=function(e){return this.rotate(e,1,0,0),this},p.default.RendererGL.prototype.rotateY=function(e){return this.rotate(e,0,1,0),this},p.default.RendererGL.prototype.rotateZ=function(e){return this.rotate(e,0,0,1),this},p.default.RendererGL.prototype.push=function(){var e=p.default.Renderer.prototype.push.apply(this),t=e.properties;return t.uMVMatrix=this.uMVMatrix.copy(),t.uPMatrix=this.uPMatrix.copy(),t._curCamera=this._curCamera,this._curCamera=this._curCamera.copy(),t.ambientLightColors=this.ambientLightColors.slice(),t.specularColors=this.specularColors.slice(),t.directionalLightDirections=this.directionalLightDirections.slice(),t.directionalLightDiffuseColors=this.directionalLightDiffuseColors.slice(),t.directionalLightSpecularColors=this.directionalLightSpecularColors.slice(),t.pointLightPositions=this.pointLightPositions.slice(),t.pointLightDiffuseColors=this.pointLightDiffuseColors.slice(),t.pointLightSpecularColors=this.pointLightSpecularColors.slice(),t.spotLightPositions=this.spotLightPositions.slice(),t.spotLightDirections=this.spotLightDirections.slice(),t.spotLightDiffuseColors=this.spotLightDiffuseColors.slice(),t.spotLightSpecularColors=this.spotLightSpecularColors.slice(),t.spotLightAngle=this.spotLightAngle.slice(),t.spotLightConc=this.spotLightConc.slice(),t.userFillShader=this.userFillShader,t.userStrokeShader=this.userStrokeShader,t.userPointShader=this.userPointShader,t.pointSize=this.pointSize,t.curStrokeWeight=this.curStrokeWeight,t.curStrokeColor=this.curStrokeColor,t.curFillColor=this.curFillColor,t.curAmbientColor=this.curAmbientColor,t.curSpecularColor=this.curSpecularColor,t.curEmissiveColor=this.curEmissiveColor,t._useSpecularMaterial=this._useSpecularMaterial,t._useEmissiveMaterial=this._useEmissiveMaterial,t._useShininess=this._useShininess,t.constantAttenuation=this.constantAttenuation,t.linearAttenuation=this.linearAttenuation,t.quadraticAttenuation=this.quadraticAttenuation,t._enableLighting=this._enableLighting,t._useNormalMaterial=this._useNormalMaterial,t._tex=this._tex,t.drawMode=this.drawMode,t._currentNormal=this._currentNormal,t.curBlendMode=this.curBlendMode,e},p.default.RendererGL.prototype.resetMatrix=function(){return this.uMVMatrix.set(this._curCamera.cameraMatrix.mat4[0],this._curCamera.cameraMatrix.mat4[1],this._curCamera.cameraMatrix.mat4[2],this._curCamera.cameraMatrix.mat4[3],this._curCamera.cameraMatrix.mat4[4],this._curCamera.cameraMatrix.mat4[5],this._curCamera.cameraMatrix.mat4[6],this._curCamera.cameraMatrix.mat4[7],this._curCamera.cameraMatrix.mat4[8],this._curCamera.cameraMatrix.mat4[9],this._curCamera.cameraMatrix.mat4[10],this._curCamera.cameraMatrix.mat4[11],this._curCamera.cameraMatrix.mat4[12],this._curCamera.cameraMatrix.mat4[13],this._curCamera.cameraMatrix.mat4[14],this._curCamera.cameraMatrix.mat4[15]),this},p.default.RendererGL.prototype._getImmediateStrokeShader=function(){var e=this.userStrokeShader;return e&&e.isStrokeShader()?e:this._getLineShader()},p.default.RendererGL.prototype._getRetainedStrokeShader=p.default.RendererGL.prototype._getImmediateStrokeShader,p.default.RendererGL.prototype._getImmediateFillShader=function(){var e=this.userFillShader;if(this._useNormalMaterial&&(!e||!e.isNormalShader()))return this._getNormalShader();if(this._enableLighting){if(!e||!e.isLightShader())return this._getLightShader()}else if(this._tex){if(!e||!e.isTextureShader())return this._getLightShader()}else if(!e)return this._getImmediateModeShader();return e},p.default.RendererGL.prototype._getRetainedFillShader=function(){if(this._useNormalMaterial)return this._getNormalShader();var e=this.userFillShader;if(this._enableLighting){if(!e||!e.isLightShader())return this._getLightShader()}else if(this._tex){if(!e||!e.isTextureShader())return this._getLightShader()}else if(!e)return this._getColorShader();return e},p.default.RendererGL.prototype._getImmediatePointShader=function(){var e=this.userPointShader;return e&&e.isPointShader()?e:this._getPointShader()},p.default.RendererGL.prototype._getRetainedLineShader=p.default.RendererGL.prototype._getImmediateLineShader,p.default.RendererGL.prototype._getLightShader=function(){return this._defaultLightShader||(this._pInst._glAttributes.perPixelLighting?this._defaultLightShader=new p.default.Shader(this,y.phongVert,y.phongFrag):this._defaultLightShader=new p.default.Shader(this,y.lightVert,y.lightTextureFrag)),this._defaultLightShader},p.default.RendererGL.prototype._getImmediateModeShader=function(){return this._defaultImmediateModeShader||(this._defaultImmediateModeShader=new p.default.Shader(this,y.immediateVert,y.vertexColorFrag)),this._defaultImmediateModeShader},p.default.RendererGL.prototype._getNormalShader=function(){return this._defaultNormalShader||(this._defaultNormalShader=new p.default.Shader(this,y.normalVert,y.normalFrag)),this._defaultNormalShader},p.default.RendererGL.prototype._getColorShader=function(){return this._defaultColorShader||(this._defaultColorShader=new p.default.Shader(this,y.normalVert,y.basicFrag)),this._defaultColorShader},p.default.RendererGL.prototype._getPointShader=function(){return this._defaultPointShader||(this._defaultPointShader=new p.default.Shader(this,y.pointVert,y.pointFrag)),this._defaultPointShader},p.default.RendererGL.prototype._getLineShader=function(){return this._defaultLineShader||(this._defaultLineShader=new p.default.Shader(this,y.lineVert,y.lineFrag)),this._defaultLineShader},p.default.RendererGL.prototype._getFontShader=function(){return this._defaultFontShader||(this.GL.getExtension("OES_standard_derivatives"),this._defaultFontShader=new p.default.Shader(this,y.fontVert,y.fontFrag)),this._defaultFontShader},p.default.RendererGL.prototype._getEmptyTexture=function(){var e;return this._emptyTexture||((e=new p.default.Image(1,1)).set(0,0,255),this._emptyTexture=new p.default.Texture(this,e)),this._emptyTexture},p.default.RendererGL.prototype.getTexture=function(e){var t=this.textures,r=!0,o=!1,n=void 0;try{for(var s,i=t[Symbol.iterator]();!(r=(s=i.next()).done);r=!0){var a=s.value;if(a.src===e)return a}}catch(e){o=!0,n=e}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}o=new p.default.Texture(this,e);return t.push(o),o},p.default.RendererGL.prototype._setStrokeUniforms=function(e){e.bindShader(),e.setUniform("uUseLineColor",this._useLineColor),e.setUniform("uMaterialColor",this.curStrokeColor),e.setUniform("uStrokeWeight",this.curStrokeWeight),e.setUniform("uStrokeCap",f[this.curStrokeCap]),e.setUniform("uStrokeJoin",h[this.curStrokeJoin])},p.default.RendererGL.prototype._setFillUniforms=function(e){e.bindShader(),e.setUniform("uUseVertexColor",this._useVertexColor),e.setUniform("uMaterialColor",this.curFillColor),e.setUniform("isTexture",!!this._tex),this._tex&&e.setUniform("uSampler",this._tex),e.setUniform("uTint",this._tint),e.setUniform("uAmbientMatColor",this.curAmbientColor),e.setUniform("uSpecularMatColor",this.curSpecularColor),e.setUniform("uEmissiveMatColor",this.curEmissiveColor),e.setUniform("uSpecular",this._useSpecularMaterial),e.setUniform("uEmissive",this._useEmissiveMaterial),e.setUniform("uShininess",this._useShininess),e.setUniform("uUseLighting",this._enableLighting);var t=this.pointLightDiffuseColors.length/3,t=(e.setUniform("uPointLightCount",t),e.setUniform("uPointLightLocation",this.pointLightPositions),e.setUniform("uPointLightDiffuseColors",this.pointLightDiffuseColors),e.setUniform("uPointLightSpecularColors",this.pointLightSpecularColors),this.directionalLightDiffuseColors.length/3),t=(e.setUniform("uDirectionalLightCount",t),e.setUniform("uLightingDirection",this.directionalLightDirections),e.setUniform("uDirectionalDiffuseColors",this.directionalLightDiffuseColors),e.setUniform("uDirectionalSpecularColors",this.directionalLightSpecularColors),this.ambientLightColors.length/3),t=(e.setUniform("uAmbientLightCount",t),e.setUniform("uAmbientColor",this.ambientLightColors),this.spotLightDiffuseColors.length/3);e.setUniform("uSpotLightCount",t),e.setUniform("uSpotLightAngle",this.spotLightAngle),e.setUniform("uSpotLightConc",this.spotLightConc),e.setUniform("uSpotLightDiffuseColors",this.spotLightDiffuseColors),e.setUniform("uSpotLightSpecularColors",this.spotLightSpecularColors),e.setUniform("uSpotLightLocation",this.spotLightPositions),e.setUniform("uSpotLightDirection",this.spotLightDirections),e.setUniform("uConstantAttenuation",this.constantAttenuation),e.setUniform("uLinearAttenuation",this.linearAttenuation),e.setUniform("uQuadraticAttenuation",this.quadraticAttenuation),e.bindTextures()},p.default.RendererGL.prototype._setPointUniforms=function(e){e.bindShader(),e.setUniform("uMaterialColor",this.curStrokeColor),e.setUniform("uPointSize",this.pointSize*this._pInst._pixelDensity)},p.default.RendererGL.prototype._bindBuffer=function(e,t,r,o,n){t=t||this.GL.ARRAY_BUFFER,this.GL.bindBuffer(t,e),void 0!==r&&(e=new(o||Float32Array)(r),this.GL.bufferData(t,e,n||this.GL.STATIC_DRAW))},p.default.RendererGL.prototype._arraysEqual=function(e,t){var r=e.length;if(r!==t.length)return!1;for(var o=0;o>7,127&d,c>>7,127&c);for(var f=0;f>7,127&h,0,0)}}return{cellImageInfo:a,dimOffset:t,dimImageInfo:n}}}}var V=Math.sqrt(3);B.default.RendererGL.prototype._renderText=function(e,t,r,o,n){if(this._textFont&&"string"!=typeof this._textFont){if(!(n<=o)&&this._doFill){if(this._isOpenType()){e.push();var n=this._doStroke,s=this.drawMode,i=(this._doStroke=!1,this.drawMode=E.TEXTURE,this._textFont.font),a=(a=this._textFont._fontInfo)||(this._textFont._fontInfo=new T(i)),r=this._textFont._handleAlignment(this,t,r,o),o=this._textSize/i.unitsPerEm,l=(this.translate(r.x,r.y,0),this.scale(o,o,1),this.GL),r=!this._defaultFontShader,u=this._getFontShader(),c=(u.init(),u.bindShader(),r&&(u.setUniform("uGridImageSize",[64,64]),u.setUniform("uCellsImageSize",[64,64]),u.setUniform("uStrokeImageSize",[64,64]),u.setUniform("uGridSize",[9,9])),this._applyColorBlend(this.curFillColor),this.retainedMode.geometry.glyph),d=(c||((o=this._textGeom=new B.default.Geometry(1,1,function(){for(var e=0;e<=1;e++)for(var t=0;t<=1;t++)this.vertices.push(new B.default.Vector(t,e,0)),this.uvs.push(t,e)})).computeFaces().computeNormals(),c=this.createBuffers("glyph",o)),!0),r=!1,o=void 0;try{for(var f,h=this.retainedMode.buffers.text[Symbol.iterator]();!(d=(f=h.next()).done);d=!0)f.value._prepareBuffer(c,u)}catch(e){r=!0,o=e}finally{try{d||null==h.return||h.return()}finally{if(r)throw o}}this._bindBuffer(c.indexBuffer,l.ELEMENT_ARRAY_BUFFER),u.setUniform("uMaterialColor",this.curFillColor);try{var p=0,m=null,y=i.stringToGlyphs(t),g=!0,v=!1,b=void 0;try{for(var j,_=y[Symbol.iterator]();!(g=(j=_.next()).done);g=!0){var x,w,S=j.value,M=(m&&(p+=i.getKerningValue(m,S)),a.getGlyphInfo(S));M.uGlyphRect&&(x=M.rowInfo,w=M.colInfo,u.setUniform("uSamplerStrokes",M.strokeImageInfo.imageData),u.setUniform("uSamplerRowStrokes",x.cellImageInfo.imageData),u.setUniform("uSamplerRows",x.dimImageInfo.imageData),u.setUniform("uSamplerColStrokes",w.cellImageInfo.imageData),u.setUniform("uSamplerCols",w.dimImageInfo.imageData),u.setUniform("uGridOffset",M.uGridOffset),u.setUniform("uGlyphRect",M.uGlyphRect),u.setUniform("uGlyphOffset",p),u.bindTextures(),l.drawElements(l.TRIANGLES,6,this.GL.UNSIGNED_SHORT,0)),p+=S.advanceWidth,m=S}}catch(e){v=!0,b=e}finally{try{g||null==_.return||_.return()}finally{if(v)throw b}}}finally{u.unbindShader(),this._doStroke=n,this.drawMode=s,e.pop()}}else console.log("WEBGL: only Opentype (.otf) and Truetype (.ttf) fonts are supported");return e}}else console.log("WEBGL: you must load and set a font before drawing text. See `loadFont` and `textFont` for more details.")}},{"../core/constants":256,"../core/main":267,"./p5.RendererGL.Retained":320,"./p5.Shader":322,"core-js/modules/es.array.iterator":158,"core-js/modules/es.object.get-own-property-descriptor":173,"core-js/modules/es.object.to-string":177,"core-js/modules/es.regexp.exec":181,"core-js/modules/es.string.iterator":186,"core-js/modules/es.string.split":191,"core-js/modules/es.string.sub":192,"core-js/modules/es.symbol":196,"core-js/modules/es.symbol.description":194,"core-js/modules/es.symbol.iterator":195,"core-js/modules/es.weak-map":228,"core-js/modules/web.dom-collections.iterator":230}]},{},[251])(251)}); \ No newline at end of file diff --git a/piano-visualizer.js b/piano-visualizer.js new file mode 100644 index 0000000..fd98e92 --- /dev/null +++ b/piano-visualizer.js @@ -0,0 +1,222 @@ + +function setup() { + createCanvas(1098, 118).parent('piano-visualizer'); + colorMode(HSB, 360, 100, 100, 100); + keyOnColor = color(326, 100, 100, 100); // <---- 編輯這裡換「按下時」的顏色![HSB Color Mode] + pedaledColor = color(326, 100, 70, 100); // <---- 編輯這裡換「踏板踩住」的顏色![HSB Color Mode] + smooth(2); + frameRate(60); + initKeys(); + +} + +function draw() { + background(0, 0, 20, 100); + pushHistories(); + drawWhiteKeys(); + drawBlackKeys(); + // drawPedalLines(); + // drawNotes(); + + drawTexts(); +} + +function calculateSessionTime() { + let currentTime = new Date(); + let timeElapsed = currentTime - sessionStartTime; + // Convert time elapsed to hours, minutes, and seconds + let seconds = Math.floor((timeElapsed / 1000) % 60); + let minutes = Math.floor((timeElapsed / (1000 * 60)) % 60); + let hours = Math.floor((timeElapsed / (1000 * 60 * 60)) % 24); + sessionTotalSeconds = Math.floor(timeElapsed / 1000); + // Pad minutes and seconds with leading zeros + let paddedMinutes = String(minutes).padStart(2, '0'); + let paddedSeconds = String(seconds).padStart(2, '0'); + let timeText = `${hours}:${paddedMinutes}:${paddedSeconds}`; + return timeText; +} + +function initKeys() { + for (i = 0; i<128; i++) { + isKeyOn[i] = 0; + isPedaled[i] = 0; + } +} + +function drawWhiteKeys() { + let wIndex = 0; // white key index + stroke(0, 0, 0); + strokeWeight(1); + for (let i = 21; i < 109; i++) { + if (isBlack[i % 12] == 0) { + // it's a white key + if (isKeyOn[i] == 1 && !rainbowMode) { + fill(keyOnColor); // keypressed + } else if (isKeyOn[i] == 1 && rainbowMode) { + fill(map(i, 21, 108, 0, 1080)%360, 100, 100, 100); // rainbowMode + } else if (isPedaled[i] == 1 && !rainbowMode) { + fill(pedaledColor); // pedaled + } else if (isPedaled[i] == 1 && rainbowMode) { + fill(map(i, 21, 108, 0, 1080)%360, 100, 70, 100); // pedaled rainbowMode + } else { + fill(0, 0, 100); // white key + } + let thisX = border + wIndex*(whiteKeyWidth+whiteKeySpace); + rect(thisX, keyAreaY, whiteKeyWidth, keyAreaHeight, radius); + // println(wIndex); + wIndex++; + } + } +} + +function drawBlackKeys() { + let wIndex = 0; // white key index + stroke(0, 0, 0); + strokeWeight(1.5); + for (let i = 21; i < 109; i++) { + if (isBlack[i % 12] == 0) { + // it's a white key + wIndex++; + } + + if (isBlack[i % 12] > 0) { + // it's a black key + if (isKeyOn[i] == 1 && !rainbowMode) { + fill(keyOnColor); // keypressed + } else if (isKeyOn[i] == 1 && rainbowMode) { + fill(map(i, 21, 108, 0, 1080)%360, 100, 100, 100); // rainbowMode + } else if (isPedaled[i] == 1 && !rainbowMode) { + fill(pedaledColor); // pedaled + } else if (isPedaled[i] == 1 && rainbowMode) { + fill(map(i, 21, 108, 0, 1080)%360, 100, 70, 100); // pedaled rainbowMode + } else { + fill(0, 0, 0); // white key + } + + let thisX = border + (wIndex-1)*(whiteKeyWidth+whiteKeySpace) + isBlack[i % 12]; + rect(thisX, keyAreaY-1, blackKeyWidth, blackKeyHeight, bRadius); + } + } +} + +function drawTexts() { + stroke(0, 0, 10, 100); + fill(0, 0, 100, 90) + textFont('Monospace'); + textStyle(BOLD); + textSize(14); + textAlign(LEFT, TOP); + + // TIME + let timeText = "TIME" + "\n" + calculateSessionTime(); + text(timeText, 5, 79); + + // PEDAL + let pedalText = "PEDALS" + "\nL " + convertNumberToBars(cc67now) + " R " + convertNumberToBars(cc64now) + text(pedalText, 860, 79); + + // NOTES + let notesText = "NOTE COUNT" + "\n" + totalNotesPlayed; + text(notesText, 95, 79); + + // CALORIES + let caloriesText = "CALORIES" + "\n" + (totalIntensityScore/250).toFixed(3); // 250 Intensity = 1 kcal. + text(caloriesText, 350, 79); + + // SHORT-TERM DENSITY + let shortTermDensity = shortTermTotal.reduce((accumulator, currentValue) => accumulator + currentValue, 0); // Sum the array. + let shortTermDensityText = "NOTES/S" + "\n" + shortTermDensity; + text(shortTermDensityText, 200, 79); + + // LEGATO SCORE + let legatoScore = legatoHistory.reduce((accumulator, currentValue) => accumulator + currentValue, 0) + legatoScore /= 60; + let legatoText = "LEGATO" + "\n" + legatoScore.toFixed(2); + text(legatoText, 280, 79); + + // NOW PLAYING + let nowPlayingText = "KEYS" + "\n" + truncateString(getPressedKeys(), 47); + text(nowPlayingText, 440, 79); +} + +function pushHistories() { + shortTermTotal.push(notesThisFrame); + shortTermTotal.shift(); + notesThisFrame = 0; + + + legatoHistory.push(isKeyOn.reduce((accumulator, currentValue) => accumulator + currentValue, 0)); + legatoHistory.shift(); + + +} + +function convertNumberToBars(number) { + if (number < 0 || number > 127) { + throw new Error('Number must be between 0 and 127'); + } + + const maxBars = 10; + const scaleFactor = 128 / maxBars; + + // Calculate the number of bars + const numberOfBars = Math.ceil(number / scaleFactor); + + // Create a string with the calculated number of "|" characters + const barString = '|'.repeat(numberOfBars); + + // Calculate the number of "." characters required to fill the remaining space + const numberOfDots = maxBars - numberOfBars; + + // Create a string with the calculated number of "." characters + const dotString = '.'.repeat(numberOfDots); + + // Combine the "|" and "." strings + const combinedString = barString + dotString; + + return combinedString; +} + +function getPressedKeys() { + let pressedOrPedaled = []; + + for (let i = 0; i < isKeyOn.length; i++) { + pressedOrPedaled[i] = isKeyOn[i] === 1 || isPedaled[i] === 1 ? 1 : 0; + + } + + + + let noteNames = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']; // default if sharp + if ([0, 1, 3, 5, 8, 10].includes(pressedOrPedaled.indexOf(1) % 12)) { + // flat + noteNames = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B']; + } + + const pressedKeys = []; + + for (let i = 0; i < pressedOrPedaled.length; i++) { + if (pressedOrPedaled[i] === 1) { + const noteName = noteNames[i % 12]; + const octave = Math.floor(i / 12) - 1; + pressedKeys.push(`${noteName}${octave}`); + } + } + + return pressedKeys.join(' '); +} + +function truncateString(str, maxLength = 40) { + if (str.length <= maxLength) { + return str; + } + + return str.slice(0, maxLength - 3) + '...'; +} + +function mouseClicked() { + // Save the canvas content as an image file + if (mouseX < 50 && mouseY < 50) { + saveCanvas('nicechord-pianometer', 'png'); + } +} \ No newline at end of file diff --git a/style.css b/style.css new file mode 100644 index 0000000..7f6bcdf --- /dev/null +++ b/style.css @@ -0,0 +1,547 @@ +/*! style.css v1.0.0 | ISC License | https://github.com/ungoldman/style.css */ +html { + color: rgb(210, 209, 202); + background-color: #202328; + box-sizing: border-box; + font-family: -apple-system, BlinkMacSystemFont, "avenir next", avenir, "segoe ui", "fira sans", roboto, noto, "droid sans", "liberation sans", "lucida grande", "helvetica neue", helvetica, "franklin gothic medium", "century gothic", cantarell, oxygen, ubuntu, sans-serif; + font-size: calc(14px + 0.25vw); + line-height: 1.55; + -webkit-font-kerning: normal; + font-kerning: normal; + text-rendering: optimizeLegibility; + -webkit-font-feature-settings: "kern", "liga"1, "calt"0; + font-feature-settings: "kern", "liga"1, "calt"0; + -ms-text-size-adjust: 100%; + -webkit-text-size-adjust: 100%; + height: 100%; +} + +#main { + display: flex; + margin-top: 0.5rem; + flex-wrap: wrap; + justify-content: space-evenly; + align-items: center; + +} + +#controls { + width: 600px; + height: 100%; +} + +#piano-visualizer { + margin-top: 0.2rem; + margin-bottom: 1rem; +} + +.center { + text-align: center; +} + +.left { + text-align: left; +} + +body { + margin: 0; + height: 100%; +} + +article, +aside, +footer, +header, +nav, +section, +figcaption, +figure, +main { + display: block; +} + +*, +*::before, +*::after { + box-sizing: inherit; +} + +p, +blockquote, +ul, +ol, +dl, +table, +pre { + margin-top: 0; + margin-bottom: 1.25em; +} + +small { + font-size: 80%; +} + +h1, +h2, +h3, +h4, +h5, +h6 { + font-weight: 500; + line-height: 1.25em; + margin-top: 0; + margin-bottom: 0.5rem; + position: relative; + text-align: center; + color: #ddd; +} + +h1 small, +h2 small, +h3 small, +h4 small, +h5 small, +h6 small { + color: #777; + font-size: 0.7em; + font-weight: 300; +} + +h1 code, +h2 code, +h3 code, +h4 code, +h5 code, +h6 code { + font-size: 0.9em; +} + +h1 { + font-size: 2.75em; +} + +h2 { + font-size: 2.25em; +} + +h3 { + font-size: 1.75em; +} + +h4 { + font-size: 1.5em; +} + +h5 { + font-size: 1.25em; +} + +h6 { + font-size: 1.15em; + color: #575757; +} + +p { + letter-spacing: -0.01em; +} + +a { + background-color: transparent; + -webkit-text-decoration-skip: objects; + color: #0074d9; + text-decoration: none; +} + +a:active, +a:hover { + outline-width: 0; + outline: 0; +} + +a:active, +a:focus, +a:hover { + text-decoration: underline; +} + +ul, +ol { + padding: 0; + padding-left: 2em; +} + +ul ol, +ol ol { + list-style-type: lower-roman; +} + +ul ul, +ul ol, +ol ul, +ol ol { + margin-top: 0; + margin-bottom: 0; +} + +ul ul ol, +ul ol ol, +ol ul ol, +ol ol ol { + list-style-type: lower-alpha; +} + +li>p { + margin-top: 1em; +} + +blockquote { + margin: 0 0 1rem; + padding: 0 1rem; + color: #7d7d7d; + border-left: 4px solid #d6d6d6; +} + +blockquote> :first-child { + margin-top: 0; +} + +blockquote> :last-child { + margin-bottom: 0; +} + +b, +strong { + font-weight: inherit; + font-weight: 600; +} + +mark { + background-color: #ff0; + color: #000; +} + +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} + +sub { + bottom: -0.25em; +} + +sup { + top: -0.5em; +} + +code, +pre, +kbd, +samp { + font-family: menlo, inconsolata, consolas, "fira mono", "noto mono", "droid sans mono", "liberation mono", "dejavu sans mono", "ubuntu mono", monaco, "courier new", monospace; + font-size: 90%; +} + +pre, +code { + background-color: #f7f7f7; + border-radius: 3px; +} + +pre { + overflow: auto; + word-wrap: normal; + padding: 1em; + line-height: 1.45; +} + +pre code { + background: transparent; + display: inline; + padding: 0; + line-height: inherit; + word-wrap: normal; +} + +pre code::before, +pre code::after { + content: normal; +} + +pre>code { + border: 0; + font-size: 1em; + white-space: pre; + word-break: normal; +} + +code { + padding: 0.2em 0; + margin: 0; +} + +code::before, +code::after { + letter-spacing: -0.2em; + content: '\00a0'; +} + +kbd { + background-color: #e6e6e6; + background-image: linear-gradient(#fafafa, #e6e6e6); + background-repeat: repeat-x; + border: 1px solid #d6d6d6; + border-radius: 2px; + box-shadow: 0 1px 0 #d6d6d6; + color: #303030; + display: inline-block; + line-height: 0.95em; + margin: 0 1px; + padding: 5px 5px 1px; +} + +td, +th { + padding: 0; +} + +table { + border-collapse: collapse; + border-spacing: 0; + display: block; + width: 100%; + overflow: auto; + word-break: normal; + word-break: keep-all; +} + +table th, +table td { + padding: 6px 13px; + border: 1px solid #ddd; +} + +table th { + font-weight: bold; +} + +table tr { + background-color: #fff; + border-top: 1px solid #ccc; +} + +table tr:nth-child(2n) { + background-color: #f8f8f8; +} + +hr { + box-sizing: content-box; + overflow: visible; + background: transparent; + height: 4px; + padding: 0; + margin: 1em 0; + background-color: #e7e7e7; + border: 0 none; +} + +hr::before { + display: table; + content: ''; +} + +hr::after { + display: table; + clear: both; + content: ''; +} + +img { + border-style: none; + border: 0; + max-width: 100%; +} + +svg:not(:root) { + overflow: hidden; +} + +figure { + margin: 1em 0; +} + +figure img { + background: white; + border: 1px solid #c7c7c7; + padding: 0.25em; +} + +figcaption { + font-style: italic; + font-size: 0.75em; + font-weight: 200; + margin: 0; +} + +abbr[title] { + border-bottom: none; + text-decoration: underline; + text-decoration: underline dotted; +} + +dfn { + font-style: italic; +} + +dd { + margin-left: 0; +} + +dl { + padding: 0; +} + +dl dt { + padding: 0; + margin-top: 1em; + font-size: 1em; + font-style: italic; + font-weight: 600; +} + +dl dd { + padding: 0 1em; + margin-bottom: 1.25em; +} + +audio, +video { + display: inline-block; +} + +audio:not([controls]) { + display: none; + height: 0; +} + +input { + margin: 0; +} + +button, +input, +optgroup, +select, +textarea { + font-family: sans-serif; + font-size: 100%; + line-height: 1.15; + margin: 0; +} + +button, +input { + overflow: visible; +} + +button, +select { + text-transform: none; +} + +button, +html [type="button"], +[type="reset"], +[type="submit"] { + -webkit-appearance: button; +} + +button::-moz-focus-inner, +[type="button"]::-moz-focus-inner, +[type="reset"]::-moz-focus-inner, +[type="submit"]::-moz-focus-inner { + border-style: none; + padding: 0; +} + +button:-moz-focusring, +[type="button"]:-moz-focusring, +[type="reset"]:-moz-focusring, +[type="submit"]:-moz-focusring { + outline: 1px dotted ButtonText; +} + +fieldset { + border: 1px solid #c0c0c0; + margin: 0 2px; + padding: 0.35em 0.625em 0.75em; +} + +legend { + color: inherit; + display: table; + max-width: 100%; + padding: 0; + white-space: normal; +} + +progress { + display: inline-block; + vertical-align: baseline; +} + +textarea { + overflow: auto; +} + +[type="checkbox"], +[type="radio"] { + padding: 0; +} + +[type="number"]::-webkit-inner-spin-button, +[type="number"]::-webkit-outer-spin-button { + height: auto; +} + +[type="search"] { + -webkit-appearance: textfield; + outline-offset: -2px; +} + +[type="search"]::-webkit-search-cancel-button, +[type="search"]::-webkit-search-decoration { + -webkit-appearance: none; +} + +[disabled] { + cursor: default; +} + +::-webkit-file-upload-button { + -webkit-appearance: button; + font: inherit; +} + +details, +menu { + display: block; +} + +summary { + display: list-item; +} + +canvas { + display: inline-block; +} + +template { + display: none; +} + +[hidden] { + display: none; +} \ No newline at end of file diff --git a/webmidi.js b/webmidi.js new file mode 100644 index 0000000..8ba6941 --- /dev/null +++ b/webmidi.js @@ -0,0 +1,4427 @@ +(function(scope) { + + "use strict"; + + /** + * The `WebMidi` object makes it easier to work with the Web MIDI API. Basically, it simplifies + * two things: sending outgoing MIDI messages and reacting to incoming MIDI messages. + * + * Sending MIDI messages is done via an `Output` object. All available outputs can be accessed in + * the `WebMidi.outputs` array. There is one `Output` object for each output port available on + * your system. Similarly, reacting to MIDI messages as they are coming in is simply a matter of + * adding a listener to an `Input` object. Similarly, all inputs can be found in the + * `WebMidi.inputs` array. + * + * Please note that a single hardware device might create more than one input and/or output ports. + * + * #### Sending messages + * + * To send MIDI messages, you simply need to call the desired method (`playNote()`, + * `sendPitchBend()`, `stopNote()`, etc.) from an `Output` object and pass in the appropriate + * parameters. All the native MIDI communication will be handled for you. The only additional + * thing that needs to be done is to first enable `WebMidi`. Here is an example: + * + * WebMidi.enable(function(err) { + * if (err) console.log("An error occurred", err); + * WebMidi.outputs[0].playNote("C3"); + * }); + * + * The code above, calls the `WebMidi.enable()` method. Upon success, this method executes the + * callback function specified as a parameter. In this case, the callback calls the `playnote()` + * function to play a 3rd octave C on the first available output port. + * + * #### Receiving messages + * + * Receiving messages is just as easy. You simply have to set a callback function to be triggered + * when a specific MIDI message is received. For example, here"s how to listen for pitch bend + * events on the first input port: + * + * WebMidi.enable(function(err) { + * if (err) console.log("An error occurred", err); + * + * WebMidi.inputs[0].addListener("pitchbend", "all", function(e) { + * console.log("Pitch value: " + e.value); + * }); + * + * }); + * + * As you can see, this library is much easier to use than the native Web MIDI API. No need to + * manually craft or decode binary MIDI messages anymore! + * + * @class WebMidi + * @static + * + * @throws Error WebMidi is a singleton, it cannot be instantiated directly. + * + * @todo Switch away from yuidoc (deprecated) to be able to serve doc over https + * @todo Yuidoc does not allow multiple exceptions (@throws) for a single method ?! + * + */ + function WebMidi() { + + // Singleton. Prevent instantiation through WebMidi.__proto__.constructor() + if (WebMidi.prototype._singleton) { + throw new Error("WebMidi is a singleton, it cannot be instantiated directly."); + } + WebMidi.prototype._singleton = this; + + // MIDI inputs and outputs + this._inputs = []; + this._outputs = []; + + // Object to hold all user-defined handlers for interface-wide events (connected, disconnected, + // etc.) + this._userHandlers = {}; + + // Array of statechange events to process. These events must be parsed synchronously so they do + // not override each other. + this._stateChangeQueue = []; + + // Indicates whether we are currently processing a statechange event (in which case new events + // are to be queued). + this._processingStateChange = false; + + // Events triggered at the interface level (WebMidi) + this._midiInterfaceEvents = ["connected", "disconnected"]; + + // the current nrpns being constructed, by channel + this._nrpnBuffer = [[],[],[],[], [],[],[],[], [],[],[],[], [],[],[],[]]; + + // Enable/Disable NRPN event dispatch + this._nrpnEventsEnabled = true; + + // NRPN message types + this._nrpnTypes = ["entry", "increment", "decrement"]; + + // Notes and semitones for note guessing + this._notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]; + this._semitones = {C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 }; + + // Define some "static" properties + Object.defineProperties(this, { + + /** + * [read-only] List of valid MIDI system messages and matching hexadecimal values. + * + * Note: values 249 and 253 are actually dispatched by the Web MIDI API but the MIDI 1.0 does + * not say what they are used for. About those values, it only states: undefined (reserved) + * + * @property MIDI_SYSTEM_MESSAGES + * @type Object + * @static + * + * @since 2.0.0 + */ + MIDI_SYSTEM_MESSAGES: { + value: { + + // System common messages + sysex: 0xF0, // 240 + timecode: 0xF1, // 241 + songposition: 0xF2, // 242 + songselect: 0xF3, // 243 + tuningrequest: 0xF6, // 246 + sysexend: 0xF7, // 247 (never actually received - simply ends a sysex) + + // System real-time messages + clock: 0xF8, // 248 + start: 0xFA, // 250 + continue: 0xFB, // 251 + stop: 0xFC, // 252 + activesensing: 0xFE, // 254 + reset: 0xFF, // 255 + + // Custom WebMidi.js messages + midimessage: 0, + unknownsystemmessage: -1 + }, + writable: false, + enumerable: true, + configurable: false + }, + + /** + * [read-only] An object containing properties for each MIDI channel messages and their + * associated hexadecimal value. + * + * @property MIDI_CHANNEL_MESSAGES + * @type Object + * @static + * + * @since 2.0.0 + */ + MIDI_CHANNEL_MESSAGES: { + value: { + noteoff: 0x8, // 8 + noteon: 0x9, // 9 + keyaftertouch: 0xA, // 10 + controlchange: 0xB, // 11 + channelmode: 0xB, // 11 + nrpn: 0xB, // 11 + programchange: 0xC, // 12 + channelaftertouch: 0xD, // 13 + pitchbend: 0xE // 14 + }, + writable: false, + enumerable: true, + configurable: false + }, + + /** + * [read-only] An object containing properties for each registered parameters and their + * associated pair of hexadecimal values. MIDI registered parameters extend the original list + * of control change messages (a.k.a. CC messages). Currently, there are only a limited number + * of them. + * + * @property MIDI_REGISTERED_PARAMETER + * @type Object + * @static + * + * @since 2.0.0 + */ + MIDI_REGISTERED_PARAMETER: { + value: { + pitchbendrange: [0x00, 0x00], + channelfinetuning: [0x00, 0x01], + channelcoarsetuning: [0x00, 0x02], + tuningprogram: [0x00, 0x03], + tuningbank: [0x00, 0x04], + modulationrange: [0x00, 0x05], + + azimuthangle: [0x3D, 0x00], + elevationangle: [0x3D, 0x01], + gain: [0x3D, 0x02], + distanceratio: [0x3D, 0x03], + maximumdistance: [0x3D, 0x04], + maximumdistancegain: [0x3D, 0x05], + referencedistanceratio: [0x3D, 0x06], + panspreadangle: [0x3D, 0x07], + rollangle: [0x3D, 0x08] + }, + writable: false, + enumerable: true, + configurable: false + }, + + /** + * [read-only] An object containing properties for each MIDI control change messages (a.k.a. + * CC messages) and their associated hexadecimal value. + * + * @property MIDI_CONTROL_CHANGE_MESSAGES + * @type Object + * @static + * + * @since 2.0.0 + */ + MIDI_CONTROL_CHANGE_MESSAGES: { + value: { + bankselectcoarse: 0, + modulationwheelcoarse: 1, + breathcontrollercoarse: 2, + footcontrollercoarse: 4, + portamentotimecoarse: 5, + dataentrycoarse: 6, + volumecoarse: 7, + balancecoarse: 8, + pancoarse: 10, + expressioncoarse: 11, + effectcontrol1coarse: 12, + effectcontrol2coarse: 13, + generalpurposeslider1: 16, + generalpurposeslider2: 17, + generalpurposeslider3: 18, + generalpurposeslider4: 19, + bankselectfine: 32, + modulationwheelfine: 33, + breathcontrollerfine: 34, + footcontrollerfine: 36, + portamentotimefine: 37, + dataentryfine: 38, + volumefine: 39, + balancefine: 40, + panfine: 42, + expressionfine: 43, + effectcontrol1fine: 44, + effectcontrol2fine: 45, + holdpedal: 64, + portamento: 65, + sustenutopedal: 66, + softpedal: 67, + legatopedal: 68, + hold2pedal: 69, + soundvariation: 70, + resonance: 71, + soundreleasetime: 72, + soundattacktime: 73, + brightness: 74, + soundcontrol6: 75, + soundcontrol7: 76, + soundcontrol8: 77, + soundcontrol9: 78, + soundcontrol10: 79, + generalpurposebutton1: 80, + generalpurposebutton2: 81, + generalpurposebutton3: 82, + generalpurposebutton4: 83, + reverblevel: 91, + tremololevel: 92, + choruslevel: 93, + celestelevel: 94, + phaserlevel: 95, + databuttonincrement: 96, + databuttondecrement: 97, + nonregisteredparametercoarse: 98, + nonregisteredparameterfine: 99, + registeredparametercoarse: 100, + registeredparameterfine: 101 + }, + writable: false, + enumerable: true, + configurable: false + }, + + /** + * [read-only] An object containing properties for MIDI control change messages + * that make up NRPN messages + * + * @property MIDI_NRPN_MESSAGES + * @type Object + * @static + * + * @since 2.0.0 + */ + MIDI_NRPN_MESSAGES: { + value: { + entrymsb: 6, + entrylsb: 38, + increment: 96, + decrement: 97, + paramlsb: 98, + parammsb: 99, + nullactiveparameter: 127 + }, + writable: false, + enumerable: true, + configurable: false + }, + + /** + * [read-only] List of MIDI channel mode messages as defined in the official MIDI + * specification. + * + * @property MIDI_CHANNEL_MODE_MESSAGES + * @type Object + * @static + * + * @since 2.0.0 + */ + MIDI_CHANNEL_MODE_MESSAGES: { + value: { + allsoundoff: 120, + resetallcontrollers: 121, + localcontrol: 122, + allnotesoff: 123, + omnimodeoff: 124, + omnimodeon: 125, + monomodeon: 126, + polymodeon: 127 + }, + writable: false, + enumerable: true, + configurable: false + }, + + /** + * An integer to offset the octave both in inbound and outbound messages. By default, middle C + * (MIDI note number 60) is placed on the 4th octave (C4). + * + * If, for example, `octaveOffset` is set to 2, MIDI note number 60 will be reported as C6. If + * `octaveOffset` is set to -1, MIDI note number 60 will be reported as C3. + * + * @property octaveOffset + * @type Number + * @static + * + * @since 2.1 + */ + octaveOffset: { + value: 0, + writable: true, + enumerable: true, + configurable: false + } + + }); + + // Define getters/setters + Object.defineProperties(this, { + + /** + * [read-only] Indicates whether the environment supports the Web MIDI API or not. + * + * Note: in environments that do not offer built-in MIDI support, this will report true if the + * `navigator.requestMIDIAccess` function is available. For example, if you have installed + * WebMIDIAPIShim but no plugin, this property will be true even though actual support might + * not be there. + * + * @property supported + * @type Boolean + * @static + */ + supported: { + enumerable: true, + get: function() { + return "requestMIDIAccess" in navigator; + } + }, + + /** + * [read-only] Indicates whether the interface to the host"s MIDI subsystem is currently + * enabled. + * + * @property enabled + * @type Boolean + * @static + */ + enabled: { + enumerable: true, + get: function() { + return this.interface !== undefined; + }.bind(this) + }, + + /** + * [read-only] An array of all currently available MIDI input ports. + * + * @property inputs + * @type {Array} + * @static + */ + inputs: { + enumerable: true, + get: function() { + return this._inputs; + }.bind(this) + }, + + /** + * [read-only] An array of all currently available MIDI output ports. + * + * @property outputs + * @type {Array} + * @static + */ + outputs: { + enumerable: true, + get: function() { + return this._outputs; + }.bind(this) + }, + + /** + * [read-only] Indicates whether the interface to the host"s MIDI subsystem is currently + * active. + * + * @property sysexEnabled + * @type Boolean + * @static + */ + sysexEnabled: { + enumerable: true, + get: function() { + return !!(this.interface && this.interface.sysexEnabled); + }.bind(this) + }, + + /** + * [read-only] Indicates whether WebMidi should dispatch Non-Registered + * Parameter Number events (which are generally groups of CC messages) + * If correct sequences of CC messages are received, NRPN events will + * fire. The first out of order NRPN CC will fall through the collector + * logic and all CC messages buffered will be discarded as incomplete. + * + * @private + * + * @property nrpnEventsEnabled + * @type Boolean + * @static + */ + nrpnEventsEnabled: { + enumerable: true, + get: function() { + return !!(this._nrpnEventsEnabled); + }.bind(this), + set: function(enabled) { + this._nrpnEventsEnabled = enabled; + return this._nrpnEventsEnabled; + } + }, + + /** + * [read-only] NRPN message types + * + * @property nrpnTypes + * @type Array + * @static + */ + nrpnTypes: { + enumerable: true, + get: function() { + return this._nrpnTypes; + }.bind(this) + }, + + /** + * [read-only] Current MIDI performance time in milliseconds. This can be used to queue events + * in the future. + * + * @property time + * @type DOMHighResTimeStamp + * @static + */ + time: { + enumerable: true, + get: function() { + return performance.now(); + } + } + + }); + + } + + // WebMidi is a singleton so we instantiate it ourselves and keep it in a var for internal + // reference. + var wm = new WebMidi(); + + /** + * Checks if the Web MIDI API is available and then tries to connect to the host's MIDI subsystem. + * This is an asynchronous operation. When it's done, the specified handler callback will be + * executed. If an error occurred, the callback function will receive an `Error` object as its + * sole parameter. + * + * To enable the use of system exclusive messages, the `sysex` parameter should be set to true. + * However, under some environments (e.g. Jazz-Plugin), the sysex parameter is ignored and sysex + * is always enabled. + * + * Warning: starting with Chrome v77, the Web MIDI API must be hosted on a secure origin + * (`https://`, `localhost` or `file:///`) and the user will always be prompted to authorize the + * operation (no matter if `sysex` is requested or not). + * + * @method enable + * @static + * + * @param [callback] {Function} A function to execute upon success. This function will receive an + * `Error` object upon failure to enable the Web MIDI API. + * @param [sysex=false] {Boolean} Whether to enable MIDI system exclusive messages or not. + * + * @throws Error The Web MIDI API is not supported by your browser. + * @throws Error Jazz-Plugin must be installed to use WebMIDIAPIShim. + */ + WebMidi.prototype.enable = function(callback, sysex) { + + // Why are you not using a Promise-based API for the enable() method? + // + // Short answer: because of IE. + // + // Long answer: + // + // IE 11 and below still do not support promises. Therefore, WebMIDIAPIShim has to implement a + // simple Promise look-alike object to handle the call to requestMIDIAccess(). This look-alike + // is not a fully-fledged Promise object. It does not support using catch() for example. This + // means that, to provide a real Promise-based interface for the enable() method, we would need + // to add a dependency in the form of a Promise polyfill. So, to keep things simpler, we will + // stick to the good old callback based enable() function. + + if (this.enabled) return; + + if ( !this.supported) { + + if (typeof callback === "function") { + callback( new Error("The Web MIDI API is not supported by your browser.") ); + } + + return; + + } + + navigator.requestMIDIAccess({sysex: sysex}).then( + + function(midiAccess) { + + var events = [], + promises = [], + promiseTimeout; + + this.interface = midiAccess; + this._resetInterfaceUserHandlers(); + + // We setup a temporary `statechange` handler that will catch all events triggered while we + // setup. Those events will be re-triggered after calling the user"s callback. This will + // allow the user to listen to "connected" events which can be very convenient. + this.interface.onstatechange = function (e) { + events.push(e); + }; + + // Here we manually open the inputs and outputs. Usually, this is optional. When the ports + // are not explicitely opened, they will be opened automatically (and asynchonously) by + // setting a listener on `midimessage` (MIDIInput) or calling `send()` (MIDIOutput). + // However, we do not want that here. We want to be sure that "connected" events will be + // available in the user"s callback. So, what we do is open all input and output ports and + // wait until all promises are resolved. Then, we re-trigger the events after the user"s + // callback has been executed. This seems like the most sensible and practical way. + var inputs = midiAccess.inputs.values(); + for (var input = inputs.next(); input && !input.done; input = inputs.next()) { + promises.push(input.value.open()); + } + + var outputs = midiAccess.outputs.values(); + for (var output = outputs.next(); output && !output.done; output = outputs.next()) { + promises.push(output.value.open()); + } + + // Since this library might be used in environments without support for promises (such as + // Jazz-Midi) or in environments that are not properly opening the ports (such as Web MIDI + // Browser), we fall back to a timer-based approach if the promise-based approach fails. + function onPortsOpen() { + + clearTimeout(promiseTimeout); + + this._updateInputsAndOutputs(); + this.interface.onstatechange = this._onInterfaceStateChange.bind(this); + + // We execute the callback and then re-trigger the statechange events. + if (typeof callback === "function") { callback.call(this); } + + events.forEach(function (event) { + this._onInterfaceStateChange(event); + }.bind(this)); + + } + + promiseTimeout = setTimeout(onPortsOpen.bind(this), 200); + + if (Promise) { + Promise + .all(promises) + .catch(function(err) { console.warn(err); }) + .then(onPortsOpen.bind(this)); + } + + // When MIDI access is requested, all input and output ports have their "state" set to + // "connected". However, the value of their "connection" property is "closed". + // + // A `MIDIInput` becomes `open` when you explicitely call its `open()` method or when you + // assign a listener to its `onmidimessage` property. A `MIDIOutput` becomes `open` when you + // use the `send()` method or when you can explicitely call its `open()` method. + // + // Calling `_updateInputsAndOutputs()` attaches listeners to all inputs. As per the spec, + // this triggers a `statechange` event on MIDIAccess. + + }.bind(this), + + function (err) { + if (typeof callback === "function") { callback.call(this, err); } + }.bind(this) + + ); + + }; + + /** + * Completely disables `WebMidi` by unlinking the MIDI subsystem's interface and destroying all + * `Input` and `Output` objects that may be available. This also means that any listener(s) that + * may have been defined on `WebMidi` or any `Input` objects will be destroyed. + * + * @method disable + * @static + * + * @since 2.0.0 + */ + WebMidi.prototype.disable = function() { + + if ( !this.supported ) { + throw new Error("The Web MIDI API is not supported by your browser."); + } + + if (this.enabled) { + + this.removeListener(); + + this.inputs.forEach(function (input) { + input.removeListener(); + }); + + } + + if (this.interface) this.interface.onstatechange = undefined; + this.interface = undefined; // also resets enabled, sysexEnabled, nrpnEventsEnabled + this._inputs = []; + this._outputs = []; + this._nrpnEventsEnabled = true; + this._resetInterfaceUserHandlers(); + + }; + + /** + * Adds an event listener on the `WebMidi` object that will trigger a function callback when the + * specified event happens. + * + * WebMidi must be enabled before adding event listeners. + * + * Currently, only one event is being dispatched by the `WebMidi` object: + * + * * {{#crossLink "WebMidi/statechange:event"}}statechange{{/crossLink}} + * + * @method addListener + * @static + * @chainable + * + * @param type {String} The type of the event. + * + * @param listener {Function} A callback function to execute when the specified event is detected. + * This function will receive an event parameter object. For details on this object"s properties, + * check out the documentation for the various events (links above). + * + * @throws {Error} WebMidi must be enabled before adding event listeners. + * @throws {TypeError} The specified event type is not supported. + * @throws {TypeError} The "listener" parameter must be a function. + * + * @return {WebMidi} Returns the `WebMidi` object so methods can be chained. + */ + WebMidi.prototype.addListener = function(type, listener) { + + if (!this.enabled) { + throw new Error("WebMidi must be enabled before adding event listeners."); + } + + if (typeof listener !== "function") { + throw new TypeError("The 'listener' parameter must be a function."); + } + + if (this._midiInterfaceEvents.indexOf(type) >= 0) { + this._userHandlers[type].push(listener); + } else { + throw new TypeError("The specified event type is not supported."); + } + + return this; + + }; + + /** + * Checks if the specified event type is already defined to trigger the specified listener + * function. + * + * @method hasListener + * @static + * + * @param {String} type The type of the event. + * @param {Function} listener The callback function to check for. + * + * @throws {Error} WebMidi must be enabled before checking event listeners. + * @throws {TypeError} The "listener" parameter must be a function. + * @throws {TypeError} The specified event type is not supported. + * + * @return {Boolean} Boolean value indicating whether or not a callback is already defined for + * this event type. + */ + WebMidi.prototype.hasListener = function(type, listener) { + + if (!this.enabled) { + throw new Error("WebMidi must be enabled before checking event listeners."); + } + + if (typeof listener !== "function") { + throw new TypeError("The 'listener' parameter must be a function."); + } + + if (this._midiInterfaceEvents.indexOf(type) >= 0) { + + for (var o = 0; o < this._userHandlers[type].length; o++) { + if (this._userHandlers[type][o] === listener) { + return true; + } + } + + } else { + throw new TypeError("The specified event type is not supported."); + } + + return false; + + }; + + /** + * Removes the specified listener(s). If the `listener` parameter is left undefined, all listeners + * for the specified `type` will be removed. If both the `listener` and the `type` parameters are + * omitted, all listeners attached to the `WebMidi` object will be removed. + * + * @method removeListener + * @static + * @chainable + * + * @param {String} [type] The type of the event. + * @param {Function} [listener] The callback function to check for. + * + * @throws {Error} WebMidi must be enabled before removing event listeners. + * @throws {TypeError} The "listener" parameter must be a function. + * @throws {TypeError} The specified event type is not supported. + * + * @return {WebMidi} The `WebMidi` object for easy method chaining. + */ + WebMidi.prototype.removeListener = function(type, listener) { + + if (!this.enabled) { + throw new Error("WebMidi must be enabled before removing event listeners."); + } + + if (listener !== undefined && typeof listener !== "function") { + throw new TypeError("The 'listener' parameter must be a function."); + } + + if (this._midiInterfaceEvents.indexOf(type) >= 0) { + + if (listener) { + + for (var o = 0; o < this._userHandlers[type].length; o++) { + if (this._userHandlers[type][o] === listener) { + this._userHandlers[type].splice(o, 1); + } + } + + } else { + this._userHandlers[type] = []; + } + + } else if (type === undefined) { + + this._resetInterfaceUserHandlers(); + + } else { + throw new TypeError("The specified event type is not supported."); + } + + return this; + + }; + + /** + * Returns a sanitized array of valid MIDI channel numbers (1-16). The parameter should be one of + * the following: + * + * * a single integer + * * an array of integers + * * the special value `"all"` + * * the special value `"none"` + * + * Passing `"all"` or `undefined` as a parameter to this function results in all channels being + * returned (1-16). Passing `"none"` results in no channel being returned (as an empty array). + * + * Note: parameters that cannot successfully be parsed to integers between 1 and 16 are silently + * ignored. + * + * @method toMIDIChannels + * @static + * + * @param [channel="all"] {Number|Array|"all"|"none"} + * @returns {Array} An array of 0 or more valid MIDI channel numbers + */ + WebMidi.prototype.toMIDIChannels = function(channel) { + + var channels; + + if (channel === "all" || channel === undefined) { + channels = ["all"]; + } else if (channel === "none") { + channels = []; + return channels; + } else if (!Array.isArray(channel)) { + channels = [channel]; + } else { + channels = channel; + } + + // In order to preserve backwards-compatibility, we let this assignment as it is. + if (channels.indexOf("all") > -1) { + channels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + } + + return channels + .map(function(ch) { + return parseInt(ch); + }) + .filter(function(ch) { + return (ch >= 1 && ch <= 16); + }); + + }; + + /** + * + * Returns the `Input` object that matches the specified ID string or `false` if no matching input + * is found. As per the Web MIDI API specification, IDs are strings (not integers). + * + * Please note that IDs change from one host to another. For example, Chrome does not use the same + * kind of IDs as Jazz-Plugin. + * + * @method getInputById + * @static + * + * @param id {String} The ID string of the port. IDs can be viewed by looking at the + * `WebMidi.inputs` array. + * + * @returns {Input|false} A MIDIInput port matching the specified ID string. If no matching port + * can be found, the method returns `false`. + * + * @throws Error WebMidi is not enabled. + * + * @since 2.0.0 + */ + WebMidi.prototype.getInputById = function(id) { + + if (!this.enabled) throw new Error("WebMidi is not enabled."); + + id = String(id); + + for (var i = 0; i < this.inputs.length; i++) { + if (this.inputs[i].id === id) return this.inputs[i]; + } + + return false; + + }; + + /** + * Returns the `Output` object that matches the specified ID string or `false` if no matching + * output is found. As per the Web MIDI API specification, IDs are strings (not integers). + * + * Please note that IDs change from one host to another. For example, Chrome does not use the same + * kind of IDs as Jazz-Plugin. + * + * @method getOutputById + * @static + * + * @param id {String} The ID string of the port. IDs can be viewed by looking at the + * `WebMidi.outputs` array. + * + * @returns {Output|false} A MIDIOutput port matching the specified ID string. If no matching port + * can be found, the method returns `false`. + * + * @throws Error WebMidi is not enabled. + * + * @since 2.0.0 + */ + WebMidi.prototype.getOutputById = function(id) { + + if (!this.enabled) throw new Error("WebMidi is not enabled."); + + id = String(id); + + for (var i = 0; i < this.outputs.length; i++) { + if (this.outputs[i].id === id) return this.outputs[i]; + } + + return false; + + }; + + /** + * Returns the first MIDI `Input` whose name *contains* the specified string. + * + * Please note that the port names change from one host to another. For example, Chrome does + * not report port names in the same way as the Jazz-Plugin does. + * + * @method getInputByName + * @static + * + * @param name {String} The name of a MIDI input port such as those visible in the + * `WebMidi.inputs` array. + * + * @returns {Input|False} The `Input` that was found or `false` if no input matched the specified + * name. + * + * @throws Error WebMidi is not enabled. + * @throws TypeError The name must be a string. + * + * @since 2.0.0 + */ + WebMidi.prototype.getInputByName = function(name) { + + if (!this.enabled) { + throw new Error("WebMidi is not enabled."); + } + + for (var i = 0; i < this.inputs.length; i++) { + if (~this.inputs[i].name.indexOf(name)) { return this.inputs[i]; } + } + + return false; + + }; + + /** + * Returns the octave number for the specified MIDI note number (0-127). By default, the value is + * based on middle C (note number 60) being placed on the 4th octave (C4). However, by using the + * octaveOffset property, you can offset the result as much + * as you want. + * + * @method getOctave + * @static + * + * @param number {Number} An integer representing a valid MIDI note number (between 0 and 127). + * + * @returns {Number} The octave (as a signed integer) or `undefined`. + * + * @since 2.0.0-rc.6 + */ + WebMidi.prototype.getOctave = function(number) { + + if (number != null && number >= 0 && number <= 127) { + return Math.floor(Math.floor(number) / 12 - 1) + Math.floor(wm.octaveOffset); + } + + }; + + /** + * Returns the first MIDI `Output` that matches the specified name. + * + * Please note that the port names change from one host to another. For example, Chrome does + * not report port names in the same way as the Jazz-Plugin does. + * + * @method getOutputByName + * @static + * + * @param name {String} The name of a MIDI output port such as those visible in the + * `WebMidi.outputs` array. + * + * @returns {Output|False} The `Output` that was found or `false` if no output matched the + * specified name. + * + * @throws Error WebMidi is not enabled. + * + * @since 2.0.0 + */ + WebMidi.prototype.getOutputByName = function(name) { + + if (!this.enabled) { + throw new Error("WebMidi is not enabled."); + } + + for (var i = 0; i < this.outputs.length; i++) { + if (~this.outputs[i].name.indexOf(name)) { return this.outputs[i]; } + } + + return false; + + }; + + /** + * Returns a valid MIDI note number (0-127) given the specified input. The input usually is a note + * name (C3, F#4, D-2, G8, etc.). If an integer between 0 and 127, it will simply be returned as + * is. + * + * @method guessNoteNumber + * @static + * + * @param input {Number|String} A string to extract the note number from. An integer can also be + * used, in which case it will simply be returned (if between 0 and 127). + * @throws {Error} Invalid input value + * @returns {Number} A valid MIDI note number (0-127). + */ + WebMidi.prototype.guessNoteNumber = function(input) { + + var output = false; + + if (input && input.toFixed && input >= 0 && input <= 127) { // uint + output = Math.round(input); + } else if (parseInt(input) >= 0 && parseInt(input) <= 127) { // uint as string + output = parseInt(input); + } else if (typeof input === "string" || input instanceof String) { // string + output = this.noteNameToNumber(input); + } + + if (output === false) throw new Error("Invalid input value (" + input + ")."); + return output; + + }; + + /** + * Returns a MIDI note number matching the note name passed in the form of a string parameter. The + * note name must include the octave number. The name can also optionally include a sharp (#), + * a double sharp (##), a flat (b) or a double flat (bb) symbol: C5, G4, D#-1, F0, Gb7, Eb-1, + * Abb4, B##6, etc. + * + * Note that, in converting note names to numbers, C4 is considered to be middle C (MIDI note + * number 60) as per the scientific pitch notation standard. + * + * Also note that the resulting note number is offset by the `octaveOffset` value (if not zero). + * For example, if you pass in "C4" and the `octaveOffset` value is 2 the resulting MIDI note + * number will be 36. + * + * @method noteNameToNumber + * @static + * + * @param name {String} The name of the note in the form of a letter, followed by an optional "#", + * "##", "b" or "bb" followed by the octave number. + * + * @throws {RangeError} Invalid note name. + * @throws {RangeError} Invalid note name or note outside valid range. + * @return {Number} The MIDI note number (between 0 and 127) + */ + WebMidi.prototype.noteNameToNumber = function(name) { + + if (typeof name !== "string") name = ""; + + var matches = name.match(/([CDEFGAB])(#{0,2}|b{0,2})(-?\d+)/i); + if(!matches) throw new RangeError("Invalid note name."); + + var semitones = wm._semitones[matches[1].toUpperCase()]; + var octave = parseInt(matches[3]); + var result = ((octave + 1 - Math.floor(wm.octaveOffset)) * 12) + semitones; + + + if (matches[2].toLowerCase().indexOf("b") > -1) { + result -= matches[2].length; + } else if (matches[2].toLowerCase().indexOf("#") > -1) { + result += matches[2].length; + } + + if (result < 0 || result > 127) { + throw new RangeError("Invalid note name or note outside valid range."); + } + + return result; + + }; + + /** + * @method _updateInputsAndOutputs + * @static + * @protected + */ + WebMidi.prototype._updateInputsAndOutputs = function() { + this._updateInputs(); + this._updateOutputs(); + }; + + /** + * @method _updateInputs + * @static + * @protected + */ + WebMidi.prototype._updateInputs = function() { + + // Check for items to remove from the existing array (because they are no longer being reported + // by the MIDI back-end). + for (var i = 0; i < this._inputs.length; i++) { + + var remove = true; + + var updated = this.interface.inputs.values(); + for (var input = updated.next(); input && !input.done; input = updated.next()) { + if (this._inputs[i]._midiInput === input.value) { + remove = false; + break; + } + } + + if (remove) { + this._inputs.splice(i, 1); + } + + } + + // Check for items to add in the existing inputs array because they just appeared in the MIDI + // back-end inputs list. We must check for the existence of this.interface because it might + // have been closed via WebMidi.disable(). + this.interface && this.interface.inputs.forEach(function (nInput) { + + var add = true; + + for (var j = 0; j < this._inputs.length; j++) { + if (this._inputs[j]._midiInput === nInput) { + add = false; + } + } + + if (add) { + this._inputs.push( new Input(nInput) ); + } + + }.bind(this)); + + }; + + /** + * @method _updateOutputs + * @static + * @protected + */ + WebMidi.prototype._updateOutputs = function() { + + // Check for items to remove from the existing array (because they are no longer being reported + // by the MIDI back-end). + for (var i = 0; i < this._outputs.length; i++) { + + var remove = true; + + var updated = this.interface.outputs.values(); + for (var output = updated.next(); output && !output.done; output = updated.next()) { + if (this._outputs[i]._midiOutput === output.value) { + remove = false; + break; + } + } + + if (remove) { + this._outputs.splice(i, 1); + } + + } + + // Check for items to add in the existing inputs array because they just appeared in the MIDI + // back-end outputs list. We must check for the existence of this.interface because it might + // have been closed via WebMidi.disable(). + this.interface && this.interface.outputs.forEach(function (nOutput) { + + var add = true; + + for (var j = 0; j < this._outputs.length; j++) { + if (this._outputs[j]._midiOutput === nOutput) { + add = false; + } + } + + if (add) { + this._outputs.push( new Output(nOutput) ); + } + + }.bind(this)); + + }; + + /** + * @method _onInterfaceStateChange + * @static + * @protected + */ + WebMidi.prototype._onInterfaceStateChange = function(e) { + + this._updateInputsAndOutputs(); + + /** + * Event emitted when a MIDI port becomes available. This event is typically fired whenever a + * MIDI device is plugged in. Please note that it may fire several times if a device possesses + * multiple input/output ports. + * + * @event connected + * @param {Object} event + * @param {Number} event.timestamp The timestamp when the event occurred (in milliseconds since + * the epoch). + * @param {String} event.type The type of event that occurred. + * @param {String} event.port The actual `Input` or `Output` object associated to the event. + */ + + /** + * Event emitted when a MIDI port becomes unavailable. This event is typically fired whenever a + * MIDI device is unplugged. Please note that it may fire several times if a device possesses + * multiple input/output ports. + * + * @event disconnected + * @param {Object} event + * @param {Number} event.timestamp The timestamp when the event occurred (in milliseconds since + * the epoch). + * @param {String} event.type The type of event that occurred. + * @param {String} event.port An generic object containing details about the port that triggered + * the event. + */ + var event = { + timestamp: e.timeStamp, + type: e.port.state + }; + + if (this.interface && e.port.state === "connected") { + + if (e.port.type === "output") { + event.port = this.getOutputById(e.port.id); + } else if (e.port.type === "input") { + event.port = this.getInputById(e.port.id); + } + + } else { + + event.port = { + connection: "closed", + id: e.port.id, + manufacturer: e.port.manufacturer, + name: e.port.name, + state: e.port.state, + type: e.port.type + }; + + } + + this._userHandlers[e.port.state].forEach(function (handler) { + handler(event); + }); + + }; + + /** + * @method _resetInterfaceUserHandlers + * @static + * @protected + */ + WebMidi.prototype._resetInterfaceUserHandlers = function() { + + for (var i = 0; i < this._midiInterfaceEvents.length; i++) { + this._userHandlers[this._midiInterfaceEvents[i]] = []; + } + + }; + + /** + * The `Input` object represents a MIDI input port on the host system. This object is created by + * the MIDI subsystem and cannot be instantiated directly. + * + * You will find all available `Input` objects in the `WebMidi.inputs` array. + * + * @class Input + * @param {MIDIInput} midiInput `MIDIInput` object + */ + function Input(midiInput) { + + var that = this; + + // User-defined handlers list + this._userHandlers = { channel: {}, system: {} }; + + // Reference to the actual MIDIInput object + this._midiInput = midiInput; + + Object.defineProperties(this, { + + /** + * [read-only] Status of the MIDI port"s connection (`pending`, `open` or `closed`) + * + * @property connection + * @type String + */ + connection: { + enumerable: true, + get: function () { + return that._midiInput.connection; + } + }, + + /** + * [read-only] ID string of the MIDI port. The ID is host-specific. Do not expect the same ID + * on different platforms. For example, Google Chrome and the Jazz-Plugin report completely + * different IDs for the same port. + * + * @property id + * @type String + */ + id: { + enumerable: true, + get: function () { + return that._midiInput.id; + } + }, + + /** + * [read-only] Name of the manufacturer of the device that makes this port available. + * + * @property manufacturer + * @type String + */ + manufacturer: { + enumerable: true, + get: function () { + return that._midiInput.manufacturer; + } + }, + + /** + * [read-only] Name of the MIDI port + * + * @property name + * @type String + */ + name: { + enumerable: true, + get: function () { + return that._midiInput.name; + } + }, + + /** + * [read-only] State of the MIDI port (`connected` or `disconnected`) + * + * @property state + * @type String + */ + state: { + enumerable: true, + get: function () { + return that._midiInput.state; + } + }, + + /** + * [read-only] Type of the MIDI port (`input`) + * + * @property type + * @type String + */ + type: { + enumerable: true, + get: function () { + return that._midiInput.type; + } + } + + }); + + this._initializeUserHandlers(); + this._midiInput.onmidimessage = this._onMidiMessage.bind(this); + + } + + /** + * Adds an event listener to the `Input` that will trigger a function callback when the specified + * event happens. The events that are dispatched can be channel-specific or Input-wide. + * + * Here is a list of events that are dispatched by `Input` objects and that can be listened to. + * + * Channel-specific MIDI events: + * + * * {{#crossLink "Input/noteoff:event"}}noteoff{{/crossLink}} + * * {{#crossLink "Input/noteon:event"}}noteon{{/crossLink}} + * * {{#crossLink "Input/keyaftertouch:event"}}keyaftertouch{{/crossLink}} + * * {{#crossLink "Input/controlchange:event"}}controlchange{{/crossLink}} + * * {{#crossLink "Input/channelmode:event"}}channelmode{{/crossLink}} + * * {{#crossLink "Input/programchange:event"}}programchange{{/crossLink}} + * * {{#crossLink "Input/channelaftertouch:event"}}channelaftertouch{{/crossLink}} + * * {{#crossLink "Input/pitchbend:event"}}pitchbend{{/crossLink}} + * + * Input-wide MIDI events: + * + * * {{#crossLink "Input/sysex:event"}}sysex{{/crossLink}} + * * {{#crossLink "Input/timecode:event"}}timecode{{/crossLink}} + * * {{#crossLink "Input/songposition:event"}}songposition{{/crossLink}} + * * {{#crossLink "Input/songselect:event"}}songselect{{/crossLink}} + * * {{#crossLink "Input/tuningrequest:event"}}tuningrequest{{/crossLink}} + * * {{#crossLink "Input/clock:event"}}clock{{/crossLink}} + * * {{#crossLink "Input/start:event"}}start{{/crossLink}} + * * {{#crossLink "Input/continue:event"}}continue{{/crossLink}} + * * {{#crossLink "Input/stop:event"}}stop{{/crossLink}} + * * {{#crossLink "Input/activesensing:event"}}activesensing{{/crossLink}} + * * {{#crossLink "Input/reset:event"}}reset{{/crossLink}} + * * {{#crossLink "Input/midimessage:event"}}midimessage{{/crossLink}} + * * {{#crossLink "Input/unknownsystemmessage:event"}}unknownsystemmessage{{/crossLink}} + * + * For device-wide events, the `channel` parameter will be silently ignored. You can simply use + * `undefined` in that case. + * + * If you want to view all incoming MIDI traffic, you can listen to the input-wide `midimessage` + * event. This event is dispatched for every single message that is received on that input. + * + * @method addListener + * @chainable + * + * @param type {String} The type of the event. + * + * @param channel {Number|Array|String} The MIDI channel to listen on (integer between 1 and 16). + * You can also specify an array of channel numbers or the value "all" (or leave it undefined for + * input-wide events). + * + * @param listener {Function} A callback function to execute when the specified event is detected. + * This function will receive an event parameter object. For details on this object"s properties, + * check out the documentation for the various events (links above). + * + * @throws {RangeError} The "channel" parameter is invalid. + * @throws {TypeError} The "listener" parameter must be a function. + * @throws {TypeError} The specified event type is not supported. + * + * @return {WebMidi} Returns the `WebMidi` object so methods can be chained. + */ + Input.prototype.addListener = function(type, channel, listener) { + + var that = this; + + if (channel === undefined) { channel = "all"; } + if (!Array.isArray(channel)) { channel = [channel]; } + + // Check if channel entries are valid + channel.forEach(function(item){ + if (item !== "all" && !(item >= 1 && item <= 16)) { + throw new RangeError( + "The 'channel' parameter is invalid." + ); + } + }); + + if (typeof listener !== "function") { + throw new TypeError("The 'listener' parameter must be a function."); + } + + if (wm.MIDI_SYSTEM_MESSAGES[type] !== undefined) { + + if (!this._userHandlers.system[type]) this._userHandlers.system[type] = []; + this._userHandlers.system[type].push(listener); + + } else if (wm.MIDI_CHANNEL_MESSAGES[type] !== undefined) { + + // If "all" is present anywhere in the channel array, use all 16 channels + if (channel.indexOf("all") > -1) { + channel = []; + for (var j = 1; j <= 16; j++) { channel.push(j); } + } + + if (!this._userHandlers.channel[type]) { this._userHandlers.channel[type] = []; } + + // Push all channel listeners in the array + channel.forEach(function(ch){ + + if (!that._userHandlers.channel[type][ch]) { + that._userHandlers.channel[type][ch] = []; + } + + that._userHandlers.channel[type][ch].push(listener); + + }); + + } else { + throw new TypeError("The specified event type is not supported."); + } + + return this; + + }; + + /** + * This is an alias to the {{#crossLink "Input/addListener"}}Input.addListener(){{/crossLink}} + * function. + * + * @method on + * @since 2.0.0 + */ + Input.prototype.on = Input.prototype.addListener; + + /** + * Checks if the specified event type is already defined to trigger the listener function on the + * specified channel(s). If more than one channel is specified, the function will return `true` + * only if all channels have the listener defined. + * + * For device-wide events (`sysex`, `start`, etc.), the `channel` parameter is silently ignored. + * We suggest you use `undefined` in such cases. + * + * @method hasListener + * + * @param type {String} The type of the event. + * @param channel {Number|Array|String} The MIDI channel to check on (between 1 and 16). You + * can also specify an array of channel numbers or the string "all". + * @param listener {Function} The callback function to check for. + * + * @throws {TypeError} The "listener" parameter must be a function. + * + * @return {Boolean} Boolean value indicating whether or not the channel(s) already have this + * listener defined. + */ + Input.prototype.hasListener = function(type, channel, listener) { + + var that = this; + + if (typeof listener !== "function") { + throw new TypeError("The 'listener' parameter must be a function."); + } + + if (channel === undefined) { channel = "all"; } + if (channel.constructor !== Array) { channel = [channel]; } + + if (wm.MIDI_SYSTEM_MESSAGES[type] !== undefined) { + + for (var o = 0; o < this._userHandlers.system[type].length; o++) { + if (this._userHandlers.system[type][o] === listener) { return true; } + } + + } else if (wm.MIDI_CHANNEL_MESSAGES[type] !== undefined) { + + // If "all" is present anywhere in the channel array, use all 16 channels + if (channel.indexOf("all") > -1) { + channel = []; + for (var j = 1; j <= 16; j++) { channel.push(j); } + } + + if (!this._userHandlers.channel[type]) { return false; } + + // Go through all specified channels + return channel.every(function(chNum) { + var listeners = that._userHandlers.channel[type][chNum]; + return listeners && listeners.indexOf(listener) > -1; + }); + + } + + return false; + + }; + + /** + * Removes the specified listener from the specified channel(s). If the `listener` parameter is + * left undefined, all listeners for the specified `type` will be removed from all channels. If + * the `channel` is also omitted, all listeners of the specified type will be removed from all + * channels. If no parameters are defined, all listeners attached to any channel of the `Input` + * will be removed. + * + * For device-wide events (`sysex`, `start`, etc.), the `channel` parameter is silently ignored. + * You can use `undefined` in such cases. + * + * @method removeListener + * @chainable + * + * @param [type] {String} The type of the event. + * @param [channel] {Number|String|Array} The MIDI channel(s) to check on. It can be a uint + * (between 1 and 16) an array of channel numbers or the special value "all". + * @param [listener] {Function} The callback function to check for. + * + * @throws {TypeError} The specified event type is not supported. + * @throws {TypeError} The "listener" parameter must be a function.. + * + * @return {Input} The `Input` object for easy method chaining. + */ + Input.prototype.removeListener = function(type, channel, listener) { + + var that = this; + + if (listener !== undefined && typeof listener !== "function") { + throw new TypeError("The 'listener' parameter must be a function."); + } + + if (channel === undefined) { channel = "all"; } + if (channel.constructor !== Array) { channel = [channel]; } + + if (wm.MIDI_SYSTEM_MESSAGES[type] !== undefined) { + + if (listener === undefined) { + + this._userHandlers.system[type] = []; + + } else { + + for (var o = 0; o < this._userHandlers.system[type].length; o++) { + if (this._userHandlers.system[type][o] === listener) { + this._userHandlers.system[type].splice(o, 1); + } + } + + } + + } else if (wm.MIDI_CHANNEL_MESSAGES[type] !== undefined) { + + // If "all" is present anywhere in the channel array, use all 16 channels + if (channel.indexOf("all") > -1) { + channel = []; + for (var j = 1; j <= 16; j++) { channel.push(j); } + } + + if (!this._userHandlers.channel[type]) { return this; } + + // Go through all specified channels + channel.forEach(function(chNum) { + var listeners = that._userHandlers.channel[type][chNum]; + if (!listeners) { return; } + + if (listener === undefined) { + that._userHandlers.channel[type][chNum] = []; + } else { + for (var l = 0; l < listeners.length; l++) { + if (listeners[l] === listener) { listeners.splice(l, 1); } + } + } + + }); + + } else if (type === undefined) { + this._initializeUserHandlers(); + } else { + throw new TypeError("The specified event type is not supported."); + } + + return this; + + }; + + /** + * @method _initializeUserHandlers + * @protected + */ + Input.prototype._initializeUserHandlers = function() { + + for (var prop1 in wm.MIDI_CHANNEL_MESSAGES) { + if (Object.prototype.hasOwnProperty.call(wm.MIDI_CHANNEL_MESSAGES, prop1)) { + this._userHandlers.channel[prop1] = {}; + } + } + + for (var prop2 in wm.MIDI_SYSTEM_MESSAGES) { + if (Object.prototype.hasOwnProperty.call(wm.MIDI_SYSTEM_MESSAGES, prop2)) { + this._userHandlers.system[prop2] = []; + } + } + + }; + + /** + * @method _onMidiMessage + * @protected + */ + Input.prototype._onMidiMessage = function(e) { + + // Execute "midimessage" listeners (if any) + if (this._userHandlers.system["midimessage"].length > 0) { + + var event = { + target: this, + data: e.data, + timestamp: e.timeStamp, + type: "midimessage" + }; + + /** + * Event emitted when a MIDI message is received. This should be used primarily for debugging + * purposes. + * + * @event midimessage + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit values. + * @param {uint} event.timestamp The timestamp when the event occurred (in milliseconds since + * the [Unix Epoch](https://en.wikipedia.org/wiki/Unix_time)). + * @param {String} event.type The type of event that occurred. + * @since 2.1 + */ + this._userHandlers.system["midimessage"].forEach( + function(callback) { callback(event); } + ); + + } + + if (e.data[0] < 240) { // channel-specific message + this._parseChannelEvent(e); + this._parseNrpnEvent(e); + } else if (e.data[0] <= 255) { // system message + this._parseSystemEvent(e); + } + + }; + + /** + * Parses channel events and constructs NRPN message parts in valid sequences. + * Keeps a separate NRPN buffer for each channel. + * Emits an event after it receives the final CC parts msb 127 lsb 127. + * If a message is incomplete and other messages are received before + * the final 127 bytes, the incomplete message is cleared. + * @method _parseNrpnEvent + * @param e Event + * @protected + */ + Input.prototype._parseNrpnEvent = function(e) { + + var command = e.data[0] >> 4; + var channelBufferIndex = (e.data[0] & 0xf); // use this for index of channel in _nrpnBuffer + var channel = channelBufferIndex + 1; + var data1, data2; + + if (e.data.length > 1) { + data1 = e.data[1]; + data2 = e.data.length > 2 ? e.data[2] : undefined; + } + + // nrpn disabled + if(!wm.nrpnEventsEnabled) { + return; + } + + // nrpn enabled, message not valid for nrpn + if( + !( + command === wm.MIDI_CHANNEL_MESSAGES.controlchange && + ( + (data1 >= wm.MIDI_NRPN_MESSAGES.increment && data1 <= wm.MIDI_NRPN_MESSAGES.parammsb) || + data1 === wm.MIDI_NRPN_MESSAGES.entrymsb || + data1 === wm.MIDI_NRPN_MESSAGES.entrylsb + ) + ) + ) { + return; + } + + // set up a CC event to parse as NRPN part + var ccEvent = { + target: this, + type: "controlchange", + data: e.data, + timestamp: e.timeStamp, + channel: channel, + controller: { + number: data1, + name: this.getCcNameByNumber(data1) + }, + value: data2 + }; + if( + // if we get a starting MSB(CC99 - 0-126) vs an end MSB(CC99 - 127) + // destroy inclomplete NRPN and begin building again + ccEvent.controller.number === wm.MIDI_NRPN_MESSAGES.parammsb && + ccEvent.value != wm.MIDI_NRPN_MESSAGES.nullactiveparameter + ) { + wm._nrpnBuffer[channelBufferIndex] = []; + wm._nrpnBuffer[channelBufferIndex][0] = ccEvent; + } else if( + // add the param LSB + wm._nrpnBuffer[channelBufferIndex].length === 1 && + ccEvent.controller.number === wm.MIDI_NRPN_MESSAGES.paramlsb + ) { + wm._nrpnBuffer[channelBufferIndex].push(ccEvent); + + } else if( + // add data inc/dec or value MSB for 14bit + wm._nrpnBuffer[channelBufferIndex].length === 2 && + (ccEvent.controller.number === wm.MIDI_NRPN_MESSAGES.increment || + ccEvent.controller.number === wm.MIDI_NRPN_MESSAGES.decrement || + ccEvent.controller.number === wm.MIDI_NRPN_MESSAGES.entrymsb) + ) { + wm._nrpnBuffer[channelBufferIndex].push(ccEvent); + + } else if( + // if we have a value MSB, only add an LSB to pair with that + wm._nrpnBuffer[channelBufferIndex].length === 3 && + wm._nrpnBuffer[channelBufferIndex][2].number === wm.MIDI_NRPN_MESSAGES.entrymsb && + ccEvent.controller.number === wm.MIDI_NRPN_MESSAGES.entrylsb + ) { + wm._nrpnBuffer[channelBufferIndex].push(ccEvent); + + } else if( + // add an end MSB(CC99 - 127) + wm._nrpnBuffer[channelBufferIndex].length >= 3 && + wm._nrpnBuffer[channelBufferIndex].length <= 4 && + ccEvent.controller.number === wm.MIDI_NRPN_MESSAGES.parammsb && + ccEvent.value === wm.MIDI_NRPN_MESSAGES.nullactiveparameter + ) { + wm._nrpnBuffer[channelBufferIndex].push(ccEvent); + + } else if( + // add an end LSB(CC99 - 127) + wm._nrpnBuffer[channelBufferIndex].length >= 4 && + wm._nrpnBuffer[channelBufferIndex].length <= 5 && + ccEvent.controller.number === wm.MIDI_NRPN_MESSAGES.paramlsb && + ccEvent.value === wm.MIDI_NRPN_MESSAGES.nullactiveparameter + ) { + wm._nrpnBuffer[channelBufferIndex].push(ccEvent); + // now we have a full inc or dec NRPN message, lets create that event! + + var rawData = []; + + wm._nrpnBuffer[channelBufferIndex].forEach(function(ev) { + rawData.push(ev.data); + }); + + var nrpnNumber = (wm._nrpnBuffer[channelBufferIndex][0].value<<7) | + (wm._nrpnBuffer[channelBufferIndex][1].value); + var nrpnValue = wm._nrpnBuffer[channelBufferIndex][2].value; + if(wm._nrpnBuffer[channelBufferIndex].length === 6) { + nrpnValue = (wm._nrpnBuffer[channelBufferIndex][2].value<<7) | + (wm._nrpnBuffer[channelBufferIndex][3].value); + } + var nrpnControllerType = ""; + switch (wm._nrpnBuffer[channelBufferIndex][2].controller.number) { + case wm.MIDI_NRPN_MESSAGES.entrymsb: + nrpnControllerType = wm._nrpnTypes[0]; + break; + case wm.MIDI_NRPN_MESSAGES.increment: + nrpnControllerType = wm._nrpnTypes[1]; + break; + case wm.MIDI_NRPN_MESSAGES.decrement: + nrpnControllerType = wm._nrpnTypes[2]; + break; + default: + throw new Error("The NPRN type was unidentifiable."); + } + + /** + * Event emitted when a valid NRPN message sequence has been received on a specific device and + * channel. + * + * @private + * + * @event nrpn + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Array} event.data The raw MIDI message as arrays of 8 bit values( Uint8Array ). + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {uint} event.channel The channel where the event occurred (between 1 and 16). + * @param {String} event.type The type of event that occurred. + * @param {Object} event.controller + * @param {uint} event.controller.number The number of the NRPN. + * @param {String} event.controller.name The usual name or function of the controller. + * @param {uint} event.value The value received (between 0 and 65535). + */ + + var nrpnEvent = { + timestamp: ccEvent.timestamp, + channel: ccEvent.channel, + type: "nrpn", + data: rawData, + controller: { + number: nrpnNumber, + type: nrpnControllerType, + name: "Non-Registered Parameter " + nrpnNumber + }, + value: nrpnValue + }; + + // now we are done building an NRPN, so clear the NRPN buffer for this channel + wm._nrpnBuffer[channelBufferIndex] = []; + // If some callbacks have been defined for this event, on that device and channel, execute + // them. + if ( + this._userHandlers.channel[nrpnEvent.type] && + this._userHandlers.channel[nrpnEvent.type][nrpnEvent.channel] + ) { + this._userHandlers.channel[nrpnEvent.type][nrpnEvent.channel].forEach( + function(callback) { callback(nrpnEvent); } + ); + } + } else { + // something didn't match, clear the incomplete NRPN message by + wm._nrpnBuffer[channelBufferIndex] = []; + } + }; + + /** + * @method _parseChannelEvent + * @param e Event + * @protected + */ + Input.prototype._parseChannelEvent = function(e) { + + var command = e.data[0] >> 4; + var channel = (e.data[0] & 0xf) + 1; + var data1, data2; + + if (e.data.length > 1) { + data1 = e.data[1]; + data2 = e.data.length > 2 ? e.data[2] : undefined; + } + + // Returned event + var event = { + target: this, + data: e.data, + timestamp: e.timeStamp, + channel: channel + }; + + if ( + command === wm.MIDI_CHANNEL_MESSAGES.noteoff || + (command === wm.MIDI_CHANNEL_MESSAGES.noteon && data2 === 0) + ) { + + /** + * Event emitted when a note off MIDI message has been received on a specific device and + * channel. + * + * @event noteoff + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {uint} event.channel The channel where the event occurred (between 1 and 16). + * @param {String} event.type The type of event that occurred. + * @param {Object} event.note + * @param {uint} event.note.number The MIDI note number. + * @param {String} event.note.name The usual note name (C, C#, D, D#, etc.). + * @param {uint} event.note.octave The octave (between -2 and 8). + * @param {Number} event.velocity The release velocity (between 0 and 1). + * @param {Number} event.rawVelocity The attack velocity expressed as a 7-bit integer (between + * 0 and 127). + */ + event.type = "noteoff"; + event.note = { + number: data1, + name: wm._notes[data1 % 12], + octave: wm.getOctave(data1) + }; + event.velocity = data2 / 127; + event.rawVelocity = data2; + + } else if (command === wm.MIDI_CHANNEL_MESSAGES.noteon) { + + /** + * Event emitted when a note on MIDI message has been received on a specific device and + * channel. + * + * @event noteon + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {uint} event.channel The channel where the event occurred (between 1 and 16). + * @param {String} event.type The type of event that occurred. + * @param {Object} event.note + * @param {uint} event.note.number The MIDI note number. + * @param {String} event.note.name The usual note name (C, C#, D, D#, etc.). + * @param {uint} event.note.octave The octave (between -2 and 8). + * @param {Number} event.velocity The attack velocity (between 0 and 1). + * @param {Number} event.rawVelocity The attack velocity expressed as a 7-bit integer (between + * 0 and 127). + */ + event.type = "noteon"; + event.note = { + number: data1, + name: wm._notes[data1 % 12], + octave: wm.getOctave(data1) + }; + event.velocity = data2 / 127; + event.rawVelocity = data2; + + } else if (command === wm.MIDI_CHANNEL_MESSAGES.keyaftertouch) { + + /** + * Event emitted when a key-specific aftertouch MIDI message has been received on a specific + * device and channel. + * + * @event keyaftertouch + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {uint} event.channel The channel where the event occurred (between 1 and 16). + * @param {String} event.type The type of event that occurred. + * @param {Object} event.note + * @param {uint} event.note.number The MIDI note number. + * @param {String} event.note.name The usual note name (C, C#, D, D#, etc.). + * @param {uint} event.note.octave The octave (between -2 and 8). + * @param {Number} event.value The aftertouch amount (between 0 and 1). + */ + event.type = "keyaftertouch"; + event.note = { + number: data1, + name: wm._notes[data1 % 12], + octave: wm.getOctave(data1) + }; + event.value = data2 / 127; + + } else if ( + command === wm.MIDI_CHANNEL_MESSAGES.controlchange && + data1 >= 0 && data1 <= 119 + ) { + + /** + * Event emitted when a control change MIDI message has been received on a specific device and + * channel. + * + * @event controlchange + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {uint} event.channel The channel where the event occurred (between 1 and 16). + * @param {String} event.type The type of event that occurred. + * @param {Object} event.controller + * @param {uint} event.controller.number The number of the controller. + * @param {String} event.controller.name The usual name or function of the controller. + * @param {uint} event.value The value received (between 0 and 127). + */ + event.type = "controlchange"; + event.controller = { + number: data1, + name: this.getCcNameByNumber(data1) + }; + event.value = data2; + + } else if ( + command === wm.MIDI_CHANNEL_MESSAGES.channelmode && + data1 >= 120 && data1 <= 127 + ) { + + /** + * Event emitted when a channel mode MIDI message has been received on a specific device and + * channel. + * + * @event channelmode + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {uint} event.channel The channel where the event occurred (between 1 and 16). + * @param {String} event.type The type of event that occurred. + * @param {Object} event.controller + * @param {uint} event.controller.number The number of the controller. + * @param {String} event.controller.name The usual name or function of the controller. + * @param {uint} event.value The value received (between 0 and 127). + */ + event.type = "channelmode"; + event.controller = { + number: data1, + name: this.getChannelModeByNumber(data1) + }; + event.value = data2; + + } else if (command === wm.MIDI_CHANNEL_MESSAGES.programchange) { + + /** + * Event emitted when a program change MIDI message has been received on a specific device and + * channel. + * + * @event programchange + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {uint} event.channel The channel where the event occurred (between 1 and 16). + * @param {String} event.type The type of event that occurred. + * @param {uint} event.value The value received (between 0 and 127). + */ + event.type = "programchange"; + event.value = data1; + + } else if (command === wm.MIDI_CHANNEL_MESSAGES.channelaftertouch) { + + /** + * Event emitted when a channel-wide aftertouch MIDI message has been received on a specific + * device and channel. + * + * @event channelaftertouch + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {uint} event.channel The channel where the event occurred (between 1 and 16). + * @param {String} event.type The type of event that occurred. + * @param {Number} event.value The aftertouch value received (between 0 and 1). + */ + event.type = "channelaftertouch"; + event.value = data1 / 127; + + } else if (command === wm.MIDI_CHANNEL_MESSAGES.pitchbend) { + + /** + * Event emitted when a pitch bend MIDI message has been received on a specific device and + * channel. + * + * @event pitchbend + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {uint} event.channel The channel where the event occurred (between 1 and 16). + * @param {String} event.type The type of event that occurred. + * @param {Number} event.value The pitch bend value received (between -1 and 1). + */ + event.type = "pitchbend"; + event.value = ((data2 << 7) + data1 - 8192) / 8192; + } else { + event.type = "unknownchannelmessage"; + } + + // If some callbacks have been defined for this event, on that device and channel, execute them. + if ( + this._userHandlers.channel[event.type] && + this._userHandlers.channel[event.type][channel] + ) { + + this._userHandlers.channel[event.type][channel].forEach( + function(callback) { callback(event); } + ); + } + + }; + + /** + * Returns the name of a control change message matching the specified number. If no match is + * found, the function returns `undefined`. + * + * @method getCcNameByNumber + * + * @param number {Number} The number of the control change message. + * @returns {String|undefined} The matching control change name or `undefined`. + * + * @throws RangeError The control change number must be between 0 and 119. + * + * @since 2.0.0 + */ + Input.prototype.getCcNameByNumber = function(number) { + + number = Math.floor(number); + + if ( !(number >= 0 && number <= 119) ) { + throw new RangeError("The control change number must be between 0 and 119."); + } + + for (var cc in wm.MIDI_CONTROL_CHANGE_MESSAGES) { + + if ( + Object.prototype.hasOwnProperty.call(wm.MIDI_CONTROL_CHANGE_MESSAGES, cc) && + number === wm.MIDI_CONTROL_CHANGE_MESSAGES[cc] + ) { + return cc; + } + + } + + return undefined; + + }; + + /** + * Returns the channel mode name matching the specified number. If no match is found, the function + * returns `undefined`. + * + * @method getChannelModeByNumber + * + * @param number {Number} The number of the channel mode message. + * @returns {String|undefined} The matching channel mode message"s name or `undefined`; + * + * @throws RangeError The channel mode number must be between 120 and 127. + * + * @since 2.0.0 + */ + Input.prototype.getChannelModeByNumber = function(number) { + + number = Math.floor(number); + + if ( !(number >= 120 && status <= 127) ) { + throw new RangeError("The control change number must be between 120 and 127."); + } + + for (var cm in wm.MIDI_CHANNEL_MODE_MESSAGES) { + + if ( + Object.prototype.hasOwnProperty.call(wm.MIDI_CHANNEL_MODE_MESSAGES, cm) && + number === wm.MIDI_CHANNEL_MODE_MESSAGES[cm] + ) { + return cm; + } + + } + + }; + + /** + * @method _parseSystemEvent + * @protected + */ + Input.prototype._parseSystemEvent = function(e) { + + var command = e.data[0]; + + // Returned event + var event = { + target: this, + data: e.data, + timestamp: e.timeStamp + }; + + if (command === wm.MIDI_SYSTEM_MESSAGES.sysex) { + + /** + * Event emitted when a system exclusive MIDI message has been received. You should note that, + * to receive `sysex` events, you must call the `WebMidi.enable()` method with a second + * parameter set to `true`: + * + * WebMidi.enable(function(err) { + * + * if (err) { + * console.log("WebMidi could not be enabled."); + * } + * + * var input = WebMidi.inputs[0]; + * + * input.addListener("sysex", "all", function (e) { + * console.log(e); + * }); + * + * }, true); + * + * @event sysex + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {String} event.type The type of event that occurred. + * + */ + event.type = "sysex"; + + } else if (command === wm.MIDI_SYSTEM_MESSAGES.timecode) { + + /** + * Event emitted when a system MIDI time code quarter frame message has been received. + * + * @event timecode + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {String} event.type The type of event that occurred. + */ + event.type = "timecode"; + + } else if (command === wm.MIDI_SYSTEM_MESSAGES.songposition) { + + /** + * Event emitted when a system song position pointer MIDI message has been received. + * + * @event songposition + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {String} event.type The type of event that occurred. + */ + event.type = "songposition"; + + } else if (command === wm.MIDI_SYSTEM_MESSAGES.songselect) { + + /** + * Event emitted when a system song select MIDI message has been received. + * + * @event songselect + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {String} event.type The type of event that occurred. + * @param {String} event.song Song (or sequence) number to select. + */ + event.type = "songselect"; + event.song = e.data[1]; + + } else if (command === wm.MIDI_SYSTEM_MESSAGES.tuningrequest) { + + /** + * Event emitted when a system tune request MIDI message has been received. + * + * @event tuningrequest + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit + * values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {String} event.type The type of event that occurred. + */ + event.type = "tuningrequest"; + + } else if (command === wm.MIDI_SYSTEM_MESSAGES.clock) { + + /** + * Event emitted when a system timing clock MIDI message has been received. + * + * @event clock + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit + * values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {String} event.type The type of event that occurred. + */ + event.type = "clock"; + + } else if (command === wm.MIDI_SYSTEM_MESSAGES.start) { + + /** + * Event emitted when a system start MIDI message has been received. + * + * @event start + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit + * values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {String} event.type The type of event that occurred. + */ + event.type = "start"; + + } else if (command === wm.MIDI_SYSTEM_MESSAGES.continue) { + + /** + * Event emitted when a system continue MIDI message has been received. + * + * @event continue + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit + * values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {String} event.type The type of event that occurred. + */ + event.type = "continue"; + + } else if (command === wm.MIDI_SYSTEM_MESSAGES.stop) { + + /** + * Event emitted when a system stop MIDI message has been received. + * + * @event stop + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit + * values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {String} event.type The type of event that occurred. + */ + event.type = "stop"; + + } else if (command === wm.MIDI_SYSTEM_MESSAGES.activesensing) { + + /** + * Event emitted when a system active sensing MIDI message has been received. + * + * @event activesensing + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {String} event.type The type of event that occurred. + */ + event.type = "activesensing"; + + } else if (command === wm.MIDI_SYSTEM_MESSAGES.reset) { + + /** + * Event emitted when a system reset MIDI message has been received. + * + * @event reset + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {String} event.type The type of event that occurred. + */ + event.type = "reset"; + + } else { + + /** + * Event emitted when an unknown system MIDI message has been received. It could be, for + * example, one of the undefined/reserved messages. + * + * @event unknownsystemmessage + * + * @param {Object} event + * @param {Input} event.target The `Input` that triggered the event. + * @param {Uint8Array} event.data The raw MIDI message as an array of 8 bit values. + * @param {Number} event.timestamp The time when the event occurred (in milliseconds) + * @param {String} event.type The type of event that occurred. + */ + event.type = "unknownsystemmessage"; + + } + + // If some callbacks have been defined for this event, execute them. + if (this._userHandlers.system[event.type]) { + this._userHandlers.system[event.type].forEach( + function(callback) { callback(event); } + ); + } + + }; + + /** + * The `Output` object represents a MIDI output port on the host system. This object is created by + * the MIDI subsystem and cannot be instantiated directly. + * + * You will find all available `Output` objects in the `WebMidi.outputs` array. + * + * @class Output + * @param {MIDIOutput} midiOutput Actual `MIDIOutput` object as defined by the MIDI subsystem + */ + function Output(midiOutput) { + + var that = this; + + this._midiOutput = midiOutput; + + Object.defineProperties(this, { + + /** + * [read-only] Status of the MIDI port"s connection + * + * @property connection + * @type String + */ + connection: { + enumerable: true, + get: function () { + return that._midiOutput.connection; + } + }, + + /** + * [read-only] ID string of the MIDI port + * + * @property id + * @type String + */ + id: { + enumerable: true, + get: function () { + return that._midiOutput.id; + } + }, + + /** + * [read-only] Manufacturer of the device to which this port belongs + * + * @property manufacturer + * @type String + */ + manufacturer: { + enumerable: true, + get: function () { + return that._midiOutput.manufacturer; + } + }, + + /** + * [read-only] Name of the MIDI port + * + * @property name + * @type String + */ + name: { + enumerable: true, + get: function () { + return that._midiOutput.name; + } + }, + + /** + * [read-only] State of the MIDI port + * + * @property state + * @type String + */ + state: { + enumerable: true, + get: function () { + return that._midiOutput.state; + } + }, + + /** + * [read-only] Type of the MIDI port (`output`) + * + * @property type + * @type String + */ + type: { + enumerable: true, + get: function () { + return that._midiOutput.type; + } + } + + }); + + } + + /** + * Sends a MIDI message on the MIDI output port, at the scheduled timestamp. + * + * Unless, you are familiar with the details of the MIDI message format, you should not use this + * method directly. Instead, use one of the simpler helper methods: `playNote()`, `stopNote()`, + * `sendControlChange()`, `sendSystemMessage()`, etc. + * + * @method send + * @chainable + * + * @param status {Number} The MIDI status byte of the message (128-255). + * + * @param [data=[]] {Array} An array of uints for the message. The number of data bytes varies + * depending on the status byte. It is perfectly legal to send no data for some message types (use + * undefined or an empty array in this case). Each byte must be between 0 and 255. + * + * @param [timestamp=0] {DOMHighResTimeStamp} The timestamp at which to send the message. You can + * use `WebMidi.time` to retrieve the current timestamp. To send immediately, leave blank or use + * 0. + * + * @throws {RangeError} The status byte must be an integer between 128 (0x80) and 255 (0xFF). + * @throws {RangeError} Data bytes must be integers between 0 (0x00) and 255 (0x7F). + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.send = function(status, data, timestamp) { + + if ( !(status >= 128 && status <= 255) ) { + throw new RangeError("The status byte must be an integer between 128 (0x80) and 255 (0xFF)."); + } + + if (data === undefined) data = []; + if ( !Array.isArray(data) ) data = [data]; + + var message = []; + + data.forEach(function(item){ + + var parsed = Math.floor(item); // mandatory because of "null" + + if (parsed >= 0 && parsed <= 255) { + message.push(parsed); + } else { + throw new RangeError("Data bytes must be integers between 0 (0x00) and 255 (0xFF)."); + } + + }); + + this._midiOutput.send([status].concat(message), parseFloat(timestamp) || 0); + + return this; + + }; + + /** + * Sends a MIDI *system exclusive* (sysex) message. The generated message will automatically be + * prepended with the *sysex* byte (0xF0) and terminated with the *end of sysex* byte (0xF7). + * + * To use the `sendSysex()` method, system exclusive message support must have been enabled. To + * do so, you must pass `true` as the second parameter to `WebMidi.enable()`: + * + * WebMidi.enable(function (err) { + * if (err) { + * console.warn(err); + * } else { + * console.log("Sysex is enabled!"); + * } + * }, true); + * + * Note that, depending on browser, version and platform, it may be necessary to serve the page + * over HTTPS to enable sysex support. + * + * #### Examples + * + * If you want to send a sysex message to a Korg device connected to the first output, you would + * use the following code: + * + * WebMidi.outputs[0].sendSysex(0x42, [0x1, 0x2, 0x3, 0x4, 0x5]); + * + * The parameters can be specified using any number notation (decimal, hex, binary, etc.). + * Therefore, the code below is equivalent to the code above: + * + * WebMidi.outputs[0].sendSysex(66, [1, 2, 3, 4, 5]); + * + * The above code sends the byte values 1, 2, 3, 4 and 5 to Korg devices (hex 42 is the same as + * decimal 66). + * + * Some manufacturers are identified using 3 bytes. In this case, you would use a 3-position array + * as the first parameter. For example, to send the same sysex message to a + * *Native Instruments* device: + * + * WebMidi.outputs[0].sendSysex([0x00, 0x21, 0x09], [0x1, 0x2, 0x3, 0x4, 0x5]); + * + * There is no limit for the length of the data array. However, it is generally suggested to keep + * system exclusive messages to 64Kb or less. + * + * @method sendSysex + * @chainable + * + * @param manufacturer {Number|Array} An unsigned integer or an array of three unsigned integers + * between 0 and 127 that identify the targeted manufacturer. The *MIDI Manufacturers Association* + * maintains a full list of + * [Manufacturer ID Numbers](https://www.midi.org/specifications-old/item/manufacturer-id-numbers) + * . + * + * @param [data=[]] {Array} An array of uints between 0 and 127. This is the data you wish to + * transfer. + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @throw Sysex message support must first be activated. + * @throw The data bytes of a sysex message must be integers between 0 (0x00) and 127 (0x7F). + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.sendSysex = function(manufacturer, data, options) { + + if (!wm.sysexEnabled) { + throw new Error("Sysex message support must first be activated."); + } + + options = options || {}; + + manufacturer = [].concat(manufacturer); + + data.forEach(function(item){ + if (item < 0 || item > 127) { + throw new RangeError( + "The data bytes of a sysex message must be integers between 0 (0x00) and 127 (0x7F)." + ); + } + }); + + data = manufacturer.concat(data, wm.MIDI_SYSTEM_MESSAGES.sysexend); + this.send(wm.MIDI_SYSTEM_MESSAGES.sysex, data, this._parseTimeParameter(options.time)); + + return this; + + }; + + /** + * Sends a *MIDI Timecode Quarter Frame* message. Please note that no processing is being done on + * the data. It is up to the developer to format the data according to the + * [MIDI Timecode](https://en.wikipedia.org/wiki/MIDI_timecode) format. + * + * @method sendTimecodeQuarterFrame + * @chainable + * + * @param value {Number} The quarter frame message content (integer between 0 and 127). + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.sendTimecodeQuarterFrame = function(value, options) { + options = options || {}; + this.send(wm.MIDI_SYSTEM_MESSAGES.timecode, value, this._parseTimeParameter(options.time)); + return this; + }; + + /** + * Sends a *Song Position* MIDI message. The value is expressed in MIDI beats (between 0 and + * 16383) which are 16th note. Position 0 is always the start of the song. + * + * @method sendSongPosition + * @chainable + * + * @param [value=0] {Number} The MIDI beat to cue to (int between 0 and 16383). + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.sendSongPosition = function(value, options) { + + value = Math.floor(value) || 0; + + options = options || {}; + + var msb = (value >> 7) & 0x7F; + var lsb = value & 0x7F; + + this.send( + wm.MIDI_SYSTEM_MESSAGES.songposition, + [msb, lsb], + this._parseTimeParameter(options.time) + ); + return this; + + }; + + /** + * Sends a *Song Select* MIDI message. Beware that some devices will display position 0 as + * position 1 for user-friendlyness. + * + * @method sendSongSelect + * @chainable + * + * @param value {Number} The number of the song to select (integer between 0 and 127). + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @throws The song number must be between 0 and 127. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.sendSongSelect = function(value, options) { + + value = Math.floor(value); + + options = options || {}; + + if ( !(value >= 0 && value <= 127) ) { + throw new RangeError("The song number must be between 0 and 127."); + } + + this.send(wm.MIDI_SYSTEM_MESSAGES.songselect, [value], this._parseTimeParameter(options.time)); + + return this; + + }; + + /** + * Sends a *MIDI tuning request* real-time message. + * + * Note: there is currently a bug in Chrome"s MIDI implementation. If you try to use this + * function, Chrome will actually throw a "Message is incomplete" error. The bug is + * [scheduled to be fixed](https://bugs.chromium.org/p/chromium/issues/detail?id=610116). + * + * @method sendTuningRequest + * @chainable + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.sendTuningRequest = function(options) { + options = options || {}; + this.send( + wm.MIDI_SYSTEM_MESSAGES.tuningrequest, + undefined, + this._parseTimeParameter(options.time) + ); + return this; + }; + + /** + * Sends a *MIDI Clock* real-time message. According to the standard, there are 24 MIDI Clocks + * for every quarter note. + * + * @method sendClock + * @chainable + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.sendClock = function(options) { + options = options || {}; + this.send(wm.MIDI_SYSTEM_MESSAGES.clock, undefined, this._parseTimeParameter(options.time)); + return this; + }; + + /** + * Sends a *Start* real-time message. A MIDI Start message starts the playback of the current + * song at beat 0. To start playback elsewhere in the song, use the `sendContinue()` function. + * + * @method sendStart + * @chainable + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.sendStart = function(options) { + options = options || {}; + this.send(wm.MIDI_SYSTEM_MESSAGES.start, undefined, this._parseTimeParameter(options.time)); + return this; + }; + + /** + * Sends a *Continue* real-time message. This resumes song playback where it was previously + * stopped or where it was last cued with a song position message. To start playback from the + * start, use the `sendStart()` function. + * + * @method sendContinue + * @chainable + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @return {WebMidi} Returns the `WebMidi` object so methods can be chained. + */ + Output.prototype.sendContinue = function(options) { + options = options || {}; + this.send(wm.MIDI_SYSTEM_MESSAGES.continue, undefined, this._parseTimeParameter(options.time)); + return this; + }; + + /** + * Sends a *Stop* real-time message. This tells the device connected to this port to stop playback + * immediately (or at the scheduled time). + * + * @method sendStop + * @chainable + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.sendStop = function(options) { + options = options || {}; + this.send(wm.MIDI_SYSTEM_MESSAGES.stop, undefined, this._parseTimeParameter(options.time)); + return this; + }; + + /** + * Sends an *Active Sensing* real-time message. This tells the device connected to this port that + * the connection is still good. Active sensing messages should be sent every 300 ms if there was + * no other activity on the MIDI port. + * + * @method sendActiveSensing + * @chainable + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.sendActiveSensing = function(options) { + options = options || {}; + this.send( + wm.MIDI_SYSTEM_MESSAGES.activesensing, + [], + this._parseTimeParameter(options.time) + ); + return this; + }; + + /** + * Sends *Reset* real-time message. This tells the device connected to this port that is should + * reset itself to a default state. + * + * @method sendReset + * @chainable + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.sendReset = function(options) { + options = options || {}; + this.send(wm.MIDI_SYSTEM_MESSAGES.reset, undefined, this._parseTimeParameter(options.time)); + return this; + }; + + /** + * Sends a MIDI **note off** message to the specified channel(s) for a single note or multiple + * simultaneous notes (chord). You can delay the execution of the **note off** command by using + * the `time` property of the `options` parameter (in milliseconds). + * + * @method stopNote + * @chainable + * + * @param note {Number|Array|String} The note(s) you wish to stop. The notes can be specified in + * one of three ways. The first way is by using the MIDI note number (an integer between `0` and + * `127`). The second way is by using the note name followed by the octave (C3, G#4, F-1, Db7). + * The octave range should be between -2 and 8. The lowest note is C-2 (MIDI note number 0) and + * the highest note is G8 (MIDI note number 127). It is also possible to specify an array of note + * numbers and/or names. The final way is to use the special value `all` to send an "allnotesoff" + * channel message. + * + * @param [channel=all] {Number|Array|String} The MIDI channel number (between `1` and `16`) or an + * array of channel numbers. If the special value `all` is used (default), the message will be + * sent to all 16 channels. + * + * @param {Object} [options={}] + * + * @param {Boolean} [options.rawVelocity=false] Controls whether the release velocity is set using + * an integer between `0` and `127` (`true`) or a decimal number between `0` and `1` (`false`, + * default). + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @param {Number} [options.velocity=0.5] The velocity at which to release the note (between `0` + * and `1`). If the `rawVelocity` option is `true`, the value should be specified as an integer + * between `0` and `127`. An invalid velocity value will silently trigger the default of `0.5`. + * Note that when the first parameter to `stopNote()` is `all`, the release velocity is silently + * ignored. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.stopNote = function(note, channel, options) { + + if (note === "all") { + return this.sendChannelMode("allnotesoff", 0, channel, options); + } + + var nVelocity = 64; + + options = options || {}; + + if (options.rawVelocity) { + + if (!isNaN(options.velocity) && options.velocity >= 0 && options.velocity <= 127) { + nVelocity = options.velocity; + } + + } else { + + if (!isNaN(options.velocity) && options.velocity >= 0 && options.velocity <= 1) { + nVelocity = options.velocity * 127; + } + + } + + // Send note off messages + this._convertNoteToArray(note).forEach(function(item) { + + wm.toMIDIChannels(channel).forEach(function(ch) { + + this.send( + (wm.MIDI_CHANNEL_MESSAGES.noteoff << 4) + (ch - 1), + [item, Math.round(nVelocity)], + this._parseTimeParameter(options.time) + ); + + }.bind(this)); + + }.bind(this)); + + return this; + + }; + + /** + * Requests the playback of a single note or multiple notes on the specified channel(s). You can + * delay the execution of the **note on** command by using the `time` property of the `options` + * parameter (milliseconds). + * + * If no duration is specified in the `options`, the note will play until a matching **note off** + * is sent. If a duration is specified, a **note off** will be automatically sent after said + * duration. + * + * Note: As per the MIDI standard, a **note on** event with a velocity of `0` is considered to be + * a **note off**. + * + * @method playNote + * @chainable + * + * @param note {Number|String|Array} The note(s) you wish to play. The notes can be specified in + * one of two ways. The first way is by using the MIDI note number (an integer between 0 and 127). + * The second way is by using the note name followed by the octave (C3, G#4, F-1, Db7). The octave + * range should be between -2 and 8. The lowest note is C-2 (MIDI note number 0) and the highest + * note is G8 (MIDI note number 127). It is also possible to specify an array of note numbers + * and/or names. + * + * @param [channel=all] {Number|Array|String} The MIDI channel number (between `1` and `16`) or an + * array of channel numbers. If the special value **all** is used (default), the message will be + * sent to all 16 channels. + * + * @param {Object} [options={}] + * + * @param {Number} [options.duration=undefined] The number of milliseconds (integer) to wait + * before sending a matching **note off** event. If left undefined, only a **note on** message is + * sent. + * + * @param {Boolean} [options.rawVelocity=false] Controls whether the attack and release velocities + * are set using integers between `0` and `127` (`true`) or a decimal number between `0` and `1` + * (`false`, default). + * + * @param {Number} [options.release=0.5] The velocity at which to release the note (between `0` + * and `1`). If the `rawVelocity` option is `true`, the value should be specified as an integer + * between `0` and `127`. An invalid velocity value will silently trigger the default of `0.5`. + * This is only used with the **note off** event triggered when `options.duration` is set. + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @param {Number} [options.velocity=0.5] The velocity at which to play the note (between `0` and + * `1`). If the `rawVelocity` option is `true`, the value should be specified as an integer + * between `0` and `127`. An invalid velocity value will silently trigger the default of `0.5`. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.playNote = function(note, channel, options) { + + var time, + nVelocity = 64; + + options = options || {}; + + if (options.rawVelocity) { + + if (!isNaN(options.velocity) && options.velocity >= 0 && options.velocity <= 127) { + nVelocity = options.velocity; + } + + } else { + + if (!isNaN(options.velocity) && options.velocity >= 0 && options.velocity <= 1) { + nVelocity = options.velocity * 127; + } + + } + + time = this._parseTimeParameter(options.time); + + // Send note on messages + this._convertNoteToArray(note).forEach(function(item) { + + wm.toMIDIChannels(channel).forEach(function(ch) { + this.send( + (wm.MIDI_CHANNEL_MESSAGES.noteon << 4) + (ch - 1), + [item, Math.round(nVelocity)], + time + ); + }.bind(this)); + + }.bind(this)); + + // Send note off messages (only if a valid duration has been defined) + if (!isNaN(options.duration)) { + + if (options.duration <= 0) { options.duration = 0; } + + var nRelease = 64; + + if (options.rawVelocity) { + + if (!isNaN(options.release) && options.release >= 0 && options.release <= 127) { + nRelease = options.release; + } + + } else { + + if (!isNaN(options.release) && options.release >= 0 && options.release <= 1) { + nRelease = options.release * 127; + } + + } + + this._convertNoteToArray(note).forEach(function(item) { + + wm.toMIDIChannels(channel).forEach(function(ch) { + + this.send( + (wm.MIDI_CHANNEL_MESSAGES.noteoff << 4) + (ch - 1), + [item, Math.round(nRelease)], + (time || wm.time) + options.duration + ); + }.bind(this)); + + }.bind(this)); + + } + + return this; + + }; + + /** + * Sends a MIDI `key aftertouch` message to the specified channel(s) at the scheduled time. This + * is a key-specific aftertouch. For a channel-wide aftertouch message, use + * {{#crossLink "WebMidi/sendChannelAftertouch:method"}}sendChannelAftertouch(){{/crossLink}}. + * + * @method sendKeyAftertouch + * @chainable + * + * @param note {Number|String|Array} The note for which you are sending an aftertouch value. The + * notes can be specified in one of two ways. The first way is by using the MIDI note number (an + * integer between 0 and 127). The second way is by using the note name followed by the octave + * (C3, G#4, F-1, Db7). The octave range should be between -2 and 8. The lowest note is C-2 (MIDI + * note number 0) and the highest note is G8 (MIDI note number 127). It is also possible to use + * an array of note names and/or numbers. + * + * @param [channel=all] {Number|Array|String} The MIDI channel number (between 1 and 16) or an + * array of channel numbers. If the special value "all" is used, the message will be sent to all + * 16 channels. + * + * @param {Number} [pressure=0.5] The pressure level to send (between 0 and 1). + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @throws {RangeError} The channel must be between 1 and 16. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.sendKeyAftertouch = function(note, channel, pressure, options) { + + var that = this; + + options = options || {}; + + if (channel < 1 || channel > 16) { + throw new RangeError("The channel must be between 1 and 16."); + } + + if (isNaN(pressure) || pressure < 0 || pressure > 1) { + pressure = 0.5; + } + + var nPressure = Math.round(pressure * 127); + + this._convertNoteToArray(note).forEach(function(item) { + + wm.toMIDIChannels(channel).forEach(function(ch) { + that.send( + (wm.MIDI_CHANNEL_MESSAGES.keyaftertouch << 4) + (ch - 1), + [item, nPressure], + that._parseTimeParameter(options.time) + ); + }); + + }); + + return this; + + }; + + /** + * Sends a MIDI `control change` message (a.k.a. CC message) to the specified channel(s) at the + * scheduled time. The control change message to send can be specified numerically or by using one + * of the following common names: + * + * * `bankselectcoarse` (#0) + * * `modulationwheelcoarse` (#1) + * * `breathcontrollercoarse` (#2) + * * `footcontrollercoarse` (#4) + * * `portamentotimecoarse` (#5) + * * `dataentrycoarse` (#6) + * * `volumecoarse` (#7) + * * `balancecoarse` (#8) + * * `pancoarse` (#10) + * * `expressioncoarse` (#11) + * * `effectcontrol1coarse` (#12) + * * `effectcontrol2coarse` (#13) + * * `generalpurposeslider1` (#16) + * * `generalpurposeslider2` (#17) + * * `generalpurposeslider3` (#18) + * * `generalpurposeslider4` (#19) + * * `bankselectfine` (#32) + * * `modulationwheelfine` (#33) + * * `breathcontrollerfine` (#34) + * * `footcontrollerfine` (#36) + * * `portamentotimefine` (#37) + * * `dataentryfine` (#38) + * * `volumefine` (#39) + * * `balancefine` (#40) + * * `panfine` (#42) + * * `expressionfine` (#43) + * * `effectcontrol1fine` (#44) + * * `effectcontrol2fine` (#45) + * * `holdpedal` (#64) + * * `portamento` (#65) + * * `sustenutopedal` (#66) + * * `softpedal` (#67) + * * `legatopedal` (#68) + * * `hold2pedal` (#69) + * * `soundvariation` (#70) + * * `resonance` (#71) + * * `soundreleasetime` (#72) + * * `soundattacktime` (#73) + * * `brightness` (#74) + * * `soundcontrol6` (#75) + * * `soundcontrol7` (#76) + * * `soundcontrol8` (#77) + * * `soundcontrol9` (#78) + * * `soundcontrol10` (#79) + * * `generalpurposebutton1` (#80) + * * `generalpurposebutton2` (#81) + * * `generalpurposebutton3` (#82) + * * `generalpurposebutton4` (#83) + * * `reverblevel` (#91) + * * `tremololevel` (#92) + * * `choruslevel` (#93) + * * `celestelevel` (#94) + * * `phaserlevel` (#95) + * * `databuttonincrement` (#96) + * * `databuttondecrement` (#97) + * * `nonregisteredparametercoarse` (#98) + * * `nonregisteredparameterfine` (#99) + * * `registeredparametercoarse` (#100) + * * `registeredparameterfine` (#101) + * + * Note: as you can see above, not all control change message have a matching common name. This + * does not mean you cannot use the others. It simply means you will need to use their number + * instead of their name. + * + * @method sendControlChange + * @chainable + * + * @param controller {Number|String} The MIDI controller number (0-119) or name. + * + * @param [value=0] {Number} The value to send (0-127). + * + * @param [channel=all] {Number|Array|String} The MIDI channel number (between 1 and 16) or an + * array of channel numbers. If the special value "all" is used, the message will be sent to all + * 16 channels. + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @throws {RangeError} Controller numbers must be between 0 and 119. + * @throws {RangeError} Value must be between 0 and 127. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.sendControlChange = function(controller, value, channel, options) { + + options = options || {}; + + if (typeof controller === "string") { + + controller = wm.MIDI_CONTROL_CHANGE_MESSAGES[controller]; + if (controller === undefined) throw new TypeError("Invalid controller name."); + + } else { + + controller = Math.floor(controller); + if ( !(controller >= 0 && controller <= 119) ) { + throw new RangeError("Controller numbers must be between 0 and 119."); + } + + } + + value = Math.floor(value) || 0; + if ( !(value >= 0 && value <= 127) ) { + throw new RangeError("Controller value must be between 0 and 127."); + } + + wm.toMIDIChannels(channel).forEach(function(ch) { + this.send( + (wm.MIDI_CHANNEL_MESSAGES.controlchange << 4) + (ch - 1), + [controller, value], + this._parseTimeParameter(options.time) + ); + }.bind(this)); + + return this; + + }; + + /** + * Selects a MIDI registered parameter so it is affected by data entry, data increment and data + * decrement messages. + * + * @method _selectRegisteredParameter + * @protected + * + * @param parameter {Array} A two-position array specifying the two control bytes (0x65, 0x64) + * that identify the registered parameter. + * @param channel + * @param time + * + * @returns {Output} + */ + Output.prototype._selectRegisteredParameter = function(parameter, channel, time) { + + var that = this; + + parameter[0] = Math.floor(parameter[0]); + if ( !(parameter[0] >= 0 && parameter[0] <= 127) ) { + throw new RangeError("The control65 value must be between 0 and 127"); + } + + parameter[1] = Math.floor(parameter[1]); + if ( !(parameter[1] >= 0 && parameter[1] <= 127) ) { + throw new RangeError("The control64 value must be between 0 and 127"); + } + + wm.toMIDIChannels(channel).forEach(function() { + that.sendControlChange(0x65, parameter[0], channel, {time: time}); + that.sendControlChange(0x64, parameter[1], channel, {time: time}); + }); + + return this; + + }; + + /** + * Selects a MIDI non-registered parameter so it is affected by data entry, data increment and + * data decrement messages. + * + * @method _selectNonRegisteredParameter + * @protected + * + * @param parameter {Array} A two-position array specifying the two control bytes (0x63, 0x62) + * that identify the registered parameter. + * @param channel + * @param time + * + * @returns {Output} + */ + Output.prototype._selectNonRegisteredParameter = function(parameter, channel, time) { + + var that = this; + + parameter[0] = Math.floor(parameter[0]); + if ( !(parameter[0] >= 0 && parameter[0] <= 127) ) { + throw new RangeError("The control63 value must be between 0 and 127"); + } + + parameter[1] = Math.floor(parameter[1]); + if ( !(parameter[1] >= 0 && parameter[1] <= 127) ) { + throw new RangeError("The control62 value must be between 0 and 127"); + } + + wm.toMIDIChannels(channel).forEach(function() { + that.sendControlChange(0x63, parameter[0], channel, {time: time}); + that.sendControlChange(0x62, parameter[1], channel, {time: time}); + }); + + return this; + + }; + + /** + * Sets the value of the currently selected MIDI registered parameter. + * + * @method _setCurrentRegisteredParameter + * @protected + * + * @param data {int|Array} + * @param channel + * @param time + * + * @returns {Output} + */ + Output.prototype._setCurrentRegisteredParameter = function(data, channel, time) { + + var that = this; + + data = [].concat(data); + + data[0] = Math.floor(data[0]); + if ( !(data[0] >= 0 && data[0] <= 127) ) { + throw new RangeError("The msb value must be between 0 and 127"); + } + + wm.toMIDIChannels(channel).forEach(function() { + that.sendControlChange(0x06, data[0], channel, {time: time}); + }); + + data[1] = Math.floor(data[1]); + if(data[1] >= 0 && data[1] <= 127) { + wm.toMIDIChannels(channel).forEach(function() { + that.sendControlChange(0x26, data[1], channel, {time: time}); + }); + } + + return this; + + }; + + /** + * Deselects the currently active MIDI registered parameter so it is no longer affected by data + * entry, data increment and data decrement messages. + * + * Current best practice recommends doing that after each call to + * `_setCurrentRegisteredParameter()`. + * + * @method _deselectRegisteredParameter + * @protected + * + * @param channel + * @param time + * + * @returns {Output} + */ + Output.prototype._deselectRegisteredParameter = function(channel, time) { + + var that = this; + + wm.toMIDIChannels(channel).forEach(function() { + that.sendControlChange(0x65, 0x7F, channel, {time: time}); + that.sendControlChange(0x64, 0x7F, channel, {time: time}); + }); + + return this; + + }; + + /** + * Sets the specified MIDI registered parameter to the desired value. The value is defined with + * up to two bytes of data that each can go from 0 to 127. + * + * >Unless you are very familiar with the MIDI standard you probably should favour one of the + * >simpler to use functions such as: `setPitchbendRange()`, `setModulationRange()`, + * >`setMasterTuning()`, etc. + * + * MIDI registered parameters extend the original list of control change messages. Currently, + * there are only a limited number of them. Here are the original registered parameters with the + * identifier that can be used as the first parameter of this function: + * + * * Pitchbend Range (0x00, 0x00): `pitchbendrange` + * * Channel Fine Tuning (0x00, 0x01): `channelfinetuning` + * * Channel Coarse Tuning (0x00, 0x02): `channelcoarsetuning` + * * Tuning Program (0x00, 0x03): `tuningprogram` + * * Tuning Bank (0x00, 0x04): `tuningbank` + * * Modulation Range (0x00, 0x05): `modulationrange` + * + * Note that the **Tuning Program** and **Tuning Bank** parameters are part of the *MIDI Tuning + * Standard*, which is not widely implemented. + * + * Another set of extra parameters have been later added for 3D sound controllers. They are: + * + * * Azimuth Angle (0x3D, 0x00): `azimuthangle` + * * Elevation Angle (0x3D, 0x01): `elevationangle` + * * Gain (0x3D, 0x02): `gain` + * * Distance Ratio (0x3D, 0x03): `distanceratio` + * * Maximum Distance (0x3D, 0x04): `maximumdistance` + * * Maximum Distance Gain (0x3D, 0x05): `maximumdistancegain` + * * Reference Distance Ratio (0x3D, 0x06): `referencedistanceratio` + * * Pan Spread Angle (0x3D, 0x07): `panspreadangle` + * * Roll Angle (0x3D, 0x08): `rollangle` + * + * @method setRegisteredParameter + * @chainable + * + * @param parameter {String|Array} A string identifying the parameter"s name (see above) or a + * two-position array specifying the two control bytes (0x65, 0x64) that identify the registered + * parameter. + * + * @param [data=[]] {Number|Array} An single integer or an array of integers with a maximum length + * of 2 specifying the desired data. + * + * @param [channel=all] {Number|Array|String} The MIDI channel number (between 1 and 16) or an + * array of channel numbers. If the special value "all" is used, the message will be sent to all + * 16 channels. + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @returns {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.setRegisteredParameter = function(parameter, data, channel, options) { + + var that = this; + + options = options || {}; + + if ( !Array.isArray(parameter) ) { + if ( !wm.MIDI_REGISTERED_PARAMETER[parameter]) { + throw new Error("The specified parameter is not available."); + } + parameter = wm.MIDI_REGISTERED_PARAMETER[parameter]; + } + + wm.toMIDIChannels(channel).forEach(function() { + that._selectRegisteredParameter(parameter, channel, options.time); + that._setCurrentRegisteredParameter(data, channel, options.time); + that._deselectRegisteredParameter(channel, options.time); + }); + + return this; + + }; + + /** + * Sets a non-registered parameter to the specified value. The NRPN is selected by passing in a + * two-position array specifying the values of the two control bytes. The value is specified by + * passing in an single integer (most cases) or an array of two integers. + * + * NRPNs are not standardized in any way. Each manufacturer is free to implement them any way + * they see fit. For example, according to the Roland GS specification, you can control the + * **vibrato rate** using NRPN (1, 8). Therefore, to set the **vibrato rate** value to **123** you + * would use: + * + * WebMidi.outputs[0].setNonRegisteredParameter([1, 8], 123); + * + * Obviously, you should select a channel so the message is not sent to all channels. For + * instance, to send to channel 1 of the first output port, you would use: + * + * WebMidi.outputs[0].setNonRegisteredParameter([1, 8], 123, 1); + * + * In some rarer cases, you need to send two values with your NRPN messages. In such cases, you + * would use a 2-position array. For example, for its **ClockBPM** parameter (2, 63), Novation + * uses a 14-bit value that combines an MSB and an LSB (7-bit values). So, for example, if the + * value to send was 10, you could use: + * + * WebMidi.outputs[0].setNonRegisteredParameter([2, 63], [0, 10]); + * + * For further implementation details, refer to the manufacturer"s documentation. + * + * @method setNonRegisteredParameter + * @chainable + * + * @param parameter {Array} A two-position array specifying the two control bytes (0x63, + * 0x62) that identify the non-registered parameter. + * + * @param [data=[]] {Number|Array} An integer or an array of integers with a length of 1 or 2 + * specifying the desired data. + * + * @param [channel=all] {Number|Array|String} The MIDI channel number (between 1 and 16) or an + * array of channel numbers. If the special value "all" is used, the message will be sent to all + * 16 channels. + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @returns {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.setNonRegisteredParameter = function(parameter, data, channel, options) { + + var that = this; + + options = options || {}; + + if ( + !(parameter[0] >= 0 && parameter[0] <= 127) || + !(parameter[1] >= 0 && parameter[1] <= 127) + ) { + throw new Error( + "Position 0 and 1 of the 2-position parameter array must both be between 0 and 127." + ); + } + + data = [].concat(data); + + wm.toMIDIChannels(channel).forEach(function() { + that._selectNonRegisteredParameter(parameter, channel, options.time); + that._setCurrentRegisteredParameter(data, channel, options.time); + that._deselectRegisteredParameter(channel, options.time); + }); + + return this; + + }; + + /** + * Increments the specified MIDI registered parameter by 1. + * + * >Unless you are very familiar with the MIDI standard you probably should favour one of the + * >simpler to use functions such as: `setPitchbendRange()`, `setModulationRange()`, + * >`setMasterTuning()`, etc. + * + * Here is the full list of parameter names that can be used with this function: + * + * * Pitchbend Range (0x00, 0x00): `pitchbendrange` + * * Channel Fine Tuning (0x00, 0x01): `channelfinetuning` + * * Channel Coarse Tuning (0x00, 0x02): `channelcoarsetuning` + * * Tuning Program (0x00, 0x03): `tuningprogram` + * * Tuning Bank (0x00, 0x04): `tuningbank` + * * Modulation Range (0x00, 0x05): `modulationrange` + * * Azimuth Angle (0x3D, 0x00): `azimuthangle` + * * Elevation Angle (0x3D, 0x01): `elevationangle` + * * Gain (0x3D, 0x02): `gain` + * * Distance Ratio (0x3D, 0x03): `distanceratio` + * * Maximum Distance (0x3D, 0x04): `maximumdistance` + * * Maximum Distance Gain (0x3D, 0x05): `maximumdistancegain` + * * Reference Distance Ratio (0x3D, 0x06): `referencedistanceratio` + * * Pan Spread Angle (0x3D, 0x07): `panspreadangle` + * * Roll Angle (0x3D, 0x08): `rollangle` + * + * @method incrementRegisteredParameter + * @chainable + * + * @param parameter {String|Array} A string identifying the parameter"s name (see above) or a + * two-position array specifying the two control bytes (0x65, 0x64) that identify the registered + * parameter. + * + * @param [channel=all] {uint|Array|String} The MIDI channel number (between 1 and 16) or an + * array of channel numbers. If the special value "all" is used, the message will be sent to all + * 16 channels. + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @throws Error The specified parameter is not available. + * + * @returns {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.incrementRegisteredParameter = function(parameter, channel, options) { + + var that = this; + + options = options || {}; + + if ( !Array.isArray(parameter) ) { + if ( !wm.MIDI_REGISTERED_PARAMETER[parameter]) { + throw new Error("The specified parameter is not available."); + } + parameter = wm.MIDI_REGISTERED_PARAMETER[parameter]; + } + + wm.toMIDIChannels(channel).forEach(function() { + that._selectRegisteredParameter(parameter, channel, options.time); + that.sendControlChange(0x60, 0, channel, {time: options.time}); + that._deselectRegisteredParameter(channel, options.time); + }); + + return this; + + }; + + /** + * Decrements the specified MIDI registered parameter by 1. + * + * >Unless you are very familiar with the MIDI standard you probably should favour one of the + * >simpler to use functions such as: `setPitchbendRange()`, `setModulationRange()`, + * >`setMasterTuning()`, etc. + * + * Here is the full list of parameter names that can be used with this function: + * + * * Pitchbend Range (0x00, 0x00): `pitchbendrange` + * * Channel Fine Tuning (0x00, 0x01): `channelfinetuning` + * * Channel Coarse Tuning (0x00, 0x02): `channelcoarsetuning` + * * Tuning Program (0x00, 0x03): `tuningprogram` + * * Tuning Bank (0x00, 0x04): `tuningbank` + * * Modulation Range (0x00, 0x05): `modulationrange` + * * Azimuth Angle (0x3D, 0x00): `azimuthangle` + * * Elevation Angle (0x3D, 0x01): `elevationangle` + * * Gain (0x3D, 0x02): `gain` + * * Distance Ratio (0x3D, 0x03): `distanceratio` + * * Maximum Distance (0x3D, 0x04): `maximumdistance` + * * Maximum Distance Gain (0x3D, 0x05): `maximumdistancegain` + * * Reference Distance Ratio (0x3D, 0x06): `referencedistanceratio` + * * Pan Spread Angle (0x3D, 0x07): `panspreadangle` + * * Roll Angle (0x3D, 0x08): `rollangle` + * + * @method decrementRegisteredParameter + * @chainable + * + * @param parameter {String|Array} A string identifying the parameter"s name (see above) or a + * two-position array specifying the two control bytes (0x65, 0x64) that identify the registered + * parameter. + * + * @param [channel=all] {Number|Array|String} The MIDI channel number (between 1 and 16) or an + * array of channel numbers. If the special value "all" is used, the message will be sent to all + * 16 channels. + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @throws TypeError The specified parameter is not available. + * + * @returns {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.decrementRegisteredParameter = function(parameter, channel, options) { + + options = options || {}; + + if ( !Array.isArray(parameter) ) { + if ( !wm.MIDI_REGISTERED_PARAMETER[parameter]) { + throw new TypeError("The specified parameter is not available."); + } + parameter = wm.MIDI_REGISTERED_PARAMETER[parameter]; + } + + wm.toMIDIChannels(channel).forEach(function() { + this._selectRegisteredParameter(parameter, channel, options.time); + this.sendControlChange(0x61, 0, channel, {time: options.time}); + this._deselectRegisteredParameter(channel, options.time); + }.bind(this)); + + return this; + + }; + + /** + * Sends a pitch bend range message to the specified channel(s) at the scheduled time so that they + * adjust the range used by their pitch bend lever. The range can be specified with the + * `semitones` parameter, the `cents` parameter or by specifying both parameters at the same time. + * + * @method setPitchBendRange + * @chainable + * + * @param [semitones=0] {Number} The desired adjustment value in semitones (integer between + * 0-127). While nothing imposes that in the specification, it is very common for manufacturers to + * limit the range to 2 octaves (-12 semitones to 12 semitones). + * + * @param [cents=0] {Number} The desired adjustment value in cents (integer between 0-127). + * + * @param [channel=all] {Number|Array|String} The MIDI channel number (between 1 and 16) or an + * array of channel numbers. If the special value "all" is used, the message will be sent to all + * 16 channels. + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @throws {RangeError} The semitones value must be between 0 and 127. + * @throws {RangeError} The cents value must be between 0 and 127. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.setPitchBendRange = function(semitones, cents, channel, options) { + + var that = this; + + options = options || {}; + + semitones = Math.floor(semitones) || 0; + if ( !(semitones >= 0 && semitones <= 127) ) { + throw new RangeError("The semitones value must be between 0 and 127"); + } + + cents = Math.floor(cents) || 0; + if ( !(cents >= 0 && cents <= 127) ) { + throw new RangeError("The cents value must be between 0 and 127"); + } + + wm.toMIDIChannels(channel).forEach(function() { + that.setRegisteredParameter( + "pitchbendrange", [semitones, cents], channel, {time: options.time} + ); + }); + + return this; + + }; + + /** + * Sends a modulation depth range message to the specified channel(s) so that they adjust the + * depth of their modulation wheel"s range. The range can be specified with the `semitones` + * parameter, the `cents` parameter or by specifying both parameters at the same time. + * + * @method setModulationRange + * @chainable + * + * @param [semitones=0] {Number} The desired adjustment value in semitones (integer between + * 0-127). + * + * @param [cents=0] {Number} The desired adjustment value in cents (0-127). + * + * @param [channel=all] {Number|Array|String} The MIDI channel number (between 1 and 16) or an + * array of channel numbers. If the special value "all" is used, the message will be sent to all + * 16 channels. + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @throws {RangeError} The semitones value must be between 0 and 127. + * @throws {RangeError} The cents value must be between 0 and 127. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.setModulationRange = function(semitones, cents, channel, options) { + + var that = this; + + options = options || {}; + + semitones = Math.floor(semitones) || 0; + if ( !(semitones >= 0 && semitones <= 127) ) { + throw new RangeError("The semitones value must be between 0 and 127"); + } + + cents = Math.floor(cents) || 0; + if ( !(cents >= 0 && cents <= 127) ) { + throw new RangeError("The cents value must be between 0 and 127"); + } + + wm.toMIDIChannels(channel).forEach(function() { + that.setRegisteredParameter( + "modulationrange", [semitones, cents], channel, {time: options.time} + ); + }); + + return this; + + }; + + /** + * Sends a master tuning message to the specified channel(s). The value is decimal and must be + * larger than -65 semitones and smaller than 64 semitones. + * + * >Because of the way the MIDI specification works, the decimal portion of the value will be + * >encoded with a resolution of 14bit. The integer portion must be between -64 and 63 + * >inclusively. For those familiar with the MIDI protocol, this function actually generates + * >**Master Coarse Tuning** and **Master Fine Tuning** RPN messages. + * + * @method setMasterTuning + * @chainable + * + * @param [value=0.0] {Number} The desired decimal adjustment value in semitones (-65 < x < 64) + * + * @param [channel=all] {Number|Array|String} The MIDI channel number (between 1 and 16) or an + * array of channel numbers. If the special value "all" is used, the message will be sent to all + * 16 channels. + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @throws {RangeError} The value must be a decimal number between larger than -65 and smaller + * than 64. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.setMasterTuning = function(value, channel, options) { + + var that = this; + + options = options || {}; + + value = parseFloat(value) || 0.0; + + if (value <= -65 || value >= 64) { + throw new RangeError( + "The value must be a decimal number larger than -65 and smaller than 64." + ); + } + + var coarse = Math.floor(value) + 64; + var fine = value - Math.floor(value); + + // Calculate MSB and LSB for fine adjustment (14bit resolution) + fine = Math.round((fine + 1) / 2 * 16383); + var msb = (fine >> 7) & 0x7F; + var lsb = fine & 0x7F; + + wm.toMIDIChannels(channel).forEach(function() { + that.setRegisteredParameter("channelcoarsetuning", coarse, channel, {time: options.time}); + that.setRegisteredParameter("channelfinetuning", [msb, lsb], channel, {time: options.time}); + }); + + return this; + + }; + + /** + * Sets the MIDI tuning program to use. Note that the **Tuning Program** parameter is part of the + * *MIDI Tuning Standard*, which is not widely implemented. + * + * @method setTuningProgram + * @chainable + * + * @param value {Number} The desired tuning program (0-127). + * + * @param [channel=all] {Number|Array|String} The MIDI channel number (between 1 and 16) or an + * array of channel numbers. If the special value "all" is used, the message will be sent to all + * 16 channels. + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @throws {RangeError} The program value must be between 0 and 127. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.setTuningProgram = function(value, channel, options) { + + var that = this; + + options = options || {}; + + value = Math.floor(value); + if ( !(value >= 0 && value <= 127) ) { + throw new RangeError("The program value must be between 0 and 127"); + } + + wm.toMIDIChannels(channel).forEach(function() { + that.setRegisteredParameter("tuningprogram", value, channel, {time: options.time}); + }); + + return this; + + }; + + /** + * Sets the MIDI tuning bank to use. Note that the **Tuning Bank** parameter is part of the + * *MIDI Tuning Standard*, which is not widely implemented. + * + * @method setTuningBank + * @chainable + * + * @param value {Number} The desired tuning bank (0-127). + * + * @param [channel=all] {Number|Array|String} The MIDI channel number (between 1 and 16) or an + * array of channel numbers. If the special value "all" is used, the message will be sent to all + * 16 channels. + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @throws {RangeError} The bank value must be between 0 and 127. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.setTuningBank = function(value, channel, options) { + + var that = this; + + options = options || {}; + + value = Math.floor(value) || 0; + if ( !(value >= 0 && value <= 127) ) { + throw new RangeError("The bank value must be between 0 and 127"); + } + + wm.toMIDIChannels(channel).forEach(function() { + that.setRegisteredParameter("tuningbank", value, channel, {time: options.time}); + }); + + return this; + + }; + + /** + * Sends a MIDI `channel mode` message to the specified channel(s). The channel mode message to + * send can be specified numerically or by using one of the following common names: + * + * * `allsoundoff` (#120) + * * `resetallcontrollers` (#121) + * * `localcontrol` (#122) + * * `allnotesoff` (#123) + * * `omnimodeoff` (#124) + * * `omnimodeon` (#125) + * * `monomodeon` (#126) + * * `polymodeon` (#127) + * + * It should be noted that, per the MIDI specification, only `localcontrol` and `monomodeon` may + * require a value that"s not zero. For that reason, the `value` parameter is optional and + * defaults to 0. + * + * @method sendChannelMode + * @chainable + * + * @param command {Number|String} The numerical identifier of the channel mode message (integer + * between 120-127) or its name as a string. + * @param [value=0] {Number} The value to send (integer between 0-127). + * @param [channel=all] {Number|Array|String} The MIDI channel number (between 1 and 16) or an + * array of channel numbers. If the special value "all" is used, the message will be sent to all + * 16 channels. + * @param {Object} [options={}] + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @throws {TypeError} Invalid channel mode message name. + * @throws {RangeError} Channel mode controller numbers must be between 120 and 127. + * @throws {RangeError} Value must be an integer between 0 and 127. + * + * @return {Output} Returns the `Output` object so methods can be chained. + * + */ + Output.prototype.sendChannelMode = function(command, value, channel, options) { + + options = options || {}; + + if (typeof command === "string") { + + command = wm.MIDI_CHANNEL_MODE_MESSAGES[command]; + + if (!command) { + throw new TypeError("Invalid channel mode message name."); + } + + } else { + + command = Math.floor(command); + + if ( !(command >= 120 && command <= 127) ) { + throw new RangeError("Channel mode numerical identifiers must be between 120 and 127."); + } + + } + + value = Math.floor(value) || 0; + + if (value < 0 || value > 127) { + throw new RangeError("Value must be an integer between 0 and 127."); + } + + wm.toMIDIChannels(channel).forEach(function(ch) { + + this.send( + (wm.MIDI_CHANNEL_MESSAGES.channelmode << 4) + (ch - 1), + [command, value], + this._parseTimeParameter(options.time) + ); + + }.bind(this)); + + return this; + + }; + + /** + * Sends a MIDI `program change` message to the specified channel(s) at the scheduled time. + * + * @method sendProgramChange + * @chainable + * + * @param program {Number} The MIDI patch (program) number (0-127) + * + * @param [channel=all] {Number|Array|String} The MIDI channel number (between 1 and 16) or an + * array of channel numbers. If the special value "all" is used, the message will be sent to all + * 16 channels. + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @throws {RangeError} Program numbers must be between 0 and 127. + * + * @return {Output} Returns the `Output` object so methods can be chained. + * + */ + Output.prototype.sendProgramChange = function(program, channel, options) { + + var that = this; + + options = options || {}; + + program = Math.floor(program); + if (isNaN(program) || program < 0 || program > 127) { + throw new RangeError("Program numbers must be between 0 and 127."); + } + + wm.toMIDIChannels(channel).forEach(function(ch) { + that.send( + (wm.MIDI_CHANNEL_MESSAGES.programchange << 4) + (ch - 1), + [program], + that._parseTimeParameter(options.time) + ); + }); + + return this; + + }; + + /** + * Sends a MIDI `channel aftertouch` message to the specified channel(s). For key-specific + * aftertouch, you should instead use `sendKeyAftertouch()`. + * + * @method sendChannelAftertouch + * @chainable + * + * @param [pressure=0.5] {Number} The pressure level (between 0 and 1). An invalid pressure value + * will silently trigger the default behaviour. + * + * @param [channel=all] {Number|Array|String} The MIDI channel number (between 1 and 16) or + * an array of channel numbers. If the special value "all" is used, the message will be sent to + * all 16 channels. + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.sendChannelAftertouch = function(pressure, channel, options) { + + var that = this; + + options = options || {}; + + pressure = parseFloat(pressure); + if (isNaN(pressure) || pressure < 0 || pressure > 1) { pressure = 0.5; } + + var nPressure = Math.round(pressure * 127); + + wm.toMIDIChannels(channel).forEach(function(ch) { + that.send( + (wm.MIDI_CHANNEL_MESSAGES.channelaftertouch << 4) + (ch - 1), + [nPressure], + that._parseTimeParameter(options.time) + ); + }); + + return this; + + }; + + /** + * Sends a MIDI `pitch bend` message to the specified channel(s) at the scheduled time. + * + * @method sendPitchBend + * @chainable + * + * @param bend {Number} The intensity level of the bend (between -1 and 1). A value of zero means + * no bend. + * + * @param [channel=all] {Number|Array|String} The MIDI channel number (between 1 and 16) or an + * array of channel numbers. If the special value "all" is used, the message will be sent to all + * 16 channels. + * + * @param {Object} [options={}] + * + * @param {DOMHighResTimeStamp|String} [options.time=undefined] This value can be one of two + * things. If the value is a string starting with the + sign and followed by a number, the request + * will be delayed by the specified number (in milliseconds). Otherwise, the value is considered a + * timestamp and the request will be scheduled at that timestamp. The `DOMHighResTimeStamp` value + * is relative to the navigation start of the document. To retrieve the current time, you can use + * `WebMidi.time`. If `time` is not present or is set to a time in the past, the request is to be + * sent as soon as possible. + * + * @throws {RangeError} Pitch bend value must be between -1 and 1. + * + * @return {Output} Returns the `Output` object so methods can be chained. + */ + Output.prototype.sendPitchBend = function(bend, channel, options) { + + var that = this; + + options = options || {}; + + if (isNaN(bend) || bend < -1 || bend > 1) { + throw new RangeError("Pitch bend value must be between -1 and 1."); + } + + var nLevel = Math.round((bend + 1) / 2 * 16383); + var msb = (nLevel >> 7) & 0x7F; + var lsb = nLevel & 0x7F; + + wm.toMIDIChannels(channel).forEach(function(ch) { + that.send( + (wm.MIDI_CHANNEL_MESSAGES.pitchbend << 4) + (ch - 1), + [lsb, msb], + that._parseTimeParameter(options.time) + ); + }); + + return this; + + }; + + /** + * Returns a timestamp, relative to the navigation start of the document, derived from the `time` + * parameter. If the parameter is a string starting with the "+" sign and followed by a number, + * the resulting value will be the sum of the current timestamp plus that number. Otherwise, the + * value will be returned as is. + * + * If the calculated return value is 0, less than zero or an otherwise invalid value, `undefined` + * will be returned. + * + * @method _parseTimeParameter + * @param [time] {Number|String} + * @return DOMHighResTimeStamp + * @protected + */ + Output.prototype._parseTimeParameter = function(time) { + + var value, + parsed = parseFloat(time); + + if (typeof time === "string" && time.substring(0, 1) === "+") { + if (parsed && parsed > 0) value = wm.time + parsed; + } else { + if (parsed > wm.time) value = parsed; + } + + return value; + + }; + + /** + * Converts an input value (which can be a uint, a string or an array of the previous two) to an + * array of MIDI note numbers. + * + * @method _convertNoteToArray + * @param [note] {Number|Array|String} + * @returns {Array} + * @protected + */ + Output.prototype._convertNoteToArray = function(note) { + + var notes = []; + + if ( !Array.isArray(note) ) { note = [note]; } + + note.forEach(function(item) { + notes.push(wm.guessNoteNumber(item)); + }); + + return notes; + + }; + + // Check if RequireJS/AMD is used. If it is, use it to define our module instead of + // polluting the global space. + if ( typeof define === "function" && typeof define.amd === "object") { + define([], function () { + return wm; + }); + } else if (typeof module !== "undefined" && module.exports) { + module.exports = wm; + } else { + if (!scope.WebMidi) { scope.WebMidi = wm; } + } + +}(this));