diff --git a/.eslintrc b/.eslintrc index 0d49b7d271..f43caa2d63 100644 --- a/.eslintrc +++ b/.eslintrc @@ -12,7 +12,8 @@ "extends": ["eslint:recommended", "prettier"], "plugins": ["prettier"], "parserOptions": { - "ecmaVersion": 2017 + "ecmaVersion": 2017, + "sourceType": "module" }, "rules": { "prettier/prettier": ["error"], diff --git a/Gruntfile.js b/Gruntfile.js index a076f30b05..99ccc5d183 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -251,6 +251,7 @@ module.exports = grunt => { src: ['test/node/**/*.js'], options: { reporter: reporter, + require: '@babel/register', ui: 'tdd' } } diff --git a/package-lock.json b/package-lock.json index 91eb2e6b2f..372e03be06 100644 --- a/package-lock.json +++ b/package-lock.json @@ -718,6 +718,28 @@ "semver": "^5.3.0" } }, + "@babel/register": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@babel/register/-/register-7.4.4.tgz", + "integrity": "sha512-sn51H88GRa00+ZoMqCVgOphmswG4b7mhf9VOB0LUBAieykq2GnRFerlN+JQkO/ntT7wz4jaHNSRPg9IdMPEUkA==", + "dev": true, + "requires": { + "core-js": "^3.0.0", + "find-cache-dir": "^2.0.0", + "lodash": "^4.17.11", + "mkdirp": "^0.5.1", + "pirates": "^4.0.0", + "source-map-support": "^0.5.9" + }, + "dependencies": { + "core-js": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.1.4.tgz", + "integrity": "sha512-YNZN8lt82XIMLnLirj9MhKDFZHalwzzrL9YLt6eb0T5D0EDl4IQ90IGkua8mHbnxNrkj1d8hbdizMc0Qmg1WnQ==", + "dev": true + } + } + }, "@babel/runtime": { "version": "7.3.4", "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.3.4.tgz", @@ -1194,7 +1216,8 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/aproba/-/aproba-1.2.0.tgz", "integrity": "sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==", - "dev": true + "dev": true, + "optional": true }, "archiver": { "version": "1.3.0", @@ -1303,6 +1326,7 @@ "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-1.1.4.tgz", "integrity": "sha1-u13KOCu5TwXhUZQ3PRb9O6HKEQ0=", "dev": true, + "optional": true, "requires": { "delegates": "^1.0.0", "readable-stream": "^2.0.6" @@ -1359,12 +1383,6 @@ "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=", "dev": true }, - "array-from": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/array-from/-/array-from-2.1.1.tgz", - "integrity": "sha1-z+nYwmYoudxa7MYqn12PHzUsEZU=", - "dev": true - }, "array-map": { "version": "0.0.0", "resolved": "https://registry.npmjs.org/array-map/-/array-map-0.0.0.tgz", @@ -1537,6 +1555,15 @@ } } }, + "babel-messages": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.23.0.tgz", + "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0" + } + }, "babel-plugin-istanbul": { "version": "5.1.4", "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-5.1.4.tgz", @@ -1559,12 +1586,113 @@ } } }, + "babel-plugin-static-fs": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/babel-plugin-static-fs/-/babel-plugin-static-fs-1.2.0.tgz", + "integrity": "sha512-7zsDPvDzCBwfbU53WKym5LxTe1PxQHE/dGo+EfIELlBcn08TpU7SlPJILcc6YVAyTrpVUNioQfWiUyMWk1DJVg==", + "dev": true, + "requires": { + "babel-template": "^6.3.13", + "babel-types": "^6.4.1", + "events": "^1.1.0" + }, + "dependencies": { + "events": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/events/-/events-1.1.1.tgz", + "integrity": "sha1-nr23Y1rQmccNzEwqH1AEKI6L2SQ=", + "dev": true + } + } + }, + "babel-runtime": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", + "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", + "dev": true, + "requires": { + "core-js": "^2.4.0", + "regenerator-runtime": "^0.11.0" + }, + "dependencies": { + "regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==", + "dev": true + } + } + }, + "babel-template": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-template/-/babel-template-6.26.0.tgz", + "integrity": "sha1-3gPi0WOWsGn0bdn/+FIfsaDjXgI=", + "dev": true, + "requires": { + "babel-runtime": "^6.26.0", + "babel-traverse": "^6.26.0", + "babel-types": "^6.26.0", + "babylon": "^6.18.0", + "lodash": "^4.17.4" + } + }, + "babel-traverse": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-traverse/-/babel-traverse-6.26.0.tgz", + "integrity": "sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4=", + "dev": true, + "requires": { + "babel-code-frame": "^6.26.0", + "babel-messages": "^6.23.0", + "babel-runtime": "^6.26.0", + "babel-types": "^6.26.0", + "babylon": "^6.18.0", + "debug": "^2.6.8", + "globals": "^9.18.0", + "invariant": "^2.2.2", + "lodash": "^4.17.4" + }, + "dependencies": { + "globals": { + "version": "9.18.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz", + "integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ==", + "dev": true + } + } + }, + "babel-types": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz", + "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", + "dev": true, + "requires": { + "babel-runtime": "^6.26.0", + "esutils": "^2.0.2", + "lodash": "^4.17.4", + "to-fast-properties": "^1.0.3" + }, + "dependencies": { + "to-fast-properties": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz", + "integrity": "sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=", + "dev": true + } + } + }, "babelify": { "version": "10.0.0", "resolved": "https://registry.npmjs.org/babelify/-/babelify-10.0.0.tgz", "integrity": "sha512-X40FaxyH7t3X+JFAKvb1H9wooWKLRCi8pg3m8poqtdZaIng+bjzp9RvKQCvRjF9isHiPkXspbbXT/zwXLtwgwg==", "dev": true }, + "babylon": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz", + "integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ==", + "dev": true + }, "backo2": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/backo2/-/backo2-1.0.2.tgz", @@ -1852,6 +1980,7 @@ "resolved": "https://registry.npmjs.org/boom/-/boom-0.4.2.tgz", "integrity": "sha1-emNune1O/O+xnO9JR6PGffrukRs=", "dev": true, + "optional": true, "requires": { "hoek": "0.9.x" }, @@ -1860,7 +1989,8 @@ "version": "0.9.1", "resolved": "https://registry.npmjs.org/hoek/-/hoek-0.9.1.tgz", "integrity": "sha1-PTIkYrrfB3Fup+uFuviAec3c5QU=", - "dev": true + "dev": true, + "optional": true } } }, @@ -1992,18 +2122,6 @@ } } }, - "brfs": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/brfs/-/brfs-2.0.2.tgz", - "integrity": "sha512-IrFjVtwu4eTJZyu8w/V2gxU7iLTtcHih67sgEdzrhjLBMHp2uYefUBfdM4k2UvcuWMgV7PQDZHSLeNWnLFKWVQ==", - "dev": true, - "requires": { - "quote-stream": "^1.0.1", - "resolve": "^1.1.5", - "static-module": "^3.0.2", - "through2": "^2.0.0" - } - }, "brorand": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.1.0.tgz", @@ -2242,12 +2360,6 @@ "integrity": "sha1-DTM+PwDqxQqhRUq9MO+MKl2ackI=", "dev": true }, - "buffer-equal": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/buffer-equal/-/buffer-equal-0.0.1.tgz", - "integrity": "sha1-kbx0sR6kBbyRa8aqkI+q+ltKrEs=", - "dev": true - }, "buffer-fill": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/buffer-fill/-/buffer-fill-1.0.0.tgz", @@ -2692,6 +2804,12 @@ "graceful-readlink": ">= 1.0.0" } }, + "commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", + "dev": true + }, "component-bind": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/component-bind/-/component-bind-1.0.0.tgz", @@ -2804,7 +2922,8 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=", - "dev": true + "dev": true, + "optional": true }, "constants-browserify": { "version": "1.0.0", @@ -3271,7 +3390,8 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=", - "dev": true + "dev": true, + "optional": true }, "depd": { "version": "1.1.2", @@ -3779,19 +3899,6 @@ "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", "dev": true }, - "escodegen": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.9.1.tgz", - "integrity": "sha512-6hTjO1NAWkHnDk3OqQ4YrCuwwmGHL9S3nPlzBOUG/R44rda3wLNrfvQ5fkSGjyhHFKM7ALPKcKGrwvCLe0lC7Q==", - "dev": true, - "requires": { - "esprima": "^3.1.3", - "estraverse": "^4.2.0", - "esutils": "^2.0.2", - "optionator": "^0.8.1", - "source-map": "~0.6.1" - } - }, "escope": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/escope/-/escope-3.6.0.tgz", @@ -4161,12 +4268,6 @@ } } }, - "esprima": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", - "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=", - "dev": true - }, "esprima-extract-comments": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/esprima-extract-comments/-/esprima-extract-comments-0.2.1.tgz", @@ -4217,12 +4318,6 @@ "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", "dev": true }, - "estree-is-function": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/estree-is-function/-/estree-is-function-1.0.0.tgz", - "integrity": "sha512-nSCWn1jkSq2QAtkaVLJZY2ezwcFO161HVc174zL1KPW3RJ+O6C3eJb8Nx7OXzvhoEv+nLgSR1g71oWUHUDTrJA==", - "dev": true - }, "esutils": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", @@ -4964,6 +5059,41 @@ } } }, + "find-cache-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-2.1.0.tgz", + "integrity": "sha512-Tq6PixE0w/VMFfCgbONnkiQIVol/JJL7nRMi20fqzA4NRs9AfeqMGeRdPi3wIhYkxjeBaWh2rxwapn5Tu3IqOQ==", + "dev": true, + "requires": { + "commondir": "^1.0.1", + "make-dir": "^2.0.0", + "pkg-dir": "^3.0.0" + }, + "dependencies": { + "make-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", + "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "dev": true, + "requires": { + "pify": "^4.0.1", + "semver": "^5.6.0" + } + }, + "pify": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", + "dev": true + }, + "semver": { + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz", + "integrity": "sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==", + "dev": true + } + } + }, "find-up": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", @@ -5180,7 +5310,8 @@ "version": "2.1.1", "resolved": false, "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", - "dev": true + "dev": true, + "optional": true }, "aproba": { "version": "1.2.0", @@ -5204,13 +5335,15 @@ "version": "1.0.0", "resolved": false, "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", - "dev": true + "dev": true, + "optional": true }, "brace-expansion": { "version": "1.1.11", "resolved": false, "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", "dev": true, + "optional": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -5227,19 +5360,22 @@ "version": "1.1.0", "resolved": false, "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=", - "dev": true + "dev": true, + "optional": true }, "concat-map": { "version": "0.0.1", "resolved": false, "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", - "dev": true + "dev": true, + "optional": true }, "console-control-strings": { "version": "1.1.0", "resolved": false, "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=", - "dev": true + "dev": true, + "optional": true }, "core-util-is": { "version": "1.0.2", @@ -5370,7 +5506,8 @@ "version": "2.0.3", "resolved": false, "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", - "dev": true + "dev": true, + "optional": true }, "ini": { "version": "1.3.5", @@ -5384,6 +5521,7 @@ "resolved": false, "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", "dev": true, + "optional": true, "requires": { "number-is-nan": "^1.0.0" } @@ -5400,6 +5538,7 @@ "resolved": false, "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", "dev": true, + "optional": true, "requires": { "brace-expansion": "^1.1.7" } @@ -5408,13 +5547,15 @@ "version": "0.0.8", "resolved": false, "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", - "dev": true + "dev": true, + "optional": true }, "minipass": { "version": "2.3.5", "resolved": false, "integrity": "sha512-Gi1W4k059gyRbyVUZQ4mEqLm0YIUiGYfvxhF6SIlk3ui1WVxMTGfGdQ2SInh3PDrRTVvPKgULkpJtT4RH10+VA==", "dev": true, + "optional": true, "requires": { "safe-buffer": "^5.1.2", "yallist": "^3.0.0" @@ -5435,6 +5576,7 @@ "resolved": false, "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", "dev": true, + "optional": true, "requires": { "minimist": "0.0.8" } @@ -5530,7 +5672,8 @@ "version": "1.0.1", "resolved": false, "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", - "dev": true + "dev": true, + "optional": true }, "object-assign": { "version": "4.1.1", @@ -5544,6 +5687,7 @@ "resolved": false, "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", "dev": true, + "optional": true, "requires": { "wrappy": "1" } @@ -5639,7 +5783,8 @@ "version": "5.1.2", "resolved": false, "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "dev": true + "dev": true, + "optional": true }, "safer-buffer": { "version": "2.1.2", @@ -5681,6 +5826,7 @@ "resolved": false, "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", "dev": true, + "optional": true, "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", @@ -5702,6 +5848,7 @@ "resolved": false, "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "dev": true, + "optional": true, "requires": { "ansi-regex": "^2.0.0" } @@ -5750,13 +5897,15 @@ "version": "1.0.2", "resolved": false, "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", - "dev": true + "dev": true, + "optional": true }, "yallist": { "version": "3.0.3", "resolved": false, "integrity": "sha512-S+Zk8DEWE6oKpV+vI3qWkaK+jSbIK86pCwe2IF/xwIpQ8jEuxpw9NyaGjmp9+BoJv5FV2piqCDcoCtStppiq2A==", - "dev": true + "dev": true, + "optional": true } } }, @@ -5765,6 +5914,7 @@ "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.11.tgz", "integrity": "sha1-XB+x8RdHcRTwYyoOtLcbPLD9MXE=", "dev": true, + "optional": true, "requires": { "graceful-fs": "^4.1.2", "inherits": "~2.0.0", @@ -5789,6 +5939,7 @@ "resolved": "https://registry.npmjs.org/gauge/-/gauge-2.7.4.tgz", "integrity": "sha1-LANAXHU4w51+s3sxcCLjJfsBi/c=", "dev": true, + "optional": true, "requires": { "aproba": "^1.0.3", "console-control-strings": "^1.0.0", @@ -7094,7 +7245,8 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=", - "dev": true + "dev": true, + "optional": true }, "has-value": { "version": "1.0.0", @@ -9186,15 +9338,6 @@ "yallist": "^2.1.2" } }, - "magic-string": { - "version": "0.22.5", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.22.5.tgz", - "integrity": "sha512-oreip9rJZkzvA8Qzk9HFs8fZGF/u7H/gtrE8EN6RjKJ9kh2HlC+yQ2QezifqTZfGyiuAV0dRv5a+y/8gBb1m9w==", - "dev": true, - "requires": { - "vlq": "^0.2.2" - } - }, "make-dir": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.1.0.tgz", @@ -9398,23 +9541,6 @@ "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=", "dev": true }, - "merge-source-map": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/merge-source-map/-/merge-source-map-1.0.4.tgz", - "integrity": "sha1-pd5GU42uhNQRTMXqArR3KmNGcB8=", - "dev": true, - "requires": { - "source-map": "^0.5.6" - }, - "dependencies": { - "source-map": { - "version": "0.5.7", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", - "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", - "dev": true - } - } - }, "methods": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", @@ -10083,6 +10209,12 @@ } } }, + "node-modules-regexp": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-modules-regexp/-/node-modules-regexp-1.0.0.tgz", + "integrity": "sha1-jZ2+KJZKSsVxLpExZCEHxx6Q7EA=", + "dev": true + }, "node-releases": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-1.1.11.tgz", @@ -10191,6 +10323,7 @@ "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-4.1.2.tgz", "integrity": "sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg==", "dev": true, + "optional": true, "requires": { "are-we-there-yet": "~1.1.2", "console-control-strings": "~1.1.0", @@ -11356,12 +11489,6 @@ } } }, - "object-inspect": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.4.1.tgz", - "integrity": "sha512-wqdhLpfCUbEsoEwl3FXwGyv8ief1k/1aUdIPCqVnupM6e8l63BEJdiF/0swtn04/8p05tG/T0FrpTlfwvljOdw==", - "dev": true - }, "object-keys": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", @@ -11950,6 +12077,35 @@ "pinkie": "^2.0.0" } }, + "pirates": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.1.tgz", + "integrity": "sha512-WuNqLTbMI3tmfef2TKxlQmAiLHKtFhlsCZnPIpuv2Ow0RDVO8lfy1Opf4NUzlMXLjPl+Men7AuVdX6TA+s+uGA==", + "dev": true, + "requires": { + "node-modules-regexp": "^1.0.0" + } + }, + "pkg-dir": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz", + "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", + "dev": true, + "requires": { + "find-up": "^3.0.0" + }, + "dependencies": { + "find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "dev": true, + "requires": { + "locate-path": "^3.0.0" + } + } + } + }, "platform": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.5.tgz", @@ -12178,6 +12334,7 @@ "resolved": "https://registry.npmjs.org/pump/-/pump-1.0.3.tgz", "integrity": "sha512-8k0JupWme55+9tCVE+FS5ULT3K6AbgqrGa58lTT49RpyfwwcGedHqaC5LlQNdEAumn/wFsu6aPwkuPMioy8kqw==", "dev": true, + "optional": true, "requires": { "end-of-stream": "^1.1.0", "once": "^1.3.1" @@ -12312,17 +12469,6 @@ "integrity": "sha1-nsYfeQSYdXB9aUFFlv2Qek1xHnM=", "dev": true }, - "quote-stream": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/quote-stream/-/quote-stream-1.0.2.tgz", - "integrity": "sha1-hJY/jJwmuULhU/7rU6rnRlK34LI=", - "dev": true, - "requires": { - "buffer-equal": "0.0.1", - "minimist": "^1.1.3", - "through2": "^2.0.0" - } - }, "randombytes": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.0.6.tgz", @@ -12854,7 +13000,8 @@ "version": "2.2.8", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.2.8.tgz", "integrity": "sha1-5Dm+Kq7jJzIZUnMPmaiSnk/FBYI=", - "dev": true + "dev": true, + "optional": true }, "ripemd160": { "version": "2.0.2", @@ -13015,20 +13162,6 @@ } } }, - "scope-analyzer": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/scope-analyzer/-/scope-analyzer-2.0.5.tgz", - "integrity": "sha512-+U5H0417mnTEstCD5VwOYO7V4vYuSqwqjFap40ythe67bhMFL5C3UgPwyBv7KDJsqUBIKafOD57xMlh1rN7eaw==", - "dev": true, - "requires": { - "array-from": "^2.1.1", - "es6-map": "^0.1.5", - "es6-set": "^0.1.5", - "es6-symbol": "^3.1.1", - "estree-is-function": "^1.0.0", - "get-assigned-identifiers": "^1.1.0" - } - }, "semver": { "version": "5.4.1", "resolved": "https://registry.npmjs.org/semver/-/semver-5.4.1.tgz", @@ -13233,12 +13366,6 @@ "safe-buffer": "^5.0.1" } }, - "shallow-copy": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/shallow-copy/-/shallow-copy-0.0.1.tgz", - "integrity": "sha1-QV9CcC1z2BAzApLMXuhurhoRoXA=", - "dev": true - }, "shasum": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/shasum/-/shasum-1.0.2.tgz", @@ -13604,6 +13731,16 @@ "urix": "^0.1.0" } }, + "source-map-support": { + "version": "0.5.12", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.12.tgz", + "integrity": "sha512-4h2Pbvyy15EE02G+JOZpUCmqWJuqrs+sEkzewTm++BPi7Hvn/HwcqLAcNxYAyI0x13CpPPn+kMjl+hplXMHITQ==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, "source-map-url": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.0.tgz", @@ -13695,15 +13832,6 @@ "integrity": "sha1-15fhtVHKemOd7AI33G60u5vhfTU=", "dev": true }, - "static-eval": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/static-eval/-/static-eval-2.0.2.tgz", - "integrity": "sha512-N/D219Hcr2bPjLxPiV+TQE++Tsmrady7TqAJugLy7Xk1EumfDWS/f5dtBbkRCGE7wKKXuYockQoj8Rm2/pVKyg==", - "dev": true, - "requires": { - "escodegen": "^1.8.1" - } - }, "static-extend": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", @@ -13725,28 +13853,6 @@ } } }, - "static-module": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/static-module/-/static-module-3.0.2.tgz", - "integrity": "sha512-W3aj4MvIMKDoZhVR7XhX7aSlJdw/nf1QAZyJzUUDVkjeBliXNoa0IUUUsAsXm/Wp7+LxDLeZ3idnAZEDg82m2Q==", - "dev": true, - "requires": { - "acorn-node": "^1.3.0", - "concat-stream": "~1.6.0", - "convert-source-map": "^1.5.1", - "duplexer2": "~0.1.4", - "escodegen": "~1.9.0", - "has": "^1.0.1", - "magic-string": "^0.22.4", - "merge-source-map": "1.0.4", - "object-inspect": "~1.4.0", - "readable-stream": "~2.3.3", - "scope-analyzer": "^2.0.1", - "shallow-copy": "~0.0.1", - "static-eval": "^2.0.1", - "through2": "~2.0.3" - } - }, "statuses": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz", @@ -14852,12 +14958,6 @@ } } }, - "vlq": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/vlq/-/vlq-0.2.3.tgz", - "integrity": "sha512-DRibZL6DsNhIgYQ+wNdWDL2SL3bKPlVrRiBqV5yuMm++op8W4kGFtaQfCs4KEJn0wBZcHVHJ3eoywX8983k1ow==", - "dev": true - }, "vm-browserify": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-1.1.0.tgz", @@ -14936,6 +15036,7 @@ "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.2.tgz", "integrity": "sha512-ijDLlyQ7s6x1JgCLur53osjm/UXUYD9+0PbYKrBsYisYXzCxN+HC3mYDNy/dWdmf3AwqwU3CXwDCvsNgGK1S0w==", "dev": true, + "optional": true, "requires": { "string-width": "^1.0.2" } diff --git a/package.json b/package.json index b7beab0e81..262387ff26 100644 --- a/package.json +++ b/package.json @@ -39,10 +39,11 @@ "devDependencies": { "@babel/core": "^7.4.0", "@babel/preset-env": "^7.4.2", + "@babel/register": "^7.4.4", "all-contributors-cli": "^5.11.0", "babel-plugin-istanbul": "^5.1.4", + "babel-plugin-static-fs": "^1.2.0", "babelify": "^10.0.0", - "brfs": "^2.0.2", "browserify": "^16.2.3", "chai": "^3.5.0", "connect-modrewrite": "^0.10.1", diff --git a/src/app.js b/src/app.js index df05208951..9e8ff19e35 100644 --- a/src/app.js +++ b/src/app.js @@ -1,89 +1,87 @@ -'use strict'; - // core -var p5 = require('./core/main'); -require('./core/constants'); -require('./core/environment'); -require('./core/error_helpers'); -require('./core/helpers'); -require('./core/legacy'); -require('./core/p5.Element'); -require('./core/p5.Graphics'); -require('./core/p5.Renderer'); -require('./core/p5.Renderer2D'); -require('./core/rendering'); -require('./core/shim'); -require('./core/structure'); -require('./core/transform'); -require('./core/shape/2d_primitives'); -require('./core/shape/attributes'); -require('./core/shape/curves'); -require('./core/shape/vertex'); +import p5 from './core/main'; +import './core/constants'; +import './core/environment'; +import './core/error_helpers'; +import './core/helpers'; +import './core/legacy'; +import './core/p5.Element'; +import './core/p5.Graphics'; +import './core/p5.Renderer'; +import './core/p5.Renderer2D'; +import './core/rendering'; +import './core/shim'; +import './core/structure'; +import './core/transform'; +import './core/shape/2d_primitives'; +import './core/shape/attributes'; +import './core/shape/curves'; +import './core/shape/vertex'; // color -require('./color/color_conversion'); -require('./color/creating_reading'); -require('./color/p5.Color'); -require('./color/setting'); +import './color/color_conversion'; +import './color/creating_reading'; +import './color/p5.Color'; +import './color/setting'; // data -require('./data/p5.TypedDict'); -require('./data/local_storage.js'); +import './data/p5.TypedDict'; +import './data/local_storage.js'; // events -require('./events/acceleration'); -require('./events/keyboard'); -require('./events/mouse'); -require('./events/touch'); +import './events/acceleration'; +import './events/keyboard'; +import './events/mouse'; +import './events/touch'; // image -require('./image/filters'); -require('./image/image'); -require('./image/loading_displaying'); -require('./image/p5.Image'); -require('./image/pixels'); +import './image/filters'; +import './image/image'; +import './image/loading_displaying'; +import './image/p5.Image'; +import './image/pixels'; // io -require('./io/files'); -require('./io/p5.Table'); -require('./io/p5.TableRow'); -require('./io/p5.XML'); +import './io/files'; +import './io/p5.Table'; +import './io/p5.TableRow'; +import './io/p5.XML'; // math -require('./math/calculation'); -require('./math/math'); -require('./math/noise'); -require('./math/p5.Vector'); -require('./math/random'); -require('./math/trigonometry'); +import './math/calculation'; +import './math/math'; +import './math/noise'; +import './math/p5.Vector'; +import './math/random'; +import './math/trigonometry'; // typography -require('./typography/attributes'); -require('./typography/loading_displaying'); -require('./typography/p5.Font'); +import './typography/attributes'; +import './typography/loading_displaying'; +import './typography/p5.Font'; // utilities -require('./utilities/array_functions'); -require('./utilities/conversion'); -require('./utilities/string_functions'); -require('./utilities/time_date'); +import './utilities/array_functions'; +import './utilities/conversion'; +import './utilities/string_functions'; +import './utilities/time_date'; // webgl -require('./webgl/3d_primitives'); -require('./webgl/interaction'); -require('./webgl/light'); -require('./webgl/loading'); -require('./webgl/material'); -require('./webgl/p5.Camera'); -require('./webgl/p5.Geometry'); -require('./webgl/p5.Matrix'); -require('./webgl/p5.RendererGL.Immediate'); -require('./webgl/p5.RendererGL'); -require('./webgl/p5.RendererGL.Retained'); -require('./webgl/p5.Shader'); -require('./webgl/p5.Texture'); -require('./webgl/text'); +import './webgl/3d_primitives'; +import './webgl/interaction'; +import './webgl/light'; +import './webgl/loading'; +import './webgl/material'; +import './webgl/p5.Camera'; +import './webgl/p5.Geometry'; +import './webgl/p5.Matrix'; +import './webgl/p5.RendererGL.Immediate'; +import './webgl/p5.RendererGL'; +import './webgl/p5.RendererGL.Retained'; +import './webgl/p5.Shader'; +import './webgl/p5.Texture'; +import './webgl/text'; -require('./core/init'); +import './core/init'; module.exports = p5; diff --git a/src/color/color_conversion.js b/src/color/color_conversion.js index 2f5ee25e4c..7f431bcb38 100644 --- a/src/color/color_conversion.js +++ b/src/color/color_conversion.js @@ -5,8 +5,6 @@ * @requires core */ -'use strict'; - /** * Conversions adapted from . * @@ -15,19 +13,19 @@ * interchangeably. */ -var p5 = require('../core/main'); +import p5 from '../core/main'; p5.ColorConversion = {}; /** * Convert an HSBA array to HSLA. */ -p5.ColorConversion._hsbaToHSLA = function(hsba) { - var hue = hsba[0]; - var sat = hsba[1]; - var val = hsba[2]; +p5.ColorConversion._hsbaToHSLA = hsba => { + const hue = hsba[0]; + let sat = hsba[1]; + const val = hsba[2]; // Calculate lightness. - var li = (2 - sat) * val / 2; + const li = (2 - sat) * val / 2; // Convert saturation. if (li !== 0) { @@ -47,21 +45,21 @@ p5.ColorConversion._hsbaToHSLA = function(hsba) { /** * Convert an HSBA array to RGBA. */ -p5.ColorConversion._hsbaToRGBA = function(hsba) { - var hue = hsba[0] * 6; // We will split hue into 6 sectors. - var sat = hsba[1]; - var val = hsba[2]; +p5.ColorConversion._hsbaToRGBA = hsba => { + const hue = hsba[0] * 6; // We will split hue into 6 sectors. + const sat = hsba[1]; + const val = hsba[2]; - var RGBA = []; + let RGBA = []; if (sat === 0) { RGBA = [val, val, val, hsba[3]]; // Return early if grayscale. } else { - var sector = Math.floor(hue); - var tint1 = val * (1 - sat); - var tint2 = val * (1 - sat * (hue - sector)); - var tint3 = val * (1 - sat * (1 + sector - hue)); - var red, green, blue; + const sector = Math.floor(hue); + const tint1 = val * (1 - sat); + const tint2 = val * (1 - sat * (hue - sector)); + const tint3 = val * (1 - sat * (1 + sector - hue)); + let red, green, blue; if (sector === 1) { // Yellow to green. red = tint2; @@ -102,13 +100,13 @@ p5.ColorConversion._hsbaToRGBA = function(hsba) { /** * Convert an HSLA array to HSBA. */ -p5.ColorConversion._hslaToHSBA = function(hsla) { - var hue = hsla[0]; - var sat = hsla[1]; - var li = hsla[2]; +p5.ColorConversion._hslaToHSBA = hsla => { + const hue = hsla[0]; + let sat = hsla[1]; + const li = hsla[2]; // Calculate brightness. - var val; + let val; if (li < 0.5) { val = (1 + sat) * li; } else { @@ -130,18 +128,18 @@ p5.ColorConversion._hslaToHSBA = function(hsla) { * components, and pick a convenient third one ('zest') so that we don't need * to calculate formal HSBA saturation. */ -p5.ColorConversion._hslaToRGBA = function(hsla) { - var hue = hsla[0] * 6; // We will split hue into 6 sectors. - var sat = hsla[1]; - var li = hsla[2]; +p5.ColorConversion._hslaToRGBA = hsla => { + const hue = hsla[0] * 6; // We will split hue into 6 sectors. + const sat = hsla[1]; + const li = hsla[2]; - var RGBA = []; + let RGBA = []; if (sat === 0) { RGBA = [li, li, li, hsla[3]]; // Return early if grayscale. } else { // Calculate brightness. - var val; + let val; if (li < 0.5) { val = (1 + sat) * li; } else { @@ -149,10 +147,10 @@ p5.ColorConversion._hslaToRGBA = function(hsla) { } // Define zest. - var zest = 2 * li - val; + const zest = 2 * li - val; // Implement projection (project onto green by default). - var hzvToRGB = function(hue, zest, val) { + const hzvToRGB = (hue, zest, val) => { if (hue < 0) { // Hue must wrap to allow projection onto red and blue. hue += 6; @@ -189,15 +187,15 @@ p5.ColorConversion._hslaToRGBA = function(hsla) { /** * Convert an RGBA array to HSBA. */ -p5.ColorConversion._rgbaToHSBA = function(rgba) { - var red = rgba[0]; - var green = rgba[1]; - var blue = rgba[2]; +p5.ColorConversion._rgbaToHSBA = rgba => { + const red = rgba[0]; + const green = rgba[1]; + const blue = rgba[2]; - var val = Math.max(red, green, blue); - var chroma = val - Math.min(red, green, blue); + const val = Math.max(red, green, blue); + const chroma = val - Math.min(red, green, blue); - var hue, sat; + let hue, sat; if (chroma === 0) { // Return early if grayscale. hue = 0; @@ -228,17 +226,17 @@ p5.ColorConversion._rgbaToHSBA = function(rgba) { /** * Convert an RGBA array to HSLA. */ -p5.ColorConversion._rgbaToHSLA = function(rgba) { - var red = rgba[0]; - var green = rgba[1]; - var blue = rgba[2]; +p5.ColorConversion._rgbaToHSLA = rgba => { + const red = rgba[0]; + const green = rgba[1]; + const blue = rgba[2]; - var val = Math.max(red, green, blue); - var min = Math.min(red, green, blue); - var li = val + min; // We will halve this later. - var chroma = val - min; + const val = Math.max(red, green, blue); + const min = Math.min(red, green, blue); + const li = val + min; // We will halve this later. + const chroma = val - min; - var hue, sat; + let hue, sat; if (chroma === 0) { // Return early if grayscale. hue = 0; @@ -270,4 +268,4 @@ p5.ColorConversion._rgbaToHSLA = function(rgba) { return [hue / 6, sat, li / 2, rgba[3]]; }; -module.exports = p5.ColorConversion; +export default p5.ColorConversion; diff --git a/src/color/creating_reading.js b/src/color/creating_reading.js index 0c78a98382..d9a9535723 100644 --- a/src/color/creating_reading.js +++ b/src/color/creating_reading.js @@ -6,12 +6,10 @@ * @requires constants */ -'use strict'; - -var p5 = require('../core/main'); -var constants = require('../core/constants'); -require('./p5.Color'); -require('../core/error_helpers'); +import p5 from '../core/main'; +import * as constants from '../core/constants'; +import './p5.Color'; +import '../core/error_helpers'; /** * Extracts the alpha value from a color or pixel array. @@ -325,7 +323,7 @@ p5.prototype.color = function() { return arguments[0]; // Do nothing if argument is already a color object. } - var args = arguments[0] instanceof Array ? arguments[0] : arguments; + const args = arguments[0] instanceof Array ? arguments[0] : arguments; return new p5.Color(this, args); }; @@ -442,18 +440,14 @@ p5.prototype.hue = function(c) { p5.prototype.lerpColor = function(c1, c2, amt) { p5._validateParameters('lerpColor', arguments); - var mode = this._colorMode; - var maxes = this._colorMaxes; - var l0, l1, l2, l3; - var fromArray, toArray; + const mode = this._colorMode; + const maxes = this._colorMaxes; + let l0, l1, l2, l3; + let fromArray, toArray; if (mode === constants.RGB) { - fromArray = c1.levels.map(function(level) { - return level / 255; - }); - toArray = c2.levels.map(function(level) { - return level / 255; - }); + fromArray = c1.levels.map(level => level / 255); + toArray = c2.levels.map(level => level / 255); } else if (mode === constants.HSB) { c1._getBrightness(); // Cache hsba so it definitely exists. c2._getBrightness(); @@ -465,7 +459,7 @@ p5.prototype.lerpColor = function(c1, c2, amt) { fromArray = c1.hsla; toArray = c2.hsla; } else { - throw new Error(mode + 'cannot be used for interpolation.'); + throw new Error(`${mode}cannot be used for interpolation.`); } // Prevent extrapolation. @@ -474,9 +468,7 @@ p5.prototype.lerpColor = function(c1, c2, amt) { // Define lerp here itself if user isn't using math module. // Maintains the definition as found in math/calculation.js if (typeof this.lerp === 'undefined') { - this.lerp = function(start, stop, amt) { - return amt * (stop - start) + start; - }; + this.lerp = (start, stop, amt) => amt * (stop - start) + start; } // Perform interpolation. @@ -600,4 +592,4 @@ p5.prototype.saturation = function(c) { return this.color(c)._getSaturation(); }; -module.exports = p5; +export default p5; diff --git a/src/color/p5.Color.js b/src/color/p5.Color.js index 9ec2a33ac2..6d3e415f82 100644 --- a/src/color/p5.Color.js +++ b/src/color/p5.Color.js @@ -7,11 +7,9 @@ * @requires color_conversion */ -'use strict'; - -var p5 = require('../core/main'); -var constants = require('../core/constants'); -var color_conversion = require('./color_conversion'); +import p5 from '../core/main'; +import * as constants from '../core/constants'; +import color_conversion from './color_conversion'; /** * Each color stores the color mode and level maxes that applied at the @@ -39,7 +37,7 @@ p5.Color = function(pInst, vals) { this.mode !== constants.HSL && this.mode !== constants.HSB ) { - throw new Error(this.mode + ' is an invalid colorMode.'); + throw new Error(`${this.mode} is an invalid colorMode.`); } else { this._array = p5.Color._parseInputs.apply(this, vals); } @@ -84,9 +82,9 @@ p5.Color = function(pInst, vals) { * canvas with text representation of color */ p5.Color.prototype.toString = function(format) { - var a = this.levels; - var f = this._array; - var alpha = f[3]; // String representation uses normalized alpha + const a = this.levels; + const f = this._array; + const alpha = f[3]; // String representation uses normalized alpha switch (format) { case '#rrggbb': @@ -370,10 +368,10 @@ p5.Color.prototype.setAlpha = function(new_alpha) { // calculates and stores the closest screen levels p5.Color.prototype._calculateLevels = function() { - var array = this._array; + const array = this._array; // (loop backwards for performance) - var levels = (this.levels = new Array(array.length)); - for (var i = array.length - 1; i >= 0; --i) { + const levels = (this.levels = new Array(array.length)); + for (let i = array.length - 1; i >= 0; --i) { levels[i] = Math.round(array[i] * 255); } }; @@ -465,7 +463,7 @@ p5.Color.prototype._getSaturation = function() { /** * CSS named colors. */ -var namedColors = { +const namedColors = { aliceblue: '#f0f8ff', antiquewhite: '#faebd7', aqua: '#00ffff', @@ -623,15 +621,15 @@ var namedColors = { * Note that RGB values of .9 are not parsed by IE, but are supported here for * color string consistency. */ -var WHITESPACE = /\s*/; // Match zero or more whitespace characters. -var INTEGER = /(\d{1,3})/; // Match integers: 79, 255, etc. -var DECIMAL = /((?:\d+(?:\.\d+)?)|(?:\.\d+))/; // Match 129.6, 79, .9, etc. -var PERCENT = new RegExp(DECIMAL.source + '%'); // Match 12.9%, 79%, .9%, etc. +const WHITESPACE = /\s*/; // Match zero or more whitespace characters. +const INTEGER = /(\d{1,3})/; // Match integers: 79, 255, etc. +const DECIMAL = /((?:\d+(?:\.\d+)?)|(?:\.\d+))/; // Match 129.6, 79, .9, etc. +const PERCENT = new RegExp(`${DECIMAL.source}%`); // Match 12.9%, 79%, .9%, etc. /** * Full color string patterns. The capture groups are necessary. */ -var colorPatterns = { +const colorPatterns = { // Match colors in format #XXX, e.g. #416. HEX3: /^#([a-f0-9])([a-f0-9])([a-f0-9])$/i, @@ -795,11 +793,11 @@ var colorPatterns = { * */ p5.Color._parseInputs = function(r, g, b, a) { - var numArgs = arguments.length; - var mode = this.mode; - var maxes = this.maxes[mode]; - var results = []; - var i; + const numArgs = arguments.length; + const mode = this.mode; + const maxes = this.maxes[mode]; + let results = []; + let i; if (numArgs >= 3) { // Argument is a list of component values. @@ -818,7 +816,7 @@ p5.Color._parseInputs = function(r, g, b, a) { // Constrain components to the range [0,1]. // (loop backwards for performance) for (i = results.length - 1; i >= 0; --i) { - var result = results[i]; + const result = results[i]; if (result < 0) { results[i] = 0; } else if (result > 1) { @@ -835,7 +833,7 @@ p5.Color._parseInputs = function(r, g, b, a) { return results; } } else if (numArgs === 1 && typeof r === 'string') { - var str = r.trim().toLowerCase(); + const str = r.trim().toLowerCase(); // Return if string is a named colour. if (namedColors[str]) { @@ -847,59 +845,47 @@ p5.Color._parseInputs = function(r, g, b, a) { // #rgb results = colorPatterns.HEX3.exec(str) .slice(1) - .map(function(color) { - return parseInt(color + color, 16) / 255; - }); + .map(color => parseInt(color + color, 16) / 255); results[3] = 1; return results; } else if (colorPatterns.HEX6.test(str)) { // #rrggbb results = colorPatterns.HEX6.exec(str) .slice(1) - .map(function(color) { - return parseInt(color, 16) / 255; - }); + .map(color => parseInt(color, 16) / 255); results[3] = 1; return results; } else if (colorPatterns.HEX4.test(str)) { // #rgba results = colorPatterns.HEX4.exec(str) .slice(1) - .map(function(color) { - return parseInt(color + color, 16) / 255; - }); + .map(color => parseInt(color + color, 16) / 255); return results; } else if (colorPatterns.HEX8.test(str)) { // #rrggbbaa results = colorPatterns.HEX8.exec(str) .slice(1) - .map(function(color) { - return parseInt(color, 16) / 255; - }); + .map(color => parseInt(color, 16) / 255); return results; } else if (colorPatterns.RGB.test(str)) { // rgb(R,G,B) results = colorPatterns.RGB.exec(str) .slice(1) - .map(function(color) { - return color / 255; - }); + .map(color => color / 255); results[3] = 1; return results; } else if (colorPatterns.RGB_PERCENT.test(str)) { // rgb(R%,G%,B%) results = colorPatterns.RGB_PERCENT.exec(str) .slice(1) - .map(function(color) { - return parseFloat(color) / 100; - }); + .map(color => parseFloat(color) / 100); results[3] = 1; return results; } else if (colorPatterns.RGBA.test(str)) { // rgba(R,G,B,A) results = colorPatterns.RGBA.exec(str) .slice(1) - .map(function(color, idx) { + .map((color, idx) => { if (idx === 3) { return parseFloat(color); } @@ -910,7 +896,7 @@ p5.Color._parseInputs = function(r, g, b, a) { // rgba(R%,G%,B%,A%) results = colorPatterns.RGBA_PERCENT.exec(str) .slice(1) - .map(function(color, idx) { + .map((color, idx) => { if (idx === 3) { return parseFloat(color); } @@ -924,7 +910,7 @@ p5.Color._parseInputs = function(r, g, b, a) { // hsl(H,S,L) results = colorPatterns.HSL.exec(str) .slice(1) - .map(function(color, idx) { + .map((color, idx) => { if (idx === 0) { return parseInt(color, 10) / 360; } @@ -935,7 +921,7 @@ p5.Color._parseInputs = function(r, g, b, a) { // hsla(H,S,L,A) results = colorPatterns.HSLA.exec(str) .slice(1) - .map(function(color, idx) { + .map((color, idx) => { if (idx === 0) { return parseInt(color, 10) / 360; } else if (idx === 3) { @@ -944,9 +930,7 @@ p5.Color._parseInputs = function(r, g, b, a) { return parseInt(color, 10) / 100; }); } - results = results.map(function(value) { - return Math.max(Math.min(value, 1), 0); - }); + results = results.map(value => Math.max(Math.min(value, 1), 0)); if (results.length) { return color_conversion._hslaToRGBA(results); } @@ -956,7 +940,7 @@ p5.Color._parseInputs = function(r, g, b, a) { // hsb(H,S,B) results = colorPatterns.HSB.exec(str) .slice(1) - .map(function(color, idx) { + .map((color, idx) => { if (idx === 0) { return parseInt(color, 10) / 360; } @@ -967,7 +951,7 @@ p5.Color._parseInputs = function(r, g, b, a) { // hsba(H,S,B,A) results = colorPatterns.HSBA.exec(str) .slice(1) - .map(function(color, idx) { + .map((color, idx) => { if (idx === 0) { return parseInt(color, 10) / 360; } else if (idx === 3) { @@ -1008,14 +992,12 @@ p5.Color._parseInputs = function(r, g, b, a) { } // Constrain components to the range [0,1]. - results = results.map(function(value) { - return Math.max(Math.min(value, 1), 0); - }); + results = results.map(value => Math.max(Math.min(value, 1), 0)); } else { - throw new Error(arguments + 'is not a valid color representation.'); + throw new Error(`${arguments}is not a valid color representation.`); } return results; }; -module.exports = p5.Color; +export default p5.Color; diff --git a/src/color/setting.js b/src/color/setting.js index 9004f61585..4f914291b4 100644 --- a/src/color/setting.js +++ b/src/color/setting.js @@ -6,11 +6,9 @@ * @requires constants */ -'use strict'; - -var p5 = require('../core/main'); -var constants = require('../core/constants'); -require('./p5.Color'); +import p5 from '../core/main'; +import * as constants from '../core/constants'; +import './p5.Color'; /** * The background() function sets the color used for the background of the @@ -173,8 +171,8 @@ require('./p5.Color'); * @chainable */ -p5.prototype.background = function() { - this._renderer.background.apply(this._renderer, arguments); +p5.prototype.background = function(...args) { + this._renderer.background(...args); return this; }; @@ -317,7 +315,7 @@ p5.prototype.colorMode = function(mode, max1, max2, max3, maxA) { this._colorMode = mode; // Set color maxes. - var maxes = this._colorMaxes[mode]; + const maxes = this._colorMaxes[mode]; if (arguments.length === 2) { maxes[0] = max1; // Red maxes[1] = max1; // Green @@ -488,10 +486,10 @@ p5.prototype.colorMode = function(mode, max1, max2, max3, maxA) { * @param {p5.Color} color the fill color * @chainable */ -p5.prototype.fill = function() { +p5.prototype.fill = function(...args) { this._renderer._setProperty('_fillSet', true); this._renderer._setProperty('_doFill', true); - this._renderer.fill.apply(this._renderer, arguments); + this._renderer.fill(...args); return this; }; @@ -741,11 +739,11 @@ p5.prototype.noStroke = function() { * @chainable */ -p5.prototype.stroke = function() { +p5.prototype.stroke = function(...args) { this._renderer._setProperty('_strokeSet', true); this._renderer._setProperty('_doStroke', true); - this._renderer.stroke.apply(this._renderer, arguments); + this._renderer.stroke(...args); return this; }; -module.exports = p5; +export default p5; diff --git a/src/core/constants.js b/src/core/constants.js index 74f2950117..cfce6438d1 100644 --- a/src/core/constants.js +++ b/src/core/constants.js @@ -4,584 +4,580 @@ * @for p5 */ -'use strict'; +const _PI = Math.PI; -var PI = Math.PI; - -module.exports = { - // GRAPHICS RENDERER - /** - * The default, two-dimensional renderer. - * @property {String} P2D - * @final - */ - P2D: 'p2d', - /** - * One of the two render modes in p5.js: P2D (default renderer) and WEBGL - * Enables 3D render by introducing the third dimension: Z - * @property {String} WEBGL - * @final - */ - WEBGL: 'webgl', +// GRAPHICS RENDERER +/** + * The default, two-dimensional renderer. + * @property {String} P2D + * @final + */ +export const P2D = 'p2d'; +/** + * One of the two render modes in p5.js: P2D (default renderer) and WEBGL + * Enables 3D render by introducing the third dimension: Z + * @property {String} WEBGL + * @final + */ +export const WEBGL = 'webgl'; - // ENVIRONMENT - /** - * @property {String} ARROW - * @final - */ - ARROW: 'default', - /** - * @property {String} CROSS - * @final - */ - CROSS: 'crosshair', - /** - * @property {String} HAND - * @final - */ - HAND: 'pointer', - /** - * @property {String} MOVE - * @final - */ - MOVE: 'move', - /** - * @property {String} TEXT - * @final - */ - TEXT: 'text', - /** - * @property {String} WAIT - * @final - */ - WAIT: 'wait', +// ENVIRONMENT +/** + * @property {String} ARROW + * @final + */ +export const ARROW = 'default'; +/** + * @property {String} CROSS + * @final + */ +export const CROSS = 'crosshair'; +/** + * @property {String} HAND + * @final + */ +export const HAND = 'pointer'; +/** + * @property {String} MOVE + * @final + */ +export const MOVE = 'move'; +/** + * @property {String} TEXT + * @final + */ +export const TEXT = 'text'; +/** + * @property {String} WAIT + * @final + */ +export const WAIT = 'wait'; - // TRIGONOMETRY +// TRIGONOMETRY - /** - * HALF_PI is a mathematical constant with the value - * 1.57079632679489661923. It is half the ratio of the - * circumference of a circle to its diameter. It is useful in - * combination with the trigonometric functions sin() and cos(). - * - * @property {Number} HALF_PI - * @final - * - * @example - *
- * arc(50, 50, 80, 80, 0, HALF_PI); - *
- * - * @alt - * 80x80 white quarter-circle with curve toward bottom right of canvas. - * - */ - HALF_PI: PI / 2, - /** - * PI is a mathematical constant with the value - * 3.14159265358979323846. It is the ratio of the circumference - * of a circle to its diameter. It is useful in combination with - * the trigonometric functions sin() and cos(). - * - * @property {Number} PI - * @final - * - * @example - *
- * arc(50, 50, 80, 80, 0, PI); - *
- * - * @alt - * white half-circle with curve toward bottom of canvas. - * - */ - PI: PI, - /** - * QUARTER_PI is a mathematical constant with the value 0.7853982. - * It is one quarter the ratio of the circumference of a circle to - * its diameter. It is useful in combination with the trigonometric - * functions sin() and cos(). - * - * @property {Number} QUARTER_PI - * @final - * - * @example - *
- * arc(50, 50, 80, 80, 0, QUARTER_PI); - *
- * - * @alt - * white eighth-circle rotated about 40 degrees with curve bottom right canvas. - * - */ - QUARTER_PI: PI / 4, - /** - * TAU is an alias for TWO_PI, a mathematical constant with the - * value 6.28318530717958647693. It is twice the ratio of the - * circumference of a circle to its diameter. It is useful in - * combination with the trigonometric functions sin() and cos(). - * - * @property {Number} TAU - * @final - * - * @example - *
- * arc(50, 50, 80, 80, 0, TAU); - *
- * - * @alt - * 80x80 white ellipse shape in center of canvas. - * - */ - TAU: PI * 2, - /** - * TWO_PI is a mathematical constant with the value - * 6.28318530717958647693. It is twice the ratio of the - * circumference of a circle to its diameter. It is useful in - * combination with the trigonometric functions sin() and cos(). - * - * @property {Number} TWO_PI - * @final - * - * @example - *
- * arc(50, 50, 80, 80, 0, TWO_PI); - *
- * - * @alt - * 80x80 white ellipse shape in center of canvas. - * - */ - TWO_PI: PI * 2, - /** - * Constant to be used with angleMode() function, to set the mode which - * p5.js interprates and calculates angles (either DEGREES or RADIANS). - * @property {String} DEGREES - * @final - * - * @example - *
- * function setup() { - * angleMode(DEGREES); - * } - *
- */ - DEGREES: 'degrees', - /** - * Constant to be used with angleMode() function, to set the mode which - * p5.js interprates and calculates angles (either RADIANS or DEGREES). - * @property {String} RADIANS - * @final - * - * @example - *
- * function setup() { - * angleMode(RADIANS); - * } - *
- */ - RADIANS: 'radians', - DEG_TO_RAD: PI / 180.0, - RAD_TO_DEG: 180.0 / PI, +/** + * HALF_PI is a mathematical constant with the value + * 1.57079632679489661923. It is half the ratio of the + * circumference of a circle to its diameter. It is useful in + * combination with the trigonometric functions sin() and cos(). + * + * @property {Number} HALF_PI + * @final + * + * @example + *
+ * arc(50, 50, 80, 80, 0, HALF_PI); + *
+ * + * @alt + * 80x80 white quarter-circle with curve toward bottom right of canvas. + * + */ +export const HALF_PI = _PI / 2; +/** + * PI is a mathematical constant with the value + * 3.14159265358979323846. It is the ratio of the circumference + * of a circle to its diameter. It is useful in combination with + * the trigonometric functions sin() and cos(). + * + * @property {Number} PI + * @final + * + * @example + *
+ * arc(50, 50, 80, 80, 0, PI); + *
+ * + * @alt + * white half-circle with curve toward bottom of canvas. + * + */ +export const PI = _PI; +/** + * QUARTER_PI is a mathematical constant with the value 0.7853982. + * It is one quarter the ratio of the circumference of a circle to + * its diameter. It is useful in combination with the trigonometric + * functions sin() and cos(). + * + * @property {Number} QUARTER_PI + * @final + * + * @example + *
+ * arc(50, 50, 80, 80, 0, QUARTER_PI); + *
+ * + * @alt + * white eighth-circle rotated about 40 degrees with curve bottom right canvas. + * + */ +export const QUARTER_PI = _PI / 4; +/** + * TAU is an alias for TWO_PI, a mathematical constant with the + * value 6.28318530717958647693. It is twice the ratio of the + * circumference of a circle to its diameter. It is useful in + * combination with the trigonometric functions sin() and cos(). + * + * @property {Number} TAU + * @final + * + * @example + *
+ * arc(50, 50, 80, 80, 0, TAU); + *
+ * + * @alt + * 80x80 white ellipse shape in center of canvas. + * + */ +export const TAU = _PI * 2; +/** + * TWO_PI is a mathematical constant with the value + * 6.28318530717958647693. It is twice the ratio of the + * circumference of a circle to its diameter. It is useful in + * combination with the trigonometric functions sin() and cos(). + * + * @property {Number} TWO_PI + * @final + * + * @example + *
+ * arc(50, 50, 80, 80, 0, TWO_PI); + *
+ * + * @alt + * 80x80 white ellipse shape in center of canvas. + * + */ +export const TWO_PI = _PI * 2; +/** + * Constant to be used with angleMode() function, to set the mode which + * p5.js interprates and calculates angles (either DEGREES or RADIANS). + * @property {String} DEGREES + * @final + * + * @example + *
+ * function setup() { + * angleMode(DEGREES); + * } + *
+ */ +export const DEGREES = 'degrees'; +/** + * Constant to be used with angleMode() function, to set the mode which + * p5.js interprates and calculates angles (either RADIANS or DEGREES). + * @property {String} RADIANS + * @final + * + * @example + *
+ * function setup() { + * angleMode(RADIANS); + * } + *
+ */ +export const RADIANS = 'radians'; +export const DEG_TO_RAD = _PI / 180.0; +export const RAD_TO_DEG = 180.0 / _PI; - // SHAPE - /** - * @property {String} CORNER - * @final - */ - CORNER: 'corner', - /** - * @property {String} CORNERS - * @final - */ - CORNERS: 'corners', - /** - * @property {String} RADIUS - * @final - */ - RADIUS: 'radius', - /** - * @property {String} RIGHT - * @final - */ - RIGHT: 'right', - /** - * @property {String} LEFT - * @final - */ - LEFT: 'left', - /** - * @property {String} CENTER - * @final - */ - CENTER: 'center', - /** - * @property {String} TOP - * @final - */ - TOP: 'top', - /** - * @property {String} BOTTOM - * @final - */ - BOTTOM: 'bottom', - /** - * @property {String} BASELINE - * @final - * @default alphabetic - */ - BASELINE: 'alphabetic', - /** - * @property {Number} POINTS - * @final - * @default 0x0000 - */ - POINTS: 0x0000, - /** - * @property {Number} LINES - * @final - * @default 0x0001 - */ - LINES: 0x0001, - /** - * @property {Number} LINE_STRIP - * @final - * @default 0x0003 - */ - LINE_STRIP: 0x0003, - /** - * @property {Number} LINE_LOOP - * @final - * @default 0x0002 - */ - LINE_LOOP: 0x0002, - /** - * @property {Number} TRIANGLES - * @final - * @default 0x0004 - */ - TRIANGLES: 0x0004, - /** - * @property {Number} TRIANGLE_FAN - * @final - * @default 0x0006 - */ - TRIANGLE_FAN: 0x0006, - /** - * @property {Number} TRIANGLE_STRIP - * @final - * @default 0x0005 - */ - TRIANGLE_STRIP: 0x0005, - /** - * @property {String} QUADS - * @final - */ - QUADS: 'quads', - /** - * @property {String} QUAD_STRIP - * @final - * @default quad_strip - */ - QUAD_STRIP: 'quad_strip', - /** - * @property {String} CLOSE - * @final - */ - CLOSE: 'close', - /** - * @property {String} OPEN - * @final - */ - OPEN: 'open', - /** - * @property {String} CHORD - * @final - */ - CHORD: 'chord', - /** - * @property {String} PIE - * @final - */ - PIE: 'pie', - /** - * @property {String} PROJECT - * @final - * @default square - */ - PROJECT: 'square', // PEND: careful this is counterintuitive - /** - * @property {String} SQUARE - * @final - * @default butt - */ - SQUARE: 'butt', - /** - * @property {String} ROUND - * @final - */ - ROUND: 'round', - /** - * @property {String} BEVEL - * @final - */ - BEVEL: 'bevel', - /** - * @property {String} MITER - * @final - */ - MITER: 'miter', +// SHAPE +/** + * @property {String} CORNER + * @final + */ +export const CORNER = 'corner'; +/** + * @property {String} CORNERS + * @final + */ +export const CORNERS = 'corners'; +/** + * @property {String} RADIUS + * @final + */ +export const RADIUS = 'radius'; +/** + * @property {String} RIGHT + * @final + */ +export const RIGHT = 'right'; +/** + * @property {String} LEFT + * @final + */ +export const LEFT = 'left'; +/** + * @property {String} CENTER + * @final + */ +export const CENTER = 'center'; +/** + * @property {String} TOP + * @final + */ +export const TOP = 'top'; +/** + * @property {String} BOTTOM + * @final + */ +export const BOTTOM = 'bottom'; +/** + * @property {String} BASELINE + * @final + * @default alphabetic + */ +export const BASELINE = 'alphabetic'; +/** + * @property {Number} POINTS + * @final + * @default 0x0000 + */ +export const POINTS = 0x0000; +/** + * @property {Number} LINES + * @final + * @default 0x0001 + */ +export const LINES = 0x0001; +/** + * @property {Number} LINE_STRIP + * @final + * @default 0x0003 + */ +export const LINE_STRIP = 0x0003; +/** + * @property {Number} LINE_LOOP + * @final + * @default 0x0002 + */ +export const LINE_LOOP = 0x0002; +/** + * @property {Number} TRIANGLES + * @final + * @default 0x0004 + */ +export const TRIANGLES = 0x0004; +/** + * @property {Number} TRIANGLE_FAN + * @final + * @default 0x0006 + */ +export const TRIANGLE_FAN = 0x0006; +/** + * @property {Number} TRIANGLE_STRIP + * @final + * @default 0x0005 + */ +export const TRIANGLE_STRIP = 0x0005; +/** + * @property {String} QUADS + * @final + */ +export const QUADS = 'quads'; +/** + * @property {String} QUAD_STRIP + * @final + * @default quad_strip + */ +export const QUAD_STRIP = 'quad_strip'; +/** + * @property {String} CLOSE + * @final + */ +export const CLOSE = 'close'; +/** + * @property {String} OPEN + * @final + */ +export const OPEN = 'open'; +/** + * @property {String} CHORD + * @final + */ +export const CHORD = 'chord'; +/** + * @property {String} PIE + * @final + */ +export const PIE = 'pie'; +/** + * @property {String} PROJECT + * @final + * @default square + */ +export const PROJECT = 'square'; // PEND: careful this is counterintuitive +/** + * @property {String} SQUARE + * @final + * @default butt + */ +export const SQUARE = 'butt'; +/** + * @property {String} ROUND + * @final + */ +export const ROUND = 'round'; +/** + * @property {String} BEVEL + * @final + */ +export const BEVEL = 'bevel'; +/** + * @property {String} MITER + * @final + */ +export const MITER = 'miter'; - // COLOR - /** - * @property {String} RGB - * @final - */ - RGB: 'rgb', - /** - * @property {String} HSB - * @final - */ - HSB: 'hsb', - /** - * @property {String} HSL - * @final - */ - HSL: 'hsl', +// COLOR +/** + * @property {String} RGB + * @final + */ +export const RGB = 'rgb'; +/** + * @property {String} HSB + * @final + */ +export const HSB = 'hsb'; +/** + * @property {String} HSL + * @final + */ +export const HSL = 'hsl'; - // DOM EXTENSION - /** - * AUTO allows us to automatically set the width or height of an element (but not both), - * based on the current height and width of the element. Only one parameter can - * be passed to the size function as AUTO, at a time. - * - * @property {String} AUTO - * @final - */ - AUTO: 'auto', +// DOM EXTENSION +/** + * AUTO allows us to automatically set the width or height of an element (but not both), + * based on the current height and width of the element. Only one parameter can + * be passed to the size function as AUTO, at a time. + * + * @property {String} AUTO + * @final + */ +export const AUTO = 'auto'; - // INPUT - ALT: 18, - BACKSPACE: 8, - CONTROL: 17, - DELETE: 46, - DOWN_ARROW: 40, - ENTER: 13, - ESCAPE: 27, - LEFT_ARROW: 37, - OPTION: 18, - RETURN: 13, - RIGHT_ARROW: 39, - SHIFT: 16, - TAB: 9, - UP_ARROW: 38, +// INPUT +export const ALT = 18; +export const BACKSPACE = 8; +export const CONTROL = 17; +export const DELETE = 46; +export const DOWN_ARROW = 40; +export const ENTER = 13; +export const ESCAPE = 27; +export const LEFT_ARROW = 37; +export const OPTION = 18; +export const RETURN = 13; +export const RIGHT_ARROW = 39; +export const SHIFT = 16; +export const TAB = 9; +export const UP_ARROW = 38; - // RENDERING - /** - * @property {String} BLEND - * @final - * @default source-over - */ - BLEND: 'source-over', - /** - * @property {String} ADD - * @final - * @default lighter - */ - ADD: 'lighter', - //ADD: 'add', // - //SUBTRACT: 'subtract', // - /** - * @property {String} DARKEST - * @final - */ - DARKEST: 'darken', - /** - * @property {String} LIGHTEST - * @final - * @default lighten - */ - LIGHTEST: 'lighten', - /** - * @property {String} DIFFERENCE - * @final - */ - DIFFERENCE: 'difference', - /** - * @property {String} SUBTRACT - * @final - */ - SUBTRACT: 'subtract', - /** - * @property {String} EXCLUSION - * @final - */ - EXCLUSION: 'exclusion', - /** - * @property {String} MULTIPLY - * @final - */ - MULTIPLY: 'multiply', - /** - * @property {String} SCREEN - * @final - */ - SCREEN: 'screen', - /** - * @property {String} REPLACE - * @final - * @default copy - */ - REPLACE: 'copy', - /** - * @property {String} OVERLAY - * @final - */ - OVERLAY: 'overlay', - /** - * @property {String} HARD_LIGHT - * @final - */ - HARD_LIGHT: 'hard-light', - /** - * @property {String} SOFT_LIGHT - * @final - */ - SOFT_LIGHT: 'soft-light', - /** - * @property {String} DODGE - * @final - * @default color-dodge - */ - DODGE: 'color-dodge', - /** - * @property {String} BURN - * @final - * @default color-burn - */ - BURN: 'color-burn', +// RENDERING +/** + * @property {String} BLEND + * @final + * @default source-over + */ +export const BLEND = 'source-over'; +/** + * @property {String} ADD + * @final + * @default lighter + */ +export const ADD = 'lighter'; +//ADD: 'add', // +//SUBTRACT: 'subtract', // +/** + * @property {String} DARKEST + * @final + */ +export const DARKEST = 'darken'; +/** + * @property {String} LIGHTEST + * @final + * @default lighten + */ +export const LIGHTEST = 'lighten'; +/** + * @property {String} DIFFERENCE + * @final + */ +export const DIFFERENCE = 'difference'; +/** + * @property {String} SUBTRACT + * @final + */ +export const SUBTRACT = 'subtract'; +/** + * @property {String} EXCLUSION + * @final + */ +export const EXCLUSION = 'exclusion'; +/** + * @property {String} MULTIPLY + * @final + */ +export const MULTIPLY = 'multiply'; +/** + * @property {String} SCREEN + * @final + */ +export const SCREEN = 'screen'; +/** + * @property {String} REPLACE + * @final + * @default copy + */ +export const REPLACE = 'copy'; +/** + * @property {String} OVERLAY + * @final + */ +export const OVERLAY = 'overlay'; +/** + * @property {String} HARD_LIGHT + * @final + */ +export const HARD_LIGHT = 'hard-light'; +/** + * @property {String} SOFT_LIGHT + * @final + */ +export const SOFT_LIGHT = 'soft-light'; +/** + * @property {String} DODGE + * @final + * @default color-dodge + */ +export const DODGE = 'color-dodge'; +/** + * @property {String} BURN + * @final + * @default color-burn + */ +export const BURN = 'color-burn'; - // FILTERS - /** - * @property {String} THRESHOLD - * @final - */ - THRESHOLD: 'threshold', - /** - * @property {String} GRAY - * @final - */ - GRAY: 'gray', - /** - * @property {String} OPAQUE - * @final - */ - OPAQUE: 'opaque', - /** - * @property {String} INVERT - * @final - */ - INVERT: 'invert', - /** - * @property {String} POSTERIZE - * @final - */ - POSTERIZE: 'posterize', - /** - * @property {String} DILATE - * @final - */ - DILATE: 'dilate', - /** - * @property {String} ERODE - * @final - */ - ERODE: 'erode', - /** - * @property {String} BLUR - * @final - */ - BLUR: 'blur', +// FILTERS +/** + * @property {String} THRESHOLD + * @final + */ +export const THRESHOLD = 'threshold'; +/** + * @property {String} GRAY + * @final + */ +export const GRAY = 'gray'; +/** + * @property {String} OPAQUE + * @final + */ +export const OPAQUE = 'opaque'; +/** + * @property {String} INVERT + * @final + */ +export const INVERT = 'invert'; +/** + * @property {String} POSTERIZE + * @final + */ +export const POSTERIZE = 'posterize'; +/** + * @property {String} DILATE + * @final + */ +export const DILATE = 'dilate'; +/** + * @property {String} ERODE + * @final + */ +export const ERODE = 'erode'; +/** + * @property {String} BLUR + * @final + */ +export const BLUR = 'blur'; - // TYPOGRAPHY - /** - * @property {String} NORMAL - * @final - */ - NORMAL: 'normal', - /** - * @property {String} ITALIC - * @final - */ - ITALIC: 'italic', - /** - * @property {String} BOLD - * @final - */ - BOLD: 'bold', - /** - * @property {String} BOLDITALIC - * @final - */ - BOLDITALIC: 'bold italic', +// TYPOGRAPHY +/** + * @property {String} NORMAL + * @final + */ +export const NORMAL = 'normal'; +/** + * @property {String} ITALIC + * @final + */ +export const ITALIC = 'italic'; +/** + * @property {String} BOLD + * @final + */ +export const BOLD = 'bold'; +/** + * @property {String} BOLDITALIC + * @final + */ +export const BOLDITALIC = 'bold italic'; - // TYPOGRAPHY-INTERNAL - _DEFAULT_TEXT_FILL: '#000000', - _DEFAULT_LEADMULT: 1.25, - _CTX_MIDDLE: 'middle', +// TYPOGRAPHY-INTERNAL +export const _DEFAULT_TEXT_FILL = '#000000'; +export const _DEFAULT_LEADMULT = 1.25; +export const _CTX_MIDDLE = 'middle'; - // VERTICES - LINEAR: 'linear', - QUADRATIC: 'quadratic', - BEZIER: 'bezier', - CURVE: 'curve', +// VERTICES +export const LINEAR = 'linear'; +export const QUADRATIC = 'quadratic'; +export const BEZIER = 'bezier'; +export const CURVE = 'curve'; - // WEBGL DRAWMODES - STROKE: 'stroke', - FILL: 'fill', - TEXTURE: 'texture', - IMMEDIATE: 'immediate', +// WEBGL DRAWMODES +export const STROKE = 'stroke'; +export const FILL = 'fill'; +export const TEXTURE = 'texture'; +export const IMMEDIATE = 'immediate'; - // WEBGL TEXTURE MODE - // NORMAL already exists for typography - /** - * @property {String} IMAGE - * @final - */ - IMAGE: 'image', +// WEBGL TEXTURE MODE +// NORMAL already exists for typography +/** + * @property {String} IMAGE + * @final + */ +export const IMAGE = 'image'; - // WEBGL TEXTURE WRAP AND FILTERING - // LINEAR already exists above - NEAREST: 'nearest', - REPEAT: 'repeat', - CLAMP: 'clamp', - MIRROR: 'mirror', +// WEBGL TEXTURE WRAP AND FILTERING +// LINEAR already exists above +export const NEAREST = 'nearest'; +export const REPEAT = 'repeat'; +export const CLAMP = 'clamp'; +export const MIRROR = 'mirror'; - // DEVICE-ORIENTATION - /** - * @property {String} LANDSCAPE - * @final - */ - LANDSCAPE: 'landscape', - /** - * @property {String} PORTRAIT - * @final - */ - PORTRAIT: 'portrait', +// DEVICE-ORIENTATION +/** + * @property {String} LANDSCAPE + * @final + */ +export const LANDSCAPE = 'landscape'; +/** + * @property {String} PORTRAIT + * @final + */ +export const PORTRAIT = 'portrait'; - // DEFAULTS - _DEFAULT_STROKE: '#000000', - _DEFAULT_FILL: '#FFFFFF', +// DEFAULTS +export const _DEFAULT_STROKE = '#000000'; +export const _DEFAULT_FILL = '#FFFFFF'; - /** - * @property {String} GRID - * @final - */ - GRID: 'grid', +/** + * @property {String} GRID + * @final + */ +export const GRID = 'grid'; - /** - * @property {String} AXES - * @final - */ - AXES: 'axes' -}; +/** + * @property {String} AXES + * @final + */ +export const AXES = 'axes'; diff --git a/src/core/environment.js b/src/core/environment.js index 2eeec6fdb6..84684b19f1 100644 --- a/src/core/environment.js +++ b/src/core/environment.js @@ -6,18 +6,16 @@ * @requires constants */ -'use strict'; +import p5 from './main'; +import * as C from './constants'; -var p5 = require('./main'); -var C = require('./constants'); - -var standardCursors = [C.ARROW, C.CROSS, C.HAND, C.MOVE, C.TEXT, C.WAIT]; +const standardCursors = [C.ARROW, C.CROSS, C.HAND, C.MOVE, C.TEXT, C.WAIT]; p5.prototype._frameRate = 0; p5.prototype._lastFrameTime = window.performance.now(); p5.prototype._targetFrameRate = 60; -var _windowPrint = window.print; +const _windowPrint = window.print; /** * The print() function writes to the console area of your browser. @@ -42,11 +40,11 @@ var _windowPrint = window.print; * @alt * default grey canvas */ -p5.prototype.print = function() { - if (!arguments.length) { +p5.prototype.print = (...args) => { + if (!args.length) { _windowPrint(); } else { - console.log.apply(console, arguments); + console.log(...args); } }; @@ -200,27 +198,27 @@ p5.prototype.focused = document.hasFocus(); * */ p5.prototype.cursor = function(type, x, y) { - var cursor = 'auto'; - var canvas = this._curElement.elt; - if (standardCursors.indexOf(type) > -1) { + let cursor = 'auto'; + const canvas = this._curElement.elt; + if (standardCursors.includes(type)) { // Standard css cursor cursor = type; } else if (typeof type === 'string') { - var coords = ''; + let coords = ''; if (x && y && (typeof x === 'number' && typeof y === 'number')) { // Note that x and y values must be unit-less positive integers < 32 // https://developer.mozilla.org/en-US/docs/Web/CSS/cursor - coords = x + ' ' + y; + coords = `${x} ${y}`; } if ( type.substring(0, 7) === 'http://' || type.substring(0, 8) === 'https://' ) { // Image (absolute url) - cursor = 'url(' + type + ') ' + coords + ', auto'; + cursor = `url(${type}) ${coords}, auto`; } else if (/\.(cur|jpg|jpeg|gif|png|CUR|JPG|JPEG|GIF|PNG)$/.test(type)) { // Image file (relative path) - Separated for performance reasons - cursor = 'url(' + type + ') ' + coords + ', auto'; + cursor = `url(${type}) ${coords}, auto`; } else { // Any valid string for the css cursor property cursor = type; @@ -450,8 +448,8 @@ p5.prototype.windowHeight = getWindowHeight(); p5.prototype._onresize = function(e) { this._setProperty('windowWidth', getWindowWidth()); this._setProperty('windowHeight', getWindowHeight()); - var context = this._isGlobal ? window : this; - var executeDefault; + const context = this._isGlobal ? window : this; + let executeDefault; if (typeof context.windowResized === 'function') { executeDefault = context.windowResized(e); if (executeDefault !== undefined && !executeDefault) { @@ -594,7 +592,7 @@ p5.prototype.fullscreen = function(val) { */ p5.prototype.pixelDensity = function(val) { p5._validateParameters('pixelDensity', arguments); - var returnValue; + let returnValue; if (typeof val === 'number') { if (val !== this._pixelDensity) { this._pixelDensity = val; @@ -629,12 +627,10 @@ p5.prototype.pixelDensity = function(val) { * @alt * 50x50 white ellipse with black outline in center of canvas. */ -p5.prototype.displayDensity = function() { - return window.devicePixelRatio; -}; +p5.prototype.displayDensity = () => window.devicePixelRatio; function launchFullscreen(element) { - var enabled = + const enabled = document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || @@ -693,9 +689,7 @@ function exitFullscreen() { * current url (http://p5js.org/reference/#/p5/getURL) moves right to left. * */ -p5.prototype.getURL = function() { - return location.href; -}; +p5.prototype.getURL = () => location.href; /** * Gets the current URL path as an array. * @method getURLPath @@ -714,11 +708,8 @@ p5.prototype.getURL = function() { *no display * */ -p5.prototype.getURLPath = function() { - return location.pathname.split('/').filter(function(v) { - return v !== ''; - }); -}; +p5.prototype.getURLPath = () => + location.pathname.split('/').filter(v => v !== ''); /** * Gets the current URL params as an Object. * @method getURLParams @@ -740,10 +731,10 @@ p5.prototype.getURLPath = function() { * no display. * */ -p5.prototype.getURLParams = function() { - var re = /[?&]([^&=]+)(?:[&=])([^&=]+)/gim; - var m; - var v = {}; +p5.prototype.getURLParams = () => { + const re = /[?&]([^&=]+)(?:[&=])([^&=]+)/gim; + let m; + const v = {}; while ((m = re.exec(location.search)) != null) { if (m.index === re.lastIndex) { re.lastIndex++; @@ -753,4 +744,4 @@ p5.prototype.getURLParams = function() { return v; }; -module.exports = p5; +export default p5; diff --git a/src/core/error_helpers.js b/src/core/error_helpers.js index b23f336039..ff384d2bde 100644 --- a/src/core/error_helpers.js +++ b/src/core/error_helpers.js @@ -3,27 +3,25 @@ * @requires core */ -'use strict'; - -var p5 = require('./main'); -var constants = require('./constants'); +import p5 from './main'; +import * as constants from './constants'; // p5.js blue, p5.js orange, auto dark green; fallback p5.js darkened magenta // See testColors below for all the color codes and names -var typeColors = ['#2D7BB6', '#EE9900', '#4DB200', '#C83C00']; +const typeColors = ['#2D7BB6', '#EE9900', '#4DB200', '#C83C00']; if (typeof IS_MINIFIED !== 'undefined') { - p5._validateParameters = p5._friendlyFileLoadError = p5._friendlyError = function() {}; + p5._validateParameters = p5._friendlyFileLoadError = p5._friendlyError = () => {}; } else { - var doFriendlyWelcome = false; // TEMP until we get it all working LM + let doFriendlyWelcome = false; // TEMP until we get it all working LM // for parameter validation - var dataDoc = require('../../docs/reference/data.json'); - var arrDoc = JSON.parse(JSON.stringify(dataDoc)); + const dataDoc = require('../../docs/reference/data.json'); + const arrDoc = JSON.parse(JSON.stringify(dataDoc)); // -- Borrowed from jQuery 1.11.3 -- - var class2type = {}; - var toString = class2type.toString; - var names = [ + const class2type = {}; + const toString = class2type.toString; + const names = [ 'Boolean', 'Number', 'String', @@ -34,12 +32,12 @@ if (typeof IS_MINIFIED !== 'undefined') { 'Object', 'Error' ]; - for (var n = 0; n < names.length; n++) { - class2type['[object ' + names[n] + ']'] = names[n].toLowerCase(); + for (let n = 0; n < names.length; n++) { + class2type[`[object ${names[n]}]`] = names[n].toLowerCase(); } - var getType = function(obj) { + const getType = obj => { if (obj == null) { - return obj + ''; + return `${obj}`; } return typeof obj === 'object' || typeof obj === 'function' ? class2type[toString.call(obj)] || 'object' @@ -48,12 +46,12 @@ if (typeof IS_MINIFIED !== 'undefined') { // -- End borrow -- - var friendlyWelcome = function() { + const friendlyWelcome = () => { // p5.js brand - magenta: #ED225D - //var astrixBgColor = 'transparent'; - //var astrixTxtColor = '#ED225D'; - //var welcomeBgColor = '#ED225D'; - //var welcomeTextColor = 'white'; + //const astrixBgColor = 'transparent'; + //const astrixTxtColor = '#ED225D'; + //const welcomeBgColor = '#ED225D'; + //const welcomeTextColor = 'white'; console.log( ' _ \n' + ' /\\| |/\\ \n' + @@ -77,7 +75,7 @@ if (typeof IS_MINIFIED !== 'undefined') { * * @return console logs */ - var report = function(message, func, color) { + const report = (message, func, color) => { if (doFriendlyWelcome) { friendlyWelcome(); doFriendlyWelcome = false; @@ -89,25 +87,19 @@ if (typeof IS_MINIFIED !== 'undefined') { color = typeColors[color]; } if (func === 'loadX') { - console.log('> p5.js says: ' + message); + console.log(`> p5.js says: ${message}`); } else if (func.substring(0, 4) === 'load') { console.log( - '> p5.js says: ' + - message + - '[https://github.com/processing/p5.js/wiki/Local-server]' + `> p5.js says: ${message}[https://github.com/processing/p5.js/wiki/Local-server]` ); } else { console.log( - '> p5.js says: ' + - message + - ' [http://p5js.org/reference/#p5/' + - func + - ']' + `> p5.js says: ${message} [http://p5js.org/reference/#p5/${func}]` ); } }; - var errorCases = { + const errorCases = { '0': { fileType: 'image', method: 'loadImage', @@ -160,22 +152,16 @@ if (typeof IS_MINIFIED !== 'undefined') { * @param {Number} errorType * @param {String} filePath */ - p5._friendlyFileLoadError = function(errorType, filePath) { - var errorInfo = errorCases[errorType]; - var message; + p5._friendlyFileLoadError = (errorType, filePath) => { + const errorInfo = errorCases[errorType]; + let message; if (errorType === 7 || errorType === 8) { message = errorInfo.message; } else { - message = - 'It looks like there was a problem' + - ' loading your ' + - errorInfo.fileType + - '.' + - ' Try checking if the file path [' + - filePath + - '] is correct,' + - (errorInfo.message || '') + - ' or running a local server.'; + message = `It looks like there was a problem loading your ${ + errorInfo.fileType + }. Try checking if the file path [${filePath}] is correct,${errorInfo.message || + ''} or running a local server.`; } report(message, errorInfo.method, 3); }; @@ -189,12 +175,12 @@ if (typeof IS_MINIFIED !== 'undefined') { * @param {Number} message message to be printed * @param {String} method name of method */ - p5._friendlyError = function(message, method) { + p5._friendlyError = (message, method) => { report(message, method); }; - var docCache = {}; - var builtinTypes = [ + const docCache = {}; + const builtinTypes = [ 'null', 'number', 'string', @@ -207,17 +193,17 @@ if (typeof IS_MINIFIED !== 'undefined') { // validateParameters() helper functions: // lookupParamDoc() for querying data.json - var lookupParamDoc = function(func) { + const lookupParamDoc = func => { // look for the docs in the `data.json` datastructure - var ichDot = func.lastIndexOf('.'); - var funcName = func.substr(ichDot + 1); - var funcClass = func.substr(0, ichDot) || 'p5'; + const ichDot = func.lastIndexOf('.'); + const funcName = func.substr(ichDot + 1); + const funcClass = func.substr(0, ichDot) || 'p5'; + + let queryResult; + const classitems = arrDoc.classitems; - var queryResult; - var classitems = arrDoc.classitems; - for (var ici = 0; ici < classitems.length; ici++) { - var x = classitems[ici]; + for (const x of classitems) { if (x.name === funcName && x.class === funcClass) { queryResult = x; break; @@ -225,10 +211,10 @@ if (typeof IS_MINIFIED !== 'undefined') { } // different JSON structure for funct with multi-format - var overloads = []; + const overloads = []; if (queryResult.hasOwnProperty('overloads')) { // add all the overloads - for (var i = 0; i < queryResult.overloads.length; i++) { + for (let i = 0; i < queryResult.overloads.length; i++) { overloads.push({ formats: queryResult.overloads[i].params }); } } else { @@ -237,10 +223,10 @@ if (typeof IS_MINIFIED !== 'undefined') { } // parse the parameter types for each overload - var mapConstants = {}; - var maxParams = 0; - overloads.forEach(function(overload) { - var formats = overload.formats; + const mapConstants = {}; + let maxParams = 0; + overloads.forEach(overload => { + const formats = overload.formats; // keep a record of the maximum number of arguments // this method requires. @@ -250,14 +236,14 @@ if (typeof IS_MINIFIED !== 'undefined') { // calculate the minimum number of arguments // this overload requires. - var minParams = formats.length; + let minParams = formats.length; while (minParams > 0 && formats[minParams - 1].optional) { minParams--; } overload.minParams = minParams; // loop through each parameter position, and parse its types - formats.forEach(function(format) { + formats.forEach(format => { // split this parameter's types format.types = format.type.split('|').map(function ct(type) { // array @@ -268,34 +254,34 @@ if (typeof IS_MINIFIED !== 'undefined') { }; } - var lowerType = type.toLowerCase(); + let lowerType = type.toLowerCase(); // contant if (lowerType === 'constant') { - var constant; + let constant; if (mapConstants.hasOwnProperty(format.name)) { constant = mapConstants[format.name]; } else { // parse possible constant values from description - var myRe = /either\s+(?:[A-Z0-9_]+\s*,?\s*(?:or)?\s*)+/g; - var values = {}; - var names = []; + const myRe = /either\s+(?:[A-Z0-9_]+\s*,?\s*(?:or)?\s*)+/g; + const values = {}; + const names = []; constant = mapConstants[format.name] = { - values: values, - names: names + values, + names }; - var myArray = myRe.exec(format.description); + const myArray = myRe.exec(format.description); if (func === 'endShape' && format.name === 'mode') { values[constants.CLOSE] = true; names.push('CLOSE'); } else { - var match = myArray[0]; - var reConst = /[A-Z0-9_]+/g; - var matchConst; + const match = myArray[0]; + const reConst = /[A-Z0-9_]+/g; + let matchConst; while ((matchConst = reConst.exec(match)) !== null) { - var name = matchConst[0]; + const name = matchConst[0]; if (constants.hasOwnProperty(name)) { values[constants[name]] = true; names.push(name); @@ -316,13 +302,13 @@ if (typeof IS_MINIFIED !== 'undefined') { lowerType = 'function'; } // builtin - if (builtinTypes.indexOf(lowerType) >= 0) { + if (builtinTypes.includes(lowerType)) { return { name: type, builtin: lowerType }; } // find type's prototype - var t = window; - var typeParts = type.split('.'); + let t = window; + const typeParts = type.split('.'); // special-case 'p5' since it may be non-global if (typeParts[0] === 'p5') { @@ -330,7 +316,7 @@ if (typeof IS_MINIFIED !== 'undefined') { typeParts.shift(); } - typeParts.forEach(function(p) { + typeParts.forEach(p => { t = t && t[p]; }); if (t) { @@ -342,12 +328,12 @@ if (typeof IS_MINIFIED !== 'undefined') { }); }); return { - overloads: overloads, - maxParams: maxParams + overloads, + maxParams }; }; - var isNumber = function(param) { + const isNumber = param => { switch (typeof param) { case 'number': return true; @@ -358,12 +344,12 @@ if (typeof IS_MINIFIED !== 'undefined') { } }; - var testParamType = function(param, type) { - var isArray = param instanceof Array; - var matches = true; + const testParamType = (param, type) => { + const isArray = param instanceof Array; + let matches = true; if (type.array && isArray) { - for (var i = 0; i < param.length; i++) { - var error = testParamType(param[i], type.array); + for (let i = 0; i < param.length; i++) { + const error = testParamType(param[i], type.array); if (error) return error / 2; // half error for elements } } else if (type.prototype) { @@ -403,10 +389,10 @@ if (typeof IS_MINIFIED !== 'undefined') { }; // testType() for non-object type parameter validation - var testParamTypes = function(param, types) { - var minScore = 9999; - for (var i = 0; minScore > 0 && i < types.length; i++) { - var score = testParamType(param, types[i]); + const testParamTypes = (param, types) => { + let minScore = 9999; + for (let i = 0; minScore > 0 && i < types.length; i++) { + const score = testParamType(param, types[i]); if (minScore > score) minScore = score; } return minScore; @@ -414,10 +400,10 @@ if (typeof IS_MINIFIED !== 'undefined') { // generate a score (higher is worse) for applying these args to // this overload. - var scoreOverload = function(args, argCount, overload, minScore) { - var score = 0; - var formats = overload.formats; - var minParams = overload.minParams; + const scoreOverload = (args, argCount, overload, minScore) => { + let score = 0; + const formats = overload.formats; + const minParams = overload.minParams; // check for too few/many args // the score is double number of extra/missing args @@ -429,9 +415,9 @@ if (typeof IS_MINIFIED !== 'undefined') { // loop through the formats, adding up the error score for each arg. // quit early if the score gets higher than the previous best overload. - for (var p = 0; score <= minScore && p < formats.length; p++) { - var arg = args[p]; - var format = formats[p]; + for (let p = 0; score <= minScore && p < formats.length; p++) { + const arg = args[p]; + const format = formats[p]; // '== null' checks for 'null' and typeof 'undefined' if (arg == null) { // handle non-optional and non-trailing undefined args @@ -446,33 +432,33 @@ if (typeof IS_MINIFIED !== 'undefined') { }; // gets a list of errors for this overload - var getOverloadErrors = function(args, argCount, overload) { - var formats = overload.formats; - var minParams = overload.minParams; + const getOverloadErrors = (args, argCount, overload) => { + const formats = overload.formats; + const minParams = overload.minParams; // check for too few/many args if (argCount < minParams) { return [ { type: 'TOO_FEW_ARGUMENTS', - argCount: argCount, - minParams: minParams + argCount, + minParams } ]; } else if (argCount > formats.length) { return [ { type: 'TOO_MANY_ARGUMENTS', - argCount: argCount, + argCount, maxParams: formats.length } ]; } - var errorArray = []; - for (var p = 0; p < formats.length; p++) { - var arg = args[p]; - var format = formats[p]; + const errorArray = []; + for (let p = 0; p < formats.length; p++) { + const arg = args[p]; + const format = formats[p]; // '== null' checks for 'null' and typeof 'undefined' if (arg == null) { // handle non-optional and non-trailing undefined args @@ -480,15 +466,15 @@ if (typeof IS_MINIFIED !== 'undefined') { errorArray.push({ type: 'EMPTY_VAR', position: p, - format: format + format }); } } else if (testParamTypes(arg, format.types) > 0) { errorArray.push({ type: 'WRONG_TYPE', position: p, - format: format, - arg: arg + format, + arg }); } } @@ -498,76 +484,62 @@ if (typeof IS_MINIFIED !== 'undefined') { // a custom error type, used by the mocha // tests when expecting validation errors - p5.ValidationError = (function(name) { - var err = function(message, func) { - this.message = message; - this.func = func; - if ('captureStackTrace' in Error) Error.captureStackTrace(this, err); - else this.stack = new Error().stack; - }; - err.prototype = Object.create(Error.prototype); + p5.ValidationError = (name => { + class err extends Error { + constructor(message, func) { + super(); + this.message = message; + this.func = func; + if ('captureStackTrace' in Error) Error.captureStackTrace(this, err); + else this.stack = new Error().stack; + } + } + err.prototype.name = name; - err.prototype.constructor = err; return err; })('ValidationError'); // function for generating console.log() msg - p5._friendlyParamError = function(errorObj, func) { - var message; + p5._friendlyParamError = (errorObj, func) => { + let message; function formatType() { - var format = errorObj.format; + const format = errorObj.format; return format.types - .map(function(type) { - return type.names ? type.names.join('|') : type.name; - }) + .map(type => (type.names ? type.names.join('|') : type.name)) .join('|'); } switch (errorObj.type) { - case 'EMPTY_VAR': - message = - func + - '() was expecting ' + - formatType() + - ' for parameter #' + - errorObj.position + - ' (zero-based index), received an empty variable instead.' + - ' If not intentional, this is often a problem with scope:' + - ' [https://p5js.org/examples/data-variable-scope.html]'; + case 'EMPTY_VAR': { + message = `${func}() was expecting ${formatType()} for parameter #${ + errorObj.position + } (zero-based index), received an empty variable instead. If not intentional, this is often a problem with scope: [https://p5js.org/examples/data-variable-scope.html]`; break; - case 'WRONG_TYPE': - var arg = errorObj.arg; - var argType = + } + case 'WRONG_TYPE': { + const arg = errorObj.arg; + const argType = arg instanceof Array ? 'array' : arg === null ? 'null' : arg.name || typeof arg; - message = - func + - '() was expecting ' + - formatType() + - ' for parameter #' + - errorObj.position + - ' (zero-based index), received ' + - argType + - ' instead'; + message = `${func}() was expecting ${formatType()} for parameter #${ + errorObj.position + } (zero-based index), received ${argType} instead`; break; - case 'TOO_FEW_ARGUMENTS': - message = - func + - '() was expecting at least ' + - errorObj.minParams + - ' arguments, but received only ' + - errorObj.argCount; + } + case 'TOO_FEW_ARGUMENTS': { + message = `${func}() was expecting at least ${ + errorObj.minParams + } arguments, but received only ${errorObj.argCount}`; break; - case 'TOO_MANY_ARGUMENTS': - message = - func + - '() was expecting no more than ' + - errorObj.maxParams + - ' arguments, but received ' + - errorObj.argCount; + } + case 'TOO_MANY_ARGUMENTS': { + message = `${func}() was expecting no more than ${ + errorObj.maxParams + } arguments, but received ${errorObj.argCount}`; break; + } } if (message) { @@ -576,14 +548,14 @@ if (typeof IS_MINIFIED !== 'undefined') { } try { - var re = /Function\.validateParameters.*[\r\n].*[\r\n].*\(([^)]*)/; - var location = re.exec(new Error().stack)[1]; + const re = /Function\.validateParameters.*[\r\n].*[\r\n].*\(([^)]*)/; + const location = re.exec(new Error().stack)[1]; if (location) { - message += ' at ' + location; + message += ` at ${location}`; } } catch (err) {} - report(message + '.', func, 3); + report(`${message}.`, func, 3); } }; @@ -593,7 +565,7 @@ if (typeof IS_MINIFIED !== 'undefined') { * param {Array} args user input arguments * * example: - * var a; + * const a; * ellipse(10,10,a,5); * console ouput: * "It looks like ellipse received an empty variable in spot #2." @@ -610,19 +582,19 @@ if (typeof IS_MINIFIED !== 'undefined') { } // lookup the docs in the 'data.json' file - var docs = docCache[func] || (docCache[func] = lookupParamDoc(func)); - var overloads = docs.overloads; + const docs = docCache[func] || (docCache[func] = lookupParamDoc(func)); + const overloads = docs.overloads; // ignore any trailing `undefined` arguments - var argCount = args.length; + let argCount = args.length; // '== null' checks for 'null' and typeof 'undefined' while (argCount > 0 && args[argCount - 1] == null) argCount--; // find the overload with the best score - var minScore = 99999; - var minOverload; - for (var i = 0; i < overloads.length; i++) { - var score = scoreOverload(args, argCount, overloads[i], minScore); + let minScore = 99999; + let minOverload; + for (let i = 0; i < overloads.length; i++) { + const score = scoreOverload(args, argCount, overloads[i], minScore); if (score === 0) { return; // done! } else if (minScore > score) { @@ -635,14 +607,14 @@ if (typeof IS_MINIFIED !== 'undefined') { // this should _always_ be true here... if (minScore > 0) { // get the errors for the best overload - var errorArray = getOverloadErrors( + const errorArray = getOverloadErrors( args, argCount, overloads[minOverload] ); // generate err msg - for (var n = 0; n < errorArray.length; n++) { + for (let n = 0; n < errorArray.length; n++) { p5._friendlyParamError(errorArray[n], func); } } @@ -653,7 +625,7 @@ if (typeof IS_MINIFIED !== 'undefined') { * For color blindness testing. */ /* function testColors() { - var str = 'A box of biscuits, a box of mixed biscuits and a biscuit mixer'; + const str = 'A box of biscuits, a box of mixed biscuits and a biscuit mixer'; report(str, 'print', '#ED225D'); // p5.js magenta report(str, 'print', '#2D7BB6'); // p5.js blue report(str, 'print', '#EE9900'); // p5.js orange @@ -681,18 +653,18 @@ if (typeof IS_MINIFIED !== 'undefined') { // into setup/draw. // // For more details, see https://github.com/processing/p5.js/issues/1121. -var misusedAtTopLevelCode = null; -var FAQ_URL = +let misusedAtTopLevelCode = null; +const FAQ_URL = 'https://github.com/processing/p5.js/wiki/p5.js-overview' + '#why-cant-i-assign-variables-using-p5-functions-and-' + 'variables-before-setup'; -var defineMisusedAtTopLevelCode = function() { - var uniqueNamesFound = {}; +const defineMisusedAtTopLevelCode = () => { + const uniqueNamesFound = {}; - var getSymbols = function(obj) { - return Object.getOwnPropertyNames(obj) - .filter(function(name) { + const getSymbols = obj => + Object.getOwnPropertyNames(obj) + .filter(name => { if (name[0] === '_') { return false; } @@ -704,8 +676,8 @@ var defineMisusedAtTopLevelCode = function() { return true; }) - .map(function(name) { - var type; + .map(name => { + let type; if (typeof obj[name] === 'function') { type = 'function'; @@ -715,9 +687,8 @@ var defineMisusedAtTopLevelCode = function() { type = 'variable'; } - return { name: name, type: type }; + return { name, type }; }); - }; misusedAtTopLevelCode = [].concat( getSymbols(p5.prototype), @@ -730,12 +701,10 @@ var defineMisusedAtTopLevelCode = function() { // This will ultimately ensure that we report the most specific error // possible to the user, e.g. advising them about HALF_PI instead of PI // when their code misuses the former. - misusedAtTopLevelCode.sort(function(a, b) { - return b.name.length - a.name.length; - }); + misusedAtTopLevelCode.sort((a, b) => b.name.length - a.name.length); }; -var helpForMisusedAtTopLevelCode = function(e, log) { +const helpForMisusedAtTopLevelCode = (e, log) => { if (!log) { log = console.log.bind(console); } @@ -753,7 +722,7 @@ var helpForMisusedAtTopLevelCode = function(e, log) { // return; //} - misusedAtTopLevelCode.some(function(symbol) { + misusedAtTopLevelCode.some(symbol => { // Note that while just checking for the occurrence of the // symbol name in the error message could result in false positives, // a more rigorous test is difficult because different browsers @@ -767,16 +736,13 @@ var helpForMisusedAtTopLevelCode = function(e, log) { // * ReferenceError: PI is undefined (Firefox) // * Uncaught ReferenceError: PI is not defined (Chrome) - if (e.message && e.message.match('\\W?' + symbol.name + '\\W') !== null) { + if (e.message && e.message.match(`\\W?${symbol.name}\\W`) !== null) { log( - "Did you just try to use p5.js's " + - symbol.name + - (symbol.type === 'function' ? '() ' : ' ') + - symbol.type + - '? If so, you may want to ' + - "move it into your sketch's setup() function.\n\n" + - 'For more details, see: ' + - FAQ_URL + `Did you just try to use p5.js's ${symbol.name}${ + symbol.type === 'function' ? '() ' : ' ' + }${ + symbol.type + }? If so, you may want to move it into your sketch's setup() function.\n\nFor more details, see: ${FAQ_URL}` ); return true; } @@ -793,9 +759,9 @@ if (document.readyState !== 'complete') { // global (non-instance mode) p5 APIs are used at the top-level // scope of a file, so we'll unbind our error listener now to make // sure we don't log false positives later. - window.addEventListener('load', function() { + window.addEventListener('load', () => { window.removeEventListener('error', helpForMisusedAtTopLevelCode, false); }); } -module.exports = p5; +export default p5; diff --git a/src/core/helpers.js b/src/core/helpers.js index 2f27f62a95..b6cfe371b2 100644 --- a/src/core/helpers.js +++ b/src/core/helpers.js @@ -2,20 +2,18 @@ * @requires constants */ -'use strict'; +import * as constants from './constants'; -var constants = require('./constants'); - -module.exports = { - modeAdjust: function(a, b, c, d, mode) { - if (mode === constants.CORNER) { - return { x: a, y: b, w: c, h: d }; - } else if (mode === constants.CORNERS) { - return { x: a, y: b, w: c - a, h: d - b }; - } else if (mode === constants.RADIUS) { - return { x: a - c, y: b - d, w: 2 * c, h: 2 * d }; - } else if (mode === constants.CENTER) { - return { x: a - c * 0.5, y: b - d * 0.5, w: c, h: d }; - } +function modeAdjust(a, b, c, d, mode) { + if (mode === constants.CORNER) { + return { x: a, y: b, w: c, h: d }; + } else if (mode === constants.CORNERS) { + return { x: a, y: b, w: c - a, h: d - b }; + } else if (mode === constants.RADIUS) { + return { x: a - c, y: b - d, w: 2 * c, h: 2 * d }; + } else if (mode === constants.CENTER) { + return { x: a - c * 0.5, y: b - d * 0.5, w: c, h: d }; } -}; +} + +export default { modeAdjust }; diff --git a/src/core/init.js b/src/core/init.js index 5eafd2b72b..b060da1024 100644 --- a/src/core/init.js +++ b/src/core/init.js @@ -1,6 +1,4 @@ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * _globalInit @@ -14,7 +12,7 @@ var p5 = require('../core/main'); * @private * @return {Undefined} */ -var _globalInit = function() { +const _globalInit = () => { if (!window.mocha) { // If there is a setup or draw function on the window // then instantiate p5 in "global" mode diff --git a/src/core/legacy.js b/src/core/legacy.js index c0f096bcfd..b4b358c38b 100644 --- a/src/core/legacy.js +++ b/src/core/legacy.js @@ -8,23 +8,21 @@ * call. */ -'use strict'; +import p5 from './main'; -var p5 = require('./main'); - -p5.prototype.pushStyle = function() { +p5.prototype.pushStyle = () => { throw new Error('pushStyle() not used, see push()'); }; -p5.prototype.popStyle = function() { +p5.prototype.popStyle = () => { throw new Error('popStyle() not used, see pop()'); }; -p5.prototype.popMatrix = function() { +p5.prototype.popMatrix = () => { throw new Error('popMatrix() not used, see pop()'); }; -p5.prototype.printMatrix = function() { +p5.prototype.printMatrix = () => { throw new Error( 'printMatrix() is not implemented in p5.js, ' + 'refer to [https://simonsarris.com/a-transformation-class-for-canvas-to-keep-track-of-the-transformation-matrix/] ' + @@ -32,8 +30,8 @@ p5.prototype.printMatrix = function() { ); }; -p5.prototype.pushMatrix = function() { +p5.prototype.pushMatrix = () => { throw new Error('pushMatrix() not used, see push()'); }; -module.exports = p5; +export default p5; diff --git a/src/core/main.js b/src/core/main.js index 0e3c08071c..c7294b139b 100644 --- a/src/core/main.js +++ b/src/core/main.js @@ -5,12 +5,10 @@ * @requires constants */ -'use strict'; - -require('./shim'); +import './shim'; // Core needs the PVariables object -var constants = require('./constants'); +import * as constants from './constants'; /** * This is the p5 instance constructor. @@ -34,551 +32,640 @@ var constants = require('./constants'); * @param {HTMLElement} [node] element to attach canvas to * @return {p5} a p5 instance */ -var p5 = function(sketch, node, sync) { - ////////////////////////////////////////////// - // PUBLIC p5 PROPERTIES AND METHODS - ////////////////////////////////////////////// - - /** - * Called directly before setup(), the preload() function is used to handle - * asynchronous loading of external files in a blocking way. If a preload - * function is defined, setup() will wait until any load calls within have - * finished. Nothing besides load calls (loadImage, loadJSON, loadFont, - * loadStrings, etc.) should be inside the preload function. If asynchronous - * loading is preferred, the load methods can instead be called in setup() - * or anywhere else with the use of a callback parameter. - *

- * By default the text "loading..." will be displayed. To make your own - * loading page, include an HTML element with id "p5_loading" in your - * page. More information here. - * - * @method preload - * @example - *
- * let img; - * let c; - * function preload() { - * // preload() runs once - * img = loadImage('assets/laDefense.jpg'); - * } - * - * function setup() { - * // setup() waits until preload() is done - * img.loadPixels(); - * // get color of middle pixel - * c = img.get(img.width / 2, img.height / 2); - * } - * - * function draw() { - * background(c); - * image(img, 25, 25, 50, 50); - * } - *
- * - * @alt - * nothing displayed - * - */ - - /** - * The setup() function is called once when the program starts. It's used to - * define initial environment properties such as screen size and background - * color and to load media such as images and fonts as the program starts. - * There can only be one setup() function for each program and it shouldn't - * be called again after its initial execution. - *

- * Note: Variables declared within setup() are not accessible within other - * functions, including draw(). - * - * @method setup - * @example - *
- * let a = 0; - * - * function setup() { - * background(0); - * noStroke(); - * fill(102); - * } - * - * function draw() { - * rect(a++ % width, 10, 2, 80); - * } - *
- * - * @alt - * nothing displayed - * - */ - - /** - * Called directly after setup(), the draw() function continuously executes - * the lines of code contained inside its block until the program is stopped - * or noLoop() is called. Note if noLoop() is called in setup(), draw() will - * still be executed once before stopping. draw() is called automatically and - * should never be called explicitly. - *

- * It should always be controlled with noLoop(), redraw() and loop(). After - * noLoop() stops the code in draw() from executing, redraw() causes the - * code inside draw() to execute once, and loop() will cause the code - * inside draw() to resume executing continuously. - *

- * The number of times draw() executes in each second may be controlled with - * the frameRate() function. - *

- * There can only be one draw() function for each sketch, and draw() must - * exist if you want the code to run continuously, or to process events such - * as mousePressed(). Sometimes, you might have an empty call to draw() in - * your program, as shown in the above example. - *

- * It is important to note that the drawing coordinate system will be reset - * at the beginning of each draw() call. If any transformations are performed - * within draw() (ex: scale, rotate, translate), their effects will be - * undone at the beginning of draw(), so transformations will not accumulate - * over time. On the other hand, styling applied (ex: fill, stroke, etc) will - * remain in effect. - * - * @method draw - * @example - *
- * let yPos = 0; - * function setup() { - * // setup() runs once - * frameRate(30); - * } - * function draw() { - * // draw() loops forever, until stopped - * background(204); - * yPos = yPos - 1; - * if (yPos < 0) { - * yPos = height; - * } - * line(0, yPos, width, yPos); - * } - *
- * - * @alt - * nothing displayed - * - */ - - ////////////////////////////////////////////// - // PRIVATE p5 PROPERTIES AND METHODS - ////////////////////////////////////////////// - - this._setupDone = false; - // for handling hidpi - this._pixelDensity = Math.ceil(window.devicePixelRatio) || 1; - this._userNode = node; - this._curElement = null; - this._elements = []; - this._glAttributes = null; - this._requestAnimId = 0; - this._preloadCount = 0; - this._isGlobal = false; - this._loop = true; - this._initializeInstanceVariables(); - this._defaultCanvasSize = { - width: 100, - height: 100 - }; - this._events = { - // keep track of user-events for unregistering later - mousemove: null, - mousedown: null, - mouseup: null, - dragend: null, - dragover: null, - click: null, - dblclick: null, - mouseover: null, - mouseout: null, - keydown: null, - keyup: null, - keypress: null, - touchstart: null, - touchmove: null, - touchend: null, - resize: null, - blur: null - }; - - // States used in the custom random generators - this._lcg_random_state = null; - this._gaussian_previous = false; - - this._events.wheel = null; - this._loadingScreenId = 'p5_loading'; - - // Allows methods to be registered on an instance that - // are instance-specific. - this._registeredMethods = {}; - var methods = Object.getOwnPropertyNames(p5.prototype._registeredMethods); - for (var i = 0; i < methods.length; i++) { - var prop = methods[i]; - this._registeredMethods[prop] = p5.prototype._registeredMethods[ - prop - ].slice(); - } - - if (window.DeviceOrientationEvent) { - this._events.deviceorientation = null; - } - if (window.DeviceMotionEvent && !window._isNodeWebkit) { - this._events.devicemotion = null; - } +class p5 { + constructor(sketch, node, sync) { + ////////////////////////////////////////////// + // PUBLIC p5 PROPERTIES AND METHODS + ////////////////////////////////////////////// + + /** + * Called directly before setup(), the preload() function is used to handle + * asynchronous loading of external files in a blocking way. If a preload + * function is defined, setup() will wait until any load calls within have + * finished. Nothing besides load calls (loadImage, loadJSON, loadFont, + * loadStrings, etc.) should be inside the preload function. If asynchronous + * loading is preferred, the load methods can instead be called in setup() + * or anywhere else with the use of a callback parameter. + *

+ * By default the text "loading..." will be displayed. To make your own + * loading page, include an HTML element with id "p5_loading" in your + * page. More information here. + * + * @method preload + * @example + *
+ * let img; + * let c; + * function preload() { + * // preload() runs once + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * // setup() waits until preload() is done + * img.loadPixels(); + * // get color of middle pixel + * c = img.get(img.width / 2, img.height / 2); + * } + * + * function draw() { + * background(c); + * image(img, 25, 25, 50, 50); + * } + *
+ * + * @alt + * nothing displayed + * + */ + + /** + * The setup() function is called once when the program starts. It's used to + * define initial environment properties such as screen size and background + * color and to load media such as images and fonts as the program starts. + * There can only be one setup() function for each program and it shouldn't + * be called again after its initial execution. + *

+ * Note: Variables declared within setup() are not accessible within other + * functions, including draw(). + * + * @method setup + * @example + *
+ * let a = 0; + * + * function setup() { + * background(0); + * noStroke(); + * fill(102); + * } + * + * function draw() { + * rect(a++ % width, 10, 2, 80); + * } + *
+ * + * @alt + * nothing displayed + * + */ + + /** + * Called directly after setup(), the draw() function continuously executes + * the lines of code contained inside its block until the program is stopped + * or noLoop() is called. Note if noLoop() is called in setup(), draw() will + * still be executed once before stopping. draw() is called automatically and + * should never be called explicitly. + *

+ * It should always be controlled with noLoop(), redraw() and loop(). After + * noLoop() stops the code in draw() from executing, redraw() causes the + * code inside draw() to execute once, and loop() will cause the code + * inside draw() to resume executing continuously. + *

+ * The number of times draw() executes in each second may be controlled with + * the frameRate() function. + *

+ * There can only be one draw() function for each sketch, and draw() must + * exist if you want the code to run continuously, or to process events such + * as mousePressed(). Sometimes, you might have an empty call to draw() in + * your program, as shown in the above example. + *

+ * It is important to note that the drawing coordinate system will be reset + * at the beginning of each draw() call. If any transformations are performed + * within draw() (ex: scale, rotate, translate), their effects will be + * undone at the beginning of draw(), so transformations will not accumulate + * over time. On the other hand, styling applied (ex: fill, stroke, etc) will + * remain in effect. + * + * @method draw + * @example + *
+ * let yPos = 0; + * function setup() { + * // setup() runs once + * frameRate(30); + * } + * function draw() { + * // draw() loops forever, until stopped + * background(204); + * yPos = yPos - 1; + * if (yPos < 0) { + * yPos = height; + * } + * line(0, yPos, width, yPos); + * } + *
+ * + * @alt + * nothing displayed + * + */ + + ////////////////////////////////////////////// + // PRIVATE p5 PROPERTIES AND METHODS + ////////////////////////////////////////////// + + this._setupDone = false; + // for handling hidpi + this._pixelDensity = Math.ceil(window.devicePixelRatio) || 1; + this._userNode = node; + this._curElement = null; + this._elements = []; + this._glAttributes = null; + this._requestAnimId = 0; + this._preloadCount = 0; + this._isGlobal = false; + this._loop = true; + this._initializeInstanceVariables(); + this._defaultCanvasSize = { + width: 100, + height: 100 + }; + this._events = { + // keep track of user-events for unregistering later + mousemove: null, + mousedown: null, + mouseup: null, + dragend: null, + dragover: null, + click: null, + dblclick: null, + mouseover: null, + mouseout: null, + keydown: null, + keyup: null, + keypress: null, + touchstart: null, + touchmove: null, + touchend: null, + resize: null, + blur: null + }; + + // States used in the custom random generators + this._lcg_random_state = null; + this._gaussian_previous = false; + + this._events.wheel = null; + this._loadingScreenId = 'p5_loading'; + + // Allows methods to be registered on an instance that + // are instance-specific. + this._registeredMethods = {}; + const methods = Object.getOwnPropertyNames(p5.prototype._registeredMethods); + + for (const prop of methods) { + this._registeredMethods[prop] = p5.prototype._registeredMethods[ + prop + ].slice(); + } - this._start = function() { - // Find node if id given - if (this._userNode) { - if (typeof this._userNode === 'string') { - this._userNode = document.getElementById(this._userNode); - } + if (window.DeviceOrientationEvent) { + this._events.deviceorientation = null; + } + if (window.DeviceMotionEvent && !window._isNodeWebkit) { + this._events.devicemotion = null; } - var context = this._isGlobal ? window : this; - var userPreload = context.preload; - if (userPreload) { - // Setup loading screen - // Set loading screen into dom if not present - // Otherwise displays and removes user provided loading screen - var loadingScreen = document.getElementById(this._loadingScreenId); - if (!loadingScreen) { - loadingScreen = document.createElement('div'); - loadingScreen.innerHTML = 'Loading...'; - loadingScreen.style.position = 'absolute'; - loadingScreen.id = this._loadingScreenId; - var node = this._userNode || document.body; - node.appendChild(loadingScreen); - } - var methods = this._preloadMethods; - for (var method in methods) { - // default to p5 if no object defined - methods[method] = methods[method] || p5; - var obj = methods[method]; - //it's p5, check if it's global or instance - if (obj === p5.prototype || obj === p5) { - if (this._isGlobal) { - window[method] = this._wrapPreload(this, method); - } - obj = this; + this._start = () => { + // Find node if id given + if (this._userNode) { + if (typeof this._userNode === 'string') { + this._userNode = document.getElementById(this._userNode); } - this._registeredPreloadMethods[method] = obj[method]; - obj[method] = this._wrapPreload(obj, method); } - userPreload(); - this._runIfPreloadsAreDone(); - } else { - this._setup(); - this._draw(); - } - }.bind(this); + const context = this._isGlobal ? window : this; + const userPreload = context.preload; + if (userPreload) { + // Setup loading screen + // Set loading screen into dom if not present + // Otherwise displays and removes user provided loading screen + let loadingScreen = document.getElementById(this._loadingScreenId); + if (!loadingScreen) { + loadingScreen = document.createElement('div'); + loadingScreen.innerHTML = 'Loading...'; + loadingScreen.style.position = 'absolute'; + loadingScreen.id = this._loadingScreenId; + const node = this._userNode || document.body; + node.appendChild(loadingScreen); + } + const methods = this._preloadMethods; + for (const method in methods) { + // default to p5 if no object defined + methods[method] = methods[method] || p5; + let obj = methods[method]; + //it's p5, check if it's global or instance + if (obj === p5.prototype || obj === p5) { + if (this._isGlobal) { + window[method] = this._wrapPreload(this, method); + } + obj = this; + } + this._registeredPreloadMethods[method] = obj[method]; + obj[method] = this._wrapPreload(obj, method); + } - this._runIfPreloadsAreDone = function() { - var context = this._isGlobal ? window : this; - if (context._preloadCount === 0) { - var loadingScreen = document.getElementById(context._loadingScreenId); - if (loadingScreen) { - loadingScreen.parentNode.removeChild(loadingScreen); + userPreload(); + this._runIfPreloadsAreDone(); + } else { + this._setup(); + this._draw(); } - this._lastFrameTime = window.performance.now(); - context._setup(); - context._draw(); - } - }; - - this._decrementPreload = function() { - var context = this._isGlobal ? window : this; - if (typeof context.preload === 'function') { - context._setProperty('_preloadCount', context._preloadCount - 1); - context._runIfPreloadsAreDone(); - } - }; - - this._wrapPreload = function(obj, fnName) { - return function() { - //increment counter - this._incrementPreload(); - //call original function - return this._registeredPreloadMethods[fnName].apply(obj, arguments); - }.bind(this); - }; - - this._incrementPreload = function() { - var context = this._isGlobal ? window : this; - context._setProperty('_preloadCount', context._preloadCount + 1); - }; - - this._setup = function() { - // Always create a default canvas. - // Later on if the user calls createCanvas, this default one - // will be replaced - this.createCanvas( - this._defaultCanvasSize.width, - this._defaultCanvasSize.height, - 'p2d' - ); - - // return preload functions to their normal vals if switched by preload - var context = this._isGlobal ? window : this; - if (typeof context.preload === 'function') { - for (var f in this._preloadMethods) { - context[f] = this._preloadMethods[f][f]; - if (context[f] && this) { - context[f] = context[f].bind(this); + }; + + this._runIfPreloadsAreDone = function() { + const context = this._isGlobal ? window : this; + if (context._preloadCount === 0) { + const loadingScreen = document.getElementById(context._loadingScreenId); + if (loadingScreen) { + loadingScreen.parentNode.removeChild(loadingScreen); } + this._lastFrameTime = window.performance.now(); + context._setup(); + context._draw(); } - } + }; - // Short-circuit on this, in case someone used the library in "global" - // mode earlier - if (typeof context.setup === 'function') { - context.setup(); - } - - // unhide any hidden canvases that were created - var canvases = document.getElementsByTagName('canvas'); - for (var i = 0; i < canvases.length; i++) { - var k = canvases[i]; - if (k.dataset.hidden === 'true') { - k.style.visibility = ''; - delete k.dataset.hidden; + this._decrementPreload = function() { + const context = this._isGlobal ? window : this; + if (typeof context.preload === 'function') { + context._setProperty('_preloadCount', context._preloadCount - 1); + context._runIfPreloadsAreDone(); } - } - this._lastFrameTime = window.performance.now(); - this._setupDone = true; - }.bind(this); - - this._draw = function() { - var now = window.performance.now(); - var time_since_last = now - this._lastFrameTime; - var target_time_between_frames = 1000 / this._targetFrameRate; - - // only draw if we really need to; don't overextend the browser. - // draw if we're within 5ms of when our next frame should paint - // (this will prevent us from giving up opportunities to draw - // again when it's really about time for us to do so). fixes an - // issue where the frameRate is too low if our refresh loop isn't - // in sync with the browser. note that we have to draw once even - // if looping is off, so we bypass the time delay if that - // is the case. - var epsilon = 5; - if ( - !this._loop || - time_since_last >= target_time_between_frames - epsilon - ) { - //mandatory update values(matrixs and stack) - this.redraw(); - this._frameRate = 1000.0 / (now - this._lastFrameTime); - this.deltaTime = now - this._lastFrameTime; - this._setProperty('deltaTime', this.deltaTime); - this._lastFrameTime = now; - - // If the user is actually using mouse module, then update - // coordinates, otherwise skip. We can test this by simply - // checking if any of the mouse functions are available or not. - // NOTE : This reflects only in complete build or modular build. - if (typeof this._updateMouseCoords !== 'undefined') { - this._updateMouseCoords(); - - //reset delta values so they reset even if there is no mouse event to set them - // for example if the mouse is outside the screen - this._setProperty('movedX', 0); - this._setProperty('movedY', 0); + }; + + this._wrapPreload = function(obj, fnName) { + return (...args) => { + //increment counter + this._incrementPreload(); + //call original function + return this._registeredPreloadMethods[fnName].apply(obj, args); + }; + }; + + this._incrementPreload = function() { + const context = this._isGlobal ? window : this; + context._setProperty('_preloadCount', context._preloadCount + 1); + }; + + this._setup = () => { + // Always create a default canvas. + // Later on if the user calls createCanvas, this default one + // will be replaced + this.createCanvas( + this._defaultCanvasSize.width, + this._defaultCanvasSize.height, + 'p2d' + ); + + // return preload functions to their normal vals if switched by preload + const context = this._isGlobal ? window : this; + if (typeof context.preload === 'function') { + for (const f in this._preloadMethods) { + context[f] = this._preloadMethods[f][f]; + if (context[f] && this) { + context[f] = context[f].bind(this); + } + } } - } - // get notified the next time the browser gives us - // an opportunity to draw. - if (this._loop) { - this._requestAnimId = window.requestAnimationFrame(this._draw); - } - }.bind(this); - - this._setProperty = function(prop, value) { - this[prop] = value; - if (this._isGlobal) { - window[prop] = value; - } - }.bind(this); - - /** - * Removes the entire p5 sketch. This will remove the canvas and any - * elements created by p5.js. It will also stop the draw loop and unbind - * any properties or methods from the window global scope. It will - * leave a variable p5 in case you wanted to create a new p5 sketch. - * If you like, you can set p5 = null to erase it. While all functions and - * variables and objects created by the p5 library will be removed, any - * other global variables created by your code will remain. - * - * @method remove - * @example - *
- * function draw() { - * ellipse(50, 50, 10, 10); - * } - * - * function mousePressed() { - * remove(); // remove whole sketch on mouse press - * } - *
- * - * @alt - * nothing displayed - * - */ - this.remove = function() { - var loadingScreen = document.getElementById(this._loadingScreenId); - if (loadingScreen) { - loadingScreen.parentNode.removeChild(loadingScreen); - // Add 1 to preload counter to prevent the sketch ever executing setup() - this._incrementPreload(); - } - if (this._curElement) { - // stop draw - this._loop = false; - if (this._requestAnimId) { - window.cancelAnimationFrame(this._requestAnimId); + // Short-circuit on this, in case someone used the library in "global" + // mode earlier + if (typeof context.setup === 'function') { + context.setup(); } - // unregister events sketch-wide - for (var ev in this._events) { - window.removeEventListener(ev, this._events[ev]); - } + // unhide any hidden canvases that were created + const canvases = document.getElementsByTagName('canvas'); - // remove DOM elements created by p5, and listeners - for (var i = 0; i < this._elements.length; i++) { - var e = this._elements[i]; - if (e.elt && e.elt.parentNode) { - e.elt.parentNode.removeChild(e.elt); + for (const k of canvases) { + if (k.dataset.hidden === 'true') { + k.style.visibility = ''; + delete k.dataset.hidden; } - for (var elt_ev in e._events) { - e.elt.removeEventListener(elt_ev, e._events[elt_ev]); + } + + this._lastFrameTime = window.performance.now(); + this._setupDone = true; + }; + + this._draw = () => { + const now = window.performance.now(); + const time_since_last = now - this._lastFrameTime; + const target_time_between_frames = 1000 / this._targetFrameRate; + + // only draw if we really need to; don't overextend the browser. + // draw if we're within 5ms of when our next frame should paint + // (this will prevent us from giving up opportunities to draw + // again when it's really about time for us to do so). fixes an + // issue where the frameRate is too low if our refresh loop isn't + // in sync with the browser. note that we have to draw once even + // if looping is off, so we bypass the time delay if that + // is the case. + const epsilon = 5; + if ( + !this._loop || + time_since_last >= target_time_between_frames - epsilon + ) { + //mandatory update values(matrixs and stack) + this.redraw(); + this._frameRate = 1000.0 / (now - this._lastFrameTime); + this.deltaTime = now - this._lastFrameTime; + this._setProperty('deltaTime', this.deltaTime); + this._lastFrameTime = now; + + // If the user is actually using mouse module, then update + // coordinates, otherwise skip. We can test this by simply + // checking if any of the mouse functions are available or not. + // NOTE : This reflects only in complete build or modular build. + if (typeof this._updateMouseCoords !== 'undefined') { + this._updateMouseCoords(); + + //reset delta values so they reset even if there is no mouse event to set them + // for example if the mouse is outside the screen + this._setProperty('movedX', 0); + this._setProperty('movedY', 0); } } - // call any registered remove functions - var self = this; - this._registeredMethods.remove.forEach(function(f) { - if (typeof f !== 'undefined') { - f.call(self); + // get notified the next time the browser gives us + // an opportunity to draw. + if (this._loop) { + this._requestAnimId = window.requestAnimationFrame(this._draw); + } + }; + + this._setProperty = (prop, value) => { + this[prop] = value; + if (this._isGlobal) { + window[prop] = value; + } + }; + + /** + * Removes the entire p5 sketch. This will remove the canvas and any + * elements created by p5.js. It will also stop the draw loop and unbind + * any properties or methods from the window global scope. It will + * leave a variable p5 in case you wanted to create a new p5 sketch. + * If you like, you can set p5 = null to erase it. While all functions and + * variables and objects created by the p5 library will be removed, any + * other global variables created by your code will remain. + * + * @method remove + * @example + *
+ * function draw() { + * ellipse(50, 50, 10, 10); + * } + * + * function mousePressed() { + * remove(); // remove whole sketch on mouse press + * } + *
+ * + * @alt + * nothing displayed + * + */ + this.remove = () => { + const loadingScreen = document.getElementById(this._loadingScreenId); + if (loadingScreen) { + loadingScreen.parentNode.removeChild(loadingScreen); + // Add 1 to preload counter to prevent the sketch ever executing setup() + this._incrementPreload(); + } + if (this._curElement) { + // stop draw + this._loop = false; + if (this._requestAnimId) { + window.cancelAnimationFrame(this._requestAnimId); } - }); - } - // remove window bound properties and methods - if (this._isGlobal) { - for (var p in p5.prototype) { - try { - delete window[p]; - } catch (x) { - window[p] = undefined; + + // unregister events sketch-wide + for (const ev in this._events) { + window.removeEventListener(ev, this._events[ev]); } + + // remove DOM elements created by p5, and listeners + for (const e of this._elements) { + if (e.elt && e.elt.parentNode) { + e.elt.parentNode.removeChild(e.elt); + } + for (const elt_ev in e._events) { + e.elt.removeEventListener(elt_ev, e._events[elt_ev]); + } + } + + // call any registered remove functions + const self = this; + this._registeredMethods.remove.forEach(f => { + if (typeof f !== 'undefined') { + f.call(self); + } + }); } - for (var p2 in this) { - if (this.hasOwnProperty(p2)) { + // remove window bound properties and methods + if (this._isGlobal) { + for (const p in p5.prototype) { try { - delete window[p2]; + delete window[p]; } catch (x) { - window[p2] = undefined; + window[p] = undefined; + } + } + for (const p2 in this) { + if (this.hasOwnProperty(p2)) { + try { + delete window[p2]; + } catch (x) { + window[p2] = undefined; + } } } + p5.instance = null; } - p5.instance = null; - } - }.bind(this); + }; - // call any registered init functions - this._registeredMethods.init.forEach(function(f) { - if (typeof f !== 'undefined') { - f.call(this); - } - }, this); - - var friendlyBindGlobal = this._createFriendlyGlobalFunctionBinder(); - - // If the user has created a global setup or draw function, - // assume "global" mode and make everything global (i.e. on the window) - if (!sketch) { - this._isGlobal = true; - p5.instance = this; - // Loop through methods on the prototype and attach them to the window - for (var p in p5.prototype) { - if (typeof p5.prototype[p] === 'function') { - var ev = p.substring(2); - if (!this._events.hasOwnProperty(ev)) { - if (Math.hasOwnProperty(p) && Math[p] === p5.prototype[p]) { - // Multiple p5 methods are just native Math functions. These can be - // called without any binding. - friendlyBindGlobal(p, p5.prototype[p]); - } else { - friendlyBindGlobal(p, p5.prototype[p].bind(this)); + // call any registered init functions + this._registeredMethods.init.forEach(function(f) { + if (typeof f !== 'undefined') { + f.call(this); + } + }, this); + + const friendlyBindGlobal = this._createFriendlyGlobalFunctionBinder(); + + // If the user has created a global setup or draw function, + // assume "global" mode and make everything global (i.e. on the window) + if (!sketch) { + this._isGlobal = true; + p5.instance = this; + // Loop through methods on the prototype and attach them to the window + for (const p in p5.prototype) { + if (typeof p5.prototype[p] === 'function') { + const ev = p.substring(2); + if (!this._events.hasOwnProperty(ev)) { + if (Math.hasOwnProperty(p) && Math[p] === p5.prototype[p]) { + // Multiple p5 methods are just native Math functions. These can be + // called without any binding. + friendlyBindGlobal(p, p5.prototype[p]); + } else { + friendlyBindGlobal(p, p5.prototype[p].bind(this)); + } } + } else { + friendlyBindGlobal(p, p5.prototype[p]); } - } else { - friendlyBindGlobal(p, p5.prototype[p]); } - } - // Attach its properties to the window - for (var p2 in this) { - if (this.hasOwnProperty(p2)) { - friendlyBindGlobal(p2, this[p2]); + // Attach its properties to the window + for (const p2 in this) { + if (this.hasOwnProperty(p2)) { + friendlyBindGlobal(p2, this[p2]); + } } + } else { + // Else, the user has passed in a sketch closure that may set + // user-provided 'setup', 'draw', etc. properties on this instance of p5 + sketch(this); } - } else { - // Else, the user has passed in a sketch closure that may set - // user-provided 'setup', 'draw', etc. properties on this instance of p5 - sketch(this); - } - // Bind events to window (not using container div bc key events don't work) + // Bind events to window (not using container div bc key events don't work) - for (var e in this._events) { - var f = this['_on' + e]; - if (f) { - var m = f.bind(this); - window.addEventListener(e, m, { passive: false }); - this._events[e] = m; + for (const e in this._events) { + const f = this[`_on${e}`]; + if (f) { + const m = f.bind(this); + window.addEventListener(e, m, { passive: false }); + this._events[e] = m; + } } - } - var focusHandler = function() { - this._setProperty('focused', true); - }.bind(this); - var blurHandler = function() { - this._setProperty('focused', false); - }.bind(this); - window.addEventListener('focus', focusHandler); - window.addEventListener('blur', blurHandler); - this.registerMethod('remove', function() { - window.removeEventListener('focus', focusHandler); - window.removeEventListener('blur', blurHandler); - }); - - if (document.readyState === 'complete') { - this._start(); - } else { - window.addEventListener('load', this._start.bind(this), false); + const focusHandler = () => { + this._setProperty('focused', true); + }; + const blurHandler = () => { + this._setProperty('focused', false); + }; + window.addEventListener('focus', focusHandler); + window.addEventListener('blur', blurHandler); + this.registerMethod('remove', () => { + window.removeEventListener('focus', focusHandler); + window.removeEventListener('blur', blurHandler); + }); + + if (document.readyState === 'complete') { + this._start(); + } else { + window.addEventListener('load', this._start.bind(this), false); + } } -}; -p5.prototype._initializeInstanceVariables = function() { - this._styles = []; + _initializeInstanceVariables() { + this._styles = []; - this._bezierDetail = 20; - this._curveDetail = 20; + this._bezierDetail = 20; + this._curveDetail = 20; - this._colorMode = constants.RGB; - this._colorMaxes = { - rgb: [255, 255, 255, 255], - hsb: [360, 100, 100, 1], - hsl: [360, 100, 100, 1] - }; + this._colorMode = constants.RGB; + this._colorMaxes = { + rgb: [255, 255, 255, 255], + hsb: [360, 100, 100, 1], + hsl: [360, 100, 100, 1] + }; - this._pixelsDirty = true; + this._pixelsDirty = true; - this._downKeys = {}; //Holds the key codes of currently pressed keys -}; + this._downKeys = {}; //Holds the key codes of currently pressed keys + } + + registerPreloadMethod(fnString, obj) { + // obj = obj || p5.prototype; + if (!p5.prototype._preloadMethods.hasOwnProperty(fnString)) { + p5.prototype._preloadMethods[fnString] = obj; + } + } + + registerMethod(name, m) { + const target = this || p5.prototype; + if (!target._registeredMethods.hasOwnProperty(name)) { + target._registeredMethods[name] = []; + } + target._registeredMethods[name].push(m); + } + + // create a function which provides a standardized process for binding + // globals; this is implemented as a factory primarily so that there's a + // way to redefine what "global" means for the binding function so it + // can be used in scenarios like unit testing where the window object + // might not exist + _createFriendlyGlobalFunctionBinder(options = {}) { + const globalObject = options.globalObject || window; + const log = options.log || console.log.bind(console); + const propsToForciblyOverwrite = { + // p5.print actually always overwrites an existing global function, + // albeit one that is very unlikely to be used: + // + // https://developer.mozilla.org/en-US/docs/Web/API/Window/print + print: true + }; + + return (prop, value) => { + if ( + !p5.disableFriendlyErrors && + typeof IS_MINIFIED === 'undefined' && + typeof value === 'function' && + !(prop in p5.prototype._preloadMethods) + ) { + try { + // Because p5 has so many common function names, it's likely + // that users may accidentally overwrite global p5 functions with + // their own variables. Let's allow this but log a warning to + // help users who may be doing this unintentionally. + // + // For more information, see: + // + // https://github.com/processing/p5.js/issues/1317 + + if (prop in globalObject && !(prop in propsToForciblyOverwrite)) { + throw new Error(`global "${prop}" already exists`); + } + + // It's possible that this might throw an error because there + // are a lot of edge-cases in which `Object.defineProperty` might + // not succeed; since this functionality is only intended to + // help beginners anyways, we'll just catch such an exception + // if it occurs, and fall back to legacy behavior. + Object.defineProperty(globalObject, prop, { + configurable: true, + enumerable: true, + get() { + return value; + }, + set(newValue) { + Object.defineProperty(globalObject, prop, { + configurable: true, + enumerable: true, + value: newValue, + writable: true + }); + log( + `You just changed the value of "${prop}", which was a p5 function. This could cause problems later if you're not careful.` + ); + } + }); + } catch (e) { + log( + `p5 had problems creating the global function "${prop}", possibly because your code is already using that name as a variable. You may want to rename your variable to something else.` + ); + globalObject[prop] = value; + } + } else { + globalObject[prop] = value; + } + }; + } +} // This is a pointer to our global mode p5 instance, if we're in // global mode. @@ -603,7 +690,7 @@ p5.instance = null; p5.disableFriendlyErrors = false; // attach constants to p5 prototype -for (var k in constants) { +for (const k in constants) { p5.prototype[k] = constants[k]; } @@ -625,102 +712,4 @@ p5.prototype._registeredMethods = { init: [], pre: [], post: [], remove: [] }; p5.prototype._registeredPreloadMethods = {}; -p5.prototype.registerPreloadMethod = function(fnString, obj) { - // obj = obj || p5.prototype; - if (!p5.prototype._preloadMethods.hasOwnProperty(fnString)) { - p5.prototype._preloadMethods[fnString] = obj; - } -}; - -p5.prototype.registerMethod = function(name, m) { - var target = this || p5.prototype; - if (!target._registeredMethods.hasOwnProperty(name)) { - target._registeredMethods[name] = []; - } - target._registeredMethods[name].push(m); -}; - -// create a function which provides a standardized process for binding -// globals; this is implemented as a factory primarily so that there's a -// way to redefine what "global" means for the binding function so it -// can be used in scenarios like unit testing where the window object -// might not exist -p5.prototype._createFriendlyGlobalFunctionBinder = function(options) { - options = options || {}; - - var globalObject = options.globalObject || window; - var log = options.log || console.log.bind(console); - var propsToForciblyOverwrite = { - // p5.print actually always overwrites an existing global function, - // albeit one that is very unlikely to be used: - // - // https://developer.mozilla.org/en-US/docs/Web/API/Window/print - print: true - }; - - return function(prop, value) { - if ( - !p5.disableFriendlyErrors && - typeof IS_MINIFIED === 'undefined' && - typeof value === 'function' && - !(prop in p5.prototype._preloadMethods) - ) { - try { - // Because p5 has so many common function names, it's likely - // that users may accidentally overwrite global p5 functions with - // their own variables. Let's allow this but log a warning to - // help users who may be doing this unintentionally. - // - // For more information, see: - // - // https://github.com/processing/p5.js/issues/1317 - - if (prop in globalObject && !(prop in propsToForciblyOverwrite)) { - throw new Error('global "' + prop + '" already exists'); - } - - // It's possible that this might throw an error because there - // are a lot of edge-cases in which `Object.defineProperty` might - // not succeed; since this functionality is only intended to - // help beginners anyways, we'll just catch such an exception - // if it occurs, and fall back to legacy behavior. - Object.defineProperty(globalObject, prop, { - configurable: true, - enumerable: true, - get: function() { - return value; - }, - set: function(newValue) { - Object.defineProperty(globalObject, prop, { - configurable: true, - enumerable: true, - value: newValue, - writable: true - }); - log( - 'You just changed the value of "' + - prop + - '", which was ' + - "a p5 function. This could cause problems later if you're " + - 'not careful.' - ); - } - }); - } catch (e) { - log( - 'p5 had problems creating the global function "' + - prop + - '", ' + - 'possibly because your code is already using that name as ' + - 'a variable. You may want to rename your variable to something ' + - 'else.' - ); - globalObject[prop] = value; - } - } else { - globalObject[prop] = value; - } - }; -}; - -module.exports = p5; +export default p5; diff --git a/src/core/p5.Element.js b/src/core/p5.Element.js index 3d9083159a..1bfcb6b687 100644 --- a/src/core/p5.Element.js +++ b/src/core/p5.Element.js @@ -4,9 +4,7 @@ * @for p5.Element */ -'use strict'; - -var p5 = require('./main'); +import p5 from './main'; /** * Base class for all elements added to a sketch, including canvas, @@ -244,7 +242,7 @@ p5.Element.prototype.mousePressed = function(fxn) { // Prepend the mouse property setters to the event-listener. // This is required so that mouseButton is set correctly prior to calling the callback (fxn). // For details, see https://github.com/processing/p5.js/issues/3087. - var eventPrependedFxn = function(event) { + const eventPrependedFxn = function(event) { this._pInst._setProperty('mouseIsPressed', true); this._pInst._setMouseButton(event); // Pass along the return-value of the callback: @@ -846,18 +844,18 @@ p5.Element._adjustListener = function(ev, fxn, ctx) { return this; }; -p5.Element._attachListener = function(ev, fxn, ctx) { +p5.Element._attachListener = (ev, fxn, ctx) => { // detach the old listener if there was one if (ctx._events[ev]) { p5.Element._detachListener(ev, ctx); } - var f = fxn.bind(ctx); + const f = fxn.bind(ctx); ctx.elt.addEventListener(ev, f, false); ctx._events[ev] = f; }; -p5.Element._detachListener = function(ev, ctx) { - var f = ctx._events[ev]; +p5.Element._detachListener = (ev, ctx) => { + const f = ctx._events[ev]; ctx.elt.removeEventListener(ev, f, false); ctx._events[ev] = null; }; @@ -870,4 +868,4 @@ p5.Element.prototype._setProperty = function(prop, value) { this[prop] = value; }; -module.exports = p5.Element; +export default p5.Element; diff --git a/src/core/p5.Graphics.js b/src/core/p5.Graphics.js index 520740982a..b669d55f52 100644 --- a/src/core/p5.Graphics.js +++ b/src/core/p5.Graphics.js @@ -4,10 +4,8 @@ * @for p5 */ -'use strict'; - -var p5 = require('./main'); -var constants = require('./constants'); +import p5 from './main'; +import * as constants from './constants'; /** * Thin wrapper around a renderer, to be used for creating a @@ -24,16 +22,16 @@ var constants = require('./constants'); * @param {p5} [pInst] pointer to p5 instance */ p5.Graphics = function(w, h, renderer, pInst) { - var r = renderer || constants.P2D; + const r = renderer || constants.P2D; this.canvas = document.createElement('canvas'); - var node = pInst._userNode || document.body; + const node = pInst._userNode || document.body; node.appendChild(this.canvas); p5.Element.call(this, this.canvas, pInst); // bind methods and props of p5 to the new object - for (var p in p5.prototype) { + for (const p in p5.prototype) { if (!this[p]) { if (typeof p5.prototype[p] === 'function') { this[p] = p5.prototype[p].bind(this); @@ -173,13 +171,13 @@ p5.Graphics.prototype.remove = function() { if (this.elt.parentNode) { this.elt.parentNode.removeChild(this.elt); } - var idx = this._pInst._elements.indexOf(this); + const idx = this._pInst._elements.indexOf(this); if (idx !== -1) { this._pInst._elements.splice(idx, 1); } - for (var elt_ev in this._events) { + for (const elt_ev in this._events) { this.elt.removeEventListener(elt_ev, this._events[elt_ev]); } }; -module.exports = p5.Graphics; +export default p5.Graphics; diff --git a/src/core/p5.Renderer.js b/src/core/p5.Renderer.js index e6c121dadc..e0e5efb28c 100644 --- a/src/core/p5.Renderer.js +++ b/src/core/p5.Renderer.js @@ -4,10 +4,8 @@ * @for p5 */ -'use strict'; - -var p5 = require('./main'); -var constants = require('../core/constants'); +import p5 from './main'; +import * as constants from '../core/constants'; /** * Main graphics and rendering context, as well as the base API @@ -102,8 +100,8 @@ p5.Renderer.prototype.resize = function(w, h) { this.height = h; this.elt.width = w * this._pInst._pixelDensity; this.elt.height = h * this._pInst._pixelDensity; - this.elt.style.width = w + 'px'; - this.elt.style.height = h + 'px'; + this.elt.style.width = `${w}px`; + this.elt.style.height = `${h}px`; if (this._isMainCanvas) { this._pInst._setProperty('width', this.width); this._pInst._setProperty('height', this.height); @@ -111,9 +109,9 @@ p5.Renderer.prototype.resize = function(w, h) { }; p5.Renderer.prototype.get = function(x, y, w, h) { - var pixelsState = this._pixelsState; - var pd = pixelsState._pixelDensity; - var canvas = this.canvas; + const pixelsState = this._pixelsState; + const pd = pixelsState._pixelDensity; + const canvas = this.canvas; if (typeof x === 'undefined' && typeof y === 'undefined') { // get() @@ -135,7 +133,7 @@ p5.Renderer.prototype.get = function(x, y, w, h) { // get(x,y,w,h) } - var region = new p5.Image(w, h); + const region = new p5.Image(w, h); region.canvas .getContext('2d') .drawImage(canvas, x, y, w * pd, h * pd, 0, 0, w, h); @@ -211,17 +209,17 @@ p5.Renderer.prototype.textAlign = function(h, v) { }; p5.Renderer.prototype.text = function(str, x, y, maxWidth, maxHeight) { - var p = this._pInst, - cars, - n, - ii, - jj, - line, - testLine, - testWidth, - words, - totalHeight, - finalMaxHeight = Number.MAX_VALUE; + const p = this._pInst; + let cars; + let n; + let ii; + let jj; + let line; + let testLine; + let testWidth; + let words; + let totalHeight; + let finalMaxHeight = Number.MAX_VALUE; if (!(this._doFill || this._doStroke)) { return; @@ -242,10 +240,10 @@ p5.Renderer.prototype.text = function(str, x, y, maxWidth, maxHeight) { line = ''; words = cars[ii].split(' '); for (n = 0; n < words.length; n++) { - testLine = line + words[n] + ' '; + testLine = `${line + words[n]} `; testWidth = this.textWidth(testLine); if (testWidth > maxWidth) { - line = words[n] + ' '; + line = `${words[n]} `; totalHeight += p.textLeading(); } else { line = testLine; @@ -267,7 +265,7 @@ p5.Renderer.prototype.text = function(str, x, y, maxWidth, maxHeight) { break; } - var baselineHacked = false; + let baselineHacked = false; if (typeof maxHeight !== 'undefined') { switch (this._textBaseline) { case constants.BOTTOM: @@ -290,11 +288,11 @@ p5.Renderer.prototype.text = function(str, x, y, maxWidth, maxHeight) { line = ''; words = cars[ii].split(' '); for (n = 0; n < words.length; n++) { - testLine = line + words[n] + ' '; + testLine = `${line + words[n]} `; testWidth = this.textWidth(testLine); if (testWidth > maxWidth && line.length > 0) { this._renderText(p, line, x, y, finalMaxHeight); - line = words[n] + ' '; + line = `${words[n]} `; y += p.textLeading(); } else { line = testLine; @@ -311,8 +309,9 @@ p5.Renderer.prototype.text = function(str, x, y, maxWidth, maxHeight) { } else { // Offset to account for vertically centering multiple lines of text - no // need to adjust anything for vertical align top or baseline - var offset = 0, - vAlign = p.textAlign().vertical; + let offset = 0; + + const vAlign = p.textAlign().vertical; if (vAlign === constants.CENTER) { offset = (cars.length - 1) * p.textLeading() / 2; } else if (vAlign === constants.BOTTOM) { @@ -335,8 +334,7 @@ p5.Renderer.prototype._applyDefaults = function() { /** * Helper fxn to check font type (system or otf) */ -p5.Renderer.prototype._isOpenType = function(f) { - f = f || this._textFont; +p5.Renderer.prototype._isOpenType = function(f = this._textFont) { return typeof f === 'object' && f.font && f.font.supported; }; @@ -348,17 +346,17 @@ p5.Renderer.prototype._updateTextMetrics = function() { } // Adapted from http://stackoverflow.com/a/25355178 - var text = document.createElement('span'); + const text = document.createElement('span'); text.style.fontFamily = this._textFont; - text.style.fontSize = this._textSize + 'px'; + text.style.fontSize = `${this._textSize}px`; text.innerHTML = 'ABCjgq|'; - var block = document.createElement('div'); + const block = document.createElement('div'); block.style.display = 'inline-block'; block.style.width = '1px'; block.style.height = '0px'; - var container = document.createElement('div'); + const container = document.createElement('div'); container.appendChild(text); container.appendChild(block); @@ -367,15 +365,15 @@ p5.Renderer.prototype._updateTextMetrics = function() { document.body.appendChild(container); block.style.verticalAlign = 'baseline'; - var blockOffset = calculateOffset(block); - var textOffset = calculateOffset(text); - var ascent = blockOffset[1] - textOffset[1]; + let blockOffset = calculateOffset(block); + let textOffset = calculateOffset(text); + const ascent = blockOffset[1] - textOffset[1]; block.style.verticalAlign = 'bottom'; blockOffset = calculateOffset(block); textOffset = calculateOffset(text); - var height = blockOffset[1] - textOffset[1]; - var descent = height - ascent; + const height = blockOffset[1] - textOffset[1]; + const descent = height - ascent; document.body.removeChild(container); @@ -390,7 +388,7 @@ p5.Renderer.prototype._updateTextMetrics = function() { * Adapted from http://stackoverflow.com/a/25355178 */ function calculateOffset(object) { - var currentLeft = 0, + let currentLeft = 0, currentTop = 0; if (object.offsetParent) { do { @@ -404,4 +402,4 @@ function calculateOffset(object) { return [currentLeft, currentTop]; } -module.exports = p5.Renderer; +export default p5.Renderer; diff --git a/src/core/p5.Renderer2D.js b/src/core/p5.Renderer2D.js index 1206bd835e..f4bc2da719 100644 --- a/src/core/p5.Renderer2D.js +++ b/src/core/p5.Renderer2D.js @@ -1,18 +1,16 @@ -'use strict'; +import p5 from './main'; +import * as constants from './constants'; +import filters from '../image/filters'; -var p5 = require('./main'); -var constants = require('./constants'); -var filters = require('../image/filters'); - -require('./p5.Renderer'); +import './p5.Renderer'; /** * p5.Renderer2D * The 2D graphics canvas renderer class. * extends p5.Renderer */ -var styleEmpty = 'rgba(0,0,0,0)'; -// var alphaThreshold = 0.00125; // minimum visible +const styleEmpty = 'rgba(0,0,0,0)'; +// const alphaThreshold = 0.00125; // minimum visible p5.Renderer2D = function(elt, pInst, isMainCanvas) { p5.Renderer.call(this, elt, pInst, isMainCanvas); @@ -43,17 +41,17 @@ p5.Renderer2D.prototype.resize = function(w, h) { // COLOR | Setting ////////////////////////////////////////////// -p5.Renderer2D.prototype.background = function() { +p5.Renderer2D.prototype.background = function(...args) { this.drawingContext.save(); this.resetMatrix(); - if (arguments[0] instanceof p5.Image) { - this._pInst.image(arguments[0], 0, 0, this.width, this.height); + if (args[0] instanceof p5.Image) { + this._pInst.image(args[0], 0, 0, this.width, this.height); } else { - var curFill = this._getFill(); + const curFill = this._getFill(); // create background rect - var color = this._pInst.color.apply(this._pInst, arguments); - var newFill = color.toString(); + const color = this._pInst.color(...args); + const newFill = color.toString(); this._setFill(newFill); this.drawingContext.fillRect(0, 0, this.width, this.height); // reset fill @@ -73,13 +71,13 @@ p5.Renderer2D.prototype.clear = function() { this._pixelsState._pixelsDirty = true; }; -p5.Renderer2D.prototype.fill = function() { - var color = this._pInst.color.apply(this._pInst, arguments); +p5.Renderer2D.prototype.fill = function(...args) { + const color = this._pInst.color(...args); this._setFill(color.toString()); }; -p5.Renderer2D.prototype.stroke = function() { - var color = this._pInst.color.apply(this._pInst, arguments); +p5.Renderer2D.prototype.stroke = function(...args) { + const color = this._pInst.color(...args); this._setStroke(color.toString()); }; @@ -98,7 +96,7 @@ p5.Renderer2D.prototype.image = function( dWidth, dHeight ) { - var cnv; + let cnv; if (img.gifProperties) { img._animateGif(this._pInst); } @@ -115,7 +113,7 @@ p5.Renderer2D.prototype.image = function( if (!cnv) { cnv = img.canvas || img.elt; } - var s = 1; + let s = 1; if (img.width && img.width > 0) { s = cnv.width / img.width; } @@ -143,18 +141,18 @@ p5.Renderer2D.prototype._getTintedImageCanvas = function(img) { if (!img.canvas) { return img; } - var pixels = filters._toPixels(img.canvas); - var tmpCanvas = document.createElement('canvas'); + const pixels = filters._toPixels(img.canvas); + const tmpCanvas = document.createElement('canvas'); tmpCanvas.width = img.canvas.width; tmpCanvas.height = img.canvas.height; - var tmpCtx = tmpCanvas.getContext('2d'); - var id = tmpCtx.createImageData(img.canvas.width, img.canvas.height); - var newPixels = id.data; - for (var i = 0; i < pixels.length; i += 4) { - var r = pixels[i]; - var g = pixels[i + 1]; - var b = pixels[i + 2]; - var a = pixels[i + 3]; + const tmpCtx = tmpCanvas.getContext('2d'); + const id = tmpCtx.createImageData(img.canvas.width, img.canvas.height); + const newPixels = id.data; + for (let i = 0; i < pixels.length; i += 4) { + const r = pixels[i]; + const g = pixels[i + 1]; + const b = pixels[i + 2]; + const a = pixels[i + 3]; newPixels[i] = r * this._tint[0] / 255; newPixels[i + 1] = g * this._tint[1] / 255; newPixels[i + 2] = b * this._tint[2] / 255; @@ -189,47 +187,47 @@ p5.Renderer2D.prototype.blendMode = function(mode) { ) { this.drawingContext.globalCompositeOperation = mode; } else { - throw new Error('Mode ' + mode + ' not recognized.'); + throw new Error(`Mode ${mode} not recognized.`); } }; -p5.Renderer2D.prototype.blend = function() { - var currBlend = this.drawingContext.globalCompositeOperation; - var blendMode = arguments[arguments.length - 1]; +p5.Renderer2D.prototype.blend = function(...args) { + const currBlend = this.drawingContext.globalCompositeOperation; + const blendMode = args[args.length - 1]; - var copyArgs = Array.prototype.slice.call(arguments, 0, arguments.length - 1); + const copyArgs = Array.prototype.slice.call(args, 0, args.length - 1); this.drawingContext.globalCompositeOperation = blendMode; if (this._pInst) { - this._pInst.copy.apply(this._pInst, copyArgs); + this._pInst.copy(...copyArgs); } else { - this.copy.apply(this, copyArgs); + this.copy(...copyArgs); } this.drawingContext.globalCompositeOperation = currBlend; }; -p5.Renderer2D.prototype.copy = function() { - var srcImage, sx, sy, sw, sh, dx, dy, dw, dh; - if (arguments.length === 9) { - srcImage = arguments[0]; - sx = arguments[1]; - sy = arguments[2]; - sw = arguments[3]; - sh = arguments[4]; - dx = arguments[5]; - dy = arguments[6]; - dw = arguments[7]; - dh = arguments[8]; - } else if (arguments.length === 8) { +p5.Renderer2D.prototype.copy = function(...args) { + let srcImage, sx, sy, sw, sh, dx, dy, dw, dh; + if (args.length === 9) { + srcImage = args[0]; + sx = args[1]; + sy = args[2]; + sw = args[3]; + sh = args[4]; + dx = args[5]; + dy = args[6]; + dw = args[7]; + dh = args[8]; + } else if (args.length === 8) { srcImage = this._pInst; - sx = arguments[0]; - sy = arguments[1]; - sw = arguments[2]; - sh = arguments[3]; - dx = arguments[4]; - dy = arguments[5]; - dw = arguments[6]; - dh = arguments[7]; + sx = args[0]; + sy = args[1]; + sw = args[2]; + sh = args[3]; + dx = args[4]; + dy = args[5]; + dw = args[6]; + dh = args[7]; } else { throw new Error('Signature not supported'); } @@ -238,7 +236,7 @@ p5.Renderer2D.prototype.copy = function() { this._pixelsState._pixelsDirty = true; }; -p5.Renderer2D._copyHelper = function( +p5.Renderer2D._copyHelper = ( dstImage, srcImage, sx, @@ -249,9 +247,9 @@ p5.Renderer2D._copyHelper = function( dy, dw, dh -) { +) => { srcImage.loadPixels(); - var s = srcImage.canvas.width / srcImage.width; + const s = srcImage.canvas.width / srcImage.width; dstImage.drawingContext.drawImage( srcImage.canvas, s * sx, @@ -270,8 +268,8 @@ p5.Renderer2D._copyHelper = function( // x,y are canvas-relative (pre-scaled by _pixelDensity) p5.Renderer2D.prototype._getPixel = function(x, y) { - var pixelsState = this._pixelsState; - var imageData, index; + const pixelsState = this._pixelsState; + let imageData, index; if (pixelsState._pixelsDirty) { imageData = this.drawingContext.getImageData(x, y, 1, 1).data; index = 0; @@ -288,14 +286,14 @@ p5.Renderer2D.prototype._getPixel = function(x, y) { }; p5.Renderer2D.prototype.loadPixels = function() { - var pixelsState = this._pixelsState; // if called by p5.Image + const pixelsState = this._pixelsState; // if called by p5.Image if (!pixelsState._pixelsDirty) return; pixelsState._pixelsDirty = false; - var pd = pixelsState._pixelDensity; - var w = this.width * pd; - var h = this.height * pd; - var imageData = this.drawingContext.getImageData(0, 0, w, h); + const pd = pixelsState._pixelDensity; + const w = this.width * pd; + const h = this.height * pd; + const imageData = this.drawingContext.getImageData(0, 0, w, h); // @todo this should actually set pixels per object, so diff buffers can // have diff pixel arrays. pixelsState._setProperty('imageData', imageData); @@ -306,7 +304,7 @@ p5.Renderer2D.prototype.set = function(x, y, imgOrCol) { // round down to get integer numbers x = Math.floor(x); y = Math.floor(y); - var pixelsState = this._pixelsState; + const pixelsState = this._pixelsState; if (imgOrCol instanceof p5.Image) { this.drawingContext.save(); this.drawingContext.setTransform(1, 0, 0, 1, 0, 0); @@ -318,11 +316,11 @@ p5.Renderer2D.prototype.set = function(x, y, imgOrCol) { this.drawingContext.restore(); pixelsState._pixelsDirty = true; } else { - var r = 0, + let r = 0, g = 0, b = 0, a = 0; - var idx = + let idx = 4 * (y * pixelsState._pixelDensity * @@ -360,8 +358,8 @@ p5.Renderer2D.prototype.set = function(x, y, imgOrCol) { } } // loop over pixelDensity * pixelDensity - for (var i = 0; i < pixelsState._pixelDensity; i++) { - for (var j = 0; j < pixelsState._pixelDensity; j++) { + for (let i = 0; i < pixelsState._pixelDensity; i++) { + for (let j = 0; j < pixelsState._pixelDensity; j++) { // loop over idx = 4 * @@ -379,8 +377,8 @@ p5.Renderer2D.prototype.set = function(x, y, imgOrCol) { }; p5.Renderer2D.prototype.updatePixels = function(x, y, w, h) { - var pixelsState = this._pixelsState; - var pd = pixelsState._pixelDensity; + const pixelsState = this._pixelsState; + const pd = pixelsState._pixelDensity; if ( x === undefined && y === undefined && @@ -425,11 +423,12 @@ p5.Renderer2D.prototype._acuteArcToBezier = function _acuteArcToBezier( size ) { // Evaluate constants. - var alpha = size / 2.0, + const alpha = size / 2.0, cos_alpha = Math.cos(alpha), sin_alpha = Math.sin(alpha), cot_alpha = 1.0 / Math.tan(alpha), - phi = start + alpha, // This is how far the arc needs to be rotated. + // This is how far the arc needs to be rotated. + phi = start + alpha, cos_phi = Math.cos(phi), sin_phi = Math.sin(phi), lambda = (4.0 - cos_alpha) / 3.0, @@ -456,12 +455,12 @@ p5.Renderer2D.prototype._acuteArcToBezier = function _acuteArcToBezier( * start <= stop < start + TWO_PI */ p5.Renderer2D.prototype.arc = function(x, y, w, h, start, stop, mode) { - var ctx = this.drawingContext; - var rx = w / 2.0; - var ry = h / 2.0; - var epsilon = 0.00001; // Smallest visible angle on displays up to 4K. - var arcToDraw = 0; - var curves = []; + const ctx = this.drawingContext; + const rx = w / 2.0; + const ry = h / 2.0; + const epsilon = 0.00001; // Smallest visible angle on displays up to 4K. + let arcToDraw = 0; + const curves = []; x += rx; y += ry; @@ -476,7 +475,7 @@ p5.Renderer2D.prototype.arc = function(x, y, w, h, start, stop, mode) { // Fill curves if (this._doFill) { ctx.beginPath(); - curves.forEach(function(curve, index) { + curves.forEach((curve, index) => { if (index === 0) { ctx.moveTo(x + curve.ax * rx, y + curve.ay * ry); } @@ -496,7 +495,7 @@ p5.Renderer2D.prototype.arc = function(x, y, w, h, start, stop, mode) { // Stroke curves if (this._doStroke) { ctx.beginPath(); - curves.forEach(function(curve, index) { + curves.forEach((curve, index) => { if (index === 0) { ctx.moveTo(x + curve.ax * rx, y + curve.ay * ry); } @@ -518,10 +517,10 @@ p5.Renderer2D.prototype.arc = function(x, y, w, h, start, stop, mode) { }; p5.Renderer2D.prototype.ellipse = function(args) { - var ctx = this.drawingContext; - var doFill = this._doFill, + const ctx = this.drawingContext; + const doFill = this._doFill, doStroke = this._doStroke; - var x = args[0], + const x = args[0], y = args[1], w = args[2], h = args[3]; @@ -534,12 +533,17 @@ p5.Renderer2D.prototype.ellipse = function(args) { return this; } } - var kappa = 0.5522847498, - ox = w / 2 * kappa, // control point offset horizontal - oy = h / 2 * kappa, // control point offset vertical - xe = x + w, // x-end - ye = y + h, // y-end - xm = x + w / 2, // x-middle + const kappa = 0.5522847498, + // control point offset horizontal + ox = w / 2 * kappa, + // control point offset vertical + oy = h / 2 * kappa, + // x-end + xe = x + w, + // y-end + ye = y + h, + // x-middle + xm = x + w / 2, ym = y + h / 2; // y-middle ctx.beginPath(); ctx.moveTo(x, ym); @@ -559,7 +563,7 @@ p5.Renderer2D.prototype.ellipse = function(args) { }; p5.Renderer2D.prototype.line = function(x1, y1, x2, y2) { - var ctx = this.drawingContext; + const ctx = this.drawingContext; if (!this._doStroke) { return this; } else if (this._getStroke() === styleEmpty) { @@ -574,14 +578,14 @@ p5.Renderer2D.prototype.line = function(x1, y1, x2, y2) { }; p5.Renderer2D.prototype.point = function(x, y) { - var ctx = this.drawingContext; + const ctx = this.drawingContext; if (!this._doStroke) { return this; } else if (this._getStroke() === styleEmpty) { return this; } - var s = this._getStroke(); - var f = this._getFill(); + const s = this._getStroke(); + const f = this._getFill(); x = Math.round(x); y = Math.round(y); // swapping fill color to stroke and back after for correct point rendering @@ -598,8 +602,8 @@ p5.Renderer2D.prototype.point = function(x, y) { }; p5.Renderer2D.prototype.quad = function(x1, y1, x2, y2, x3, y3, x4, y4) { - var ctx = this.drawingContext; - var doFill = this._doFill, + const ctx = this.drawingContext; + const doFill = this._doFill, doStroke = this._doStroke; if (doFill && !doStroke) { if (this._getFill() === styleEmpty) { @@ -627,16 +631,16 @@ p5.Renderer2D.prototype.quad = function(x1, y1, x2, y2, x3, y3, x4, y4) { }; p5.Renderer2D.prototype.rect = function(args) { - var x = args[0], - y = args[1], - w = args[2], - h = args[3], - tl = args[4], - tr = args[5], - br = args[6], - bl = args[7]; - var ctx = this.drawingContext; - var doFill = this._doFill, + const x = args[0]; + const y = args[1]; + const w = args[2]; + const h = args[3]; + let tl = args[4]; + let tr = args[5]; + let br = args[6]; + let bl = args[7]; + const ctx = this.drawingContext; + const doFill = this._doFill, doStroke = this._doStroke; if (doFill && !doStroke) { if (this._getFill() === styleEmpty) { @@ -665,8 +669,8 @@ p5.Renderer2D.prototype.rect = function(args) { bl = br; } - var hw = w / 2; - var hh = h / 2; + const hw = w / 2; + const hh = h / 2; // Clip radii if (w < 2 * tl) { @@ -714,14 +718,14 @@ p5.Renderer2D.prototype.rect = function(args) { }; p5.Renderer2D.prototype.triangle = function(args) { - var ctx = this.drawingContext; - var doFill = this._doFill, + const ctx = this.drawingContext; + const doFill = this._doFill, doStroke = this._doStroke; - var x1 = args[0], + const x1 = args[0], y1 = args[1]; - var x2 = args[2], + const x2 = args[2], y2 = args[3]; - var x3 = args[4], + const x3 = args[4], y3 = args[5]; if (doFill && !doStroke) { if (this._getFill() === styleEmpty) { @@ -762,16 +766,16 @@ p5.Renderer2D.prototype.endShape = function( if (!this._doStroke && !this._doFill) { return this; } - var closeShape = mode === constants.CLOSE; - var v; + const closeShape = mode === constants.CLOSE; + let v; if (closeShape && !isContour) { vertices.push(vertices[0]); } - var i, j; - var numVerts = vertices.length; + let i, j; + const numVerts = vertices.length; if (isCurve && (shapeKind === constants.POLYGON || shapeKind === null)) { if (numVerts > 3) { - var b = [], + const b = [], s = 1 - this._curveTightness; this.drawingContext.beginPath(); this.drawingContext.moveTo(vertices[1][0], vertices[1][1]); @@ -1151,7 +1155,7 @@ p5.Renderer2D.prototype.translate = function(x, y) { ////////////////////////////////////////////// p5.Renderer2D.prototype.text = function(str, x, y, maxWidth, maxHeight) { - var baselineHacked; + let baselineHacked; // baselineHacked: (HACK) // A temporary fix to conform to Processing's implementation @@ -1164,7 +1168,7 @@ p5.Renderer2D.prototype.text = function(str, x, y, maxWidth, maxHeight) { } } - var p = p5.Renderer.prototype.text.apply(this, arguments); + const p = p5.Renderer.prototype.text.apply(this, arguments); if (baselineHacked) { this.drawingContext.textBaseline = constants.BASELINE; @@ -1217,8 +1221,8 @@ p5.Renderer2D.prototype.textWidth = function(s) { }; p5.Renderer2D.prototype._applyTextProperties = function() { - var font, - p = this._pInst; + let font; + const p = this._pInst; this._setProperty('_textAscent', null); this._setProperty('_textDescent', null); @@ -1230,12 +1234,8 @@ p5.Renderer2D.prototype._applyTextProperties = function() { this._setProperty('_textStyle', this._textFont.font.styleName); } - this.drawingContext.font = - (this._textStyle || 'normal') + - ' ' + - (this._textSize || 12) + - 'px ' + - (font || 'sans-serif'); + this.drawingContext.font = `${this._textStyle || 'normal'} ${this._textSize || + 12}px ${font || 'sans-serif'}`; this.drawingContext.textAlign = this._textAlign; if (this._textBaseline === constants.CENTER) { @@ -1277,4 +1277,4 @@ p5.Renderer2D.prototype.pop = function(style) { p5.Renderer.prototype.pop.call(this, style); }; -module.exports = p5.Renderer2D; +export default p5.Renderer2D; diff --git a/src/core/rendering.js b/src/core/rendering.js index b856e9cb86..9d2d2e2b73 100644 --- a/src/core/rendering.js +++ b/src/core/rendering.js @@ -4,15 +4,13 @@ * @for p5 */ -'use strict'; - -var p5 = require('./main'); -var constants = require('./constants'); -require('./p5.Graphics'); -require('./p5.Renderer2D'); -require('../webgl/p5.RendererGL'); -var defaultId = 'defaultCanvas0'; // this gets set again in createCanvas -var defaultClass = 'p5Canvas'; +import p5 from './main'; +import * as constants from './constants'; +import './p5.Graphics'; +import './p5.Renderer2D'; +import '../webgl/p5.RendererGL'; +let defaultId = 'defaultCanvas0'; // this gets set again in createCanvas +const defaultClass = 'p5Canvas'; /** * Creates a canvas element in the document, and sets the dimensions of it @@ -53,18 +51,16 @@ var defaultClass = 'p5Canvas'; p5.prototype.createCanvas = function(w, h, renderer) { p5._validateParameters('createCanvas', arguments); //optional: renderer, otherwise defaults to p2d - var r = renderer || constants.P2D; - var c; + const r = renderer || constants.P2D; + let c; if (r === constants.WEBGL) { c = document.getElementById(defaultId); if (c) { //if defaultCanvas already exists c.parentNode.removeChild(c); //replace the existing defaultCanvas - var thisRenderer = this._renderer; - this._elements = this._elements.filter(function(e) { - return e !== thisRenderer; - }); + const thisRenderer = this._renderer; + this._elements = this._elements.filter(e => e !== thisRenderer); } c = document.createElement('canvas'); c.id = defaultId; @@ -72,11 +68,11 @@ p5.prototype.createCanvas = function(w, h, renderer) { } else { if (!this._defaultGraphicsCreated) { c = document.createElement('canvas'); - var i = 0; - while (document.getElementById('defaultCanvas' + i)) { + let i = 0; + while (document.getElementById(`defaultCanvas${i}`)) { i++; } - defaultId = 'defaultCanvas' + i; + defaultId = `defaultCanvas${i}`; c.id = defaultId; c.classList.add(defaultClass); } else { @@ -147,9 +143,9 @@ p5.prototype.resizeCanvas = function(w, h, noRedraw) { p5._validateParameters('resizeCanvas', arguments); if (this._renderer) { // save canvas properties - var props = {}; - for (var key in this.drawingContext) { - var val = this.drawingContext[key]; + const props = {}; + for (const key in this.drawingContext) { + const val = this.drawingContext[key]; if (typeof val !== 'object' && typeof val !== 'function') { props[key] = val; } @@ -158,7 +154,7 @@ p5.prototype.resizeCanvas = function(w, h, noRedraw) { this.width = w; this.height = h; // reset canvas properties - for (var savedKey in props) { + for (const savedKey in props) { try { this.drawingContext[savedKey] = props[savedKey]; } catch (err) { @@ -315,4 +311,4 @@ p5.prototype.blendMode = function(mode) { this._renderer.blendMode(mode); }; -module.exports = p5; +export default p5; diff --git a/src/core/shape/2d_primitives.js b/src/core/shape/2d_primitives.js index eda824b9f8..122b9257b3 100644 --- a/src/core/shape/2d_primitives.js +++ b/src/core/shape/2d_primitives.js @@ -6,12 +6,10 @@ * @requires constants */ -'use strict'; - -var p5 = require('../main'); -var constants = require('../constants'); -var canvas = require('../helpers'); -require('../error_helpers'); +import p5 from '../main'; +import * as constants from '../constants'; +import canvas from '../helpers'; +import '../error_helpers'; /** * This function does 3 things: @@ -35,15 +33,15 @@ require('../error_helpers'); * underlying ellipse. This is useful if you want to do something special * there (like rendering a whole ellipse instead). */ -p5.prototype._normalizeArcAngles = function( +p5.prototype._normalizeArcAngles = ( start, stop, width, height, correctForScaling -) { - var epsilon = 0.00001; // Smallest visible angle on displays up to 4K. - var separation; +) => { + const epsilon = 0.00001; // Smallest visible angle on displays up to 4K. + let separation; // The order of the steps is important here: each one builds upon the // adjustments made in the steps that precede it. @@ -93,8 +91,8 @@ p5.prototype._normalizeArcAngles = function( } return { - start: start, - stop: stop, + start, + stop, correspondToSamePoint: separation < epsilon }; }; @@ -181,8 +179,8 @@ p5.prototype.arc = function(x, y, w, h, start, stop, mode, detail) { w = Math.abs(w); h = Math.abs(h); - var vals = canvas.modeAdjust(x, y, w, h, this._renderer._ellipseMode); - var angles = this._normalizeArcAngles(start, stop, vals.w, vals.h, true); + const vals = canvas.modeAdjust(x, y, w, h, this._renderer._ellipseMode); + const angles = this._normalizeArcAngles(start, stop, vals.w, vals.h, true); if (angles.correspondToSamePoint) { // If the arc starts and ends at (near enough) the same place, we choose to @@ -261,7 +259,7 @@ p5.prototype.ellipse = function(x, y, w, h, detailX) { h = Math.abs(h); } - var vals = canvas.modeAdjust(x, y, w, h, this._renderer._ellipseMode); + const vals = canvas.modeAdjust(x, y, w, h, this._renderer._ellipseMode); this._renderer.ellipse([vals.x, vals.y, vals.w, vals.h, detailX]); return this; @@ -291,10 +289,10 @@ p5.prototype.ellipse = function(x, y, w, h, detailX) { * white circle with black outline in mid of canvas that is 55x55. */ p5.prototype.circle = function() { - var args = Array.prototype.slice.call(arguments, 0, 2); + const args = Array.prototype.slice.call(arguments, 0, 2); args.push(arguments[2]); args.push(arguments[2]); - return this.ellipse.apply(this, args); + return this.ellipse(...args); }; /** @@ -343,11 +341,11 @@ p5.prototype.circle = function() { * @param {Number} z2 the z-coordinate of the second point * @chainable */ -p5.prototype.line = function() { - p5._validateParameters('line', arguments); +p5.prototype.line = function(...args) { + p5._validateParameters('line', args); if (this._renderer._doStroke) { - this._renderer.line.apply(this._renderer, arguments); + this._renderer.line(...args); } return this; @@ -378,11 +376,11 @@ p5.prototype.line = function() { *4 points centered in the middle-right of the canvas. * */ -p5.prototype.point = function() { - p5._validateParameters('point', arguments); +p5.prototype.point = function(...args) { + p5._validateParameters('point', args); if (this._renderer._doStroke) { - this._renderer.point.apply(this._renderer, arguments); + this._renderer.point(...args); } return this; @@ -434,21 +432,21 @@ p5.prototype.point = function() { * @param {Number} z4 the z-coordinate of the fourth point * @chainable */ -p5.prototype.quad = function() { - p5._validateParameters('quad', arguments); +p5.prototype.quad = function(...args) { + p5._validateParameters('quad', args); if (this._renderer._doStroke || this._renderer._doFill) { - if (this._renderer.isP3D && arguments.length !== 12) { + if (this._renderer.isP3D && args.length !== 12) { // if 3D and we weren't passed 12 args, assume Z is 0 // prettier-ignore this._renderer.quad.call( this._renderer, - arguments[0], arguments[1], 0, - arguments[2], arguments[3], 0, - arguments[4], arguments[5], 0, - arguments[6], arguments[7], 0); + args[0], args[1], 0, + args[2], args[3], 0, + args[4], args[5], 0, + args[6], args[7], 0); } else { - this._renderer.quad.apply(this._renderer, arguments); + this._renderer.quad(...args); } } @@ -519,17 +517,17 @@ p5.prototype.rect = function() { p5._validateParameters('rect', arguments); if (this._renderer._doStroke || this._renderer._doFill) { - var vals = canvas.modeAdjust( + const vals = canvas.modeAdjust( arguments[0], arguments[1], arguments[2], arguments[3], this._renderer._rectMode ); - var args = [vals.x, vals.y, vals.w, vals.h]; + const args = [vals.x, vals.y, vals.w, vals.h]; // append the additional arguments (either cornder radii, or // segment details) to the argument list - for (var i = 4; i < arguments.length; i++) { + for (let i = 4; i < arguments.length; i++) { args[i] = arguments[i]; } this._renderer.rect(args); @@ -616,14 +614,14 @@ p5.prototype.square = function(x, y, s, tl, tr, br, bl) { * white triangle with black outline in mid-right of canvas. * */ -p5.prototype.triangle = function() { - p5._validateParameters('triangle', arguments); +p5.prototype.triangle = function(...args) { + p5._validateParameters('triangle', args); if (this._renderer._doStroke || this._renderer._doFill) { - this._renderer.triangle(arguments); + this._renderer.triangle(args); } return this; }; -module.exports = p5; +export default p5; diff --git a/src/core/shape/attributes.js b/src/core/shape/attributes.js index c90c2cce3e..2c7e56322e 100644 --- a/src/core/shape/attributes.js +++ b/src/core/shape/attributes.js @@ -6,10 +6,8 @@ * @requires constants */ -'use strict'; - -var p5 = require('../main'); -var constants = require('../constants'); +import p5 from '../main'; +import * as constants from '../constants'; /** * Modifies the location from which ellipses are drawn by changing the way @@ -349,4 +347,4 @@ p5.prototype.strokeWeight = function(w) { return this; }; -module.exports = p5; +export default p5; diff --git a/src/core/shape/curves.js b/src/core/shape/curves.js index 1704f05cb1..284efed826 100644 --- a/src/core/shape/curves.js +++ b/src/core/shape/curves.js @@ -5,10 +5,8 @@ * @requires core */ -'use strict'; - -var p5 = require('../main'); -require('../error_helpers'); +import p5 from '../main'; +import '../error_helpers'; /** * Draws a cubic Bezier curve on the screen. These curves are defined by a @@ -79,8 +77,8 @@ require('../error_helpers'); * @param {Number} z4 z-coordinate for the second anchor point * @chainable */ -p5.prototype.bezier = function() { - p5._validateParameters('bezier', arguments); +p5.prototype.bezier = function(...args) { + p5._validateParameters('bezier', args); // if the current stroke and fill settings wouldn't result in something // visible, exit immediately @@ -88,7 +86,7 @@ p5.prototype.bezier = function() { return this; } - this._renderer.bezier.apply(this._renderer, arguments); + this._renderer.bezier(...args); return this; }; @@ -182,7 +180,7 @@ p5.prototype.bezierDetail = function(d) { p5.prototype.bezierPoint = function(a, b, c, d, t) { p5._validateParameters('bezierPoint', arguments); - var adjustedT = 1 - t; + const adjustedT = 1 - t; return ( Math.pow(adjustedT, 3) * a + 3 * Math.pow(adjustedT, 2) * t * b + @@ -259,7 +257,7 @@ p5.prototype.bezierPoint = function(a, b, c, d, t) { p5.prototype.bezierTangent = function(a, b, c, d, t) { p5._validateParameters('bezierTangent', arguments); - var adjustedT = 1 - t; + const adjustedT = 1 - t; return ( 3 * d * Math.pow(t, 2) - 3 * c * Math.pow(t, 2) + @@ -351,11 +349,11 @@ p5.prototype.bezierTangent = function(a, b, c, d, t) { * @param {Number} z4 z-coordinate for the ending control point * @chainable */ -p5.prototype.curve = function() { - p5._validateParameters('curve', arguments); +p5.prototype.curve = function(...args) { + p5._validateParameters('curve', args); if (this._renderer._doStroke) { - this._renderer.curve.apply(this._renderer, arguments); + this._renderer.curve(...args); } return this; @@ -490,7 +488,7 @@ p5.prototype.curveTightness = function(t) { p5.prototype.curvePoint = function(a, b, c, d, t) { p5._validateParameters('curvePoint', arguments); - var t3 = t * t * t, + const t3 = t * t * t, t2 = t * t, f1 = -0.5 * t3 + t2 - 0.5 * t, f2 = 1.5 * t3 - 2.5 * t2 + 1.0, @@ -537,7 +535,7 @@ p5.prototype.curvePoint = function(a, b, c, d, t) { p5.prototype.curveTangent = function(a, b, c, d, t) { p5._validateParameters('curveTangent', arguments); - var t2 = t * t, + const t2 = t * t, f1 = -3 * t2 / 2 + 2 * t - 0.5, f2 = 9 * t2 / 2 - 5 * t, f3 = -9 * t2 / 2 + 4 * t + 0.5, @@ -545,4 +543,4 @@ p5.prototype.curveTangent = function(a, b, c, d, t) { return a * f1 + b * f2 + c * f3 + d * f4; }; -module.exports = p5; +export default p5; diff --git a/src/core/shape/vertex.js b/src/core/shape/vertex.js index 6a5798b261..f25f785db8 100644 --- a/src/core/shape/vertex.js +++ b/src/core/shape/vertex.js @@ -6,18 +6,16 @@ * @requires constants */ -'use strict'; - -var p5 = require('../main'); -var constants = require('../constants'); -var shapeKind = null; -var vertices = []; -var contourVertices = []; -var isBezier = false; -var isCurve = false; -var isQuadratic = false; -var isContour = false; -var isFirstContour = true; +import p5 from '../main'; +import * as constants from '../constants'; +let shapeKind = null; +let vertices = []; +let contourVertices = []; +let isBezier = false; +let isCurve = false; +let isQuadratic = false; +let isContour = false; +let isFirstContour = true; /** * Use the beginContour() and endContour() functions to create negative @@ -245,7 +243,7 @@ p5.prototype.beginContour = function() { p5.prototype.beginShape = function(kind) { p5._validateParameters('beginShape', arguments); if (this._renderer.isP3D) { - this._renderer.beginShape.apply(this._renderer, arguments); + this._renderer.beginShape(...arguments); } else { if ( kind === constants.POINTS || @@ -368,10 +366,10 @@ p5.prototype.beginShape = function(kind) { * @param {Number} z4 z-coordinate for the anchor point (for WebGL mode) * @chainable */ -p5.prototype.bezierVertex = function() { - p5._validateParameters('bezierVertex', arguments); +p5.prototype.bezierVertex = function(...args) { + p5._validateParameters('bezierVertex', args); if (this._renderer.isP3D) { - this._renderer.bezierVertex.apply(this._renderer, arguments); + this._renderer.bezierVertex(...args); } else { if (vertices.length === 0) { p5._friendlyError( @@ -380,9 +378,9 @@ p5.prototype.bezierVertex = function() { ); } else { isBezier = true; - var vert = []; - for (var i = 0; i < arguments.length; i++) { - vert[i] = arguments[i]; + const vert = []; + for (let i = 0; i < args.length; i++) { + vert[i] = args[i]; } vert.isVert = false; if (isContour) { @@ -494,13 +492,13 @@ p5.prototype.bezierVertex = function() { * Upside-down u-shape line, mid canvas with the same shape in positive z-axis. * */ -p5.prototype.curveVertex = function() { - p5._validateParameters('curveVertex', arguments); +p5.prototype.curveVertex = function(...args) { + p5._validateParameters('curveVertex', args); if (this._renderer.isP3D) { - this._renderer.curveVertex.apply(this._renderer, arguments); + this._renderer.curveVertex(...args); } else { isCurve = true; - this.vertex(arguments[0], arguments[1]); + this.vertex(args[0], args[1]); } return this; }; @@ -548,7 +546,7 @@ p5.prototype.curveVertex = function() { * */ p5.prototype.endContour = function() { - var vert = contourVertices[0].slice(); // copy all data + const vert = contourVertices[0].slice(); // copy all data vert.isVert = contourVertices[0].isVert; vert.moveTo = false; contourVertices.push(vert); @@ -559,7 +557,7 @@ p5.prototype.endContour = function() { isFirstContour = false; } - for (var i = 0; i < contourVertices.length; i++) { + for (let i = 0; i < contourVertices.length; i++) { vertices.push(contourVertices[i]); } return this; @@ -617,7 +615,7 @@ p5.prototype.endShape = function(mode) { return this; } - var closeShape = mode === constants.CLOSE; + const closeShape = mode === constants.CLOSE; // if the shape is closed, the first element is also the last element if (closeShape && !isContour) { @@ -770,19 +768,19 @@ p5.prototype.endShape = function(mode) { * @alt * backwards s-shaped black line with the same s-shaped line in postive z-axis. */ -p5.prototype.quadraticVertex = function() { - p5._validateParameters('quadraticVertex', arguments); +p5.prototype.quadraticVertex = function(...args) { + p5._validateParameters('quadraticVertex', args); if (this._renderer.isP3D) { - this._renderer.quadraticVertex.apply(this._renderer, arguments); + this._renderer.quadraticVertex(...args); } else { //if we're drawing a contour, put the points into an // array for inside drawing if (this._contourInited) { - var pt = {}; - pt.x = arguments[0]; - pt.y = arguments[1]; - pt.x3 = arguments[2]; - pt.y3 = arguments[3]; + const pt = {}; + pt.x = args[0]; + pt.y = args[1]; + pt.x3 = args[2]; + pt.y3 = args[3]; pt.type = constants.QUADRATIC; this._contourVertices.push(pt); @@ -790,9 +788,9 @@ p5.prototype.quadraticVertex = function() { } if (vertices.length > 0) { isQuadratic = true; - var vert = []; - for (var i = 0; i < arguments.length; i++) { - vert[i] = arguments[i]; + const vert = []; + for (let i = 0; i < args.length; i++) { + vert[i] = args[i]; } vert.isVert = false; if (isContour) { @@ -918,13 +916,13 @@ p5.prototype.quadraticVertex = function() { * * function ngon(n, x, y, d) { * beginShape(); - * for (var i = 0; i < n + 1; i++) { + * for (let i = 0; i < n + 1; i++) { * angle = TWO_PI / n * i; * px = x + sin(angle) * d / 2; * py = y - cos(angle) * d / 2; * vertex(px, py, 0); * } - * for (i = 0; i < n + 1; i++) { + * for (let i = 0; i < n + 1; i++) { * angle = TWO_PI / n * i; * px = x + sin(angle) * d / 4; * py = y - cos(angle) * d / 4; @@ -953,9 +951,9 @@ p5.prototype.quadraticVertex = function() { */ p5.prototype.vertex = function(x, y, moveTo, u, v) { if (this._renderer.isP3D) { - this._renderer.vertex.apply(this._renderer, arguments); + this._renderer.vertex(...arguments); } else { - var vert = []; + const vert = []; vert.isVert = true; vert[0] = x; vert[1] = y; @@ -980,4 +978,4 @@ p5.prototype.vertex = function(x, y, moveTo, u, v) { return this; }; -module.exports = p5; +export default p5; diff --git a/src/core/shim.js b/src/core/shim.js index 0553ef0aaf..eb2c14ad53 100644 --- a/src/core/shim.js +++ b/src/core/shim.js @@ -1,24 +1,19 @@ -'use strict'; - // requestAnim shim layer by Paul Irish // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ // http://my.opera.com/emoller/blog/2011/12/20/ // requestanimationframe-for-smart-er-animating // requestAnimationFrame polyfill by Erik Möller // fixes from Paul Irish and Tino Zijdel -window.requestAnimationFrame = (function() { - return ( - window.requestAnimationFrame || - window.webkitRequestAnimationFrame || - window.mozRequestAnimationFrame || - window.oRequestAnimationFrame || - window.msRequestAnimationFrame || - function(callback, element) { - // should '60' here be framerate? - window.setTimeout(callback, 1000 / 60); - } - ); -})(); +window.requestAnimationFrame = (() => + window.requestAnimationFrame || + window.webkitRequestAnimationFrame || + window.mozRequestAnimationFrame || + window.oRequestAnimationFrame || + window.msRequestAnimationFrame || + ((callback, element) => { + // should '60' here be framerate? + window.setTimeout(callback, 1000 / 60); + }))(); /** * shim for Uint8ClampedArray.slice @@ -27,8 +22,7 @@ window.requestAnimationFrame = (function() { * Enumerable set to false to protect for...in from * Uint8ClampedArray.prototype pollution. */ -(function() { - 'use strict'; +(() => { if ( typeof Uint8ClampedArray !== 'undefined' && !Uint8ClampedArray.prototype.slice @@ -50,30 +44,26 @@ window.requestAnimationFrame = (function() { * It will return the target object. * Modified from https://github.com/ljharb/object.assign */ -(function() { - 'use strict'; +(() => { if (!Object.assign) { - var keys = Object.keys; - var defineProperty = Object.defineProperty; - var canBeObject = function(obj) { - return typeof obj !== 'undefined' && obj !== null; - }; - var hasSymbols = + const keys = Object.keys; + const defineProperty = Object.defineProperty; + const canBeObject = obj => typeof obj !== 'undefined' && obj !== null; + const hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol'; - var propIsEnumerable = Object.prototype.propertyIsEnumerable; - var isEnumerableOn = function(obj) { - return function isEnumerable(prop) { + const propIsEnumerable = Object.prototype.propertyIsEnumerable; + const isEnumerableOn = obj => + function isEnumerable(prop) { return propIsEnumerable.call(obj, prop); }; - }; // per ES6 spec, this function has to have a length of 2 - var assignShim = function assign(target, source1) { + const assignShim = function assign(target, source1) { if (!canBeObject(target)) { throw new TypeError('target must be an object'); } - var objTarget = Object(target); - var s, source, i, props; + const objTarget = Object(target); + let s, source, i, props; for (s = 1; s < arguments.length; ++s) { source = Object(arguments[s]); props = keys(source); diff --git a/src/core/structure.js b/src/core/structure.js index 536900236a..e8a708c156 100644 --- a/src/core/structure.js +++ b/src/core/structure.js @@ -5,9 +5,7 @@ * @requires core */ -'use strict'; - -var p5 = require('./main'); +import p5 from './main'; /** * Stops p5.js from continuously executing the code within draw(). @@ -249,7 +247,7 @@ p5.prototype.push = function() { * */ p5.prototype.pop = function() { - var style = this._styles.pop(); + const style = this._styles.pop(); if (style) { this._renderer.pop(style.renderer); Object.assign(this, style.props); @@ -326,22 +324,22 @@ p5.prototype.redraw = function(n) { return; } - var numberOfRedraws = parseInt(n); + let numberOfRedraws = parseInt(n); if (isNaN(numberOfRedraws) || numberOfRedraws < 1) { numberOfRedraws = 1; } - var context = this._isGlobal ? window : this; - var userSetup = context.setup; - var userDraw = context.draw; + const context = this._isGlobal ? window : this; + const userSetup = context.setup; + const userDraw = context.draw; if (typeof userDraw === 'function') { if (typeof userSetup === 'undefined') { context.scale(context._pixelDensity, context._pixelDensity); } - var callMethod = function(f) { + const callMethod = f => { f.call(context); }; - for (var idxRedraw = 0; idxRedraw < numberOfRedraws; idxRedraw++) { + for (let idxRedraw = 0; idxRedraw < numberOfRedraws; idxRedraw++) { context.resetMatrix(); if (context._renderer.isP3D) { context._renderer._update(); @@ -359,4 +357,4 @@ p5.prototype.redraw = function(n) { } }; -module.exports = p5; +export default p5; diff --git a/src/core/transform.js b/src/core/transform.js index 5004bd2731..86295ef898 100644 --- a/src/core/transform.js +++ b/src/core/transform.js @@ -6,9 +6,7 @@ * @requires constants */ -'use strict'; - -var p5 = require('./main'); +import p5 from './main'; /** * Multiplies the current matrix by the one specified through the parameters. @@ -43,7 +41,7 @@ var p5 = require('./main'); * } * * function draw() { - * var step = frameCount % 20; + * let step = frameCount % 20; * background(200); * // Equivalent to translate(x, y); * applyMatrix(1, 0, 0, 1, 40 + step, 50); @@ -59,7 +57,7 @@ var p5 = require('./main'); * } * * function draw() { - * var step = frameCount % 20; + * let step = frameCount % 20; * background(200); * translate(50, 50); * // Equivalent to scale(x, y); @@ -76,10 +74,10 @@ var p5 = require('./main'); * } * * function draw() { - * var step = frameCount % 20; - * var angle = map(step, 0, 20, 0, TWO_PI); - * var cos_a = cos(angle); - * var sin_a = sin(angle); + * let step = frameCount % 20; + * let angle = map(step, 0, 20, 0, TWO_PI); + * let cos_a = cos(angle); + * let sin_a = sin(angle); * background(200); * translate(50, 50); * // Equivalent to rotate(angle); @@ -96,12 +94,12 @@ var p5 = require('./main'); * } * * function draw() { - * var step = frameCount % 20; - * var angle = map(step, 0, 20, -PI / 4, PI / 4); + * let step = frameCount % 20; + * let angle = map(step, 0, 20, -PI / 4, PI / 4); * background(200); * translate(50, 50); * // equivalent to shearX(angle); - * var shear_factor = 1 / tan(PI / 2 - angle); + * let shear_factor = 1 / tan(PI / 2 - angle); * applyMatrix(1, 0, shear_factor, 1, 0, 0); * rect(0, 0, 50, 50); * } @@ -119,10 +117,10 @@ var p5 = require('./main'); * rotateY(PI / 6); * stroke(153); * box(35); - * var rad = millis() / 1000; + * let rad = millis() / 1000; * // Set rotation angles - * var ct = cos(rad); - * var st = sin(rad); + * let ct = cos(rad); + * let st = sin(rad); * // Matrix for rotation around the Y axis * // prettier-ignore * applyMatrix( ct, 0.0, st, 0.0, @@ -143,7 +141,7 @@ var p5 = require('./main'); * */ p5.prototype.applyMatrix = function(a, b, c, d, e, f) { - this._renderer.applyMatrix.apply(this._renderer, arguments); + this._renderer.applyMatrix(...arguments); return this; }; @@ -357,12 +355,12 @@ p5.prototype.scale = function(x, y, z) { p5._validateParameters('scale', arguments); // Only check for Vector argument type if Vector is available if (x instanceof p5.Vector) { - var v = x; + const v = x; x = v.x; y = v.y; z = v.z; } else if (x instanceof Array) { - var rg = x; + const rg = x; x = rg[0]; y = rg[1]; z = rg[2] || 1; @@ -413,7 +411,7 @@ p5.prototype.scale = function(x, y, z) { */ p5.prototype.shearX = function(angle) { p5._validateParameters('shearX', arguments); - var rad = this._toRadians(angle); + const rad = this._toRadians(angle); this._renderer.applyMatrix(1, 0, Math.tan(rad), 1, 0, 0); return this; }; @@ -453,7 +451,7 @@ p5.prototype.shearX = function(angle) { */ p5.prototype.shearY = function(angle) { p5._validateParameters('shearY', arguments); - var rad = this._toRadians(angle); + const rad = this._toRadians(angle); this._renderer.applyMatrix(1, Math.tan(rad), 0, 1, 0, 0); return this; }; @@ -527,4 +525,4 @@ p5.prototype.translate = function(x, y, z) { return this; }; -module.exports = p5; +export default p5; diff --git a/src/data/local_storage.js b/src/data/local_storage.js index 269b0f6c0b..9289c6c6ef 100644 --- a/src/data/local_storage.js +++ b/src/data/local_storage.js @@ -6,8 +6,7 @@ * This module defines the p5 methods for working with local storage */ -'use strict'; -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * * Stores a value in local storage under the key name. @@ -59,11 +58,11 @@ var p5 = require('../core/main'); * If you reload the page, the last letter typed is still displaying. * */ -p5.prototype.storeItem = function(key, value) { +p5.prototype.storeItem = (key, value) => { if (typeof value === 'undefined') { console.log('You cannot store undefined variables using storeItem()'); } - var type = typeof value; + let type = typeof value; switch (type) { case 'number': case 'boolean': @@ -81,7 +80,7 @@ p5.prototype.storeItem = function(key, value) { } localStorage.setItem(key, value); - var typeKey = key + 'p5TypeID'; + const typeKey = `${key}p5TypeID`; localStorage.setItem(typeKey, type); }; @@ -129,13 +128,11 @@ p5.prototype.storeItem = function(key, value) { * */ p5.prototype.getItem = function(key) { - var value = localStorage.getItem(key); - var type = localStorage.getItem(key + 'p5TypeID'); + let value = localStorage.getItem(key); + const type = localStorage.getItem(`${key}p5TypeID`); if (typeof type === 'undefined') { console.log( - 'Unable to determine type of item stored under ' + - key + - 'in local storage. Did you save the item with something other than setItem()?' + `Unable to determine type of item stored under ${key}in local storage. Did you save the item with something other than setItem()?` ); } else if (value !== null) { switch (type) { @@ -150,7 +147,7 @@ p5.prototype.getItem = function(key) { break; case 'p5.Color': value = JSON.parse(value); - value = this.color.apply(this, value.levels); + value = this.color(...value.levels); break; case 'string': default: @@ -184,7 +181,7 @@ p5.prototype.getItem = function(key) { * } * */ -p5.prototype.clearStorage = function() { +p5.prototype.clearStorage = () => { localStorage.clear(); }; @@ -208,14 +205,12 @@ p5.prototype.clearStorage = function() { * } * */ -p5.prototype.removeItem = function(key) { +p5.prototype.removeItem = key => { if (typeof key !== 'string') { console.log( - 'The argument that you passed to removeItem() - ' + - key + - ' is not a string.' + `The argument that you passed to removeItem() - ${key} is not a string.` ); } localStorage.removeItem(key); - localStorage.removeItem(key + 'p5TypeID'); + localStorage.removeItem(`${key}p5TypeID`); }; diff --git a/src/data/p5.TypedDict.js b/src/data/p5.TypedDict.js index 40d9cf1aaf..c79865c048 100644 --- a/src/data/p5.TypedDict.js +++ b/src/data/p5.TypedDict.js @@ -9,9 +9,7 @@ * with key-value pairs. */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * @@ -168,7 +166,7 @@ p5.TypedDict.prototype.get = function(key) { if (this.data.hasOwnProperty(key)) { return this.data[key]; } else { - console.log(key + ' does not exist in this Dictionary'); + console.log(`${key} does not exist in this Dictionary`); } }; @@ -206,7 +204,7 @@ p5.TypedDict.prototype.set = function(key, value) { */ p5.TypedDict.prototype._addObj = function(obj) { - for (var key in obj) { + for (const key in obj) { this.set(key, obj[key]); } }; @@ -294,7 +292,7 @@ p5.TypedDict.prototype.remove = function(key) { if (this.data.hasOwnProperty(key)) { delete this.data[key]; } else { - throw new Error(key + ' does not exist in this Dictionary'); + throw new Error(`${key} does not exist in this Dictionary`); } }; @@ -317,8 +315,8 @@ p5.TypedDict.prototype.remove = function(key) { */ p5.TypedDict.prototype.print = function() { - for (var item in this.data) { - console.log('key:' + item + ' value:' + this.data[item]); + for (const item in this.data) { + console.log(`key:${item} value:${this.data[item]}`); } }; @@ -350,13 +348,13 @@ p5.TypedDict.prototype.print = function() { */ p5.TypedDict.prototype.saveTable = function(filename) { - var output = ''; + let output = ''; - for (var key in this.data) { - output += key + ',' + this.data[key] + '\n'; + for (const key in this.data) { + output += `${key},${this.data[key]}\n`; } - var blob = new Blob([output], { type: 'text/csv' }); + const blob = new Blob([output], { type: 'text/csv' }); p5.prototype.downloadFile(blob, filename || 'mycsv', 'csv'); }; @@ -396,9 +394,7 @@ p5.TypedDict.prototype.saveJSON = function(filename, opt) { * values for the Dictionary type */ -p5.TypedDict.prototype._validate = function(value) { - return true; -}; +p5.TypedDict.prototype._validate = value => true; /** * @@ -409,15 +405,13 @@ p5.TypedDict.prototype._validate = function(value) { * */ -p5.StringDict = function() { - p5.TypedDict.apply(this, arguments); +p5.StringDict = function(...args) { + p5.TypedDict.apply(this, args); }; p5.StringDict.prototype = Object.create(p5.TypedDict.prototype); -p5.StringDict.prototype._validate = function(value) { - return typeof value === 'string'; -}; +p5.StringDict.prototype._validate = value => typeof value === 'string'; /** * @@ -428,8 +422,8 @@ p5.StringDict.prototype._validate = function(value) { * */ -p5.NumberDict = function() { - p5.TypedDict.apply(this, arguments); +p5.NumberDict = function(...args) { + p5.TypedDict.apply(this, args); }; p5.NumberDict.prototype = Object.create(p5.TypedDict.prototype); @@ -439,9 +433,7 @@ p5.NumberDict.prototype = Object.create(p5.TypedDict.prototype); * values for the Dictionary type */ -p5.NumberDict.prototype._validate = function(value) { - return typeof value === 'number'; -}; +p5.NumberDict.prototype._validate = value => typeof value === 'number'; /** * Add the given number to the value currently stored at the given key. @@ -467,7 +459,7 @@ p5.NumberDict.prototype.add = function(key, amount) { if (this.data.hasOwnProperty(key)) { this.data[key] += amount; } else { - console.log('The key - ' + key + ' does not exist in this dictionary.'); + console.log(`The key - ${key} does not exist in this dictionary.`); } }; @@ -519,7 +511,7 @@ p5.NumberDict.prototype.mult = function(key, amount) { if (this.data.hasOwnProperty(key)) { this.data[key] *= amount; } else { - console.log('The key - ' + key + ' does not exist in this dictionary.'); + console.log(`The key - ${key} does not exist in this dictionary.`); } }; @@ -547,7 +539,7 @@ p5.NumberDict.prototype.div = function(key, amount) { if (this.data.hasOwnProperty(key)) { this.data[key] /= amount; } else { - console.log('The key - ' + key + ' does not exist in this dictionary.'); + console.log(`The key - ${key} does not exist in this dictionary.`); } }; @@ -566,8 +558,8 @@ p5.NumberDict.prototype._valueTest = function(flip) { } else if (Object.keys(this.data).length === 1) { return this.data[Object.keys(this.data)[0]]; } else { - var result = this.data[Object.keys(this.data)[0]]; - for (var key in this.data) { + let result = this.data[Object.keys(this.data)[0]]; + for (const key in this.data) { if (this.data[key] * flip < result * flip) { result = this.data[key]; } @@ -631,8 +623,8 @@ p5.NumberDict.prototype._keyTest = function(flip) { } else if (Object.keys(this.data).length === 1) { return Object.keys(this.data)[0]; } else { - var result = Object.keys(this.data)[0]; - for (var i = 1; i < Object.keys(this.data).length; i++) { + let result = Object.keys(this.data)[0]; + for (let i = 1; i < Object.keys(this.data).length; i++) { if (Object.keys(this.data)[i] * flip < result * flip) { result = Object.keys(this.data)[i]; } @@ -683,4 +675,4 @@ p5.NumberDict.prototype.maxKey = function() { return this._keyTest(-1); }; -module.exports = p5.TypedDict; +export default p5.TypedDict; diff --git a/src/events/acceleration.js b/src/events/acceleration.js index 70d6c67bcc..f93501f52b 100644 --- a/src/events/acceleration.js +++ b/src/events/acceleration.js @@ -5,9 +5,7 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * The system variable deviceOrientation always contains the orientation of @@ -359,13 +357,13 @@ p5.prototype.pRotationY = 0; */ p5.prototype.pRotationZ = 0; -var startAngleX = 0; -var startAngleY = 0; -var startAngleZ = 0; +let startAngleX = 0; +let startAngleY = 0; +let startAngleZ = 0; -var rotateDirectionX = 'clockwise'; -var rotateDirectionY = 'clockwise'; -var rotateDirectionZ = 'clockwise'; +let rotateDirectionX = 'clockwise'; +let rotateDirectionY = 'clockwise'; +let rotateDirectionZ = 'clockwise'; p5.prototype.pRotateDirectionX = undefined; p5.prototype.pRotateDirectionY = undefined; @@ -390,7 +388,7 @@ p5.prototype._updatePRotations = function() { * // Rotate the device by 90 degrees in the * // X-axis to change the value. * - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -413,8 +411,8 @@ p5.prototype._updatePRotations = function() { */ p5.prototype.turnAxis = undefined; -var move_threshold = 0.5; -var shake_threshold = 30; +let move_threshold = 0.5; +let shake_threshold = 30; /** * The setMoveThreshold() function is used to set the movement threshold for @@ -648,7 +646,7 @@ p5.prototype._handleMotion = function() { } else if (window.orientation === undefined) { this._setProperty('deviceOrientation', 'undefined'); } - var deviceMoved = this.deviceMoved || window.deviceMoved; + const deviceMoved = this.deviceMoved || window.deviceMoved; if (typeof deviceMoved === 'function') { if ( Math.abs(this.accelerationX - this.pAccelerationX) > move_threshold || @@ -658,15 +656,15 @@ p5.prototype._handleMotion = function() { deviceMoved(); } } - var deviceTurned = this.deviceTurned || window.deviceTurned; + const deviceTurned = this.deviceTurned || window.deviceTurned; if (typeof deviceTurned === 'function') { // The angles given by rotationX etc is from range -180 to 180. // The following will convert them to 0 to 360 for ease of calculation // of cases when the angles wrapped around. // _startAngleX will be converted back at the end and updated. - var wRX = this.rotationX + 180; - var wPRX = this.pRotationX + 180; - var wSAX = startAngleX + 180; + const wRX = this.rotationX + 180; + const wPRX = this.pRotationX + 180; + let wSAX = startAngleX + 180; if ((wRX - wPRX > 0 && wRX - wPRX < 270) || wRX - wPRX < -270) { rotateDirectionX = 'clockwise'; } else if (wRX - wPRX < 0 || wRX - wPRX > 270) { @@ -684,9 +682,9 @@ p5.prototype._handleMotion = function() { startAngleX = wSAX - 180; // Y-axis is identical to X-axis except for changing some names. - var wRY = this.rotationY + 180; - var wPRY = this.pRotationY + 180; - var wSAY = startAngleY + 180; + const wRY = this.rotationY + 180; + const wPRY = this.pRotationY + 180; + let wSAY = startAngleY + 180; if ((wRY - wPRY > 0 && wRY - wPRY < 270) || wRY - wPRY < -270) { rotateDirectionY = 'clockwise'; } else if (wRY - wPRY < 0 || wRY - this.pRotationY > 270) { @@ -731,10 +729,10 @@ p5.prototype._handleMotion = function() { this.pRotateDirectionZ = rotateDirectionZ; this._setProperty('turnAxis', undefined); } - var deviceShaken = this.deviceShaken || window.deviceShaken; + const deviceShaken = this.deviceShaken || window.deviceShaken; if (typeof deviceShaken === 'function') { - var accelerationChangeX; - var accelerationChangeY; + let accelerationChangeX; + let accelerationChangeY; // Add accelerationChangeZ if acceleration change on Z is needed if (this.pAccelerationX !== null) { accelerationChangeX = Math.abs(this.accelerationX - this.pAccelerationX); @@ -746,4 +744,4 @@ p5.prototype._handleMotion = function() { } }; -module.exports = p5; +export default p5; diff --git a/src/events/keyboard.js b/src/events/keyboard.js index 7e429b285d..c4071fc4a4 100644 --- a/src/events/keyboard.js +++ b/src/events/keyboard.js @@ -5,9 +5,7 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * The boolean system variable keyIsPressed is true if any key is pressed @@ -185,9 +183,9 @@ p5.prototype._onkeydown = function(e) { this._setProperty('keyCode', e.which); this._downKeys[e.which] = true; this._setProperty('key', e.key || String.fromCharCode(e.which) || e.which); - var keyPressed = this.keyPressed || window.keyPressed; + const keyPressed = this.keyPressed || window.keyPressed; if (typeof keyPressed === 'function' && !e.charCode) { - var executeDefault = keyPressed(e); + const executeDefault = keyPressed(e); if (executeDefault === false) { e.preventDefault(); } @@ -225,7 +223,7 @@ p5.prototype._onkeydown = function(e) { * */ p5.prototype._onkeyup = function(e) { - var keyReleased = this.keyReleased || window.keyReleased; + const keyReleased = this.keyReleased || window.keyReleased; this._downKeys[e.which] = false; if (!this._areDownKeys()) { @@ -238,7 +236,7 @@ p5.prototype._onkeyup = function(e) { this._setProperty('key', e.key || String.fromCharCode(e.which) || e.which); this._setProperty('keyCode', e.which); if (typeof keyReleased === 'function') { - var executeDefault = keyReleased(e); + const executeDefault = keyReleased(e); if (executeDefault === false) { e.preventDefault(); } @@ -291,9 +289,9 @@ p5.prototype._onkeypress = function(e) { } this._setProperty('_lastKeyCodeTyped', e.which); // track last keyCode this._setProperty('key', String.fromCharCode(e.which)); - var keyTyped = this.keyTyped || window.keyTyped; + const keyTyped = this.keyTyped || window.keyTyped; if (typeof keyTyped === 'function') { - var executeDefault = keyTyped(e); + const executeDefault = keyTyped(e); if (executeDefault === false) { e.preventDefault(); } @@ -396,7 +394,7 @@ p5.prototype.keyIsDown = function(code) { * @private **/ p5.prototype._areDownKeys = function() { - for (var key in this._downKeys) { + for (const key in this._downKeys) { if (this._downKeys.hasOwnProperty(key) && this._downKeys[key] === true) { return true; } @@ -404,4 +402,4 @@ p5.prototype._areDownKeys = function() { return false; }; -module.exports = p5; +export default p5; diff --git a/src/events/mouse.js b/src/events/mouse.js index d2a773c654..0e74d129d2 100644 --- a/src/events/mouse.js +++ b/src/events/mouse.js @@ -6,10 +6,8 @@ * @requires constants */ -'use strict'; - -var p5 = require('../core/main'); -var constants = require('../core/constants'); +import p5 from '../core/main'; +import * as constants from '../core/constants'; /** * @@ -433,7 +431,7 @@ p5.prototype.mouseIsPressed = false; p5.prototype._updateNextMouseCoords = function(e) { if (this._curElement !== null && (!e.touches || e.touches.length > 0)) { - var mousePos = getMousePos( + const mousePos = getMousePos( this._curElement.elt, this.width, this.height, @@ -471,9 +469,9 @@ function getMousePos(canvas, w, h, evt) { evt = evt.changedTouches[0]; } } - var rect = canvas.getBoundingClientRect(); - var sx = canvas.scrollWidth / w || 1; - var sy = canvas.scrollHeight / h || 1; + const rect = canvas.getBoundingClientRect(); + const sx = canvas.scrollWidth / w || 1; + const sy = canvas.scrollHeight / h || 1; return { x: (evt.clientX - rect.left) / sx, y: (evt.clientY - rect.top) / sy, @@ -604,8 +602,8 @@ p5.prototype._setMouseButton = function(e) { * */ p5.prototype._onmousemove = function(e) { - var context = this._isGlobal ? window : this; - var executeDefault; + const context = this._isGlobal ? window : this; + let executeDefault; this._updateNextMouseCoords(e); if (!this.mouseIsPressed) { if (typeof context.mouseMoved === 'function') { @@ -688,8 +686,8 @@ p5.prototype._onmousemove = function(e) { * */ p5.prototype._onmousedown = function(e) { - var context = this._isGlobal ? window : this; - var executeDefault; + const context = this._isGlobal ? window : this; + let executeDefault; this._setProperty('mouseIsPressed', true); this._setMouseButton(e); this._updateNextMouseCoords(e); @@ -770,8 +768,8 @@ p5.prototype._onmousedown = function(e) { * */ p5.prototype._onmouseup = function(e) { - var context = this._isGlobal ? window : this; - var executeDefault; + const context = this._isGlobal ? window : this; + let executeDefault; this._setProperty('mouseIsPressed', false); if (typeof context.mouseReleased === 'function') { executeDefault = context.mouseReleased(e); @@ -850,9 +848,9 @@ p5.prototype._ondragover = p5.prototype._onmousemove; * */ p5.prototype._onclick = function(e) { - var context = this._isGlobal ? window : this; + const context = this._isGlobal ? window : this; if (typeof context.mouseClicked === 'function') { - var executeDefault = context.mouseClicked(e); + const executeDefault = context.mouseClicked(e); if (executeDefault === false) { e.preventDefault(); } @@ -919,9 +917,9 @@ p5.prototype._onclick = function(e) { */ p5.prototype._ondblclick = function(e) { - var context = this._isGlobal ? window : this; + const context = this._isGlobal ? window : this; if (typeof context.doubleClicked === 'function') { - var executeDefault = context.doubleClicked(e); + const executeDefault = context.doubleClicked(e); if (executeDefault === false) { e.preventDefault(); } @@ -987,11 +985,11 @@ p5.prototype._pmouseWheelDeltaY = 0; * */ p5.prototype._onwheel = function(e) { - var context = this._isGlobal ? window : this; + const context = this._isGlobal ? window : this; this._setProperty('_mouseWheelDeltaY', e.deltaY); if (typeof context.mouseWheel === 'function') { e.delta = e.deltaY; - var executeDefault = context.mouseWheel(e); + const executeDefault = context.mouseWheel(e); if (executeDefault === false) { e.preventDefault(); } @@ -1034,7 +1032,7 @@ p5.prototype._onwheel = function(e) { */ p5.prototype.requestPointerLock = function() { // pointer lock object forking for cross browser - var canvas = this._curElement.elt; + const canvas = this._curElement.elt; canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock; if (!canvas.requestPointerLock) { @@ -1076,8 +1074,8 @@ p5.prototype.requestPointerLock = function() { * cursor gets locked / unlocked on mouse-click * */ -p5.prototype.exitPointerLock = function() { +p5.prototype.exitPointerLock = () => { document.exitPointerLock(); }; -module.exports = p5; +export default p5; diff --git a/src/events/touch.js b/src/events/touch.js index 4404a69b68..ad924672f7 100644 --- a/src/events/touch.js +++ b/src/events/touch.js @@ -5,9 +5,7 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * The system variable touches[] contains an array of the positions of all @@ -42,8 +40,8 @@ p5.prototype.touches = []; p5.prototype._updateTouchCoords = function(e) { if (this._curElement !== null) { - var touches = []; - for (var i = 0; i < e.touches.length; i++) { + const touches = []; + for (let i = 0; i < e.touches.length; i++) { touches[i] = getTouchInfo( this._curElement.elt, this.width, @@ -56,12 +54,11 @@ p5.prototype._updateTouchCoords = function(e) { } }; -function getTouchInfo(canvas, w, h, e, i) { - i = i || 0; - var rect = canvas.getBoundingClientRect(); - var sx = canvas.scrollWidth / w || 1; - var sy = canvas.scrollHeight / h || 1; - var touch = e.touches[i] || e.changedTouches[i]; +function getTouchInfo(canvas, w, h, e, i = 0) { + const rect = canvas.getBoundingClientRect(); + const sx = canvas.scrollWidth / w || 1; + const sy = canvas.scrollHeight / h || 1; + const touch = e.touches[i] || e.changedTouches[i]; return { x: (touch.clientX - rect.left) / sx, y: (touch.clientY - rect.top) / sy, @@ -127,8 +124,8 @@ function getTouchInfo(canvas, w, h, e, i) { * no image displayed */ p5.prototype._ontouchstart = function(e) { - var context = this._isGlobal ? window : this; - var executeDefault; + const context = this._isGlobal ? window : this; + let executeDefault; this._setProperty('mouseIsPressed', true); this._updateTouchCoords(e); this._updateNextMouseCoords(e); @@ -207,8 +204,8 @@ p5.prototype._ontouchstart = function(e) { * */ p5.prototype._ontouchmove = function(e) { - var context = this._isGlobal ? window : this; - var executeDefault; + const context = this._isGlobal ? window : this; + let executeDefault; this._updateTouchCoords(e); this._updateNextMouseCoords(e); if (typeof context.touchMoved === 'function') { @@ -284,8 +281,8 @@ p5.prototype._ontouchend = function(e) { this._setProperty('mouseIsPressed', false); this._updateTouchCoords(e); this._updateNextMouseCoords(e); - var context = this._isGlobal ? window : this; - var executeDefault; + const context = this._isGlobal ? window : this; + let executeDefault; if (typeof context.touchEnded === 'function') { executeDefault = context.touchEnded(e); if (executeDefault === false) { @@ -299,4 +296,4 @@ p5.prototype._ontouchend = function(e) { } }; -module.exports = p5; +export default p5; diff --git a/src/image/filters.js b/src/image/filters.js index c4e43d8201..075d05c568 100644 --- a/src/image/filters.js +++ b/src/image/filters.js @@ -15,9 +15,7 @@ * or the java processing implementation. */ -'use strict'; - -var Filters = {}; +const Filters = {}; /* * Helper functions @@ -33,7 +31,7 @@ var Filters = {}; * the data in thc RGBA order, with integer * values between 0 and 255 */ -Filters._toPixels = function(canvas) { +Filters._toPixels = canvas => { if (canvas instanceof ImageData) { return canvas.data; } else { @@ -54,8 +52,8 @@ Filters._toPixels = function(canvas) { * @return {Integer} 32 bit integer value representing * ARGB value. */ -Filters._getARGB = function(data, i) { - var offset = i * 4; +Filters._getARGB = (data, i) => { + const offset = i * 4; return ( ((data[offset + 3] << 24) & 0xff000000) | ((data[offset] << 16) & 0x00ff0000) | @@ -73,9 +71,9 @@ Filters._getARGB = function(data, i) { * @param {Int32Array} data source 1D array where each value * represents ARGB values */ -Filters._setPixels = function(pixels, data) { - var offset = 0; - for (var i = 0, al = pixels.length; i < al; i++) { +Filters._setPixels = (pixels, data) => { + let offset = 0; + for (let i = 0, al = pixels.length; i < al; i++) { offset = i * 4; pixels[offset + 0] = (data[i] & 0x00ff0000) >>> 16; pixels[offset + 1] = (data[i] & 0x0000ff00) >>> 8; @@ -94,7 +92,7 @@ Filters._setPixels = function(pixels, data) { * @return {ImageData} Holder of pixel data (and width and * height) for a canvas */ -Filters._toImageData = function(canvas) { +Filters._toImageData = canvas => { if (canvas instanceof ImageData) { return canvas; } else { @@ -138,13 +136,13 @@ Filters._createImageData = function(width, height) { * @param {function(ImageData,Object)} func [description] * @param {Object} filterParam [description] */ -Filters.apply = function(canvas, func, filterParam) { - var pixelsState = canvas.getContext('2d'); - var imageData = pixelsState.getImageData(0, 0, canvas.width, canvas.height); +Filters.apply = (canvas, func, filterParam) => { + const pixelsState = canvas.getContext('2d'); + const imageData = pixelsState.getImageData(0, 0, canvas.width, canvas.height); //Filters can either return a new ImageData object, or just modify //the one they received. - var newImageData = func(imageData, filterParam); + const newImageData = func(imageData, filterParam); if (newImageData instanceof ImageData) { pixelsState.putImageData( newImageData, @@ -183,20 +181,20 @@ Filters.apply = function(canvas, func, filterParam) { * @param {Canvas} canvas * @param {Float} level */ -Filters.threshold = function(canvas, level) { - var pixels = Filters._toPixels(canvas); +Filters.threshold = (canvas, level) => { + const pixels = Filters._toPixels(canvas); if (level === undefined) { level = 0.5; } - var thresh = Math.floor(level * 255); - - for (var i = 0; i < pixels.length; i += 4) { - var r = pixels[i]; - var g = pixels[i + 1]; - var b = pixels[i + 2]; - var gray = 0.2126 * r + 0.7152 * g + 0.0722 * b; - var val; + const thresh = Math.floor(level * 255); + + for (let i = 0; i < pixels.length; i += 4) { + const r = pixels[i]; + const g = pixels[i + 1]; + const b = pixels[i + 2]; + const gray = 0.2126 * r + 0.7152 * g + 0.0722 * b; + let val; if (gray >= thresh) { val = 255; } else { @@ -215,16 +213,16 @@ Filters.threshold = function(canvas, level) { * @private * @param {Canvas} canvas */ -Filters.gray = function(canvas) { - var pixels = Filters._toPixels(canvas); +Filters.gray = canvas => { + const pixels = Filters._toPixels(canvas); - for (var i = 0; i < pixels.length; i += 4) { - var r = pixels[i]; - var g = pixels[i + 1]; - var b = pixels[i + 2]; + for (let i = 0; i < pixels.length; i += 4) { + const r = pixels[i]; + const g = pixels[i + 1]; + const b = pixels[i + 2]; // CIE luminance for RGB - var gray = 0.2126 * r + 0.7152 * g + 0.0722 * b; + const gray = 0.2126 * r + 0.7152 * g + 0.0722 * b; pixels[i] = pixels[i + 1] = pixels[i + 2] = gray; } }; @@ -235,10 +233,10 @@ Filters.gray = function(canvas) { * @private * @param {Canvas} canvas */ -Filters.opaque = function(canvas) { - var pixels = Filters._toPixels(canvas); +Filters.opaque = canvas => { + const pixels = Filters._toPixels(canvas); - for (var i = 0; i < pixels.length; i += 4) { + for (let i = 0; i < pixels.length; i += 4) { pixels[i + 3] = 255; } @@ -250,10 +248,10 @@ Filters.opaque = function(canvas) { * @private * @param {Canvas} canvas */ -Filters.invert = function(canvas) { - var pixels = Filters._toPixels(canvas); +Filters.invert = canvas => { + const pixels = Filters._toPixels(canvas); - for (var i = 0; i < pixels.length; i += 4) { + for (let i = 0; i < pixels.length; i += 4) { pixels[i] = 255 - pixels[i]; pixels[i + 1] = 255 - pixels[i + 1]; pixels[i + 2] = 255 - pixels[i + 2]; @@ -271,8 +269,8 @@ Filters.invert = function(canvas) { * @param {Canvas} canvas * @param {Integer} level */ -Filters.posterize = function(canvas, level) { - var pixels = Filters._toPixels(canvas); +Filters.posterize = (canvas, level) => { + const pixels = Filters._toPixels(canvas); if (level < 2 || level > 255) { throw new Error( @@ -280,11 +278,11 @@ Filters.posterize = function(canvas, level) { ); } - var levels1 = level - 1; - for (var i = 0; i < pixels.length; i += 4) { - var rlevel = pixels[i]; - var glevel = pixels[i + 1]; - var blevel = pixels[i + 2]; + const levels1 = level - 1; + for (let i = 0; i < pixels.length; i += 4) { + const rlevel = pixels[i]; + const glevel = pixels[i + 1]; + const blevel = pixels[i + 2]; pixels[i] = ((rlevel * level) >> 8) * 255 / levels1; pixels[i + 1] = ((glevel * level) >> 8) * 255 / levels1; @@ -298,16 +296,16 @@ Filters.posterize = function(canvas, level) { * @param {Canvas} canvas * */ -Filters.dilate = function(canvas) { - var pixels = Filters._toPixels(canvas); - var currIdx = 0; - var maxIdx = pixels.length ? pixels.length / 4 : 0; - var out = new Int32Array(maxIdx); - var currRowIdx, maxRowIdx, colOrig, colOut, currLum; +Filters.dilate = canvas => { + const pixels = Filters._toPixels(canvas); + let currIdx = 0; + const maxIdx = pixels.length ? pixels.length / 4 : 0; + const out = new Int32Array(maxIdx); + let currRowIdx, maxRowIdx, colOrig, colOut, currLum; - var idxRight, idxLeft, idxUp, idxDown; - var colRight, colLeft, colUp, colDown; - var lumRight, lumLeft, lumUp, lumDown; + let idxRight, idxLeft, idxUp, idxDown; + let colRight, colLeft, colUp, colDown; + let lumRight, lumLeft, lumUp, lumDown; while (currIdx < maxIdx) { currRowIdx = currIdx; @@ -386,15 +384,15 @@ Filters.dilate = function(canvas) { * @param {Canvas} canvas * */ -Filters.erode = function(canvas) { - var pixels = Filters._toPixels(canvas); - var currIdx = 0; - var maxIdx = pixels.length ? pixels.length / 4 : 0; - var out = new Int32Array(maxIdx); - var currRowIdx, maxRowIdx, colOrig, colOut, currLum; - var idxRight, idxLeft, idxUp, idxDown; - var colRight, colLeft, colUp, colDown; - var lumRight, lumLeft, lumUp, lumDown; +Filters.erode = canvas => { + const pixels = Filters._toPixels(canvas); + let currIdx = 0; + const maxIdx = pixels.length ? pixels.length / 4 : 0; + const out = new Int32Array(maxIdx); + let currRowIdx, maxRowIdx, colOrig, colOut, currLum; + let idxRight, idxLeft, idxUp, idxDown; + let colRight, colLeft, colUp, colDown; + let lumRight, lumLeft, lumUp, lumDown; while (currIdx < maxIdx) { currRowIdx = currIdx; @@ -471,10 +469,10 @@ Filters.erode = function(canvas) { // BLUR // internal kernel stuff for the gaussian blur filter -var blurRadius; -var blurKernelSize; -var blurKernel; -var blurMult; +let blurRadius; +let blurKernelSize; +let blurKernel; +let blurMult; /* * Port of https://github.com/processing/processing/blob/ @@ -487,7 +485,7 @@ var blurMult; * [toxi 050728] */ function buildBlurKernel(r) { - var radius = (r * 3.5) | 0; + let radius = (r * 3.5) | 0; radius = radius < 1 ? 1 : radius < 248 ? radius : 248; if (blurRadius !== radius) { @@ -495,25 +493,25 @@ function buildBlurKernel(r) { blurKernelSize = (1 + blurRadius) << 1; blurKernel = new Int32Array(blurKernelSize); blurMult = new Array(blurKernelSize); - for (var l = 0; l < blurKernelSize; l++) { + for (let l = 0; l < blurKernelSize; l++) { blurMult[l] = new Int32Array(256); } - var bk, bki; - var bm, bmi; + let bk, bki; + let bm, bmi; - for (var i = 1, radiusi = radius - 1; i < radius; i++) { + for (let i = 1, radiusi = radius - 1; i < radius; i++) { blurKernel[radius + i] = blurKernel[radiusi] = bki = radiusi * radiusi; bm = blurMult[radius + i]; bmi = blurMult[radiusi--]; - for (var j = 0; j < 256; j++) { + for (let j = 0; j < 256; j++) { bm[j] = bmi[j] = bki * j; } } bk = blurKernel[radius] = radius * radius; bm = blurMult[radius]; - for (var k = 0; k < 256; k++) { + for (let k = 0; k < 256; k++) { bm[k] = bk * k; } } @@ -522,24 +520,24 @@ function buildBlurKernel(r) { // Port of https://github.com/processing/processing/blob/ // master/core/src/processing/core/PImage.java#L1433 function blurARGB(canvas, radius) { - var pixels = Filters._toPixels(canvas); - var width = canvas.width; - var height = canvas.height; - var numPackedPixels = width * height; - var argb = new Int32Array(numPackedPixels); - for (var j = 0; j < numPackedPixels; j++) { + const pixels = Filters._toPixels(canvas); + const width = canvas.width; + const height = canvas.height; + const numPackedPixels = width * height; + const argb = new Int32Array(numPackedPixels); + for (let j = 0; j < numPackedPixels; j++) { argb[j] = Filters._getARGB(pixels, j); } - var sum, cr, cg, cb, ca; - var read, ri, ym, ymi, bk0; - var a2 = new Int32Array(numPackedPixels); - var r2 = new Int32Array(numPackedPixels); - var g2 = new Int32Array(numPackedPixels); - var b2 = new Int32Array(numPackedPixels); - var yi = 0; + let sum, cr, cg, cb, ca; + let read, ri, ym, ymi, bk0; + const a2 = new Int32Array(numPackedPixels); + const r2 = new Int32Array(numPackedPixels); + const g2 = new Int32Array(numPackedPixels); + const b2 = new Int32Array(numPackedPixels); + let yi = 0; buildBlurKernel(radius); - var x, y, i; - var bm; + let x, y, i; + let bm; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { cb = cg = cr = ca = sum = 0; @@ -557,7 +555,7 @@ function blurARGB(canvas, radius) { if (read >= width) { break; } - var c = argb[read + yi]; + const c = argb[read + yi]; bm = blurMult[i]; ca += bm[(c & -16777216) >>> 24]; cr += bm[(c & 16711680) >> 16]; @@ -617,8 +615,8 @@ function blurARGB(canvas, radius) { Filters._setPixels(pixels, argb); } -Filters.blur = function(canvas, radius) { +Filters.blur = (canvas, radius) => { blurARGB(canvas, radius); }; -module.exports = Filters; +export default Filters; diff --git a/src/image/image.js b/src/image/image.js index a2bbd2c58c..cc81345eb2 100644 --- a/src/image/image.js +++ b/src/image/image.js @@ -9,17 +9,15 @@ * This module defines the p5 methods for the p5.Image class * for drawing images to the main display canvas. */ -'use strict'; - -var p5 = require('../core/main'); -var omggif = require('omggif'); +import p5 from '../core/main'; +import omggif from 'omggif'; // This is not global, but ESLint is not aware that // this module is implicitly enclosed with Browserify: this overrides the // redefined-global error and permits using the name "frames" for the array // of saved animation frames. -/* global frames:true */ var frames = []; // eslint-disable-line no-unused-vars +/* global frames:true */ let frames = []; // eslint-disable-line no-unused-vars /** * Creates a new p5.Image (the datatype for storing images). This provides a @@ -152,8 +150,8 @@ p5.prototype.saveCanvas = function() { p5._validateParameters('saveCanvas', arguments); // copy arguments to array - var args = [].slice.call(arguments); - var htmlCanvas, filename, extension; + const args = [].slice.call(arguments); + let htmlCanvas, filename, extension; if (arguments[0] instanceof HTMLCanvasElement) { htmlCanvas = arguments[0]; @@ -177,7 +175,7 @@ p5.prototype.saveCanvas = function() { p5.prototype._checkFileExtension(filename, extension)[1] || 'png'; - var mimeType; + let mimeType; switch (extension) { default: //case 'png': @@ -189,43 +187,43 @@ p5.prototype.saveCanvas = function() { break; } - htmlCanvas.toBlob(function(blob) { + htmlCanvas.toBlob(blob => { p5.prototype.downloadFile(blob, filename, extension); }, mimeType); }; -p5.prototype.saveGif = function(pImg, filename) { - var props = pImg.gifProperties; +p5.prototype.saveGif = (pImg, filename) => { + const props = pImg.gifProperties; //convert loopLimit back into Netscape Block formatting - var loopLimit = props.loopLimit; + let loopLimit = props.loopLimit; if (loopLimit === 1) { loopLimit = null; } else if (loopLimit === null) { loopLimit = 0; } - var gifFormatDelay = props.delay / 10; - var opts = { + const gifFormatDelay = props.delay / 10; + const opts = { loop: loopLimit, delay: gifFormatDelay }; - var buffer = new Uint8Array( + const buffer = new Uint8Array( pImg.width * pImg.height * props.numFrames * gifFormatDelay ); - var gifWriter = new omggif.GifWriter(buffer, pImg.width, pImg.height, opts); - var palette = []; + const gifWriter = new omggif.GifWriter(buffer, pImg.width, pImg.height, opts); + const palette = []; //loop over frames and build pixel -> palette index for each - for (var i = 0; i < props.numFrames; i++) { - var pixelPaletteIndex = new Uint8Array(pImg.width * pImg.height); - var data = props.frames[i].data; - var dataLength = data.length; - for (var j = 0, k = 0; j < dataLength; j += 4, k++) { - var r = data[j + 0]; - var g = data[j + 1]; - var b = data[j + 2]; - var color = (r << 16) | (g << 8) | (b << 0); - var index = palette.indexOf(color); + for (let i = 0; i < props.numFrames; i++) { + const pixelPaletteIndex = new Uint8Array(pImg.width * pImg.height); + const data = props.frames[i].data; + const dataLength = data.length; + for (let j = 0, k = 0; j < dataLength; j += 4, k++) { + const r = data[j + 0]; + const g = data[j + 1]; + const b = data[j + 2]; + const color = (r << 16) | (g << 8) | (b << 0); + const index = palette.indexOf(color); if (index === -1) { pixelPaletteIndex[k] = palette.length; palette.push(color); @@ -234,7 +232,7 @@ p5.prototype.saveGif = function(pImg, filename) { } } // force palette to be power of 2 - var powof2 = 1; + let powof2 = 1; while (powof2 < palette.length) { powof2 <<= 1; } @@ -243,8 +241,8 @@ p5.prototype.saveGif = function(pImg, filename) { gifWriter.addFrame(0, 0, pImg.width, pImg.height, pixelPaletteIndex, opts); } gifWriter.end(); - var extension = 'gif'; - var blob = new Blob([buffer], { type: 'image/gif' }); + const extension = 'gif'; + const blob = new Blob([buffer], { type: 'image/gif' }); p5.prototype.downloadFile(blob, filename, extension); }; @@ -293,27 +291,26 @@ p5.prototype.saveGif = function(pImg, filename) { */ p5.prototype.saveFrames = function(fName, ext, _duration, _fps, callback) { p5._validateParameters('saveFrames', arguments); - var duration = _duration || 3; + let duration = _duration || 3; duration = p5.prototype.constrain(duration, 0, 15); duration = duration * 1000; - var fps = _fps || 15; + let fps = _fps || 15; fps = p5.prototype.constrain(fps, 0, 22); - var count = 0; + let count = 0; - var makeFrame = p5.prototype._makeFrame; - var cnv = this._curElement.elt; - var frameFactory = setInterval(function() { + const makeFrame = p5.prototype._makeFrame; + const cnv = this._curElement.elt; + const frameFactory = setInterval(() => { makeFrame(fName + count, ext, cnv); count++; }, 1000 / fps); - setTimeout(function() { + setTimeout(() => { clearInterval(frameFactory); if (callback) { callback(frames); } else { - for (var i = 0; i < frames.length; i++) { - var f = frames[i]; + for (const f of frames) { p5.prototype.downloadFile(f.imageData, f.filename, f.ext); } } @@ -322,13 +319,13 @@ p5.prototype.saveFrames = function(fName, ext, _duration, _fps, callback) { }; p5.prototype._makeFrame = function(filename, extension, _cnv) { - var cnv; + let cnv; if (this) { cnv = this._curElement.elt; } else { cnv = _cnv; } - var mimeType; + let mimeType; if (!extension) { extension = 'png'; mimeType = 'image/png'; @@ -348,15 +345,15 @@ p5.prototype._makeFrame = function(filename, extension, _cnv) { break; } } - var downloadMime = 'image/octet-stream'; - var imageData = cnv.toDataURL(mimeType); + const downloadMime = 'image/octet-stream'; + let imageData = cnv.toDataURL(mimeType); imageData = imageData.replace(mimeType, downloadMime); - var thisFrame = {}; + const thisFrame = {}; thisFrame.imageData = imageData; thisFrame.filename = filename; thisFrame.ext = extension; frames.push(thisFrame); }; -module.exports = p5; +export default p5; diff --git a/src/image/loading_displaying.js b/src/image/loading_displaying.js index 289aed046e..64954c0ba4 100644 --- a/src/image/loading_displaying.js +++ b/src/image/loading_displaying.js @@ -5,15 +5,13 @@ * @requires core */ -'use strict'; +import p5 from '../core/main'; +import Filters from './filters'; +import canvas from '../core/helpers'; +import * as constants from '../core/constants'; +import omggif from 'omggif'; -var p5 = require('../core/main'); -var Filters = require('./filters'); -var canvas = require('../core/helpers'); -var constants = require('../core/constants'); -var omggif = require('omggif'); - -require('../core/error_helpers'); +import '../core/error_helpers'; /** * Loads an image from a path and creates a p5.Image from it. @@ -66,33 +64,33 @@ require('../core/error_helpers'); */ p5.prototype.loadImage = function(path, successCallback, failureCallback) { p5._validateParameters('loadImage', arguments); - var pImg = new p5.Image(1, 1, this); - var self = this; + const pImg = new p5.Image(1, 1, this); + const self = this; - var req = new Request(path, { + const req = new Request(path, { method: 'GET', mode: 'cors' }); - fetch(path, req).then(function(response) { + fetch(path, req).then(response => { // GIF section - if (response.headers.get('content-type').indexOf('image/gif') !== -1) { + if (response.headers.get('content-type').includes('image/gif')) { response.arrayBuffer().then( - function(arrayBuffer) { + arrayBuffer => { if (arrayBuffer) { - var byteArray = new Uint8Array(arrayBuffer); + const byteArray = new Uint8Array(arrayBuffer); _createGif( byteArray, pImg, successCallback, failureCallback, - function(pImg) { + (pImg => { self._decrementPreload(); - }.bind(self) + }).bind(self) ); } }, - function(e) { + e => { if (typeof failureCallback === 'function') { failureCallback(e); } else { @@ -102,9 +100,9 @@ p5.prototype.loadImage = function(path, successCallback, failureCallback) { ); } else { // Non-GIF Section - var img = new Image(); + const img = new Image(); - img.onload = function() { + img.onload = () => { pImg.width = pImg.canvas.width = img.width; pImg.height = pImg.canvas.height = img.height; @@ -117,7 +115,7 @@ p5.prototype.loadImage = function(path, successCallback, failureCallback) { self._decrementPreload(); }; - img.onerror = function(e) { + img.onerror = e => { p5._friendlyFileLoadError(0, img.src); if (typeof failureCallback === 'function') { failureCallback(e); @@ -153,20 +151,20 @@ function _createGif( failureCallback, finishCallback ) { - var gifReader = new omggif.GifReader(arrayBuffer); + const gifReader = new omggif.GifReader(arrayBuffer); pImg.width = pImg.canvas.width = gifReader.width; pImg.height = pImg.canvas.height = gifReader.height; - var frames = []; - var numFrames = gifReader.numFrames(); - var framePixels = new Uint8ClampedArray(pImg.width * pImg.height * 4); + const frames = []; + const numFrames = gifReader.numFrames(); + let framePixels = new Uint8ClampedArray(pImg.width * pImg.height * 4); // I didn't realize this at first but some GIFs encode with frame // Reworking delay to be frame level will make it less powerful // to modify for users. For now this works with 99% of GIFs that // I can find and for those that it doesn't there is just a retiming // of the frames, which would be minor for all but the strangest GIFs - var averageDelay = 0; + let averageDelay = 0; if (numFrames > 1) { - var loadGIFFrameIntoImage = function(frameNum, gifReader) { + const loadGIFFrameIntoImage = (frameNum, gifReader) => { try { gifReader.decodeAndBlitFrameRGBA(frameNum, framePixels); } catch (e) { @@ -178,8 +176,8 @@ function _createGif( } } }; - for (var j = 0; j < numFrames; j++) { - var frameInfo = gifReader.frameInfo(j); + for (let j = 0; j < numFrames; j++) { + const frameInfo = gifReader.frameInfo(j); averageDelay += frameInfo.delay; // Some GIFs are encoded so that they expect the previous frame // to be under the current frame. This can occur at a sub-frame level @@ -191,7 +189,7 @@ function _createGif( framePixels = new Uint8ClampedArray(pImg.width * pImg.height * 4); } loadGIFFrameIntoImage(j, gifReader); - var imageData = new ImageData(framePixels, pImg.width, pImg.height); + const imageData = new ImageData(framePixels, pImg.width, pImg.height); pImg.drawingContext.putImageData(imageData, 0, 0); frames.push( pImg.drawingContext.getImageData(0, 0, pImg.width, pImg.height) @@ -205,7 +203,7 @@ function _createGif( //this is changed to more usable values for us //to repeat forever, loopCount = null //everything else is just the number of loops - var loopLimit = gifReader.loopCount(); + let loopLimit = gifReader.loopCount(); if (loopLimit === null) { loopLimit = 1; } else if (loopLimit === 0) { @@ -218,10 +216,10 @@ function _createGif( pImg.gifProperties = { displayIndex: 0, delay: averageDelay * 10, //GIF stores delay in one-hundredth of a second, shift to ms - loopLimit: loopLimit, + loopLimit, loopCount: 0, - frames: frames, - numFrames: numFrames, + frames, + numFrames, playing: true, timeDisplayed: 0 }; @@ -372,8 +370,8 @@ p5.prototype.image = function( p5._validateParameters('image', arguments); - var defW = img.width; - var defH = img.height; + let defW = img.width; + let defH = img.height; if (img.elt && img.elt.videoWidth && !img.canvas) { // video no canvas @@ -381,14 +379,14 @@ p5.prototype.image = function( defH = img.elt.videoHeight; } - var _dx = dx; - var _dy = dy; - var _dw = dWidth || defW; - var _dh = dHeight || defH; - var _sx = sx || 0; - var _sy = sy || 0; - var _sw = sWidth || defW; - var _sh = sHeight || defH; + const _dx = dx; + const _dy = dy; + const _dw = dWidth || defW; + const _dh = dHeight || defH; + let _sx = sx || 0; + let _sy = sy || 0; + let _sw = sWidth || defW; + let _sh = sHeight || defH; _sw = _sAssign(_sw, defW); _sh = _sAssign(_sh, defH); @@ -396,7 +394,7 @@ p5.prototype.image = function( // This part needs cleanup and unit tests // see issues https://github.com/processing/p5.js/issues/1741 // and https://github.com/processing/p5.js/issues/1673 - var pd = 1; + let pd = 1; if (img.elt && !img.canvas && img.elt.style.width) { //if img is video and img.elt.size() has been used and @@ -415,7 +413,7 @@ p5.prototype.image = function( _sh *= pd; _sw *= pd; - var vals = canvas.modeAdjust(_dx, _dy, _dw, _dh, this._renderer._imageMode); + const vals = canvas.modeAdjust(_dx, _dy, _dw, _dh, this._renderer._imageMode); // tint the image if there is a tint this._renderer.image(img, _sx, _sy, _sw, _sh, vals.x, vals.y, vals.w, vals.h); @@ -515,9 +513,9 @@ p5.prototype.image = function( * @method tint * @param {p5.Color} color the tint color */ -p5.prototype.tint = function() { - p5._validateParameters('tint', arguments); - var c = this.color.apply(this, arguments); +p5.prototype.tint = function(...args) { + p5._validateParameters('tint', args); + const c = this.color(...args); this._renderer._tint = c.levels; }; @@ -563,19 +561,19 @@ p5.prototype._getTintedImageCanvas = function(img) { if (!img.canvas) { return img; } - var pixels = Filters._toPixels(img.canvas); - var tmpCanvas = document.createElement('canvas'); + const pixels = Filters._toPixels(img.canvas); + const tmpCanvas = document.createElement('canvas'); tmpCanvas.width = img.canvas.width; tmpCanvas.height = img.canvas.height; - var tmpCtx = tmpCanvas.getContext('2d'); - var id = tmpCtx.createImageData(img.canvas.width, img.canvas.height); - var newPixels = id.data; + const tmpCtx = tmpCanvas.getContext('2d'); + const id = tmpCtx.createImageData(img.canvas.width, img.canvas.height); + const newPixels = id.data; - for (var i = 0; i < pixels.length; i += 4) { - var r = pixels[i]; - var g = pixels[i + 1]; - var b = pixels[i + 2]; - var a = pixels[i + 3]; + for (let i = 0; i < pixels.length; i += 4) { + const r = pixels[i]; + const g = pixels[i + 1]; + const b = pixels[i + 2]; + const a = pixels[i + 3]; newPixels[i] = r * this._renderer._tint[0] / 255; newPixels[i + 1] = g * this._renderer._tint[1] / 255; @@ -663,4 +661,4 @@ p5.prototype.imageMode = function(m) { } }; -module.exports = p5; +export default p5; diff --git a/src/image/p5.Image.js b/src/image/p5.Image.js index 608568b737..b4da3554be 100644 --- a/src/image/p5.Image.js +++ b/src/image/p5.Image.js @@ -11,10 +11,8 @@ * drawing images to the main display canvas. */ -'use strict'; - -var p5 = require('../core/main'); -var Filters = require('./filters'); +import p5 from '../core/main'; +import Filters from './filters'; /* * Class methods @@ -227,21 +225,21 @@ p5.Image = function(width, height) { * */ p5.Image.prototype._animateGif = function(pInst) { - var props = this.gifProperties; + const props = this.gifProperties; if (props.playing) { props.timeDisplayed += pInst.deltaTime; } if (props.timeDisplayed >= props.delay) { //GIF is bound to 'realtime' so can skip frames - var skips = Math.floor(props.timeDisplayed / props.delay); + const skips = Math.floor(props.timeDisplayed / props.delay); props.timeDisplayed = 0; props.displayIndex += skips; props.loopCount = Math.floor(props.displayIndex / props.numFrames); if (props.loopLimit !== null && props.loopCount >= props.loopLimit) { props.playing = false; } else { - var ind = props.displayIndex % props.numFrames; + const ind = props.displayIndex % props.numFrames; this.drawingContext.putImageData(props.frames[ind], 0, 0); props.displayIndex = ind; this._pixelsDirty = true; @@ -493,20 +491,20 @@ p5.Image.prototype.resize = function(width, height) { width = Math.floor(width); height = Math.floor(height); - var tempCanvas = document.createElement('canvas'); + const tempCanvas = document.createElement('canvas'); tempCanvas.width = width; tempCanvas.height = height; if (this.gifProperties) { - var props = this.gifProperties; + const props = this.gifProperties; //adapted from github.com/LinusU/resize-image-data - var nearestNeighbor = function(src, dst) { - var pos = 0; - for (var y = 0; y < dst.height; y++) { - for (var x = 0; x < dst.width; x++) { - var srcX = Math.floor(x * src.width / dst.width); - var srcY = Math.floor(y * src.height / dst.height); - var srcPos = (srcY * src.width + srcX) * 4; + const nearestNeighbor = (src, dst) => { + let pos = 0; + for (let y = 0; y < dst.height; y++) { + for (let x = 0; x < dst.width; x++) { + const srcX = Math.floor(x * src.width / dst.width); + const srcY = Math.floor(y * src.height / dst.height); + let srcPos = (srcY * src.width + srcX) * 4; dst.data[pos++] = src.data[srcPos++]; // R dst.data[pos++] = src.data[srcPos++]; // G dst.data[pos++] = src.data[srcPos++]; // B @@ -514,8 +512,11 @@ p5.Image.prototype.resize = function(width, height) { } } }; - for (var i = 0; i < props.numFrames; i++) { - var resizedImageData = this.drawingContext.createImageData(width, height); + for (let i = 0; i < props.numFrames; i++) { + const resizedImageData = this.drawingContext.createImageData( + width, + height + ); nearestNeighbor(props.frames[i], resizedImageData); props.frames[i] = resizedImageData; } @@ -601,28 +602,28 @@ p5.Image.prototype.resize = function(width, height) { * @param {Integer} dw * @param {Integer} dh */ -p5.Image.prototype.copy = function() { - var srcImage, sx, sy, sw, sh, dx, dy, dw, dh; - if (arguments.length === 9) { - srcImage = arguments[0]; - sx = arguments[1]; - sy = arguments[2]; - sw = arguments[3]; - sh = arguments[4]; - dx = arguments[5]; - dy = arguments[6]; - dw = arguments[7]; - dh = arguments[8]; - } else if (arguments.length === 8) { +p5.Image.prototype.copy = function(...args) { + let srcImage, sx, sy, sw, sh, dx, dy, dw, dh; + if (args.length === 9) { + srcImage = args[0]; + sx = args[1]; + sy = args[2]; + sw = args[3]; + sh = args[4]; + dx = args[5]; + dy = args[6]; + dw = args[7]; + dh = args[8]; + } else if (args.length === 8) { srcImage = this; - sx = arguments[0]; - sy = arguments[1]; - sw = arguments[2]; - sh = arguments[3]; - dx = arguments[4]; - dy = arguments[5]; - dw = arguments[6]; - dh = arguments[7]; + sx = args[0]; + sy = args[1]; + sw = args[2]; + sh = args[3]; + dx = args[4]; + dy = args[5]; + dw = args[6]; + dh = args[7]; } else { throw new Error('Signature not supported'); } @@ -668,14 +669,14 @@ p5.Image.prototype.mask = function(p5Image) { if (p5Image === undefined) { p5Image = this; } - var currBlend = this.drawingContext.globalCompositeOperation; + const currBlend = this.drawingContext.globalCompositeOperation; - var scaleFactor = 1; + let scaleFactor = 1; if (p5Image instanceof p5.Renderer) { scaleFactor = p5Image._pInst._pixelDensity; } - var copyArgs = [ + const copyArgs = [ p5Image, 0, 0, @@ -820,8 +821,8 @@ p5.Image.prototype.filter = function(operation, value) { * @param {Integer} dh * @param {Constant} blendMode */ -p5.Image.prototype.blend = function() { - p5.prototype.blend.apply(this, arguments); +p5.Image.prototype.blend = function(...args) { + p5.prototype.blend.apply(this, args); this.setModified(true); }; @@ -924,7 +925,7 @@ p5.Image.prototype.save = function(filename, extension) { */ p5.Image.prototype.reset = function() { if (this.gifProperties) { - var props = this.gifProperties; + const props = this.gifProperties; props.playing = true; props.timeSinceStart = 0; props.timeDisplayed = 0; @@ -961,7 +962,7 @@ p5.Image.prototype.reset = function() { */ p5.Image.prototype.getCurrentFrame = function() { if (this.gifProperties) { - var props = this.gifProperties; + const props = this.gifProperties; return props.displayIndex % props.numFrames; } }; @@ -998,7 +999,7 @@ p5.Image.prototype.getCurrentFrame = function() { */ p5.Image.prototype.setFrame = function(index) { if (this.gifProperties) { - var props = this.gifProperties; + const props = this.gifProperties; if (index < props.numFrames && index >= 0) { props.timeDisplayed = 0; props.displayIndex = index; @@ -1163,4 +1164,4 @@ p5.Image.prototype.delay = function(d) { } }; -module.exports = p5.Image; +export default p5.Image; diff --git a/src/image/pixels.js b/src/image/pixels.js index b7e40e829d..b2a44ccf57 100644 --- a/src/image/pixels.js +++ b/src/image/pixels.js @@ -5,11 +5,9 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); -var Filters = require('./filters'); -require('../color/p5.Color'); +import p5 from '../core/main'; +import Filters from './filters'; +import '../color/p5.Color'; /** * { + for (const k in resp) { ret[k] = resp[k]; } if (typeof callback !== 'undefined') { @@ -166,7 +165,7 @@ p5.prototype.loadJSON = function() { self._decrementPreload(); }, - function(err) { + err => { // Error handling p5._friendlyFileLoadError(5, path); @@ -242,14 +241,14 @@ p5.prototype.loadJSON = function() { * randomly generated text from a file, for example "i have three feet" * */ -p5.prototype.loadStrings = function() { - p5._validateParameters('loadStrings', arguments); +p5.prototype.loadStrings = function(...args) { + p5._validateParameters('loadStrings', args); - var ret = []; - var callback, errorCallback; + const ret = []; + let callback, errorCallback; - for (var i = 1; i < arguments.length; i++) { - var arg = arguments[i]; + for (let i = 1; i < args.length; i++) { + const arg = args[i]; if (typeof arg === 'function') { if (typeof callback === 'undefined') { callback = arg; @@ -259,15 +258,15 @@ p5.prototype.loadStrings = function() { } } - var self = this; + const self = this; p5.prototype.httpDo.call( this, - arguments[0], + args[0], 'GET', 'text', - function(data) { + data => { // split lines handling mac/windows/linux endings - var lines = data + const lines = data .replace(/\r\n/g, '\r') .replace(/\n/g, '\r') .split(/\r/); @@ -392,20 +391,20 @@ p5.prototype.loadStrings = function() { * @return {Object} */ p5.prototype.loadTable = function(path) { - var callback; - var errorCallback; - var options = []; - var header = false; - var ext = path.substring(path.lastIndexOf('.') + 1, path.length); - var sep = ','; - var separatorSet = false; + let callback; + let errorCallback; + const options = []; + let header = false; + const ext = path.substring(path.lastIndexOf('.') + 1, path.length); + let sep = ','; + let separatorSet = false; if (ext === 'tsv') { //Only need to check extension is tsv because csv is default sep = '\t'; } - for (var i = 1; i < arguments.length; i++) { + for (let i = 1; i < arguments.length; i++) { if (typeof arguments[i] === 'function') { if (typeof callback === 'undefined') { callback = arguments[i]; @@ -435,48 +434,48 @@ p5.prototype.loadTable = function(path) { } } - var t = new p5.Table(); + const t = new p5.Table(); - var self = this; + const self = this; this.httpDo( path, 'GET', 'table', - function(resp) { - var state = {}; + resp => { + const state = {}; // define constants - var PRE_TOKEN = 0, + const PRE_TOKEN = 0, MID_TOKEN = 1, POST_TOKEN = 2, POST_RECORD = 4; - var QUOTE = '"', + const QUOTE = '"', CR = '\r', LF = '\n'; - var records = []; - var offset = 0; - var currentRecord = null; - var currentChar; + const records = []; + let offset = 0; + let currentRecord = null; + let currentChar; - var tokenBegin = function() { + const tokenBegin = () => { state.currentState = PRE_TOKEN; state.token = ''; }; - var tokenEnd = function() { + const tokenEnd = () => { currentRecord.push(state.token); tokenBegin(); }; - var recordBegin = function() { + const recordBegin = () => { state.escaped = false; currentRecord = []; tokenBegin(); }; - var recordEnd = function() { + const recordEnd = () => { state.currentState = POST_RECORD; records.push(currentRecord); currentRecord = null; @@ -549,12 +548,12 @@ p5.prototype.loadTable = function(path) { if (header) { t.columns = records.shift(); } else { - for (i = 0; i < records[0].length; i++) { + for (let i = 0; i < records[0].length; i++) { t.columns[i] = 'null'; } } - var row; - for (i = 0; i < records.length; i++) { + let row; + for (let i = 0; i < records.length; i++) { //Handles row of 'undefined' at end of some CSVs if (records[i].length === 1) { if (records[i][0] === 'undefined' || records[i][0] === '') { @@ -572,7 +571,7 @@ p5.prototype.loadTable = function(path) { self._decrementPreload(); }, - function(err) { + err => { // Error handling p5._friendlyFileLoadError(2, path); @@ -589,16 +588,16 @@ p5.prototype.loadTable = function(path) { // helper function to turn a row into a JSON object function makeObject(row, headers) { - var ret = {}; + const ret = {}; headers = headers || []; if (typeof headers === 'undefined') { - for (var j = 0; j < row.length; j++) { + for (let j = 0; j < row.length; j++) { headers[j.toString()] = j; } } - for (var i = 0; i < headers.length; i++) { - var key = headers[i]; - var val = row[i]; + for (let i = 0; i < headers.length; i++) { + const key = headers[i]; + const val = row[i]; ret[key] = val; } return ret; @@ -670,12 +669,12 @@ function makeObject(row, headers) { * no image displayed * */ -p5.prototype.loadXML = function() { - var ret = new p5.XML(); - var callback, errorCallback; +p5.prototype.loadXML = function(...args) { + const ret = new p5.XML(); + let callback, errorCallback; - for (var i = 1; i < arguments.length; i++) { - var arg = arguments[i]; + for (let i = 1; i < args.length; i++) { + const arg = args[i]; if (typeof arg === 'function') { if (typeof callback === 'undefined') { callback = arg; @@ -685,13 +684,13 @@ p5.prototype.loadXML = function() { } } - var self = this; + const self = this; this.httpDo( - arguments[0], + args[0], 'GET', 'xml', - function(xml) { - for (var key in xml) { + xml => { + for (const key in xml) { ret[key] = xml[key]; } if (typeof callback !== 'undefined') { @@ -745,14 +744,14 @@ p5.prototype.loadXML = function() { * */ p5.prototype.loadBytes = function(file, callback, errorCallback) { - var ret = {}; + const ret = {}; - var self = this; + const self = this; this.httpDo( file, 'GET', 'arrayBuffer', - function(arrayBuffer) { + arrayBuffer => { ret.bytes = new Uint8Array(arrayBuffer); if (typeof callback === 'function') { @@ -761,7 +760,7 @@ p5.prototype.loadBytes = function(file, callback, errorCallback) { self._decrementPreload(); }, - function(err) { + err => { // Error handling p5._friendlyFileLoadError(6, file); @@ -847,7 +846,7 @@ p5.prototype.loadBytes = function(file, callback, errorCallback) { p5.prototype.httpGet = function() { p5._validateParameters('httpGet', arguments); - var args = Array.prototype.slice.call(arguments); + const args = Array.prototype.slice.call(arguments); args.splice(1, 0, 'GET'); return p5.prototype.httpDo.apply(this, args); }; @@ -952,7 +951,7 @@ p5.prototype.httpGet = function() { p5.prototype.httpPost = function() { p5._validateParameters('httpPost', arguments); - var args = Array.prototype.slice.call(arguments); + const args = Array.prototype.slice.call(arguments); args.splice(1, 0, 'POST'); return p5.prototype.httpDo.apply(this, args); }; @@ -1038,42 +1037,42 @@ p5.prototype.httpPost = function() { * @param {function} [errorCallback] * @return {Promise} */ -p5.prototype.httpDo = function() { - var type; - var callback; - var errorCallback; - var request; - var promise; - var jsonpOptions = {}; - var cbCount = 0; - var contentType = 'text/plain'; +p5.prototype.httpDo = (...args) => { + let type; + let callback; + let errorCallback; + let request; + let promise; + const jsonpOptions = {}; + let cbCount = 0; + let contentType = 'text/plain'; // Trim the callbacks off the end to get an idea of how many arguments are passed - for (var i = arguments.length - 1; i > 0; i--) { - if (typeof arguments[i] === 'function') { + for (let i = args.length - 1; i > 0; i--) { + if (typeof args[i] === 'function') { cbCount++; } else { break; } } // The number of arguments minus callbacks - var argsCount = arguments.length - cbCount; - var path = arguments[0]; + const argsCount = args.length - cbCount; + const path = args[0]; if ( argsCount === 2 && typeof path === 'string' && - typeof arguments[1] === 'object' + typeof args[1] === 'object' ) { // Intended for more advanced use, pass in Request parameters directly - request = new Request(path, arguments[1]); - callback = arguments[2]; - errorCallback = arguments[3]; + request = new Request(path, args[1]); + callback = args[2]; + errorCallback = args[3]; } else { // Provided with arguments - var method = 'GET'; - var data; + let method = 'GET'; + let data; - for (var j = 1; j < arguments.length; j++) { - var a = arguments[j]; + for (let j = 1; j < args.length; j++) { + const a = args[j]; if (typeof a === 'string') { if (a === 'GET' || a === 'POST' || a === 'PUT' || a === 'DELETE') { method = a; @@ -1097,7 +1096,7 @@ p5.prototype.httpDo = function() { a.hasOwnProperty('jsonpCallback') || a.hasOwnProperty('jsonpCallbackFunction') ) { - for (var attr in a) { + for (const attr in a) { jsonpOptions[attr] = a[attr]; } } else if (a instanceof p5.XML) { @@ -1117,7 +1116,7 @@ p5.prototype.httpDo = function() { } request = new Request(path, { - method: method, + method, mode: 'cors', body: data, headers: new Headers({ @@ -1127,9 +1126,9 @@ p5.prototype.httpDo = function() { } // do some sort of smart type checking if (!type) { - if (path.indexOf('json') !== -1) { + if (path.includes('json')) { type = 'json'; - } else if (path.indexOf('xml') !== -1) { + } else if (path.includes('xml')) { type = 'xml'; } else { type = 'text'; @@ -1141,14 +1140,14 @@ p5.prototype.httpDo = function() { } else { promise = fetch(request); } - promise = promise.then(function(res) { + promise = promise.then(res => { if (!res.ok) { - var err = new Error(res.body); + const err = new Error(res.body); err.status = res.status; err.ok = false; throw err; } else { - var fileSize = 0; + let fileSize = 0; if (type !== 'jsonp') { fileSize = res.headers.get('content-length'); } @@ -1164,9 +1163,9 @@ p5.prototype.httpDo = function() { case 'arrayBuffer': return res.arrayBuffer(); case 'xml': - return res.text().then(function(text) { - var parser = new DOMParser(); - var xml = parser.parseFromString(text, 'text/xml'); + return res.text().then(text => { + const parser = new DOMParser(); + const xml = parser.parseFromString(text, 'text/xml'); return new p5.XML(xml.documentElement); }); default: @@ -1174,7 +1173,7 @@ p5.prototype.httpDo = function() { } } }); - promise.then(callback || function() {}); + promise.then(callback || (() => {})); promise.catch(errorCallback || console.error); return promise; }; @@ -1206,7 +1205,7 @@ p5.prototype._pWriters = []; * * function mousePressed() { * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { - * var writer = createWriter('squares.txt'); + * const writer = createWriter('squares.txt'); * for (let i = 0; i < 10; i++) { * writer.print(i * i); * } @@ -1218,9 +1217,9 @@ p5.prototype._pWriters = []; * */ p5.prototype.createWriter = function(name, extension) { - var newPW; + let newPW; // check that it doesn't already exist - for (var i in p5.prototype._pWriters) { + for (const i in p5.prototype._pWriters) { if (p5.prototype._pWriters[i].name === name) { // if a p5.PrintWriter w/ this name already exists... // return p5.prototype._pWriters[i]; // return it w/ contents intact. @@ -1241,7 +1240,7 @@ p5.prototype.createWriter = function(name, extension) { * @param {String} [extension] */ p5.PrintWriter = function(filename, extension) { - var self = this; + let self = this; this.name = filename; this.content = ''; //Changed to write because it was being overloaded by function below. @@ -1326,7 +1325,7 @@ p5.PrintWriter = function(filename, extension) { * */ this.print = function(data) { - this.content += data + '\n'; + this.content += `${data}\n`; }; /** * Clears the data already written to the PrintWriter object @@ -1371,11 +1370,11 @@ p5.PrintWriter = function(filename, extension) { */ this.close = function() { // convert String to Array for the writeFile Blob - var arr = []; + const arr = []; arr.push(this.content); p5.prototype.writeFile(arr, filename, extension); // remove from _pWriters array and delete self - for (var i in p5.prototype._pWriters) { + for (const i in p5.prototype._pWriters) { if (p5.prototype._pWriters[i].name === this.name) { // remove from _pWriters array p5.prototype._pWriters.splice(i, 1); @@ -1478,12 +1477,12 @@ p5.PrintWriter = function(filename, extension) { */ p5.prototype.save = function(object, _filename, _options) { // parse the arguments and figure out which things we are saving - var args = arguments; + const args = arguments; // ================================================= // OPTION 1: saveCanvas... // if no arguments are provided, save canvas - var cnv = this._curElement ? this._curElement.elt : this.elt; + const cnv = this._curElement ? this._curElement.elt : this.elt; if (args.length === 0) { p5.prototype.saveCanvas(cnv); return; @@ -1499,7 +1498,7 @@ p5.prototype.save = function(object, _filename, _options) { } else { // ================================================= // OPTION 2: extension clarifies saveStrings vs. saveJSON - var extension = _checkFileExtension(args[1], args[2])[1]; + const extension = _checkFileExtension(args[1], args[2])[1]; switch (extension) { case 'json': p5.prototype.saveJSON(args[0], args[1], args[2]); @@ -1569,7 +1568,7 @@ p5.prototype.save = function(object, _filename, _options) { */ p5.prototype.saveJSON = function(json, filename, opt) { p5._validateParameters('saveJSON', arguments); - var stringify; + let stringify; if (opt) { stringify = JSON.stringify(json); } else { @@ -1623,9 +1622,9 @@ p5.prototype.saveJSONArray = p5.prototype.saveJSON; */ p5.prototype.saveStrings = function(list, filename, extension) { p5._validateParameters('saveStrings', arguments); - var ext = extension || 'txt'; - var pWriter = this.createWriter(filename, ext); - for (var i = 0; i < list.length; i++) { + const ext = extension || 'txt'; + const pWriter = this.createWriter(filename, ext); + for (let i = 0; i < list.length; i++) { if (i < list.length - 1) { pWriter.print(list[i]); } else { @@ -1691,24 +1690,24 @@ function escapeHelper(content) { */ p5.prototype.saveTable = function(table, filename, options) { p5._validateParameters('saveTable', arguments); - var ext; + let ext; if (options === undefined) { ext = filename.substring(filename.lastIndexOf('.') + 1, filename.length); } else { ext = options; } - var pWriter = this.createWriter(filename, ext); + const pWriter = this.createWriter(filename, ext); - var header = table.columns; + const header = table.columns; - var sep = ','; // default to CSV + let sep = ','; // default to CSV if (ext === 'tsv') { sep = '\t'; } if (ext !== 'html') { // make header if it has values if (header[0] !== '0') { - for (var h = 0; h < header.length; h++) { + for (let h = 0; h < header.length; h++) { if (h < header.length - 1) { pWriter.write(header[h] + sep); } else { @@ -1719,8 +1718,8 @@ p5.prototype.saveTable = function(table, filename, options) { } // make rows - for (var i = 0; i < table.rows.length; i++) { - var j; + for (let i = 0; i < table.rows.length; i++) { + let j; for (j = 0; j < table.rows[i].arr.length; j++) { if (j < table.rows[i].arr.length - 1) { pWriter.write(table.rows[i].arr[j] + sep); @@ -1736,7 +1735,7 @@ p5.prototype.saveTable = function(table, filename, options) { // otherwise, make HTML pWriter.print(''); pWriter.print(''); - var str = ' '); @@ -1747,21 +1746,21 @@ p5.prototype.saveTable = function(table, filename, options) { // make header if it has values if (header[0] !== '0') { pWriter.print(' '); - for (var k = 0; k < header.length; k++) { - var e = escapeHelper(header[k]); - pWriter.print(' ' + e); + for (let k = 0; k < header.length; k++) { + const e = escapeHelper(header[k]); + pWriter.print(` ${e}`); pWriter.print(' '); } pWriter.print(' '); } // make rows - for (var row = 0; row < table.rows.length; row++) { + for (let row = 0; row < table.rows.length; row++) { pWriter.print(' '); - for (var col = 0; col < table.columns.length; col++) { - var entry = table.rows[row].getString(col); - var htmlEntry = escapeHelper(entry); - pWriter.print(' ' + htmlEntry); + for (let col = 0; col < table.columns.length; col++) { + const entry = table.rows[row].getString(col); + const htmlEntry = escapeHelper(entry); + pWriter.print(` ${htmlEntry}`); pWriter.print(' '); } pWriter.print(' '); @@ -1786,13 +1785,13 @@ p5.prototype.saveTable = function(table, filename, options) { * @param {String} [extension] * @private */ -p5.prototype.writeFile = function(dataToDownload, filename, extension) { - var type = 'application/octet-stream'; +p5.prototype.writeFile = (dataToDownload, filename, extension) => { + let type = 'application/octet-stream'; if (p5.prototype._isSafari()) { type = 'text/plain'; } - var blob = new Blob(dataToDownload, { - type: type + const blob = new Blob(dataToDownload, { + type }); p5.prototype.downloadFile(blob, filename, extension); }; @@ -1810,22 +1809,21 @@ p5.prototype.writeFile = function(dataToDownload, filename, extension) { * @param {String} [filename] * @param {String} [extension] */ -p5.prototype.downloadFile = function(data, fName, extension) { - var fx = _checkFileExtension(fName, extension); - var filename = fx[0]; +p5.prototype.downloadFile = (data, fName, extension) => { + const fx = _checkFileExtension(fName, extension); + const filename = fx[0]; if (data instanceof Blob) { - var fileSaver = require('file-saver'); fileSaver.saveAs(data, filename); return; } - var a = document.createElement('a'); + const a = document.createElement('a'); a.href = data; a.download = filename; // Firefox requires the link to be added to the DOM before click() - a.onclick = function(e) { + a.onclick = e => { destroyClickedElement(e); e.stopPropagation(); }; @@ -1835,10 +1833,10 @@ p5.prototype.downloadFile = function(data, fName, extension) { // Safari will open this file in the same page as a confusing Blob. if (p5.prototype._isSafari()) { - var aText = 'Hello, Safari user! To download this file...\n'; + let aText = 'Hello, Safari user! To download this file...\n'; aText += '1. Go to File --> Save As.\n'; aText += '2. Choose "Page Source" as the Format.\n'; - aText += '3. Name it with this extension: ."' + fx[1] + '"'; + aText += `3. Name it with this extension: ."${fx[1]}"`; alert(aText); } a.click(); @@ -1861,16 +1859,16 @@ function _checkFileExtension(filename, extension) { if (!filename) { filename = 'untitled'; } - var ext = ''; + let ext = ''; // make sure the file will have a name, see if filename needs extension - if (filename && filename.indexOf('.') > -1) { + if (filename && filename.includes('.')) { ext = filename.split('.').pop(); } // append extension if it doesn't exist if (extension) { if (ext !== extension) { ext = extension; - filename = filename + '.' + ext; + filename = `${filename}.${ext}`; } } return [filename, ext]; @@ -1884,8 +1882,8 @@ p5.prototype._checkFileExtension = _checkFileExtension; * @return {Boolean} [description] * @private */ -p5.prototype._isSafari = function() { - var x = Object.prototype.toString.call(window.HTMLElement); +p5.prototype._isSafari = () => { + const x = Object.prototype.toString.call(window.HTMLElement); return x.indexOf('Constructor') > 0; }; @@ -1900,4 +1898,4 @@ function destroyClickedElement(event) { document.body.removeChild(event.target); } -module.exports = p5; +export default p5; diff --git a/src/io/p5.Table.js b/src/io/p5.Table.js index abe1a46af7..ab08a1d920 100644 --- a/src/io/p5.Table.js +++ b/src/io/p5.Table.js @@ -4,9 +4,7 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * Table Options @@ -106,11 +104,11 @@ p5.Table = function(rows) { */ p5.Table.prototype.addRow = function(row) { // make sure it is a valid TableRow - var r = row || new p5.TableRow(); + const r = row || new p5.TableRow(); if (typeof r.arr === 'undefined' || typeof r.obj === 'undefined') { //r = new p5.prototype.TableRow(r); - throw new Error('invalid TableRow: ' + r); + throw new Error(`invalid TableRow: ${r}`); } r.table = this; this.rows.push(r); @@ -160,7 +158,7 @@ p5.Table.prototype.addRow = function(row) { */ p5.Table.prototype.removeRow = function(id) { this.rows[id].table = null; // remove reference to table - var chunk = this.rows.splice(id + 1, this.rows.length); + const chunk = this.rows.splice(id + 1, this.rows.length); this.rows.pop(); this.rows = this.rows.concat(chunk); }; @@ -308,14 +306,14 @@ p5.Table.prototype.getRows = function() { p5.Table.prototype.findRow = function(value, column) { // try the Object if (typeof column === 'string') { - for (var i = 0; i < this.rows.length; i++) { + for (let i = 0; i < this.rows.length; i++) { if (this.rows[i].obj[column] === value) { return this.rows[i]; } } } else { // try the Array - for (var j = 0; j < this.rows.length; j++) { + for (let j = 0; j < this.rows.length; j++) { if (this.rows[j].arr[column] === value) { return this.rows[j]; } @@ -376,16 +374,16 @@ p5.Table.prototype.findRow = function(value, column) { * */ p5.Table.prototype.findRows = function(value, column) { - var ret = []; + const ret = []; if (typeof column === 'string') { - for (var i = 0; i < this.rows.length; i++) { + for (let i = 0; i < this.rows.length; i++) { if (this.rows[i].obj[column] === value) { ret.push(this.rows[i]); } } } else { // try the Array - for (var j = 0; j < this.rows.length; j++) { + for (let j = 0; j < this.rows.length; j++) { if (this.rows[j].arr[column] === value) { ret.push(this.rows[j]); } @@ -438,13 +436,13 @@ p5.Table.prototype.findRows = function(value, column) { */ p5.Table.prototype.matchRow = function(regexp, column) { if (typeof column === 'number') { - for (var j = 0; j < this.rows.length; j++) { + for (let j = 0; j < this.rows.length; j++) { if (this.rows[j].arr[column].match(regexp)) { return this.rows[j]; } } } else { - for (var i = 0; i < this.rows.length; i++) { + for (let i = 0; i < this.rows.length; i++) { if (this.rows[i].obj[column].match(regexp)) { return this.rows[i]; } @@ -503,15 +501,15 @@ p5.Table.prototype.matchRow = function(regexp, column) { * */ p5.Table.prototype.matchRows = function(regexp, column) { - var ret = []; + const ret = []; if (typeof column === 'number') { - for (var j = 0; j < this.rows.length; j++) { + for (let j = 0; j < this.rows.length; j++) { if (this.rows[j].arr[column].match(regexp)) { ret.push(this.rows[j]); } } } else { - for (var i = 0; i < this.rows.length; i++) { + for (let i = 0; i < this.rows.length; i++) { if (this.rows[i].obj[column].match(regexp)) { ret.push(this.rows[i]); } @@ -560,13 +558,13 @@ p5.Table.prototype.matchRows = function(regexp, column) { * */ p5.Table.prototype.getColumn = function(value) { - var ret = []; + const ret = []; if (typeof value === 'string') { - for (var i = 0; i < this.rows.length; i++) { + for (let i = 0; i < this.rows.length; i++) { ret.push(this.rows[i].obj[value]); } } else { - for (var j = 0; j < this.rows.length; j++) { + for (let j = 0; j < this.rows.length; j++) { ret.push(this.rows[j].arr[value]); } } @@ -662,7 +660,7 @@ p5.Table.prototype.clearRows = function() { * */ p5.Table.prototype.addColumn = function(title) { - var t = title || null; + const t = title || null; this.columns.push(t); }; @@ -776,35 +774,33 @@ p5.Table.prototype.getRowCount = function() { * */ p5.Table.prototype.removeTokens = function(chars, column) { - var escape = function(s) { - return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'); - }; - var charArray = []; - for (var i = 0; i < chars.length; i++) { + const escape = s => s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'); + const charArray = []; + for (let i = 0; i < chars.length; i++) { charArray.push(escape(chars.charAt(i))); } - var regex = new RegExp(charArray.join('|'), 'g'); + const regex = new RegExp(charArray.join('|'), 'g'); if (typeof column === 'undefined') { - for (var c = 0; c < this.columns.length; c++) { - for (var d = 0; d < this.rows.length; d++) { - var s = this.rows[d].arr[c]; + for (let c = 0; c < this.columns.length; c++) { + for (let d = 0; d < this.rows.length; d++) { + let s = this.rows[d].arr[c]; s = s.replace(regex, ''); this.rows[d].arr[c] = s; this.rows[d].obj[this.columns[c]] = s; } } } else if (typeof column === 'string') { - for (var j = 0; j < this.rows.length; j++) { - var val = this.rows[j].obj[column]; + for (let j = 0; j < this.rows.length; j++) { + let val = this.rows[j].obj[column]; val = val.replace(regex, ''); this.rows[j].obj[column] = val; - var pos = this.columns.indexOf(column); + const pos = this.columns.indexOf(column); this.rows[j].arr[pos] = val; } } else { - for (var k = 0; k < this.rows.length; k++) { - var str = this.rows[k].arr[column]; + for (let k = 0; k < this.rows.length; k++) { + let str = this.rows[k].arr[column]; str = str.replace(regex, ''); this.rows[k].arr[column] = str; this.rows[k].obj[this.columns[column]] = str; @@ -847,28 +843,28 @@ p5.Table.prototype.removeTokens = function(chars, column) { * */ p5.Table.prototype.trim = function(column) { - var regex = new RegExp(' ', 'g'); + const regex = new RegExp(' ', 'g'); if (typeof column === 'undefined') { - for (var c = 0; c < this.columns.length; c++) { - for (var d = 0; d < this.rows.length; d++) { - var s = this.rows[d].arr[c]; + for (let c = 0; c < this.columns.length; c++) { + for (let d = 0; d < this.rows.length; d++) { + let s = this.rows[d].arr[c]; s = s.replace(regex, ''); this.rows[d].arr[c] = s; this.rows[d].obj[this.columns[c]] = s; } } } else if (typeof column === 'string') { - for (var j = 0; j < this.rows.length; j++) { - var val = this.rows[j].obj[column]; + for (let j = 0; j < this.rows.length; j++) { + let val = this.rows[j].obj[column]; val = val.replace(regex, ''); this.rows[j].obj[column] = val; - var pos = this.columns.indexOf(column); + const pos = this.columns.indexOf(column); this.rows[j].arr[pos] = val; } } else { - for (var k = 0; k < this.rows.length; k++) { - var str = this.rows[k].arr[column]; + for (let k = 0; k < this.rows.length; k++) { + let str = this.rows[k].arr[column]; str = str.replace(regex, ''); this.rows[k].arr[column] = str; this.rows[k].obj[this.columns[column]] = str; @@ -917,8 +913,8 @@ p5.Table.prototype.trim = function(column) { * */ p5.Table.prototype.removeColumn = function(c) { - var cString; - var cNumber; + let cString; + let cNumber; if (typeof c === 'string') { // find the position of c in the columns cString = c; @@ -928,13 +924,13 @@ p5.Table.prototype.removeColumn = function(c) { cString = this.columns[c]; } - var chunk = this.columns.splice(cNumber + 1, this.columns.length); + const chunk = this.columns.splice(cNumber + 1, this.columns.length); this.columns.pop(); this.columns = this.columns.concat(chunk); - for (var i = 0; i < this.rows.length; i++) { - var tempR = this.rows[i].arr; - var chip = tempR.splice(cNumber + 1, tempR.length); + for (let i = 0; i < this.rows.length; i++) { + const tempR = this.rows[i].arr; + const chip = tempR.splice(cNumber + 1, tempR.length); tempR.pop(); this.rows[i].arr = tempR.concat(chip); delete this.rows[i].obj[cString]; @@ -1270,10 +1266,10 @@ p5.Table.prototype.getString = function(row, column) { * */ p5.Table.prototype.getObject = function(headerColumn) { - var tableObject = {}; - var obj, cPos, index; + const tableObject = {}; + let obj, cPos, index; - for (var i = 0; i < this.rows.length; i++) { + for (let i = 0; i < this.rows.length; i++) { obj = this.rows[i].obj; if (typeof headerColumn === 'string') { @@ -1282,9 +1278,7 @@ p5.Table.prototype.getObject = function(headerColumn) { index = obj[headerColumn]; tableObject[index] = obj; } else { - throw new Error( - 'This table has no column named "' + headerColumn + '"' - ); + throw new Error(`This table has no column named "${headerColumn}"`); } } else { tableObject[i] = this.rows[i].obj; @@ -1332,11 +1326,11 @@ p5.Table.prototype.getObject = function(headerColumn) { * */ p5.Table.prototype.getArray = function() { - var tableArray = []; - for (var i = 0; i < this.rows.length; i++) { + const tableArray = []; + for (let i = 0; i < this.rows.length; i++) { tableArray.push(this.rows[i].arr); } return tableArray; }; -module.exports = p5; +export default p5; diff --git a/src/io/p5.TableRow.js b/src/io/p5.TableRow.js index 0c35b1d98e..d13b131bbb 100644 --- a/src/io/p5.TableRow.js +++ b/src/io/p5.TableRow.js @@ -4,9 +4,7 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * A TableRow object represents a single row of data values, @@ -23,15 +21,15 @@ var p5 = require('../core/main'); * @param {String} [separator] comma separated values (csv) by default */ p5.TableRow = function(str, separator) { - var arr = []; - var obj = {}; + let arr = []; + const obj = {}; if (str) { separator = separator || ','; arr = str.split(separator); } - for (var i = 0; i < arr.length; i++) { - var key = i; - var val = arr[i]; + for (let i = 0; i < arr.length; i++) { + const key = i; + const val = arr[i]; obj[key] = val; } this.arr = arr; @@ -82,23 +80,21 @@ p5.TableRow = function(str, separator) { p5.TableRow.prototype.set = function(column, value) { // if typeof column is string, use .obj if (typeof column === 'string') { - var cPos = this.table.columns.indexOf(column); // index of columnID + const cPos = this.table.columns.indexOf(column); // index of columnID if (cPos >= 0) { this.obj[column] = value; this.arr[cPos] = value; } else { - throw new Error('This table has no column named "' + column + '"'); + throw new Error(`This table has no column named "${column}"`); } } else { // if typeof column is number, use .arr if (column < this.table.columns.length) { this.arr[column] = value; - var cTitle = this.table.columns[column]; + const cTitle = this.table.columns[column]; this.obj[cTitle] = value; } else { - throw new Error( - 'Column #' + column + ' is out of the range of this table' - ); + throw new Error(`Column #${column} is out of the range of this table`); } } }; @@ -143,7 +139,7 @@ p5.TableRow.prototype.set = function(column, value) { * no image displayed */ p5.TableRow.prototype.setNum = function(column, value) { - var floatVal = parseFloat(value); + const floatVal = parseFloat(value); this.set(column, floatVal); }; @@ -188,7 +184,7 @@ p5.TableRow.prototype.setNum = function(column, value) { * no image displayed */ p5.TableRow.prototype.setString = function(column, value) { - var stringVal = value.toString(); + const stringVal = value.toString(); this.set(column, stringVal); }; @@ -283,7 +279,7 @@ p5.TableRow.prototype.get = function(column) { * no image displayed */ p5.TableRow.prototype.getNum = function(column) { - var ret; + let ret; if (typeof column === 'string') { ret = parseFloat(this.obj[column]); } else { @@ -291,7 +287,7 @@ p5.TableRow.prototype.getNum = function(column) { } if (ret.toString() === 'NaN') { - throw 'Error: ' + this.obj[column] + ' is NaN (Not a Number)'; + throw `Error: ${this.obj[column]} is NaN (Not a Number)`; } return ret; }; @@ -347,4 +343,4 @@ p5.TableRow.prototype.getString = function(column) { } }; -module.exports = p5; +export default p5; diff --git a/src/io/p5.XML.js b/src/io/p5.XML.js index 11de5dce5b..d151bacd15 100644 --- a/src/io/p5.XML.js +++ b/src/io/p5.XML.js @@ -4,9 +4,7 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * XML is a representation of an XML object, able to parse XML code. Use @@ -55,7 +53,7 @@ var p5 = require('../core/main'); */ p5.XML = function(DOM) { if (!DOM) { - var xmlDoc = document.implementation.createDocument(null, 'doc'); + const xmlDoc = document.implementation.createDocument(null, 'doc'); this.DOM = xmlDoc.createElement('root'); } else { this.DOM = DOM; @@ -170,12 +168,12 @@ p5.XML.prototype.getName = function() { * */ p5.XML.prototype.setName = function(name) { - var content = this.DOM.innerHTML; - var attributes = this.DOM.attributes; - var xmlDoc = document.implementation.createDocument(null, 'default'); - var newDOM = xmlDoc.createElement(name); + const content = this.DOM.innerHTML; + const attributes = this.DOM.attributes; + const xmlDoc = document.implementation.createDocument(null, 'default'); + const newDOM = xmlDoc.createElement(name); newDOM.innerHTML = content; - for (var i = 0; i < attributes.length; i++) { + for (let i = 0; i < attributes.length; i++) { newDOM.setAttribute(attributes[i].nodeName, attributes.nodeValue); } this.DOM = newDOM; @@ -251,8 +249,8 @@ p5.XML.prototype.hasChildren = function() { * */ p5.XML.prototype.listChildren = function() { - var arr = []; - for (var i = 0; i < this.DOM.childNodes.length; i++) { + const arr = []; + for (let i = 0; i < this.DOM.childNodes.length; i++) { arr.push(this.DOM.childNodes[i].nodeName); } return arr; @@ -307,8 +305,8 @@ p5.XML.prototype.getChildren = function(param) { }; function elementsToP5XML(elements) { - var arr = []; - for (var i = 0; i < elements.length; i++) { + const arr = []; + for (let i = 0; i < elements.length; i++) { arr.push(new p5.XML(elements[i])); } return arr; @@ -366,8 +364,7 @@ function elementsToP5XML(elements) { */ p5.XML.prototype.getChild = function(param) { if (typeof param === 'string') { - for (var i = 0; i < this.DOM.children.length; i++) { - var child = this.DOM.children[i]; + for (const child of this.DOM.children) { if (child.tagName === param) return new p5.XML(child); } } else { @@ -483,9 +480,9 @@ p5.XML.prototype.addChild = function(node) { * */ p5.XML.prototype.removeChild = function(param) { - var ind = -1; + let ind = -1; if (typeof param === 'string') { - for (var i = 0; i < this.DOM.children.length; i++) { + for (let i = 0; i < this.DOM.children.length; i++) { if (this.DOM.children[i].tagName === param) { ind = i; break; @@ -569,11 +566,12 @@ p5.XML.prototype.getAttributeCount = function() { * */ p5.XML.prototype.listAttributes = function() { - var arr = []; - for (var i = 0; i < this.DOM.attributes.length; i++) { - var attribute = this.DOM.attributes[i]; + const arr = []; + + for (const attribute of this.DOM.attributes) { arr.push(attribute.nodeName); } + return arr; }; @@ -613,11 +611,12 @@ p5.XML.prototype.listAttributes = function() { * */ p5.XML.prototype.hasAttribute = function(name) { - var obj = {}; - for (var i = 0; i < this.DOM.attributes.length; i++) { - var attribute = this.DOM.attributes[i]; + const obj = {}; + + for (const attribute of this.DOM.attributes) { obj[attribute.nodeName] = attribute.nodeValue; } + return obj[name] ? true : false; }; @@ -659,11 +658,12 @@ p5.XML.prototype.hasAttribute = function(name) { * */ p5.XML.prototype.getNum = function(name, defaultValue) { - var obj = {}; - for (var i = 0; i < this.DOM.attributes.length; i++) { - var attribute = this.DOM.attributes[i]; + const obj = {}; + + for (const attribute of this.DOM.attributes) { obj[attribute.nodeName] = attribute.nodeValue; } + return Number(obj[name]) || defaultValue || 0; }; @@ -705,11 +705,12 @@ p5.XML.prototype.getNum = function(name, defaultValue) { * */ p5.XML.prototype.getString = function(name, defaultValue) { - var obj = {}; - for (var i = 0; i < this.DOM.attributes.length; i++) { - var attribute = this.DOM.attributes[i]; + const obj = {}; + + for (const attribute of this.DOM.attributes) { obj[attribute.nodeName] = attribute.nodeValue; } + return obj[name] ? String(obj[name]) : defaultValue || null; }; @@ -789,7 +790,7 @@ p5.XML.prototype.setAttribute = function(name, value) { * */ p5.XML.prototype.getContent = function(defaultValue) { - var str; + let str; str = this.DOM.textContent; str = str.replace(/\s\s+/g, ','); return str || defaultValue || null; @@ -863,8 +864,8 @@ p5.XML.prototype.setContent = function(content) { * */ p5.XML.prototype.serialize = function() { - var xmlSerializer = new XMLSerializer(); + const xmlSerializer = new XMLSerializer(); return xmlSerializer.serializeToString(this.DOM); }; -module.exports = p5; +export default p5; diff --git a/src/math/calculation.js b/src/math/calculation.js index 573420203b..3face100d9 100644 --- a/src/math/calculation.js +++ b/src/math/calculation.js @@ -5,9 +5,7 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * Calculates the absolute value (magnitude) of a number. Maps to Math.abs(). @@ -172,18 +170,14 @@ p5.prototype.constrain = function(n, low, high) { * @param {Number} z2 z-coordinate of the second point * @return {Number} distance between the two points */ -p5.prototype.dist = function() { - p5._validateParameters('dist', arguments); - if (arguments.length === 4) { +p5.prototype.dist = (...args) => { + p5._validateParameters('dist', args); + if (args.length === 4) { //2D - return hypot(arguments[2] - arguments[0], arguments[3] - arguments[1]); - } else if (arguments.length === 6) { + return hypot(args[2] - args[0], args[3] - args[1]); + } else if (args.length === 6) { //3D - return hypot( - arguments[3] - arguments[0], - arguments[4] - arguments[1], - arguments[5] - arguments[2] - ); + return hypot(args[3] - args[0], args[4] - args[1], args[5] - args[2]); } }; @@ -464,7 +458,7 @@ p5.prototype.mag = function(x, y) { */ p5.prototype.map = function(n, start1, stop1, start2, stop2, withinBounds) { p5._validateParameters('map', arguments); - var newval = (n - start1) / (stop1 - start1) * (stop2 - start2) + start2; + const newval = (n - start1) / (stop1 - start1) * (stop2 - start2) + start2; if (!withinBounds) { return newval; } @@ -516,12 +510,12 @@ p5.prototype.map = function(n, start1, stop1, start2, stop2, withinBounds) { * @param {Number[]} nums Numbers to compare * @return {Number} */ -p5.prototype.max = function() { - p5._validateParameters('max', arguments); - if (arguments[0] instanceof Array) { - return Math.max.apply(null, arguments[0]); +p5.prototype.max = (...args) => { + p5._validateParameters('max', args); + if (args[0] instanceof Array) { + return Math.max.apply(null, args[0]); } else { - return Math.max.apply(null, arguments); + return Math.max.apply(null, args); } }; @@ -566,12 +560,12 @@ p5.prototype.max = function() { * @param {Number[]} nums Numbers to compare * @return {Number} */ -p5.prototype.min = function() { - p5._validateParameters('min', arguments); - if (arguments[0] instanceof Array) { - return Math.min.apply(null, arguments[0]); +p5.prototype.min = (...args) => { + p5._validateParameters('min', args); + if (args[0] instanceof Array) { + return Math.min.apply(null, args[0]); } else { - return Math.min.apply(null, arguments); + return Math.min.apply(null, args); } }; @@ -744,9 +738,7 @@ p5.prototype.round = Math.round; * horizontal center line squared values displayed on top and regular on bottom. * */ -p5.prototype.sq = function(n) { - return n * n; -}; +p5.prototype.sq = n => n * n; /** * Calculates the square root of a number. The square root of a number is @@ -805,11 +797,11 @@ function hypot(x, y, z) { // Otherwise use the V8 implementation // https://github.com/v8/v8/blob/8cd3cf297287e581a49e487067f5cbd991b27123/src/js/math.js#L217 - var length = arguments.length; - var args = []; - var max = 0; - for (var i = 0; i < length; i++) { - var n = arguments[i]; + const length = arguments.length; + const args = []; + let max = 0; + for (let i = 0; i < length; i++) { + let n = arguments[i]; n = +n; if (n === Infinity || n === -Infinity) { return Infinity; @@ -824,16 +816,16 @@ function hypot(x, y, z) { if (max === 0) { max = 1; } - var sum = 0; - var compensation = 0; - for (var j = 0; j < length; j++) { - var m = args[j] / max; - var summand = m * m - compensation; - var preliminary = sum + summand; + let sum = 0; + let compensation = 0; + for (let j = 0; j < length; j++) { + const m = args[j] / max; + const summand = m * m - compensation; + const preliminary = sum + summand; compensation = preliminary - sum - summand; sum = preliminary; } return Math.sqrt(sum) * max; } -module.exports = p5; +export default p5; diff --git a/src/math/math.js b/src/math/math.js index ac5dfa4a9d..7351bea201 100644 --- a/src/math/math.js +++ b/src/math/math.js @@ -5,9 +5,7 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * Creates a new p5.Vector (the datatype for storing vectors). This provides a @@ -47,4 +45,4 @@ p5.prototype.createVector = function(x, y, z) { } }; -module.exports = p5; +export default p5; diff --git a/src/math/noise.js b/src/math/noise.js index 58d94c6744..f60b8a2d50 100644 --- a/src/math/noise.js +++ b/src/math/noise.js @@ -18,24 +18,20 @@ * @requires core */ -'use strict'; +import p5 from '../core/main'; -var p5 = require('../core/main'); +const PERLIN_YWRAPB = 4; +const PERLIN_YWRAP = 1 << PERLIN_YWRAPB; +const PERLIN_ZWRAPB = 8; +const PERLIN_ZWRAP = 1 << PERLIN_ZWRAPB; +const PERLIN_SIZE = 4095; -var PERLIN_YWRAPB = 4; -var PERLIN_YWRAP = 1 << PERLIN_YWRAPB; -var PERLIN_ZWRAPB = 8; -var PERLIN_ZWRAP = 1 << PERLIN_ZWRAPB; -var PERLIN_SIZE = 4095; +let perlin_octaves = 4; // default to medium smooth +let perlin_amp_falloff = 0.5; // 50% reduction/octave -var perlin_octaves = 4; // default to medium smooth -var perlin_amp_falloff = 0.5; // 50% reduction/octave +const scaled_cosine = i => 0.5 * (1.0 - Math.cos(i * Math.PI)); -var scaled_cosine = function(i) { - return 0.5 * (1.0 - Math.cos(i * Math.PI)); -}; - -var perlin; // will be initialized lazily by noise() or noiseSeed() +let perlin; // will be initialized lazily by noise() or noiseSeed() /** * Returns the Perlin noise value at specified coordinates. Perlin noise is @@ -104,13 +100,10 @@ var perlin; // will be initialized lazily by noise() or noiseSeed() * */ -p5.prototype.noise = function(x, y, z) { - y = y || 0; - z = z || 0; - +p5.prototype.noise = (x, y = 0, z = 0) => { if (perlin == null) { perlin = new Array(PERLIN_SIZE + 1); - for (var i = 0; i < PERLIN_SIZE + 1; i++) { + for (let i = 0; i < PERLIN_SIZE + 1; i++) { perlin[i] = Math.random(); } } @@ -125,21 +118,21 @@ p5.prototype.noise = function(x, y, z) { z = -z; } - var xi = Math.floor(x), + let xi = Math.floor(x), yi = Math.floor(y), zi = Math.floor(z); - var xf = x - xi; - var yf = y - yi; - var zf = z - zi; - var rxf, ryf; + let xf = x - xi; + let yf = y - yi; + let zf = z - zi; + let rxf, ryf; - var r = 0; - var ampl = 0.5; + let r = 0; + let ampl = 0.5; - var n1, n2, n3; + let n1, n2, n3; - for (var o = 0; o < perlin_octaves; o++) { - var of = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB); + for (let o = 0; o < perlin_octaves; o++) { + let of = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB); rxf = scaled_cosine(xf); ryf = scaled_cosine(yf); @@ -241,7 +234,7 @@ p5.prototype.noise = function(x, y, z) { * 2 vertical grey smokey patterns affected my mouse x-position and noise. * */ -p5.prototype.noiseDetail = function(lod, falloff) { +p5.prototype.noiseDetail = (lod, falloff) => { if (lod > 0) { perlin_octaves = lod; } @@ -279,29 +272,29 @@ p5.prototype.noiseDetail = function(lod, falloff) { * vertical grey lines drawing in pattern affected by noise. * */ -p5.prototype.noiseSeed = function(seed) { +p5.prototype.noiseSeed = seed => { // Linear Congruential Generator // Variant of a Lehman Generator - var lcg = (function() { + const lcg = (() => { // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes // m is basically chosen to be large (as it is the max period) // and for its relationships to a and c - var m = 4294967296; + const m = 4294967296; // a - 1 should be divisible by m's prime factors - var a = 1664525; + const a = 1664525; // c and m should be co-prime - var c = 1013904223; - var seed, z; + const c = 1013904223; + let seed, z; return { - setSeed: function(val) { + setSeed(val) { // pick a random seed if val is undefined or null // the >>> 0 casts the seed to an unsigned 32-bit integer z = seed = (val == null ? Math.random() * m : val) >>> 0; }, - getSeed: function() { + getSeed() { return seed; }, - rand: function() { + rand() { // define the recurrence relationship z = (a * z + c) % m; // return a float in [0, 1) @@ -313,9 +306,9 @@ p5.prototype.noiseSeed = function(seed) { lcg.setSeed(seed); perlin = new Array(PERLIN_SIZE + 1); - for (var i = 0; i < PERLIN_SIZE + 1; i++) { + for (let i = 0; i < PERLIN_SIZE + 1; i++) { perlin[i] = lcg.rand(); } }; -module.exports = p5; +export default p5; diff --git a/src/math/p5.Vector.js b/src/math/p5.Vector.js index 91377977b8..57e7a875da 100644 --- a/src/math/p5.Vector.js +++ b/src/math/p5.Vector.js @@ -4,10 +4,8 @@ * @requires constants */ -'use strict'; - -var p5 = require('../core/main'); -var constants = require('../core/constants'); +import p5 from '../core/main'; +import * as constants from '../core/constants'; /** * A class to describe a two or three dimensional vector, specifically @@ -50,7 +48,7 @@ var constants = require('../core/constants'); * */ p5.Vector = function Vector() { - var x, y, z; + let x, y, z; // This is how it comes in with createVector() if (arguments[0] instanceof p5) { // save reference to p5 if passed in @@ -128,7 +126,7 @@ p5.Vector = function Vector() { * */ p5.Vector.prototype.toString = function p5VectorToString() { - return 'p5.Vector Object : [' + this.x + ', ' + this.y + ', ' + this.z + ']'; + return `p5.Vector Object : [${this.x}, ${this.y}, ${this.z}]`; }; /** @@ -666,9 +664,9 @@ p5.Vector.prototype.mag = function mag() { * */ p5.Vector.prototype.magSq = function magSq() { - var x = this.x; - var y = this.y; - var z = this.z; + const x = this.x; + const y = this.y; + const z = this.z; return x * x + y * y + z * z; }; @@ -746,9 +744,9 @@ p5.Vector.prototype.dot = function dot(x, y, z) { * */ p5.Vector.prototype.cross = function cross(v) { - var x = this.y * v.z - this.z * v.y; - var y = this.z * v.x - this.x * v.z; - var z = this.x * v.y - this.y * v.x; + const x = this.y * v.z - this.z * v.y; + const y = this.z * v.x - this.x * v.z; + const z = this.x * v.y - this.y * v.x; if (this.p5) { return new p5.Vector(this.p5, [x, y, z]); } else { @@ -876,7 +874,7 @@ p5.Vector.prototype.dist = function dist(v) { * */ p5.Vector.prototype.normalize = function normalize() { - var len = this.mag(); + const len = this.mag(); // here we multiply by the reciprocal instead of calling 'div()' // since div duplicates this zero check. if (len !== 0) this.mult(1 / len); @@ -933,7 +931,7 @@ p5.Vector.prototype.normalize = function normalize() { * */ p5.Vector.prototype.limit = function limit(max) { - var mSq = this.magSq(); + const mSq = this.magSq(); if (mSq > max * max) { this.div(Math.sqrt(mSq)) //normalize it .mult(max); @@ -1061,7 +1059,7 @@ p5.Vector.prototype.setMag = function setMag(n) { * */ p5.Vector.prototype.heading = function heading() { - var h = Math.atan2(this.y, this.x); + const h = Math.atan2(this.y, this.x); if (this.p5) return this.p5._fromRadians(h); return h; }; @@ -1114,9 +1112,9 @@ p5.Vector.prototype.heading = function heading() { * */ p5.Vector.prototype.rotate = function rotate(a) { - var newHeading = this.heading() + a; + let newHeading = this.heading() + a; if (this.p5) newHeading = this.p5._toRadians(newHeading); - var mag = this.mag(); + const mag = this.mag(); this.x = Math.cos(newHeading) * mag; this.y = Math.sin(newHeading) * mag; return this; @@ -1184,13 +1182,13 @@ p5.Vector.prototype.rotate = function rotate(a) { * */ p5.Vector.prototype.angleBetween = function angleBetween(v) { - var dotmagmag = this.dot(v) / (this.mag() * v.mag()); + const dotmagmag = this.dot(v) / (this.mag() * v.mag()); // Mathematically speaking: the dotmagmag variable will be between -1 and 1 // inclusive. Practically though it could be slightly outside this range due // to floating-point rounding issues. This can make Math.acos return NaN. // // Solution: we'll clamp the value to the -1,1 range - var angle = Math.acos(Math.min(1, Math.max(-1, dotmagmag))); + const angle = Math.acos(Math.min(1, Math.max(-1, dotmagmag))); if (this.p5) return this.p5._fromRadians(angle); return angle; }; @@ -1352,7 +1350,7 @@ p5.Vector.prototype.array = function array() { * @return {Boolean} */ p5.Vector.prototype.equals = function equals(x, y, z) { - var a, b, c; + let a, b, c; if (x instanceof p5.Vector) { a = x.x || 0; b = x.y || 0; @@ -1455,14 +1453,14 @@ p5.Vector.fromAngle = function fromAngle(angle, length) { * * */ -p5.Vector.fromAngles = function(theta, phi, length) { +p5.Vector.fromAngles = (theta, phi, length) => { if (typeof length === 'undefined') { length = 1; } - var cosPhi = Math.cos(phi); - var sinPhi = Math.sin(phi); - var cosTheta = Math.cos(theta); - var sinTheta = Math.sin(theta); + const cosPhi = Math.cos(phi); + const sinPhi = Math.sin(phi); + const cosTheta = Math.cos(theta); + const sinTheta = Math.sin(theta); return new p5.Vector( length * sinTheta * sinPhi, @@ -1543,11 +1541,11 @@ p5.Vector.random2D = function random2D() { * */ p5.Vector.random3D = function random3D() { - var angle = Math.random() * constants.TWO_PI; - var vz = Math.random() * 2 - 1; - var vzBase = Math.sqrt(1 - vz * vz); - var vx = vzBase * Math.cos(angle); - var vy = vzBase * Math.sin(angle); + const angle = Math.random() * constants.TWO_PI; + const vz = Math.random() * 2 - 1; + const vzBase = Math.sqrt(1 - vz * vz); + const vx = vzBase * Math.cos(angle); + const vy = vzBase * Math.sin(angle); return new p5.Vector(vx, vy, vz); }; @@ -1741,11 +1739,11 @@ p5.Vector.lerp = function lerp(v1, v2, amt, target) { * @static */ p5.Vector.mag = function mag(vecT) { - var x = vecT.x, + const x = vecT.x, y = vecT.y, z = vecT.z; - var magSq = x * x + y * y + z * z; + const magSq = x * x + y * y + z * z; return Math.sqrt(magSq); }; -module.exports = p5.Vector; +export default p5.Vector; diff --git a/src/math/random.js b/src/math/random.js index c61e8d6450..44ae870a51 100644 --- a/src/math/random.js +++ b/src/math/random.js @@ -5,21 +5,19 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; // variables used for random number generators -var randomStateProp = '_lcg_random_state'; +const randomStateProp = '_lcg_random_state'; // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes // m is basically chosen to be large (as it is the max period) // and for its relationships to a and c -var m = 4294967296; +const m = 4294967296; // a - 1 should be divisible by m's prime factors -var a = 1664525; +const a = 1664525; // c and m should be co-prime -var c = 1013904223; -var y2 = 0; +const c = 1013904223; +let y2 = 0; // Linear Congruential Generator that stores its state at instance[stateProperty] p5.prototype._lcg = function(stateProperty) { @@ -127,7 +125,7 @@ p5.prototype.randomSeed = function(seed) { * @example */ p5.prototype.random = function(min, max) { - var rand; + let rand; if (this[randomStateProp] != null) { rand = this._lcg(randomStateProp); @@ -144,7 +142,7 @@ p5.prototype.random = function(min, max) { } } else { if (min > max) { - var tmp = min; + const tmp = min; min = max; max = tmp; } @@ -210,7 +208,7 @@ p5.prototype.random = function(min, max) { * black lines radiate from center of canvas. size determined each render */ p5.prototype.randomGaussian = function(mean, sd) { - var y1, x1, x2, w; + let y1, x1, x2, w; if (this._gaussian_previous) { y1 = y2; this._gaussian_previous = false; @@ -226,9 +224,9 @@ p5.prototype.randomGaussian = function(mean, sd) { this._gaussian_previous = true; } - var m = mean || 0; - var s = sd || 1; + const m = mean || 0; + const s = sd || 1; return y1 * s + m; }; -module.exports = p5; +export default p5; diff --git a/src/math/trigonometry.js b/src/math/trigonometry.js index 30330b42f8..a60297ea43 100644 --- a/src/math/trigonometry.js +++ b/src/math/trigonometry.js @@ -6,10 +6,8 @@ * @requires constants */ -'use strict'; - -var p5 = require('../core/main'); -var constants = require('../core/constants'); +import p5 from '../core/main'; +import * as constants from '../core/constants'; /* * all DEGREES/RADIANS conversion should be done in the p5 instance @@ -264,9 +262,7 @@ p5.prototype.tan = function(angle) { * * */ -p5.prototype.degrees = function(angle) { - return angle * constants.RAD_TO_DEG; -}; +p5.prototype.degrees = angle => angle * constants.RAD_TO_DEG; /** * Converts a degree measurement to its corresponding value in radians. @@ -289,9 +285,7 @@ p5.prototype.degrees = function(angle) { * * */ -p5.prototype.radians = function(angle) { - return angle * constants.DEG_TO_RAD; -}; +p5.prototype.radians = angle => angle * constants.DEG_TO_RAD; /** * Sets the current mode of p5 to given mode. Default mode is RADIANS. @@ -374,4 +368,4 @@ p5.prototype._fromRadians = function(angle) { return angle; }; -module.exports = p5; +export default p5; diff --git a/src/typography/attributes.js b/src/typography/attributes.js index 1566da4ce5..bdbd80f104 100644 --- a/src/typography/attributes.js +++ b/src/typography/attributes.js @@ -6,9 +6,7 @@ * @requires constants */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * Sets the current alignment for drawing text. Accepts two @@ -78,7 +76,7 @@ var p5 = require('../core/main'); */ p5.prototype.textAlign = function(horizAlign, vertAlign) { p5._validateParameters('textAlign', arguments); - return this._renderer.textAlign.apply(this._renderer, arguments); + return this._renderer.textAlign(...arguments); }; /** @@ -116,7 +114,7 @@ p5.prototype.textAlign = function(horizAlign, vertAlign) { */ p5.prototype.textLeading = function(theLeading) { p5._validateParameters('textLeading', arguments); - return this._renderer.textLeading.apply(this._renderer, arguments); + return this._renderer.textLeading(...arguments); }; /** @@ -148,7 +146,7 @@ p5.prototype.textLeading = function(theLeading) { */ p5.prototype.textSize = function(theSize) { p5._validateParameters('textSize', arguments); - return this._renderer.textSize.apply(this._renderer, arguments); + return this._renderer.textSize(...arguments); }; /** @@ -185,7 +183,7 @@ p5.prototype.textSize = function(theSize) { */ p5.prototype.textStyle = function(theStyle) { p5._validateParameters('textStyle', arguments); - return this._renderer.textStyle.apply(this._renderer, arguments); + return this._renderer.textStyle(...arguments); }; /** @@ -215,13 +213,13 @@ p5.prototype.textStyle = function(theStyle) { *Letter P and p5.js are displayed with vertical lines at end. P is wide * */ -p5.prototype.textWidth = function() { - arguments[0] += ''; - p5._validateParameters('textWidth', arguments); - if (arguments[0].length === 0) { +p5.prototype.textWidth = function(...args) { + args[0] += ''; + p5._validateParameters('textWidth', args); + if (args[0].length === 0) { return 0; } - return this._renderer.textWidth.apply(this._renderer, arguments); + return this._renderer.textWidth(...args); }; /** @@ -248,8 +246,8 @@ p5.prototype.textWidth = function() { * * */ -p5.prototype.textAscent = function() { - p5._validateParameters('textAscent', arguments); +p5.prototype.textAscent = function(...args) { + p5._validateParameters('textAscent', args); return this._renderer.textAscent(); }; @@ -277,8 +275,8 @@ p5.prototype.textAscent = function() { * * */ -p5.prototype.textDescent = function() { - p5._validateParameters('textDescent', arguments); +p5.prototype.textDescent = function(...args) { + p5._validateParameters('textDescent', args); return this._renderer.textDescent(); }; @@ -289,4 +287,4 @@ p5.prototype._updateTextMetrics = function() { return this._renderer._updateTextMetrics(); }; -module.exports = p5; +export default p5; diff --git a/src/typography/loading_displaying.js b/src/typography/loading_displaying.js index 229be37c05..a25e0af376 100644 --- a/src/typography/loading_displaying.js +++ b/src/typography/loading_displaying.js @@ -5,13 +5,11 @@ * @requires core */ -'use strict'; +import p5 from '../core/main'; +import * as constants from '../core/constants'; +import * as opentype from 'opentype.js'; -var p5 = require('../core/main'); -var constants = require('../core/constants'); -var opentype = require('opentype.js'); - -require('../core/error_helpers'); +import '../core/error_helpers'; /** * Loads an opentype font file (.otf, .ttf) from a file or a URL, @@ -86,10 +84,10 @@ require('../core/error_helpers'); */ p5.prototype.loadFont = function(path, onSuccess, onError) { p5._validateParameters('loadFont', arguments); - var p5Font = new p5.Font(this); + const p5Font = new p5.Font(this); - var self = this; - opentype.load(path, function(err, font) { + const self = this; + opentype.load(path, (err, font) => { if (err) { p5._friendlyFileLoadError(4, path); if (typeof onError !== 'undefined') { @@ -108,29 +106,26 @@ p5.prototype.loadFont = function(path, onSuccess, onError) { self._decrementPreload(); // check that we have an acceptable font type - var validFontTypes = ['ttf', 'otf', 'woff', 'woff2'], - fileNoPath = path - .split('\\') - .pop() - .split('/') - .pop(), - lastDotIdx = fileNoPath.lastIndexOf('.'), - fontFamily, - newStyle, - fileExt = lastDotIdx < 1 ? null : fileNoPath.substr(lastDotIdx + 1); + const validFontTypes = ['ttf', 'otf', 'woff', 'woff2']; + + const fileNoPath = path + .split('\\') + .pop() + .split('/') + .pop(); + + const lastDotIdx = fileNoPath.lastIndexOf('.'); + let fontFamily; + let newStyle; + const fileExt = lastDotIdx < 1 ? null : fileNoPath.substr(lastDotIdx + 1); // if so, add it to the DOM (name-only) for use with p5.dom - if (validFontTypes.indexOf(fileExt) > -1) { + if (validFontTypes.includes(fileExt)) { fontFamily = fileNoPath.substr(0, lastDotIdx); newStyle = document.createElement('style'); newStyle.appendChild( document.createTextNode( - '\n@font-face {' + - '\nfont-family: ' + - fontFamily + - ';\nsrc: url(' + - path + - ');\n}\n' + `\n@font-face {\nfont-family: ${fontFamily};\nsrc: url(${path});\n}\n` ) ); document.head.appendChild(newStyle); @@ -224,7 +219,7 @@ p5.prototype.text = function(str, x, y, maxWidth, maxHeight) { p5._validateParameters('text', arguments); return !(this._renderer._doFill || this._renderer._doStroke) ? this - : this._renderer.text.apply(this._renderer, arguments); + : this._renderer.text(...arguments); }; /** @@ -303,4 +298,4 @@ p5.prototype.textFont = function(theFont, theSize) { return this._renderer._textFont; }; -module.exports = p5; +export default p5; diff --git a/src/typography/p5.Font.js b/src/typography/p5.Font.js index 5a3545f9f4..57afc99733 100644 --- a/src/typography/p5.Font.js +++ b/src/typography/p5.Font.js @@ -7,10 +7,8 @@ * @requires constants */ -'use strict'; - -var p5 = require('../core/main'); -var constants = require('../core/constants'); +import p5 from '../core/main'; +import * as constants from '../core/constants'; /** * Base class for font handling @@ -74,20 +72,18 @@ p5.Font = function(p) { *words Lorem ipsum dol go off canvas and contained by white bounding box * */ -p5.Font.prototype.textBounds = function(str, x, y, fontSize, opts) { - x = x !== undefined ? x : 0; - y = y !== undefined ? y : 0; - +p5.Font.prototype.textBounds = function(str, x = 0, y = 0, fontSize, opts) { // Check cache for existing bounds. Take into consideration the text alignment // settings. Default alignment should match opentype's origin: left-aligned & // alphabetic baseline. - var p = (opts && opts.renderer && opts.renderer._pInst) || this.parent, - ctx = p._renderer.drawingContext, - alignment = ctx.textAlign || constants.LEFT, - baseline = ctx.textBaseline || constants.BASELINE, - cacheResults = false, - result, - key; + const p = (opts && opts.renderer && opts.renderer._pInst) || this.parent; + + const ctx = p._renderer.drawingContext; + const alignment = ctx.textAlign || constants.LEFT; + const baseline = ctx.textBaseline || constants.BASELINE; + const cacheResults = false; + let result; + let key; fontSize = fontSize || p._renderer._textSize; @@ -98,27 +94,29 @@ p5.Font.prototype.textBounds = function(str, x, y, fontSize, opts) { } if (!result) { - var minX, - minY, - maxX, - maxY, - pos, - xCoords = [], - yCoords = [], - scale = this._scale(fontSize); - - this.font.forEachGlyph(str, x, y, fontSize, opts, function( - glyph, - gX, - gY, - gFontSize - ) { - var gm = glyph.getMetrics(); - xCoords.push(gX + gm.xMin * scale); - xCoords.push(gX + gm.xMax * scale); - yCoords.push(gY + -gm.yMin * scale); - yCoords.push(gY + -gm.yMax * scale); - }); + let minX; + let minY; + let maxX; + let maxY; + let pos; + const xCoords = []; + const yCoords = []; + const scale = this._scale(fontSize); + + this.font.forEachGlyph( + str, + x, + y, + fontSize, + opts, + (glyph, gX, gY, gFontSize) => { + const gm = glyph.getMetrics(); + xCoords.push(gX + gm.xMin * scale); + xCoords.push(gX + gm.xMax * scale); + yCoords.push(gY + -gm.yMin * scale); + yCoords.push(gY + -gm.yMax * scale); + } + ); minX = Math.min.apply(null, xCoords); minY = Math.min.apply(null, yCoords); @@ -213,9 +211,9 @@ p5.Font.prototype.textBounds = function(str, x, y, fontSize, opts) { * */ p5.Font.prototype.textToPoints = function(txt, x, y, fontSize, options) { - var xoff = 0, - result = [], - glyphs = this._getGlyphs(txt); + let xoff = 0; + const result = []; + const glyphs = this._getGlyphs(txt); function isSpace(i) { return ( @@ -227,17 +225,17 @@ p5.Font.prototype.textToPoints = function(txt, x, y, fontSize, options) { fontSize = fontSize || this.parent._renderer._textSize; - for (var i = 0; i < glyphs.length; i++) { + for (let i = 0; i < glyphs.length; i++) { if (!isSpace(i)) { // fix to #1817, #2069 - var gpath = glyphs[i].getPath(x, y, fontSize), + const gpath = glyphs[i].getPath(x, y, fontSize), paths = splitPaths(gpath.commands); - for (var j = 0; j < paths.length; j++) { - var pts = pathToPoints(paths[j], options); + for (let j = 0; j < paths.length; j++) { + const pts = pathToPoints(paths[j], options); - for (var k = 0; k < pts.length; k++) { + for (let k = 0; k < pts.length; k++) { pts[k].x += xoff; result.push(pts[k]); } @@ -278,7 +276,7 @@ p5.Font.prototype._getGlyphs = function(str) { * @return {Object} the opentype path */ p5.Font.prototype._getPath = function(line, x, y, options) { - var p = + const p = (options && options.renderer && options.renderer._pInst) || this.parent, renderer = p._renderer, pos = this._handleAlignment(renderer, line, x, y); @@ -302,7 +300,7 @@ p5.Font.prototype._getPath = function(line, x, y, options) { * @return {Object} this p5.Font object */ p5.Font.prototype._getPathData = function(line, x, y, options) { - var decimals = 3; + let decimals = 3; // create path from string/position if (typeof line === 'string' && arguments.length > 2) { @@ -338,7 +336,7 @@ p5.Font.prototype._getPathData = function(line, x, y, options) { * @return {Object} this p5.Font object */ p5.Font.prototype._getSVG = function(line, x, y, options) { - var decimals = 3; + let decimals = 3; // create path from string/position if (typeof line === 'string' && arguments.length > 2) { @@ -381,9 +379,9 @@ p5.Font.prototype._getSVG = function(line, x, y, options) { * @return {p5.Font} this p5.Font object */ p5.Font.prototype._renderPath = function(line, x, y, options) { - var pdata, - pg = (options && options.renderer) || this.parent._renderer, - ctx = pg.drawingContext; + let pdata; + const pg = (options && options.renderer) || this.parent._renderer; + const ctx = pg.drawingContext; if (typeof line === 'object' && line.commands) { pdata = line.commands; @@ -393,8 +391,8 @@ p5.Font.prototype._renderPath = function(line, x, y, options) { } ctx.beginPath(); - for (var i = 0; i < pdata.length; i += 1) { - var cmd = pdata[i]; + + for (const cmd of pdata) { if (cmd.type === 'M') { ctx.moveTo(cmd.x, cmd.y); } else if (cmd.type === 'L') { @@ -443,7 +441,7 @@ p5.Font.prototype._scale = function(fontSize) { }; p5.Font.prototype._handleAlignment = function(renderer, line, x, y, textWidth) { - var fontSize = renderer._textSize; + const fontSize = renderer._textSize; if (typeof textWidth === 'undefined') { textWidth = this._textWidth(line, fontSize); @@ -470,22 +468,23 @@ p5.Font.prototype._handleAlignment = function(renderer, line, x, y, textWidth) { break; } - return { x: x, y: y }; + return { x, y }; }; // path-utils function pathToPoints(cmds, options) { - var opts = parseOpts(options, { + const opts = parseOpts(options, { sampleFactor: 0.1, simplifyThreshold: 0 }); - var len = pointAtLength(cmds, 0, 1), // total-length + const // total-length + len = pointAtLength(cmds, 0, 1), t = len / (len * opts.sampleFactor), pts = []; - for (var i = 0; i < len; i += t) { + for (let i = 0; i < len; i += t) { pts.push(pointAtLength(cmds, i)); } @@ -496,11 +495,9 @@ function pathToPoints(cmds, options) { return pts; } -function simplify(pts, angle) { - angle = typeof angle === 'undefined' ? 0 : angle; - - var num = 0; - for (var i = pts.length - 1; pts.length > 3 && i >= 0; --i) { +function simplify(pts, angle = 0) { + let num = 0; + for (let i = pts.length - 1; pts.length > 3 && i >= 0; --i) { if (collinear(at(pts, i - 1), at(pts, i), at(pts, i + 1), angle)) { // Remove the middle point pts.splice(i % pts.length, 1); @@ -511,9 +508,9 @@ function simplify(pts, angle) { } function splitPaths(cmds) { - var paths = [], - current; - for (var i = 0; i < cmds.length; i++) { + const paths = []; + let current; + for (let i = 0; i < cmds.length; i++) { if (cmds[i].type === 'M') { if (current) { paths.push(current); @@ -528,7 +525,7 @@ function splitPaths(cmds) { } function cmdToArr(cmd) { - var arr = [cmd.type]; + const arr = [cmd.type]; if (cmd.type === 'M' || cmd.type === 'L') { // moveto or lineto arr.push(cmd.x, cmd.y); @@ -545,7 +542,7 @@ function parseOpts(options, defaults) { if (typeof options !== 'object') { options = defaults; } else { - for (var key in defaults) { + for (const key in defaults) { if (typeof options[key] === 'undefined') { options[key] = defaults[key]; } @@ -557,7 +554,7 @@ function parseOpts(options, defaults) { //////////////////////// Helpers //////////////////////////// function at(v, i) { - var s = v.length; + const s = v.length; return v[i < 0 ? i % s + s : i % s]; } @@ -571,14 +568,14 @@ function collinear(a, b, c, thresholdAngle) { collinear.tmpPoint2 = []; } - var ab = collinear.tmpPoint1, + const ab = collinear.tmpPoint1, bc = collinear.tmpPoint2; ab.x = b.x - a.x; ab.y = b.y - a.y; bc.x = c.x - b.x; bc.y = c.y - b.y; - var dot = ab.x * bc.x + ab.y * bc.y, + const dot = ab.x * bc.x + ab.y * bc.y, magA = Math.sqrt(ab.x * ab.x + ab.y * ab.y), magB = Math.sqrt(bc.x * bc.x + bc.y * bc.y), angle = Math.acos(dot / (magA * magB)); @@ -593,35 +590,35 @@ function areaTriangle(a, b, c) { // Portions of below code copyright 2008 Dmitry Baranovskiy (via MIT license) function findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { - var t1 = 1 - t, - t13 = Math.pow(t1, 3), - t12 = Math.pow(t1, 2), - t2 = t * t, - t3 = t2 * t, - x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x, - y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y, - mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x), - my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y), - nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x), - ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y), - ax = t1 * p1x + t * c1x, - ay = t1 * p1y + t * c1y, - cx = t1 * c2x + t * p2x, - cy = t1 * c2y + t * p2y, - alpha = 90 - Math.atan2(mx - nx, my - ny) * 180 / Math.PI; + const t1 = 1 - t; + const t13 = Math.pow(t1, 3); + const t12 = Math.pow(t1, 2); + const t2 = t * t; + const t3 = t2 * t; + const x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x; + const y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y; + const mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x); + const my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y); + const nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x); + const ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y); + const ax = t1 * p1x + t * c1x; + const ay = t1 * p1y + t * c1y; + const cx = t1 * c2x + t * p2x; + const cy = t1 * c2y + t * p2y; + let alpha = 90 - Math.atan2(mx - nx, my - ny) * 180 / Math.PI; if (mx > nx || my < ny) { alpha += 180; } return { - x: x, - y: y, + x, + y, m: { x: mx, y: my }, n: { x: nx, y: ny }, start: { x: ax, y: ay }, end: { x: cx, y: cy }, - alpha: alpha + alpha }; } @@ -653,15 +650,15 @@ function getPointAtSegmentLength( function pointAtLength(path, length, istotal) { path = path2curve(path); - var x, - y, - p, - l, - sp = '', - subpaths = {}, - point, - len = 0; - for (var i = 0, ii = path.length; i < ii; i++) { + let x; + let y; + let p; + let l; + let sp = ''; + const subpaths = {}; + let point; + let len = 0; + for (let i = 0, ii = path.length; i < ii; i++) { p = path[i]; if (p[0] === 'M') { x = +p[1]; @@ -704,7 +701,7 @@ function pointAtLength(path, length, istotal) { } function pathToAbsolute(pathArray) { - var res = [], + let res = [], x = 0, y = 0, mx = 0, @@ -723,14 +720,15 @@ function pathToAbsolute(pathArray) { res[0] = ['M', x, y]; } - var dots, - crz = - pathArray.length === 3 && - pathArray[0][0] === 'M' && - pathArray[1][0].toUpperCase() === 'R' && - pathArray[2][0].toUpperCase() === 'Z'; + let dots; + + const crz = + pathArray.length === 3 && + pathArray[0][0] === 'M' && + pathArray[1][0].toUpperCase() === 'R' && + pathArray[2][0].toUpperCase() === 'Z'; - for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) { + for (let r, pa, i = start, ii = pathArray.length; i < ii; i++) { res.push((r = [])); pa = pathArray[i]; if (pa[0] !== String.prototype.toUpperCase.call(pa[0])) { @@ -753,7 +751,7 @@ function pathToAbsolute(pathArray) { break; case 'R': dots = [x, y].concat(pa.slice(1)); - for (var j = 2, jj = dots.length; j < jj; j++) { + for (let j = 2, jj = dots.length; j < jj; j++) { dots[j] = +dots[j] + x; dots[++j] = +dots[j] + y; } @@ -765,7 +763,7 @@ function pathToAbsolute(pathArray) { my = +pa[2] + y; break; default: - for (j = 1, jj = pa.length; j < jj; j++) { + for (let j = 1, jj = pa.length; j < jj; j++) { r[j] = +pa[j] + (j % 2 ? x : y); } } @@ -775,7 +773,7 @@ function pathToAbsolute(pathArray) { res = res.concat(catmullRom2bezier(dots, crz)); r = ['R'].concat(pa.slice(-2)); } else { - for (var k = 0, kk = pa.length; k < kk; k++) { + for (let k = 0, kk = pa.length; k < kk; k++) { r[k] = pa[k]; } } @@ -803,18 +801,18 @@ function pathToAbsolute(pathArray) { } function path2curve(path, path2) { - var p = pathToAbsolute(path), + const p = pathToAbsolute(path), p2 = path2 && pathToAbsolute(path2); - var attrs = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }; - var attrs2 = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }; - var pcoms1 = []; // path commands of original path p - var pcoms2 = []; // path commands of original path p2 - var ii; - - var processPath = function(path, d, pcom) { - var nx, - ny, - tq = { T: 1, Q: 1 }; + const attrs = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }; + const attrs2 = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }; + const pcoms1 = []; // path commands of original path p + const pcoms2 = []; // path commands of original path p2 + let ii; + + const processPath = (path, d, pcom) => { + let nx; + let ny; + const tq = { T: 1, Q: 1 }; if (!path) { return ['C', d.x, d.y, d.x, d.y, d.x, d.y]; } @@ -871,10 +869,10 @@ function path2curve(path, path2) { } return path; }, - fixArc = function(pp, i) { + fixArc = (pp, i) => { if (pp[i].length > 7) { pp[i].shift(); - var pi = pp[i]; + const pi = pp[i]; while (pi.length) { pcoms1[i] = 'A'; if (p2) { @@ -886,7 +884,7 @@ function path2curve(path, path2) { ii = Math.max(p.length, (p2 && p2.length) || 0); } }, - fixM = function(path1, path2, a1, a2, i) { + fixM = (path1, path2, a1, a2, i) => { if (path1 && path2 && path1[i][0] === 'M' && path2[i][0] !== 'M') { path2.splice(i, 0, ['M', a2.x, a2.y]); a1.bx = 0; @@ -897,11 +895,11 @@ function path2curve(path, path2) { } }; - var pfirst = ''; // temporary holder for original path command - var pcom = ''; // holder for previous path command of original path + let pfirst = ''; // temporary holder for original path command + let pcom = ''; // holder for previous path command of original path ii = Math.max(p.length, (p2 && p2.length) || 0); - for (var i = 0; i < ii; i++) { + for (let i = 0; i < ii; i++) { if (p[i]) { pfirst = p[i][0]; } // save current path command @@ -941,7 +939,7 @@ function path2curve(path, path2) { } fixM(p, p2, attrs, attrs2, i); fixM(p2, p, attrs2, attrs, i); - var seg = p[i], + const seg = p[i], seg2 = p2 && p2[i], seglen = seg.length, seg2len = p2 && seg2.length; @@ -961,20 +959,23 @@ function path2curve(path, path2) { function a2c(x1, y1, rx, ry, angle, lac, sweep_flag, x2, y2, recursive) { // for more information of where this Math came from visit: // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes - var PI = Math.PI, - _120 = PI * 120 / 180, - f1, - f2, - cx, - cy, - rad = PI / 180 * (+angle || 0), - res = [], - xy, - rotate = function(x, y, rad) { - var X = x * Math.cos(rad) - y * Math.sin(rad), - Y = x * Math.sin(rad) + y * Math.cos(rad); - return { x: X, y: Y }; - }; + const PI = Math.PI; + + const _120 = PI * 120 / 180; + let f1; + let f2; + let cx; + let cy; + const rad = PI / 180 * (+angle || 0); + let res = []; + let xy; + + const rotate = (x, y, rad) => { + const X = x * Math.cos(rad) - y * Math.sin(rad), + Y = x * Math.sin(rad) + y * Math.cos(rad); + return { x: X, y: Y }; + }; + if (!recursive) { xy = rotate(x1, y1, -rad); x1 = xy.x; @@ -982,17 +983,17 @@ function a2c(x1, y1, rx, ry, angle, lac, sweep_flag, x2, y2, recursive) { xy = rotate(x2, y2, -rad); x2 = xy.x; y2 = xy.y; - var x = (x1 - x2) / 2, - y = (y1 - y2) / 2, - h = x * x / (rx * rx) + y * y / (ry * ry); + const x = (x1 - x2) / 2; + const y = (y1 - y2) / 2; + let h = x * x / (rx * rx) + y * y / (ry * ry); if (h > 1) { h = Math.sqrt(h); rx = h * rx; ry = h * ry; } - var rx2 = rx * rx, + const rx2 = rx * rx, ry2 = ry * ry; - var k = + const k = (lac === sweep_flag ? -1 : 1) * Math.sqrt( Math.abs( @@ -1027,9 +1028,9 @@ function a2c(x1, y1, rx, ry, angle, lac, sweep_flag, x2, y2, recursive) { cx = recursive[2]; cy = recursive[3]; } - var df = f2 - f1; + let df = f2 - f1; if (Math.abs(df) > _120) { - var f2old = f2, + const f2old = f2, x2old = x2, y2old = y2; f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1); @@ -1043,7 +1044,7 @@ function a2c(x1, y1, rx, ry, angle, lac, sweep_flag, x2, y2, recursive) { ]); } df = f2 - f1; - var c1 = Math.cos(f1), + const c1 = Math.cos(f1), s1 = Math.sin(f1), c2 = Math.cos(f2), s2 = Math.sin(f2), @@ -1063,8 +1064,8 @@ function a2c(x1, y1, rx, ry, angle, lac, sweep_flag, x2, y2, recursive) { .concat(res) .join() .split(','); - var newres = []; - for (var i = 0, ii = res.length; i < ii; i++) { + const newres = []; + for (let i = 0, ii = res.length; i < ii; i++) { newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y @@ -1076,9 +1077,9 @@ function a2c(x1, y1, rx, ry, angle, lac, sweep_flag, x2, y2, recursive) { // http://schepers.cc/getting-to-the-point function catmullRom2bezier(crp, z) { - var d = []; - for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { - var p = [ + const d = []; + for (let i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { + const p = [ { x: +crp[i - 2], y: +crp[i - 1] @@ -1146,7 +1147,7 @@ function l2c(x1, y1, x2, y2) { } function q2c(x1, y1, ax, ay, x2, y2) { - var _13 = 1 / 3, + const _13 = 1 / 3, _23 = 2 / 3; return [ _13 * x1 + _23 * ax, @@ -1163,9 +1164,9 @@ function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { z = 1; } z = z > 1 ? 1 : z < 0 ? 0 : z; - var z2 = z / 2; - var n = 12; - var Tvalues = [ + const z2 = z / 2; + const n = 12; + const Tvalues = [ -0.1252, 0.1252, -0.3678, @@ -1180,8 +1181,8 @@ function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { 0.9816 ]; - var sum = 0; - var Cvalues = [ + let sum = 0; + const Cvalues = [ 0.2491, 0.2491, 0.2335, @@ -1196,8 +1197,8 @@ function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { 0.0472 ]; - for (var i = 0; i < n; i++) { - var ct = z2 * Tvalues[i] + z2, + for (let i = 0; i < n; i++) { + const ct = z2 * Tvalues[i] + z2, xbase = base3(ct, x1, x2, x3, x4), ybase = base3(ct, y1, y2, y3, y4), comb = xbase * xbase + ybase * ybase; @@ -1210,11 +1211,11 @@ function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) { if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) { return; } - var t = 1, - step = t / 2, - t2 = t - step, - l, - e = 0.01; + const t = 1; + let step = t / 2; + let t2 = t - step; + let l; + const e = 0.01; l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); while (Math.abs(l - ll) > e) { step /= 2; @@ -1225,17 +1226,17 @@ function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) { } function base3(t, p1, p2, p3, p4) { - var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4, + const t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4, t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; return t * t2 - 3 * p1 + 3 * p2; } -function cacheKey() { - var hash = ''; - for (var i = arguments.length - 1; i >= 0; --i) { - hash += '?' + arguments[i]; +function cacheKey(...args) { + let hash = ''; + for (let i = args.length - 1; i >= 0; --i) { + hash += `?${args[i]}`; } return hash; } -module.exports = p5; +export default p5; diff --git a/src/utilities/array_functions.js b/src/utilities/array_functions.js index 3ad8d7f9dc..eb8e7353b8 100644 --- a/src/utilities/array_functions.js +++ b/src/utilities/array_functions.js @@ -5,9 +5,7 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * Adds a value to the end of an array. Extends the length of @@ -21,7 +19,7 @@ var p5 = require('../core/main'); * @example *
* function setup() { - * var myArray = ['Mango', 'Apple', 'Papaya']; + * const myArray = ['Mango', 'Apple', 'Papaya']; * print(myArray); // ['Mango', 'Apple', 'Papaya'] * * append(myArray, 'Peach'); @@ -29,7 +27,7 @@ var p5 = require('../core/main'); * } *
*/ -p5.prototype.append = function(array, value) { +p5.prototype.append = (array, value) => { array.push(value); return array; }; @@ -59,11 +57,11 @@ p5.prototype.append = function(array, value) { * * @example *
- * var src = ['A', 'B', 'C']; - * var dst = [1, 2, 3]; - * var srcPosition = 1; - * var dstPosition = 0; - * var length = 2; + * let src = ['A', 'B', 'C']; + * let dst = [1, 2, 3]; + * let srcPosition = 1; + * let dstPosition = 0; + * let length = 2; * * print(src); // ['A', 'B', 'C'] * print(dst); // [ 1 , 2 , 3 ] @@ -79,10 +77,10 @@ p5.prototype.append = function(array, value) { * @param {Array} dst * @param {Integer} [length] */ -p5.prototype.arrayCopy = function(src, srcPosition, dst, dstPosition, length) { +p5.prototype.arrayCopy = (src, srcPosition, dst, dstPosition, length) => { // the index to begin splicing from dst array - var start; - var end; + let start; + let end; if (typeof length !== 'undefined') { end = Math.min(length, src.length); @@ -124,13 +122,13 @@ p5.prototype.arrayCopy = function(src, srcPosition, dst, dstPosition, length) { * @example *
* function setup() { - * var arr1 = ['A', 'B', 'C']; - * var arr2 = [1, 2, 3]; + * let arr1 = ['A', 'B', 'C']; + * let arr2 = [1, 2, 3]; * * print(arr1); // ['A','B','C'] * print(arr2); // [1,2,3] * - * var arr3 = concat(arr1, arr2); + * let arr3 = concat(arr1, arr2); * * print(arr1); // ['A','B','C'] * print(arr2); // [1, 2, 3] @@ -138,9 +136,7 @@ p5.prototype.arrayCopy = function(src, srcPosition, dst, dstPosition, length) { * } *
*/ -p5.prototype.concat = function(list0, list1) { - return list0.concat(list1); -}; +p5.prototype.concat = (list0, list1) => list0.concat(list1); /** * Reverses the order of an array, maps to Array.reverse() @@ -152,7 +148,7 @@ p5.prototype.concat = function(list0, list1) { * @example *
* function setup() { - * var myArray = ['A', 'B', 'C']; + * let myArray = ['A', 'B', 'C']; * print(myArray); // ['A','B','C'] * * reverse(myArray); @@ -160,9 +156,7 @@ p5.prototype.concat = function(list0, list1) { * } *
*/ -p5.prototype.reverse = function(list) { - return list.reverse(); -}; +p5.prototype.reverse = list => list.reverse(); /** * Decreases an array by one element and returns the shortened array, @@ -175,15 +169,15 @@ p5.prototype.reverse = function(list) { * @example *
* function setup() { - * var myArray = ['A', 'B', 'C']; + * let myArray = ['A', 'B', 'C']; * print(myArray); // ['A', 'B', 'C'] - * var newArray = shorten(myArray); + * let newArray = shorten(myArray); * print(myArray); // ['A','B','C'] * print(newArray); // ['A','B'] * } *
*/ -p5.prototype.shorten = function(list) { +p5.prototype.shorten = list => { list.pop(); return list; }; @@ -200,23 +194,23 @@ p5.prototype.shorten = function(list) { * @example *
* function setup() { - * var regularArr = ['ABC', 'def', createVector(), TAU, Math.E]; + * let regularArr = ['ABC', 'def', createVector(), TAU, Math.E]; * print(regularArr); * shuffle(regularArr, true); // force modifications to passed array * print(regularArr); * * // By default shuffle() returns a shuffled cloned array: - * var newArr = shuffle(regularArr); + * let newArr = shuffle(regularArr); * print(regularArr); * print(newArr); * } *
*/ -p5.prototype.shuffle = function(arr, bool) { - var isView = ArrayBuffer && ArrayBuffer.isView && ArrayBuffer.isView(arr); +p5.prototype.shuffle = (arr, bool) => { + const isView = ArrayBuffer && ArrayBuffer.isView && ArrayBuffer.isView(arr); arr = bool || isView ? arr : arr.slice(); - var rnd, + let rnd, tmp, idx = arr.length; while (idx > 1) { @@ -246,9 +240,9 @@ p5.prototype.shuffle = function(arr, bool) { * @example *
* function setup() { - * var words = ['banana', 'apple', 'pear', 'lime']; + * let words = ['banana', 'apple', 'pear', 'lime']; * print(words); // ['banana', 'apple', 'pear', 'lime'] - * var count = 4; // length of array + * let count = 4; // length of array * * words = sort(words, count); * print(words); // ['apple', 'banana', 'lime', 'pear'] @@ -256,24 +250,22 @@ p5.prototype.shuffle = function(arr, bool) { *
*
* function setup() { - * var numbers = [2, 6, 1, 5, 14, 9, 8, 12]; + * let numbers = [2, 6, 1, 5, 14, 9, 8, 12]; * print(numbers); // [2, 6, 1, 5, 14, 9, 8, 12] - * var count = 5; // Less than the length of the array + * let count = 5; // Less than the length of the array * * numbers = sort(numbers, count); * print(numbers); // [1,2,5,6,14,9,8,12] * } *
*/ -p5.prototype.sort = function(list, count) { - var arr = count ? list.slice(0, Math.min(count, list.length)) : list; - var rest = count ? list.slice(Math.min(count, list.length)) : []; +p5.prototype.sort = (list, count) => { + let arr = count ? list.slice(0, Math.min(count, list.length)) : list; + const rest = count ? list.slice(Math.min(count, list.length)) : []; if (typeof arr[0] === 'string') { arr = arr.sort(); } else { - arr = arr.sort(function(a, b) { - return a - b; - }); + arr = arr.sort((a, b) => a - b); } return arr.concat(rest); }; @@ -296,8 +288,8 @@ p5.prototype.sort = function(list, count) { * @example *
* function setup() { - * var myArray = [0, 1, 2, 3, 4]; - * var insArray = ['A', 'B', 'C']; + * let myArray = [0, 1, 2, 3, 4]; + * let insArray = ['A', 'B', 'C']; * print(myArray); // [0, 1, 2, 3, 4] * print(insArray); // ['A','B','C'] * @@ -306,7 +298,7 @@ p5.prototype.sort = function(list, count) { * } *
*/ -p5.prototype.splice = function(list, value, index) { +p5.prototype.splice = (list, value, index) => { // note that splice returns spliced elements and not an array Array.prototype.splice.apply(list, [index, 0].concat(value)); @@ -331,17 +323,17 @@ p5.prototype.splice = function(list, value, index) { * @example *
* function setup() { - * var myArray = [1, 2, 3, 4, 5]; + * let myArray = [1, 2, 3, 4, 5]; * print(myArray); // [1, 2, 3, 4, 5] * - * var sub1 = subset(myArray, 0, 3); - * var sub2 = subset(myArray, 2, 2); + * let sub1 = subset(myArray, 0, 3); + * let sub2 = subset(myArray, 2, 2); * print(sub1); // [1,2,3] * print(sub2); // [3,4] * } *
*/ -p5.prototype.subset = function(list, start, count) { +p5.prototype.subset = (list, start, count) => { if (typeof count !== 'undefined') { return list.slice(start, start + count); } else { @@ -349,4 +341,4 @@ p5.prototype.subset = function(list, start, count) { } }; -module.exports = p5; +export default p5; diff --git a/src/utilities/conversion.js b/src/utilities/conversion.js index 11e5c77191..1a98acbc4d 100644 --- a/src/utilities/conversion.js +++ b/src/utilities/conversion.js @@ -5,9 +5,7 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * Converts a string to its floating point representation. The contents of a @@ -23,8 +21,8 @@ var p5 = require('../core/main'); * @return {Number} floating point representation of string * @example *
- * var str = '20'; - * var diameter = float(str); + * let str = '20'; + * let diameter = float(str); * ellipse(width / 2, height / 2, diameter, diameter); *
*
@@ -37,7 +35,7 @@ var p5 = require('../core/main'); * 20 by 20 white ellipse in the center of the canvas * */ -p5.prototype.float = function(str) { +p5.prototype.float = str => { if (str instanceof Array) { return str.map(parseFloat); } @@ -71,8 +69,7 @@ p5.prototype.float = function(str) { * @param {Array} ns values to parse * @return {Number[]} integer representation of values */ -p5.prototype.int = function(n, radix) { - radix = radix || 10; +p5.prototype.int = (n, radix = 10) => { if (n === Infinity || n === 'Infinity') { return Infinity; } else if (n === -Infinity || n === '-Infinity') { @@ -84,9 +81,7 @@ p5.prototype.int = function(n, radix) { } else if (typeof n === 'boolean') { return n ? 1 : 0; } else if (n instanceof Array) { - return n.map(function(n) { - return p5.prototype.int(n, radix); - }); + return n.map(n => p5.prototype.int(n, radix)); } }; @@ -108,7 +103,7 @@ p5.prototype.int = function(n, radix) { * print(str([true, '10.3', 9.8])); // [ "true", "10.3", "9.8" ] *
*/ -p5.prototype.str = function(n) { +p5.prototype.str = n => { if (n instanceof Array) { return n.map(p5.prototype.str); } else { @@ -136,7 +131,7 @@ p5.prototype.str = function(n) { * print(boolean([0, 12, 'true'])); // [false, true, true] *
*/ -p5.prototype.boolean = function(n) { +p5.prototype.boolean = n => { if (typeof n === 'number') { return n !== 0; } else if (typeof n === 'string') { @@ -175,8 +170,8 @@ p5.prototype.boolean = function(n) { * @param {Array} ns values to parse * @return {Number[]} array of byte representation of values */ -p5.prototype.byte = function(n) { - var nn = p5.prototype.int(n, 10); +p5.prototype.byte = n => { + const nn = p5.prototype.int(n, 10); if (typeof nn === 'number') { return (nn + 128) % 256 - 128; } else if (nn instanceof Array) { @@ -208,7 +203,7 @@ p5.prototype.byte = function(n) { * @param {Array} ns values to parse * @return {String[]} array of string representation of values */ -p5.prototype.char = function(n) { +p5.prototype.char = n => { if (typeof n === 'number' && !isNaN(n)) { return String.fromCharCode(n); } else if (n instanceof Array) { @@ -239,7 +234,7 @@ p5.prototype.char = function(n) { * @param {Array} ns values to parse * @return {Number[]} integer representation of values */ -p5.prototype.unchar = function(n) { +p5.prototype.unchar = n => { if (typeof n === 'string' && n.length === 1) { return n.charCodeAt(0); } else if (n instanceof Array) { @@ -273,24 +268,22 @@ p5.prototype.unchar = function(n) { * @param {Number} [digits] * @return {String[]} hexadecimal string representation of values */ -p5.prototype.hex = function(n, digits) { +p5.prototype.hex = (n, digits) => { digits = digits === undefined || digits === null ? (digits = 8) : digits; if (n instanceof Array) { - return n.map(function(n) { - return p5.prototype.hex(n, digits); - }); + return n.map(n => p5.prototype.hex(n, digits)); } else if (n === Infinity || n === -Infinity) { - var c = n === Infinity ? 'F' : '0'; + const c = n === Infinity ? 'F' : '0'; return c.repeat(digits); } else if (typeof n === 'number') { if (n < 0) { n = 0xffffffff + n + 1; } - var hex = Number(n) + let hex = Number(n) .toString(16) .toUpperCase(); while (hex.length < digits) { - hex = '0' + hex; + hex = `0${hex}`; } if (hex.length >= digits) { hex = hex.substring(hex.length - digits, hex.length); @@ -320,12 +313,12 @@ p5.prototype.hex = function(n, digits) { * @param {Array} ns values to parse * @return {Number[]} integer representations of hexadecimal value */ -p5.prototype.unhex = function(n) { +p5.prototype.unhex = n => { if (n instanceof Array) { return n.map(p5.prototype.unhex); } else { - return parseInt('0x' + n, 16); + return parseInt(`0x${n}`, 16); } }; -module.exports = p5; +export default p5; diff --git a/src/utilities/string_functions.js b/src/utilities/string_functions.js index 4d6c30f7e7..123d3c3ba2 100644 --- a/src/utilities/string_functions.js +++ b/src/utilities/string_functions.js @@ -5,10 +5,8 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); -require('../core/error_helpers'); +import p5 from '../core/main'; +import '../core/error_helpers'; //return p5; //LM is this a mistake? @@ -25,9 +23,9 @@ require('../core/error_helpers'); * @example *
* - * var array = ['Hello', 'world!']; - * var separator = ' '; - * var message = join(array, separator); + * let array = ['Hello', 'world!']; + * let separator = ' '; + * let message = join(array, separator); * text(message, 5, 50); * *
@@ -66,9 +64,9 @@ p5.prototype.join = function(list, separator) { * @example *
* - * var string = 'Hello p5js*!'; - * var regexp = 'p5js\\*'; - * var m = match(string, regexp); + * const string = 'Hello p5js*!'; + * const regexp = 'p5js\\*'; + * let m = match(string, regexp); * text(m, 5, 50); * *
@@ -108,17 +106,17 @@ p5.prototype.match = function(str, reg) { * @example *
* - * var string = 'Hello p5js*! Hello world!'; - * var regexp = 'Hello'; + * const string = 'Hello p5js*! Hello world!'; + * const regexp = 'Hello'; * matchAll(string, regexp); * *
*/ p5.prototype.matchAll = function(str, reg) { p5._validateParameters('matchAll', arguments); - var re = new RegExp(reg, 'g'); - var match = re.exec(str); - var matches = []; + const re = new RegExp(reg, 'g'); + let match = re.exec(str); + const matches = []; while (match !== null) { matches.push(match); // matched text: match[0] @@ -151,14 +149,14 @@ p5.prototype.matchAll = function(str, reg) { * @example *
* - * var myFont; + * let myFont; * function preload() { * myFont = loadFont('assets/fonts/inconsolata.ttf'); * } * function setup() { * background(200); - * var num1 = 321; - * var num2 = -1321; + * let num1 = 321; + * let num2 = -1321; * * noStroke(); * fill(0); @@ -187,11 +185,9 @@ p5.prototype.matchAll = function(str, reg) { p5.prototype.nf = function(nums, left, right) { p5._validateParameters('nf', arguments); if (nums instanceof Array) { - return nums.map(function(x) { - return doNf(x, left, right); - }); + return nums.map(x => doNf(x, left, right)); } else { - var typeOfFirst = Object.prototype.toString.call(nums); + const typeOfFirst = Object.prototype.toString.call(nums); if (typeOfFirst === '[object Arguments]') { if (nums.length === 3) { return this.nf(nums[0], nums[1], nums[2]); @@ -207,32 +203,32 @@ p5.prototype.nf = function(nums, left, right) { }; function doNf(num, left, right) { - var neg = num < 0; - var n = neg ? num.toString().substring(1) : num.toString(); - var decimalInd = n.indexOf('.'); - var intPart = decimalInd !== -1 ? n.substring(0, decimalInd) : n; - var decPart = decimalInd !== -1 ? n.substring(decimalInd + 1) : ''; - var str = neg ? '-' : ''; + const neg = num < 0; + const n = neg ? num.toString().substring(1) : num.toString(); + const decimalInd = n.indexOf('.'); + const intPart = decimalInd !== -1 ? n.substring(0, decimalInd) : n; + let decPart = decimalInd !== -1 ? n.substring(decimalInd + 1) : ''; + let str = neg ? '-' : ''; if (typeof right !== 'undefined') { - var decimal = ''; + let decimal = ''; if (decimalInd !== -1 || right - decPart.length > 0) { decimal = '.'; } if (decPart.length > right) { decPart = decPart.substring(0, right); } - for (var i = 0; i < left - intPart.length; i++) { + for (let i = 0; i < left - intPart.length; i++) { str += '0'; } str += intPart; str += decimal; str += decPart; - for (var j = 0; j < right - decPart.length; j++) { + for (let j = 0; j < right - decPart.length; j++) { str += '0'; } return str; } else { - for (var k = 0; k < Math.max(left - intPart.length, 0); k++) { + for (let k = 0; k < Math.max(left - intPart.length, 0); k++) { str += '0'; } str += n; @@ -257,8 +253,8 @@ function doNf(num, left, right) { * * function setup() { * background(200); - * var num = 11253106.115; - * var numArr = [1, 1, 2]; + * let num = 11253106.115; + * let numArr = [1, 1, 2]; * * noStroke(); * fill(0); @@ -287,26 +283,24 @@ function doNf(num, left, right) { p5.prototype.nfc = function(num, right) { p5._validateParameters('nfc', arguments); if (num instanceof Array) { - return num.map(function(x) { - return doNfc(x, right); - }); + return num.map(x => doNfc(x, right)); } else { return doNfc(num, right); } }; function doNfc(num, right) { num = num.toString(); - var dec = num.indexOf('.'); - var rem = dec !== -1 ? num.substring(dec) : ''; - var n = dec !== -1 ? num.substring(0, dec) : num; + const dec = num.indexOf('.'); + let rem = dec !== -1 ? num.substring(dec) : ''; + let n = dec !== -1 ? num.substring(0, dec) : num; n = n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); if (right === 0) { rem = ''; } else if (typeof right !== 'undefined') { if (right > rem.length) { rem += dec === -1 ? '.' : ''; - var len = right - rem.length + 1; - for (var i = 0; i < len; i++) { + const len = right - rem.length + 1; + for (let i = 0; i < len; i++) { rem += '0'; } } else { @@ -336,8 +330,8 @@ function doNfc(num, right) { * * function setup() { * background(200); - * var num1 = 11253106.115; - * var num2 = -11253106.115; + * let num1 = 11253106.115; + * let num2 = -11253106.115; * * noStroke(); * fill(0); @@ -364,9 +358,9 @@ function doNfc(num, right) { * @param {Integer} [right] * @return {String[]} formatted Strings */ -p5.prototype.nfp = function() { - p5._validateParameters('nfp', arguments); - var nfRes = p5.prototype.nf.apply(this, arguments); +p5.prototype.nfp = function(...args) { + p5._validateParameters('nfp', args); + const nfRes = p5.prototype.nf.apply(this, args); if (nfRes instanceof Array) { return nfRes.map(addNfp); } else { @@ -375,7 +369,7 @@ p5.prototype.nfp = function() { }; function addNfp(num) { - return parseFloat(num) > 0 ? '+' + num.toString() : num.toString(); + return parseFloat(num) > 0 ? `+${num.toString()}` : num.toString(); } /** @@ -404,14 +398,14 @@ function addNfp(num) { * @example *
* - * var myFont; + * let myFont; * function preload() { * myFont = loadFont('assets/fonts/inconsolata.ttf'); * } * function setup() { * background(200); - * var num1 = 321; - * var num2 = -1321; + * let num1 = 321; + * let num2 = -1321; * * noStroke(); * fill(0); @@ -442,9 +436,9 @@ function addNfp(num) { * @param {Integer} [right] * @return {String[]} formatted Strings */ -p5.prototype.nfs = function() { - p5._validateParameters('nfs', arguments); - var nfRes = p5.prototype.nf.apply(this, arguments); +p5.prototype.nfs = function(...args) { + p5._validateParameters('nfs', args); + const nfRes = p5.prototype.nf.apply(this, args); if (nfRes instanceof Array) { return nfRes.map(addNfs); } else { @@ -453,7 +447,7 @@ p5.prototype.nfs = function() { }; function addNfs(num) { - return parseFloat(num) >= 0 ? ' ' + num.toString() : num.toString(); + return parseFloat(num) >= 0 ? ` ${num.toString()}` : num.toString(); } /** @@ -473,8 +467,8 @@ function addNfs(num) { * @example *
* - * var names = 'Pat,Xio,Alex'; - * var splitString = split(names, ','); + * const names = 'Pat,Xio,Alex'; + * let splitString = split(names, ','); * text(splitString[0], 5, 30); * text(splitString[1], 5, 50); * text(splitString[2], 5, 70); @@ -508,8 +502,8 @@ p5.prototype.split = function(str, delim) { *
* * function setup() { - * var myStr = 'Mango, Banana, Lime'; - * var myStrArr = splitTokens(myStr, ','); + * const myStr = 'Mango, Banana, Lime'; + * let myStrArr = splitTokens(myStr, ','); * * print(myStrArr); // prints : ["Mango"," Banana"," Lime"] * } @@ -518,31 +512,29 @@ p5.prototype.split = function(str, delim) { */ p5.prototype.splitTokens = function(value, delims) { p5._validateParameters('splitTokens', arguments); - var d; + let d; if (typeof delims !== 'undefined') { - var str = delims; - var sqc = /\]/g.exec(str); - var sqo = /\[/g.exec(str); + let str = delims; + const sqc = /\]/g.exec(str); + let sqo = /\[/g.exec(str); if (sqo && sqc) { str = str.slice(0, sqc.index) + str.slice(sqc.index + 1); sqo = /\[/g.exec(str); str = str.slice(0, sqo.index) + str.slice(sqo.index + 1); - d = new RegExp('[\\[' + str + '\\]]', 'g'); + d = new RegExp(`[\\[${str}\\]]`, 'g'); } else if (sqc) { str = str.slice(0, sqc.index) + str.slice(sqc.index + 1); - d = new RegExp('[' + str + '\\]]', 'g'); + d = new RegExp(`[${str}\\]]`, 'g'); } else if (sqo) { str = str.slice(0, sqo.index) + str.slice(sqo.index + 1); - d = new RegExp('[' + str + '\\[]', 'g'); + d = new RegExp(`[${str}\\[]`, 'g'); } else { - d = new RegExp('[' + str + ']', 'g'); + d = new RegExp(`[${str}]`, 'g'); } } else { d = /\s/g; } - return value.split(d).filter(function(n) { - return n; - }); + return value.split(d).filter(n => n); }; /** @@ -557,7 +549,7 @@ p5.prototype.splitTokens = function(value, delims) { * @example *
* - * var string = trim(' No new lines\n '); + * let string = trim(' No new lines\n '); * text(string + ' here', 2, 50); * *
@@ -579,4 +571,4 @@ p5.prototype.trim = function(str) { } }; -module.exports = p5; +export default p5; diff --git a/src/utilities/time_date.js b/src/utilities/time_date.js index 75e82d257c..cfbb47d1a2 100644 --- a/src/utilities/time_date.js +++ b/src/utilities/time_date.js @@ -5,9 +5,7 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * p5.js communicates with the clock on your computer. The day() function @@ -18,7 +16,7 @@ var p5 = require('../core/main'); * @example *
* - * var d = day(); + * let d = day(); * text('Current day: \n' + d, 5, 50); * *
@@ -27,9 +25,7 @@ var p5 = require('../core/main'); * Current day is displayed * */ -p5.prototype.day = function() { - return new Date().getDate(); -}; +p5.prototype.day = () => new Date().getDate(); /** * p5.js communicates with the clock on your computer. The hour() function @@ -40,7 +36,7 @@ p5.prototype.day = function() { * @example *
* - * var h = hour(); + * let h = hour(); * text('Current hour:\n' + h, 5, 50); * *
@@ -49,9 +45,7 @@ p5.prototype.day = function() { * Current hour is displayed * */ -p5.prototype.hour = function() { - return new Date().getHours(); -}; +p5.prototype.hour = () => new Date().getHours(); /** * p5.js communicates with the clock on your computer. The minute() function @@ -62,7 +56,7 @@ p5.prototype.hour = function() { * @example *
* - * var m = minute(); + * let m = minute(); * text('Current minute: \n' + m, 5, 50); * *
@@ -71,9 +65,7 @@ p5.prototype.hour = function() { * Current minute is displayed * */ -p5.prototype.minute = function() { - return new Date().getMinutes(); -}; +p5.prototype.minute = () => new Date().getMinutes(); /** * Returns the number of milliseconds (thousandths of a second) since @@ -85,7 +77,7 @@ p5.prototype.minute = function() { * @example *
* - * var millisecond = millis(); + * let millisecond = millis(); * text('Milliseconds \nrunning: \n' + millisecond, 5, 40); * *
@@ -94,9 +86,7 @@ p5.prototype.minute = function() { * number of milliseconds since program has started displayed * */ -p5.prototype.millis = function() { - return window.performance.now(); -}; +p5.prototype.millis = () => window.performance.now(); /** * p5.js communicates with the clock on your computer. The month() function @@ -107,7 +97,7 @@ p5.prototype.millis = function() { * @example *
* - * var m = month(); + * let m = month(); * text('Current month: \n' + m, 5, 50); * *
@@ -116,9 +106,9 @@ p5.prototype.millis = function() { * Current month is displayed * */ -p5.prototype.month = function() { - return new Date().getMonth() + 1; //January is 0! -}; +p5.prototype.month = () => + //January is 0! + new Date().getMonth() + 1; /** * p5.js communicates with the clock on your computer. The second() function @@ -129,7 +119,7 @@ p5.prototype.month = function() { * @example *
* - * var s = second(); + * let s = second(); * text('Current second: \n' + s, 5, 50); * *
@@ -138,9 +128,7 @@ p5.prototype.month = function() { * Current second is displayed * */ -p5.prototype.second = function() { - return new Date().getSeconds(); -}; +p5.prototype.second = () => new Date().getSeconds(); /** * p5.js communicates with the clock on your computer. The year() function @@ -151,7 +139,7 @@ p5.prototype.second = function() { * @example *
* - * var y = year(); + * let y = year(); * text('Current year: \n' + y, 5, 50); * *
@@ -160,8 +148,6 @@ p5.prototype.second = function() { * Current year is displayed * */ -p5.prototype.year = function() { - return new Date().getFullYear(); -}; +p5.prototype.year = () => new Date().getFullYear(); -module.exports = p5; +export default p5; diff --git a/src/webgl/3d_primitives.js b/src/webgl/3d_primitives.js index 68f53346a7..a667813998 100644 --- a/src/webgl/3d_primitives.js +++ b/src/webgl/3d_primitives.js @@ -6,10 +6,9 @@ * @requires p5.Geometry */ -'use strict'; -var p5 = require('../core/main'); -require('./p5.Geometry'); -var constants = require('../core/constants'); +import p5 from '../core/main'; +import './p5.Geometry'; +import * as constants from '../core/constants'; /** * Draw a plane with given a width and height @@ -63,14 +62,14 @@ p5.prototype.plane = function(width, height, detailX, detailY) { detailY = 1; } - var gId = 'plane|' + detailX + '|' + detailY; + const gId = `plane|${detailX}|${detailY}`; if (!this._renderer.geometryInHash(gId)) { - var _plane = function() { - var u, v, p; - for (var i = 0; i <= this.detailY; i++) { + const _plane = function() { + let u, v, p; + for (let i = 0; i <= this.detailY; i++) { v = i / this.detailY; - for (var j = 0; j <= this.detailX; j++) { + for (let j = 0; j <= this.detailX; j++) { u = j / this.detailX; p = new p5.Vector(u - 0.5, v - 0.5, 0); this.vertices.push(p); @@ -78,7 +77,7 @@ p5.prototype.plane = function(width, height, detailX, detailY) { } } }; - var planeGeom = new p5.Geometry(detailX, detailY, _plane); + const planeGeom = new p5.Geometry(detailX, detailY, _plane); planeGeom.computeFaces().computeNormals(); if (detailX <= 1 && detailY <= 1) { planeGeom._makeTriangleEdges()._edgesToVertices(); @@ -137,7 +136,7 @@ p5.prototype.box = function(width, height, depth, detailX, detailY) { depth = height; } - var perPixelLighting = + const perPixelLighting = this._renderer.attributes && this._renderer.attributes.perPixelLighting; if (typeof detailX === 'undefined') { detailX = perPixelLighting ? 1 : 4; @@ -146,10 +145,10 @@ p5.prototype.box = function(width, height, depth, detailX, detailY) { detailY = perPixelLighting ? 1 : 4; } - var gId = 'box|' + detailX + '|' + detailY; + const gId = `box|${detailX}|${detailY}`; if (!this._renderer.geometryInHash(gId)) { - var _box = function() { - var cubeIndices = [ + const _box = function() { + const cubeIndices = [ [0, 4, 2, 6], // -1, 0, 0],// -x [1, 3, 5, 7], // +1, 0, 0],// +x [0, 1, 4, 5], // 0, -1, 0],// -y @@ -173,15 +172,15 @@ p5.prototype.box = function(width, height, depth, detailX, detailY) { [20, 21], [22, 23] ]; - for (var i = 0; i < cubeIndices.length; i++) { - var cubeIndex = cubeIndices[i]; - var v = i * 4; - for (var j = 0; j < 4; j++) { - var d = cubeIndex[j]; + for (let i = 0; i < cubeIndices.length; i++) { + const cubeIndex = cubeIndices[i]; + const v = i * 4; + for (let j = 0; j < 4; j++) { + const d = cubeIndex[j]; //inspired by lightgl: //https://github.com/evanw/lightgl.js //octants:https://en.wikipedia.org/wiki/Octant_(solid_geometry) - var octant = new p5.Vector( + const octant = new p5.Vector( ((d & 1) * 2 - 1) / 2, ((d & 2) - 1) / 2, ((d & 4) / 2 - 1) / 2 @@ -193,7 +192,7 @@ p5.prototype.box = function(width, height, depth, detailX, detailY) { this.faces.push([v + 2, v + 1, v + 3]); } }; - var boxGeom = new p5.Geometry(detailX, detailY, _box); + const boxGeom = new p5.Geometry(detailX, detailY, _box); boxGeom.computeNormals(); if (detailX <= 4 && detailY <= 4) { boxGeom._makeTriangleEdges()._edgesToVertices(); @@ -264,7 +263,7 @@ p5.prototype.sphere = function(radius, detailX, detailY) { * and topRadius >= 0 * If topRadius == 0, topCap should be false */ -var _truncatedCone = function( +const _truncatedCone = function( bottomRadius, topRadius, height, @@ -280,17 +279,17 @@ var _truncatedCone = function( detailY = detailY < 1 ? 1 : detailY; bottomCap = bottomCap === undefined ? true : bottomCap; topCap = topCap === undefined ? topRadius !== 0 : topCap; - var start = bottomCap ? -2 : 0; - var end = detailY + (topCap ? 2 : 0); + const start = bottomCap ? -2 : 0; + const end = detailY + (topCap ? 2 : 0); //ensure constant slant for interior vertex normals - var slant = Math.atan2(bottomRadius - topRadius, height); - var sinSlant = Math.sin(slant); - var cosSlant = Math.cos(slant); - var yy, ii, jj; + const slant = Math.atan2(bottomRadius - topRadius, height); + const sinSlant = Math.sin(slant); + const cosSlant = Math.cos(slant); + let yy, ii, jj; for (yy = start; yy <= end; ++yy) { - var v = yy / detailY; - var y = height * v; - var ringRadius; + let v = yy / detailY; + let y = height * v; + let ringRadius; if (yy < 0) { //for the bottomCap edge y = 0; @@ -312,16 +311,16 @@ var _truncatedCone = function( y -= height / 2; //shift coordiate origin to the center of object for (ii = 0; ii < detailX; ++ii) { - var u = ii / detailX; - var ur = 2 * Math.PI * u; - var sur = Math.sin(ur); - var cur = Math.cos(ur); + const u = ii / detailX; + const ur = 2 * Math.PI * u; + const sur = Math.sin(ur); + const cur = Math.cos(ur); //VERTICES this.vertices.push(new p5.Vector(sur * ringRadius, y, cur * ringRadius)); //VERTEX NORMALS - var vertexNormal; + let vertexNormal; if (yy < 0) { vertexNormal = new p5.Vector(0, -1, 0); } else if (yy > detailY && topRadius) { @@ -335,10 +334,10 @@ var _truncatedCone = function( } } - var startIndex = 0; + let startIndex = 0; if (bottomCap) { for (jj = 0; jj < detailX; ++jj) { - var nextjj = (jj + 1) % detailX; + const nextjj = (jj + 1) % detailX; this.faces.push([ startIndex + jj, startIndex + detailX + nextjj, @@ -349,7 +348,7 @@ var _truncatedCone = function( } for (yy = 0; yy < detailY; ++yy) { for (ii = 0; ii < detailX; ++ii) { - var nextii = (ii + 1) % detailX; + const nextii = (ii + 1) % detailX; this.faces.push([ startIndex + ii, startIndex + nextii, @@ -436,10 +435,9 @@ p5.prototype.cylinder = function( bottomCap = true; } - var gId = - 'cylinder|' + detailX + '|' + detailY + '|' + bottomCap + '|' + topCap; + const gId = `cylinder|${detailX}|${detailY}|${bottomCap}|${topCap}`; if (!this._renderer.geometryInHash(gId)) { - var cylinderGeom = new p5.Geometry(detailX, detailY); + const cylinderGeom = new p5.Geometry(detailX, detailY); _truncatedCone.call( cylinderGeom, 1, @@ -517,9 +515,9 @@ p5.prototype.cone = function(radius, height, detailX, detailY, cap) { cap = true; } - var gId = 'cone|' + detailX + '|' + detailY + '|' + cap; + const gId = `cone|${detailX}|${detailY}|${cap}`; if (!this._renderer.geometryInHash(gId)) { - var coneGeom = new p5.Geometry(detailX, detailY); + const coneGeom = new p5.Geometry(detailX, detailY); _truncatedCone.call(coneGeom, 1, 0, 1, detailX, detailY, cap, false); if (detailX <= 24 && detailY <= 16) { coneGeom._makeTriangleEdges()._edgesToVertices(); @@ -588,29 +586,29 @@ p5.prototype.ellipsoid = function(radiusX, radiusY, radiusZ, detailX, detailY) { detailY = 16; } - var gId = 'ellipsoid|' + detailX + '|' + detailY; + const gId = `ellipsoid|${detailX}|${detailY}`; if (!this._renderer.geometryInHash(gId)) { - var _ellipsoid = function() { - for (var i = 0; i <= this.detailY; i++) { - var v = i / this.detailY; - var phi = Math.PI * v - Math.PI / 2; - var cosPhi = Math.cos(phi); - var sinPhi = Math.sin(phi); - - for (var j = 0; j <= this.detailX; j++) { - var u = j / this.detailX; - var theta = 2 * Math.PI * u; - var cosTheta = Math.cos(theta); - var sinTheta = Math.sin(theta); - var p = new p5.Vector(cosPhi * sinTheta, sinPhi, cosPhi * cosTheta); + const _ellipsoid = function() { + for (let i = 0; i <= this.detailY; i++) { + const v = i / this.detailY; + const phi = Math.PI * v - Math.PI / 2; + const cosPhi = Math.cos(phi); + const sinPhi = Math.sin(phi); + + for (let j = 0; j <= this.detailX; j++) { + const u = j / this.detailX; + const theta = 2 * Math.PI * u; + const cosTheta = Math.cos(theta); + const sinTheta = Math.sin(theta); + const p = new p5.Vector(cosPhi * sinTheta, sinPhi, cosPhi * cosTheta); this.vertices.push(p); this.vertexNormals.push(p); this.uvs.push(u, v); } } }; - var ellipsoidGeom = new p5.Geometry(detailX, detailY, _ellipsoid); + const ellipsoidGeom = new p5.Geometry(detailX, detailY, _ellipsoid); ellipsoidGeom.computeFaces(); if (detailX <= 24 && detailY <= 24) { ellipsoidGeom._makeTriangleEdges()._edgesToVertices(); @@ -680,27 +678,31 @@ p5.prototype.torus = function(radius, tubeRadius, detailX, detailY) { detailY = 16; } - var tubeRatio = (tubeRadius / radius).toPrecision(4); - var gId = 'torus|' + tubeRatio + '|' + detailX + '|' + detailY; + const tubeRatio = (tubeRadius / radius).toPrecision(4); + const gId = `torus|${tubeRatio}|${detailX}|${detailY}`; if (!this._renderer.geometryInHash(gId)) { - var _torus = function() { - for (var i = 0; i <= this.detailY; i++) { - var v = i / this.detailY; - var phi = 2 * Math.PI * v; - var cosPhi = Math.cos(phi); - var sinPhi = Math.sin(phi); - var r = 1 + tubeRatio * cosPhi; - - for (var j = 0; j <= this.detailX; j++) { - var u = j / this.detailX; - var theta = 2 * Math.PI * u; - var cosTheta = Math.cos(theta); - var sinTheta = Math.sin(theta); - - var p = new p5.Vector(r * cosTheta, r * sinTheta, tubeRatio * sinPhi); + const _torus = function() { + for (let i = 0; i <= this.detailY; i++) { + const v = i / this.detailY; + const phi = 2 * Math.PI * v; + const cosPhi = Math.cos(phi); + const sinPhi = Math.sin(phi); + const r = 1 + tubeRatio * cosPhi; + + for (let j = 0; j <= this.detailX; j++) { + const u = j / this.detailX; + const theta = 2 * Math.PI * u; + const cosTheta = Math.cos(theta); + const sinTheta = Math.sin(theta); + + const p = new p5.Vector( + r * cosTheta, + r * sinTheta, + tubeRatio * sinPhi + ); - var n = new p5.Vector(cosPhi * cosTheta, cosPhi * sinTheta, sinPhi); + const n = new p5.Vector(cosPhi * cosTheta, cosPhi * sinTheta, sinPhi); this.vertices.push(p); this.vertexNormals.push(n); @@ -708,7 +710,7 @@ p5.prototype.torus = function(radius, tubeRadius, detailX, detailY) { } } }; - var torusGeom = new p5.Geometry(detailX, detailY, _torus); + const torusGeom = new p5.Geometry(detailX, detailY, _torus); torusGeom.computeFaces(); if (detailX <= 24 && detailY <= 16) { torusGeom._makeTriangleEdges()._edgesToVertices(); @@ -766,7 +768,7 @@ p5.RendererGL.prototype.point = function(x, y, z) { z = 0; } - var _vertex = []; + const _vertex = []; _vertex.push(new p5.Vector(x, y, z)); this._drawPoints(_vertex, this._pointVertexBuffer); @@ -774,17 +776,17 @@ p5.RendererGL.prototype.point = function(x, y, z) { }; p5.RendererGL.prototype.triangle = function(args) { - var x1 = args[0], + const x1 = args[0], y1 = args[1]; - var x2 = args[2], + const x2 = args[2], y2 = args[3]; - var x3 = args[4], + const x3 = args[4], y3 = args[5]; - var gId = 'tri'; + const gId = 'tri'; if (!this.geometryInHash(gId)) { - var _triangle = function() { - var vertices = []; + const _triangle = function() { + const vertices = []; vertices.push(new p5.Vector(0, 0, 0)); vertices.push(new p5.Vector(0, 1, 0)); vertices.push(new p5.Vector(1, 0, 0)); @@ -793,7 +795,7 @@ p5.RendererGL.prototype.triangle = function(args) { this.faces = [[0, 1, 2]]; this.uvs = [0, 0, 0, 1, 1, 1]; }; - var triGeom = new p5.Geometry(1, 1, _triangle); + const triGeom = new p5.Geometry(1, 1, _triangle); triGeom._makeTriangleEdges()._edgesToVertices(); triGeom.computeNormals(); this.createBuffers(gId, triGeom); @@ -805,10 +807,10 @@ p5.RendererGL.prototype.triangle = function(args) { // this matrix multiplication transforms those two unit vectors // onto the required vector prior to rendering, and moves the // origin appropriately. - var uMVMatrix = this.uMVMatrix.copy(); + const uMVMatrix = this.uMVMatrix.copy(); try { // prettier-ignore - var mult = new p5.Matrix([ + const mult = new p5.Matrix([ x2 - x1, y2 - y1, 0, 0, // the resulting unit X-axis x3 - x1, y3 - y1, 0, 0, // the resulting unit Y-axis 0, 0, 1, 0, // the resulting unit Z-axis (unchanged) @@ -839,29 +841,29 @@ p5.RendererGL.prototype.ellipse = function(args) { }; p5.RendererGL.prototype.arc = function(args) { - var x = arguments[0]; - var y = arguments[1]; - var width = arguments[2]; - var height = arguments[3]; - var start = arguments[4]; - var stop = arguments[5]; - var mode = arguments[6]; - var detail = arguments[7] || 25; - - var shape; - var gId; + const x = arguments[0]; + const y = arguments[1]; + const width = arguments[2]; + const height = arguments[3]; + const start = arguments[4]; + const stop = arguments[5]; + const mode = arguments[6]; + const detail = arguments[7] || 25; + + let shape; + let gId; // check if it is an ellipse or an arc if (Math.abs(stop - start) >= constants.TWO_PI) { shape = 'ellipse'; - gId = shape + '|' + detail + '|'; + gId = `${shape}|${detail}|`; } else { shape = 'arc'; - gId = shape + '|' + start + '|' + stop + '|' + mode + '|' + detail + '|'; + gId = `${shape}|${start}|${stop}|${mode}|${detail}|`; } if (!this.geometryInHash(gId)) { - var _arc = function() { + const _arc = function() { this.strokeIndices = []; // if the start and stop angles are not the same, push vertices to the array @@ -873,12 +875,12 @@ p5.RendererGL.prototype.arc = function(args) { } // vertices for the perimeter of the circle - for (var i = 0; i <= detail; i++) { - var u = i / detail; - var theta = (stop - start) * u + start; + for (let i = 0; i <= detail; i++) { + const u = i / detail; + const theta = (stop - start) * u + start; - var _x = 0.5 + Math.cos(theta) / 2; - var _y = 0.5 + Math.sin(theta) / 2; + const _x = 0.5 + Math.cos(theta) / 2; + const _y = 0.5 + Math.sin(theta) / 2; this.vertices.push(new p5.Vector(_x, _y, 0)); this.uvs.push([_x, _y]); @@ -928,19 +930,19 @@ p5.RendererGL.prototype.arc = function(args) { } }; - var arcGeom = new p5.Geometry(detail, 1, _arc); + const arcGeom = new p5.Geometry(detail, 1, _arc); arcGeom.computeNormals(); if (detail <= 50) { arcGeom._makeTriangleEdges()._edgesToVertices(arcGeom); } else { - console.log('Cannot stroke ' + shape + ' with more than 50 detail'); + console.log(`Cannot stroke ${shape} with more than 50 detail`); } this.createBuffers(gId, arcGeom); } - var uMVMatrix = this.uMVMatrix.copy(); + const uMVMatrix = this.uMVMatrix.copy(); try { this.uMVMatrix.translate([x, y, 0]); @@ -955,21 +957,21 @@ p5.RendererGL.prototype.arc = function(args) { }; p5.RendererGL.prototype.rect = function(args) { - var perPixelLighting = this._pInst._glAttributes.perPixelLighting; - var x = args[0]; - var y = args[1]; - var width = args[2]; - var height = args[3]; - var detailX = args[4] || (perPixelLighting ? 1 : 24); - var detailY = args[5] || (perPixelLighting ? 1 : 16); - var gId = 'rect|' + detailX + '|' + detailY; + const perPixelLighting = this._pInst._glAttributes.perPixelLighting; + const x = args[0]; + const y = args[1]; + const width = args[2]; + const height = args[3]; + const detailX = args[4] || (perPixelLighting ? 1 : 24); + const detailY = args[5] || (perPixelLighting ? 1 : 16); + const gId = `rect|${detailX}|${detailY}`; if (!this.geometryInHash(gId)) { - var _rect = function() { - for (var i = 0; i <= this.detailY; i++) { - var v = i / this.detailY; - for (var j = 0; j <= this.detailX; j++) { - var u = j / this.detailX; - var p = new p5.Vector(u, v, 0); + const _rect = function() { + for (let i = 0; i <= this.detailY; i++) { + const v = i / this.detailY; + for (let j = 0; j <= this.detailX; j++) { + const u = j / this.detailX; + const p = new p5.Vector(u, v, 0); this.vertices.push(p); this.uvs.push(u, v); } @@ -984,7 +986,7 @@ p5.RendererGL.prototype.rect = function(args) { ]; } }; - var rectGeom = new p5.Geometry(detailX, detailY, _rect); + const rectGeom = new p5.Geometry(detailX, detailY, _rect); rectGeom .computeFaces() .computeNormals() @@ -997,7 +999,7 @@ p5.RendererGL.prototype.rect = function(args) { // opposite corners at (0,0) & (1,1). // // before rendering, this square is scaled & moved to the required location. - var uMVMatrix = this.uMVMatrix.copy(); + const uMVMatrix = this.uMVMatrix.copy(); try { this.uMVMatrix.translate([x, y, 0]); this.uMVMatrix.scale(width, height, 1); @@ -1011,33 +1013,10 @@ p5.RendererGL.prototype.rect = function(args) { // prettier-ignore p5.RendererGL.prototype.quad = function(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) { - var gId = - 'quad|' + - x1 + - '|' + - y1 + - '|' + - z1 + - '|' + - x2 + - '|' + - y2 + - '|' + - z2 + - '|' + - x3 + - '|' + - y3 + - '|' + - z3 + - '|' + - x4 + - '|' + - y4 + - '|' + - z4; + const gId = + `quad|${x1}|${y1}|${z1}|${x2}|${y2}|${z2}|${x3}|${y3}|${z3}|${x4}|${y4}|${z4}`; if (!this.geometryInHash(gId)) { - var _quad = function() { + const _quad = function() { this.vertices.push(new p5.Vector(x1, y1, z1)); this.vertices.push(new p5.Vector(x2, y2, z2)); this.vertices.push(new p5.Vector(x3, y3, z3)); @@ -1045,7 +1024,7 @@ p5.RendererGL.prototype.quad = function(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, this.uvs.push(0, 0, 1, 0, 1, 1, 0, 1); this.strokeIndices = [[0, 1], [1, 2], [2, 3], [3, 0]]; }; - var quadGeom = new p5.Geometry(2, 2, _quad); + const quadGeom = new p5.Geometry(2, 2, _quad); quadGeom .computeNormals() ._makeTriangleEdges() @@ -1083,13 +1062,13 @@ p5.RendererGL.prototype.bezier = function( x2 = z1; z1 = z2 = z3 = z4 = 0; } - var bezierDetail = this._pInst._bezierDetail || 20; //value of Bezier detail + const bezierDetail = this._pInst._bezierDetail || 20; //value of Bezier detail this.beginShape(); - for (var i = 0; i <= bezierDetail; i++) { - var c1 = Math.pow(1 - i / bezierDetail, 3); - var c2 = 3 * (i / bezierDetail) * Math.pow(1 - i / bezierDetail, 2); - var c3 = 3 * Math.pow(i / bezierDetail, 2) * (1 - i / bezierDetail); - var c4 = Math.pow(i / bezierDetail, 3); + for (let i = 0; i <= bezierDetail; i++) { + const c1 = Math.pow(1 - i / bezierDetail, 3); + const c2 = 3 * (i / bezierDetail) * Math.pow(1 - i / bezierDetail, 2); + const c3 = 3 * Math.pow(i / bezierDetail, 2) * (1 - i / bezierDetail); + const c4 = Math.pow(i / bezierDetail, 3); this.vertex( x1 * c1 + x2 * c2 + x3 * c3 + x4 * c4, y1 * c1 + y2 * c2 + y3 * c3 + y4 * c4, @@ -1124,24 +1103,24 @@ p5.RendererGL.prototype.curve = function( y2 = x2; z1 = z2 = z3 = z4 = 0; } - var curveDetail = this._pInst._curveDetail; + const curveDetail = this._pInst._curveDetail; this.beginShape(); - for (var i = 0; i <= curveDetail; i++) { - var c1 = Math.pow(i / curveDetail, 3) * 0.5; - var c2 = Math.pow(i / curveDetail, 2) * 0.5; - var c3 = i / curveDetail * 0.5; - var c4 = 0.5; - var vx = + for (let i = 0; i <= curveDetail; i++) { + const c1 = Math.pow(i / curveDetail, 3) * 0.5; + const c2 = Math.pow(i / curveDetail, 2) * 0.5; + const c3 = i / curveDetail * 0.5; + const c4 = 0.5; + const vx = c1 * (-x1 + 3 * x2 - 3 * x3 + x4) + c2 * (2 * x1 - 5 * x2 + 4 * x3 - x4) + c3 * (-x1 + x3) + c4 * (2 * x2); - var vy = + const vy = c1 * (-y1 + 3 * y2 - 3 * y3 + y4) + c2 * (2 * y1 - 5 * y2 + 4 * y3 - y4) + c3 * (-y1 + y3) + c4 * (2 * y2); - var vz = + const vz = c1 * (-z1 + 3 * z2 - 3 * z3 + z4) + c2 * (2 * z1 - 5 * z2 + 4 * z3 - z4) + c3 * (-z1 + z3) + @@ -1181,30 +1160,30 @@ p5.RendererGL.prototype.curve = function( *
*
*/ -p5.RendererGL.prototype.line = function() { - if (arguments.length === 6) { +p5.RendererGL.prototype.line = function(...args) { + if (args.length === 6) { this.beginShape(); - this.vertex(arguments[0], arguments[1], arguments[2]); - this.vertex(arguments[3], arguments[4], arguments[5]); + this.vertex(args[0], args[1], args[2]); + this.vertex(args[3], args[4], args[5]); this.endShape(); - } else if (arguments.length === 4) { + } else if (args.length === 4) { this.beginShape(); - this.vertex(arguments[0], arguments[1], 0); - this.vertex(arguments[2], arguments[3], 0); + this.vertex(args[0], args[1], 0); + this.vertex(args[2], args[3], 0); this.endShape(); } return this; }; -p5.RendererGL.prototype.bezierVertex = function() { +p5.RendererGL.prototype.bezierVertex = function(...args) { if (this.immediateMode._bezierVertex.length === 0) { throw Error('vertex() must be used once before calling bezierVertex()'); } else { - var w_x = []; - var w_y = []; - var w_z = []; - var t, _x, _y, _z, i; - var argLength = arguments.length; + let w_x = []; + let w_y = []; + let w_z = []; + let t, _x, _y, _z, i; + const argLength = args.length; t = 0; @@ -1214,10 +1193,10 @@ p5.RendererGL.prototype.bezierVertex = function() { ) { this._lookUpTableBezier = []; this._lutBezierDetail = this._pInst._curveDetail; - var step = 1 / this._lutBezierDetail; - var start = 0; - var end = 1; - var j = 0; + const step = 1 / this._lutBezierDetail; + let start = 0; + let end = 1; + let j = 0; while (start < 1) { t = parseFloat(start.toFixed(6)); this._lookUpTableBezier[j] = this._bezierCoefficients(t); @@ -1233,23 +1212,13 @@ p5.RendererGL.prototype.bezierVertex = function() { } } - var LUTLength = this._lookUpTableBezier.length; + const LUTLength = this._lookUpTableBezier.length; if (argLength === 6) { this.isBezier = true; - w_x = [ - this.immediateMode._bezierVertex[0], - arguments[0], - arguments[2], - arguments[4] - ]; - w_y = [ - this.immediateMode._bezierVertex[1], - arguments[1], - arguments[3], - arguments[5] - ]; + w_x = [this.immediateMode._bezierVertex[0], args[0], args[2], args[4]]; + w_y = [this.immediateMode._bezierVertex[1], args[1], args[3], args[5]]; for (i = 0; i < LUTLength; i++) { _x = @@ -1264,29 +1233,14 @@ p5.RendererGL.prototype.bezierVertex = function() { w_y[3] * this._lookUpTableBezier[i][3]; this.vertex(_x, _y); } - this.immediateMode._bezierVertex[0] = arguments[4]; - this.immediateMode._bezierVertex[1] = arguments[5]; + this.immediateMode._bezierVertex[0] = args[4]; + this.immediateMode._bezierVertex[1] = args[5]; } else if (argLength === 9) { this.isBezier = true; - w_x = [ - this.immediateMode._bezierVertex[0], - arguments[0], - arguments[3], - arguments[6] - ]; - w_y = [ - this.immediateMode._bezierVertex[1], - arguments[1], - arguments[4], - arguments[7] - ]; - w_z = [ - this.immediateMode._bezierVertex[2], - arguments[2], - arguments[5], - arguments[8] - ]; + w_x = [this.immediateMode._bezierVertex[0], args[0], args[3], args[6]]; + w_y = [this.immediateMode._bezierVertex[1], args[1], args[4], args[7]]; + w_z = [this.immediateMode._bezierVertex[2], args[2], args[5], args[8]]; for (i = 0; i < LUTLength; i++) { _x = w_x[0] * this._lookUpTableBezier[i][0] + @@ -1305,22 +1259,22 @@ p5.RendererGL.prototype.bezierVertex = function() { w_z[3] * this._lookUpTableBezier[i][3]; this.vertex(_x, _y, _z); } - this.immediateMode._bezierVertex[0] = arguments[6]; - this.immediateMode._bezierVertex[1] = arguments[7]; - this.immediateMode._bezierVertex[2] = arguments[8]; + this.immediateMode._bezierVertex[0] = args[6]; + this.immediateMode._bezierVertex[1] = args[7]; + this.immediateMode._bezierVertex[2] = args[8]; } } }; -p5.RendererGL.prototype.quadraticVertex = function() { +p5.RendererGL.prototype.quadraticVertex = function(...args) { if (this.immediateMode._quadraticVertex.length === 0) { throw Error('vertex() must be used once before calling quadraticVertex()'); } else { - var w_x = []; - var w_y = []; - var w_z = []; - var t, _x, _y, _z, i; - var argLength = arguments.length; + let w_x = []; + let w_y = []; + let w_z = []; + let t, _x, _y, _z, i; + const argLength = args.length; t = 0; @@ -1330,10 +1284,10 @@ p5.RendererGL.prototype.quadraticVertex = function() { ) { this._lookUpTableQuadratic = []; this._lutQuadraticDetail = this._pInst._curveDetail; - var step = 1 / this._lutQuadraticDetail; - var start = 0; - var end = 1; - var j = 0; + const step = 1 / this._lutQuadraticDetail; + let start = 0; + let end = 1; + let j = 0; while (start < 1) { t = parseFloat(start.toFixed(6)); this._lookUpTableQuadratic[j] = this._quadraticCoefficients(t); @@ -1349,21 +1303,13 @@ p5.RendererGL.prototype.quadraticVertex = function() { } } - var LUTLength = this._lookUpTableQuadratic.length; + const LUTLength = this._lookUpTableQuadratic.length; if (argLength === 4) { this.isQuadratic = true; - w_x = [ - this.immediateMode._quadraticVertex[0], - arguments[0], - arguments[2] - ]; - w_y = [ - this.immediateMode._quadraticVertex[1], - arguments[1], - arguments[3] - ]; + w_x = [this.immediateMode._quadraticVertex[0], args[0], args[2]]; + w_y = [this.immediateMode._quadraticVertex[1], args[1], args[3]]; for (i = 0; i < LUTLength; i++) { _x = @@ -1377,26 +1323,14 @@ p5.RendererGL.prototype.quadraticVertex = function() { this.vertex(_x, _y); } - this.immediateMode._quadraticVertex[0] = arguments[2]; - this.immediateMode._quadraticVertex[1] = arguments[3]; + this.immediateMode._quadraticVertex[0] = args[2]; + this.immediateMode._quadraticVertex[1] = args[3]; } else if (argLength === 6) { this.isQuadratic = true; - w_x = [ - this.immediateMode._quadraticVertex[0], - arguments[0], - arguments[3] - ]; - w_y = [ - this.immediateMode._quadraticVertex[1], - arguments[1], - arguments[4] - ]; - w_z = [ - this.immediateMode._quadraticVertex[2], - arguments[2], - arguments[5] - ]; + w_x = [this.immediateMode._quadraticVertex[0], args[0], args[3]]; + w_y = [this.immediateMode._quadraticVertex[1], args[1], args[4]]; + w_z = [this.immediateMode._quadraticVertex[2], args[2], args[5]]; for (i = 0; i < LUTLength; i++) { _x = @@ -1414,20 +1348,20 @@ p5.RendererGL.prototype.quadraticVertex = function() { this.vertex(_x, _y, _z); } - this.immediateMode._quadraticVertex[0] = arguments[3]; - this.immediateMode._quadraticVertex[1] = arguments[4]; - this.immediateMode._quadraticVertex[2] = arguments[5]; + this.immediateMode._quadraticVertex[0] = args[3]; + this.immediateMode._quadraticVertex[1] = args[4]; + this.immediateMode._quadraticVertex[2] = args[5]; } } }; -p5.RendererGL.prototype.curveVertex = function() { - var w_x = []; - var w_y = []; - var w_z = []; - var t, _x, _y, _z, i; +p5.RendererGL.prototype.curveVertex = function(...args) { + let w_x = []; + let w_y = []; + let w_z = []; + let t, _x, _y, _z, i; t = 0; - var argLength = arguments.length; + const argLength = args.length; if ( this._lookUpTableBezier.length === 0 || @@ -1435,10 +1369,10 @@ p5.RendererGL.prototype.curveVertex = function() { ) { this._lookUpTableBezier = []; this._lutBezierDetail = this._pInst._curveDetail; - var step = 1 / this._lutBezierDetail; - var start = 0; - var end = 1; - var j = 0; + const step = 1 / this._lutBezierDetail; + let start = 0; + let end = 1; + let j = 0; while (start < 1) { t = parseFloat(start.toFixed(6)); this._lookUpTableBezier[j] = this._bezierCoefficients(t); @@ -1454,11 +1388,11 @@ p5.RendererGL.prototype.curveVertex = function() { } } - var LUTLength = this._lookUpTableBezier.length; + const LUTLength = this._lookUpTableBezier.length; if (argLength === 2) { - this.immediateMode._curveVertex.push(arguments[0]); - this.immediateMode._curveVertex.push(arguments[1]); + this.immediateMode._curveVertex.push(args[0]); + this.immediateMode._curveVertex.push(args[1]); if (this.immediateMode._curveVertex.length === 8) { this.isCurve = true; w_x = this._bezierToCatmull([ @@ -1491,9 +1425,9 @@ p5.RendererGL.prototype.curveVertex = function() { } } } else if (argLength === 3) { - this.immediateMode._curveVertex.push(arguments[0]); - this.immediateMode._curveVertex.push(arguments[1]); - this.immediateMode._curveVertex.push(arguments[2]); + this.immediateMode._curveVertex.push(args[0]); + this.immediateMode._curveVertex.push(args[1]); + this.immediateMode._curveVertex.push(args[2]); if (this.immediateMode._curveVertex.length === 12) { this.isCurve = true; w_x = this._bezierToCatmull([ @@ -1555,22 +1489,22 @@ p5.RendererGL.prototype.image = function( this._pInst.texture(img); this._pInst.textureMode(constants.NORMAL); - var u0 = 0; + let u0 = 0; if (sx <= img.width) { u0 = sx / img.width; } - var u1 = 1; + let u1 = 1; if (sx + sWidth <= img.width) { u1 = (sx + sWidth) / img.width; } - var v0 = 0; + let v0 = 0; if (sy <= img.height) { v0 = sy / img.height; } - var v1 = 1; + let v1 = 1; if (sy + sHeight <= img.height) { v1 = (sy + sHeight) / img.height; } @@ -1585,4 +1519,4 @@ p5.RendererGL.prototype.image = function( this._pInst.pop(); }; -module.exports = p5; +export default p5; diff --git a/src/webgl/interaction.js b/src/webgl/interaction.js index aac2b78c75..ff5e677c3a 100644 --- a/src/webgl/interaction.js +++ b/src/webgl/interaction.js @@ -5,10 +5,8 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); -var constants = require('../core/constants'); +import p5 from '../core/main'; +import * as constants from '../core/constants'; /** * Allows movement around a 3D sketch using a mouse or trackpad. Left-clicking @@ -52,14 +50,14 @@ p5.prototype.orbitControl = function(sensitivityX, sensitivityY) { p5._validateParameters('orbitControl', arguments); // If the mouse is not in bounds of the canvas, disable all behaviors: - var mouseInCanvas = + const mouseInCanvas = this.mouseX < this.width && this.mouseX > 0 && this.mouseY < this.height && this.mouseY > 0; if (!mouseInCanvas) return; - var cam = this._renderer._curCamera; + const cam = this._renderer._curCamera; if (typeof sensitivityX === 'undefined') { sensitivityX = 1; @@ -75,22 +73,18 @@ p5.prototype.orbitControl = function(sensitivityX, sensitivityY) { // disable context menu for canvas element and add 'contextMenuDisabled' // flag to p5 instance if (this.contextMenuDisabled !== true) { - this.canvas.oncontextmenu = function() { - return false; - }; + this.canvas.oncontextmenu = () => false; this._setProperty('contextMenuDisabled', true); } // disable default scrolling behavior on the canvas element and add // 'wheelDefaultDisabled' flag to p5 instance if (this.wheelDefaultDisabled !== true) { - this.canvas.onwheel = function() { - return false; - }; + this.canvas.onwheel = () => false; this._setProperty('wheelDefaultDisabled', true); } - var scaleFactor = this.height < this.width ? this.height : this.width; + const scaleFactor = this.height < this.width ? this.height : this.width; // ZOOM if there is a change in mouseWheelDelta if (this._mouseWheelDeltaY !== this._pmouseWheelDeltaY) { @@ -105,32 +99,33 @@ p5.prototype.orbitControl = function(sensitivityX, sensitivityY) { if (this.mouseIsPressed) { // ORBIT BEHAVIOR if (this.mouseButton === this.LEFT) { - var deltaTheta = + const deltaTheta = -sensitivityX * (this.mouseX - this.pmouseX) / scaleFactor; - var deltaPhi = sensitivityY * (this.mouseY - this.pmouseY) / scaleFactor; + const deltaPhi = + sensitivityY * (this.mouseY - this.pmouseY) / scaleFactor; this._renderer._curCamera._orbit(deltaTheta, deltaPhi, 0); } else if (this.mouseButton === this.RIGHT) { // PANNING BEHAVIOR along X/Z camera axes and restricted to X/Z plane // in world space - var local = cam._getLocalAxes(); + const local = cam._getLocalAxes(); // normalize portions along X/Z axes - var xmag = Math.sqrt(local.x[0] * local.x[0] + local.x[2] * local.x[2]); + const xmag = Math.sqrt(local.x[0] * local.x[0] + local.x[2] * local.x[2]); if (xmag !== 0) { local.x[0] /= xmag; local.x[2] /= xmag; } // normalize portions along X/Z axes - var ymag = Math.sqrt(local.y[0] * local.y[0] + local.y[2] * local.y[2]); + const ymag = Math.sqrt(local.y[0] * local.y[0] + local.y[2] * local.y[2]); if (ymag !== 0) { local.y[0] /= ymag; local.y[2] /= ymag; } // move along those vectors by amount controlled by mouseX, pmouseY - var dx = -1 * sensitivityX * (this.mouseX - this.pmouseX); - var dz = -1 * sensitivityY * (this.mouseY - this.pmouseY); + const dx = -1 * sensitivityX * (this.mouseX - this.pmouseX); + const dz = -1 * sensitivityY * (this.mouseY - this.pmouseY); // restrict movement to XZ plane in world space cam.setPosition( @@ -313,12 +308,12 @@ p5.prototype.orbitControl = function(sensitivityX, sensitivityY) { * @param {Number} [axesZOff] */ -p5.prototype.debugMode = function() { +p5.prototype.debugMode = function(...args) { this._assert3d('debugMode'); - p5._validateParameters('debugMode', arguments); + p5._validateParameters('debugMode', args); // start by removing existing 'post' registered debug methods - for (var i = this._registeredMethods.post.length - 1; i >= 0; i--) { + for (let i = this._registeredMethods.post.length - 1; i >= 0; i--) { // test for equality... if ( this._registeredMethods.post[i].toString() === this._grid().toString() || @@ -329,50 +324,24 @@ p5.prototype.debugMode = function() { } // then add new debugMode functions according to the argument list - if (arguments[0] === constants.GRID) { + if (args[0] === constants.GRID) { this.registerMethod( 'post', - this._grid.call( - this, - arguments[1], - arguments[2], - arguments[3], - arguments[4], - arguments[5] - ) + this._grid.call(this, args[1], args[2], args[3], args[4], args[5]) ); - } else if (arguments[0] === constants.AXES) { + } else if (args[0] === constants.AXES) { this.registerMethod( 'post', - this._axesIcon.call( - this, - arguments[1], - arguments[2], - arguments[3], - arguments[4] - ) + this._axesIcon.call(this, args[1], args[2], args[3], args[4]) ); } else { this.registerMethod( 'post', - this._grid.call( - this, - arguments[0], - arguments[1], - arguments[2], - arguments[3], - arguments[4] - ) + this._grid.call(this, args[0], args[1], args[2], args[3], args[4]) ); this.registerMethod( 'post', - this._axesIcon.call( - this, - arguments[5], - arguments[6], - arguments[7], - arguments[8] - ) + this._axesIcon.call(this, args[5], args[6], args[7], args[8]) ); } }; @@ -411,7 +380,7 @@ p5.prototype.noDebugMode = function() { this._assert3d('noDebugMode'); // start by removing existing 'post' registered debug methods - for (var i = this._registeredMethods.post.length - 1; i >= 0; i--) { + for (let i = this._registeredMethods.post.length - 1; i >= 0; i--) { // test for equality... if ( this._registeredMethods.post[i].toString() === this._grid().toString() || @@ -450,8 +419,8 @@ p5.prototype._grid = function(size, numDivs, xOff, yOff, zOff) { zOff = 0; } - var spacing = size / numDivs; - var halfSize = size / 2; + const spacing = size / numDivs; + const halfSize = size / 2; return function() { this.push(); @@ -480,7 +449,7 @@ p5.prototype._grid = function(size, numDivs, xOff, yOff, zOff) { ); // Lines along X axis - for (var q = 0; q <= numDivs; q++) { + for (let q = 0; q <= numDivs; q++) { this.beginShape(this.LINES); this.vertex(-halfSize + xOff, yOff, q * spacing - halfSize + zOff); this.vertex(+halfSize + xOff, yOff, q * spacing - halfSize + zOff); @@ -488,7 +457,7 @@ p5.prototype._grid = function(size, numDivs, xOff, yOff, zOff) { } // Lines along Z axis - for (var i = 0; i <= numDivs; i++) { + for (let i = 0; i <= numDivs; i++) { this.beginShape(this.LINES); this.vertex(i * spacing - halfSize + xOff, yOff, -halfSize + zOff); this.vertex(i * spacing - halfSize + xOff, yOff, +halfSize + zOff); @@ -566,4 +535,4 @@ p5.prototype._axesIcon = function(size, xOff, yOff, zOff) { }; }; -module.exports = p5; +export default p5; diff --git a/src/webgl/light.js b/src/webgl/light.js index 5c9d6eeaed..77b57d2f0c 100644 --- a/src/webgl/light.js +++ b/src/webgl/light.js @@ -5,9 +5,7 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * Creates an ambient light with a color @@ -71,7 +69,7 @@ var p5 = require('../core/main'); p5.prototype.ambientLight = function(v1, v2, v3, a) { this._assert3d('ambientLight'); p5._validateParameters('ambientLight', arguments); - var color = this.color.apply(this, arguments); + const color = this.color(...arguments); this._renderer.ambientLightColors.push( color._array[0], @@ -148,15 +146,15 @@ p5.prototype.directionalLight = function(v1, v2, v3, x, y, z) { p5._validateParameters('directionalLight', arguments); //@TODO: check parameters number - var color; + let color; if (v1 instanceof p5.Color) { color = v1; } else { color = this.color(v1, v2, v3); } - var _x, _y, _z; - var v = arguments[arguments.length - 1]; + let _x, _y, _z; + const v = arguments[arguments.length - 1]; if (typeof v === 'number') { _x = arguments[arguments.length - 3]; _y = arguments[arguments.length - 2]; @@ -168,7 +166,7 @@ p5.prototype.directionalLight = function(v1, v2, v3, x, y, z) { } // normalize direction - var l = Math.sqrt(_x * _x + _y * _y + _z * _z); + const l = Math.sqrt(_x * _x + _y * _y + _z * _z); this._renderer.directionalLightDirections.push(_x / l, _y / l, _z / l); this._renderer.directionalLightColors.push( @@ -253,15 +251,15 @@ p5.prototype.pointLight = function(v1, v2, v3, x, y, z) { p5._validateParameters('pointLight', arguments); //@TODO: check parameters number - var color; + let color; if (v1 instanceof p5.Color) { color = v1; } else { color = this.color(v1, v2, v3); } - var _x, _y, _z; - var v = arguments[arguments.length - 1]; + let _x, _y, _z; + const v = arguments[arguments.length - 1]; if (typeof v === 'number') { _x = arguments[arguments.length - 3]; _y = arguments[arguments.length - 2]; @@ -401,4 +399,4 @@ p5.prototype.lightFalloff = function( return this; }; -module.exports = p5; +export default p5; diff --git a/src/webgl/loading.js b/src/webgl/loading.js index 5077d16c8a..65b0455f4e 100755 --- a/src/webgl/loading.js +++ b/src/webgl/loading.js @@ -6,10 +6,8 @@ * @requires p5.Geometry */ -'use strict'; - -var p5 = require('../core/main'); -require('./p5.Geometry'); +import p5 from '../core/main'; +import './p5.Geometry'; /** * Load a 3d model from an OBJ or STL file. @@ -99,9 +97,9 @@ require('./p5.Geometry'); */ p5.prototype.loadModel = function(path) { p5._validateParameters('loadModel', arguments); - var normalize; - var successCallback; - var failureCallback; + let normalize; + let successCallback; + let failureCallback; if (typeof arguments[1] === 'boolean') { normalize = arguments[1]; successCallback = arguments[2]; @@ -112,17 +110,17 @@ p5.prototype.loadModel = function(path) { failureCallback = arguments[2]; } - var fileType = path.slice(-4); - var model = new p5.Geometry(); - model.gid = path + '|' + normalize; - var self = this; + const fileType = path.slice(-4); + const model = new p5.Geometry(); + model.gid = `${path}|${normalize}`; + const self = this; if (fileType === '.stl') { this.httpDo( path, 'GET', 'arrayBuffer', - function(arrayBuffer) { + arrayBuffer => { parseSTL(model, arrayBuffer); if (normalize) { @@ -132,13 +130,13 @@ p5.prototype.loadModel = function(path) { if (typeof successCallback === 'function') { successCallback(model); } - }.bind(this), + }, failureCallback ); } else if (fileType === '.obj') { this.loadStrings( path, - function(strings) { + strings => { parseObj(model, strings); if (normalize) { @@ -149,7 +147,7 @@ p5.prototype.loadModel = function(path) { if (typeof successCallback === 'function') { successCallback(model); } - }.bind(this), + }, failureCallback ); } else { @@ -187,24 +185,24 @@ function parseObj(model, lines) { // used to map a specific combination (keyed on, for example, the string // "3/4/3"), to the actual index of the newly created vertex in the final // object. - var loadedVerts = { + const loadedVerts = { v: [], vt: [], vn: [] }; - var indexedVerts = {}; + const indexedVerts = {}; - for (var line = 0; line < lines.length; ++line) { + for (let line = 0; line < lines.length; ++line) { // Each line is a separate object (vertex, face, vertex normal, etc) // For each line, split it into tokens on whitespace. The first token // describes the type. - var tokens = lines[line].trim().split(/\b\s+/); + const tokens = lines[line].trim().split(/\b\s+/); if (tokens.length > 0) { if (tokens[0] === 'v' || tokens[0] === 'vn') { // Check if this line describes a vertex or vertex normal. // It will have three numeric parameters. - var vertex = new p5.Vector( + const vertex = new p5.Vector( parseFloat(tokens[1]), parseFloat(tokens[2]), parseFloat(tokens[3]) @@ -213,20 +211,20 @@ function parseObj(model, lines) { } else if (tokens[0] === 'vt') { // Check if this line describes a texture coordinate. // It will have two numeric parameters. - var texVertex = [parseFloat(tokens[1]), parseFloat(tokens[2])]; + const texVertex = [parseFloat(tokens[1]), parseFloat(tokens[2])]; loadedVerts[tokens[0]].push(texVertex); } else if (tokens[0] === 'f') { // Check if this line describes a face. // OBJ faces can have more than three points. Triangulate points. - for (var tri = 3; tri < tokens.length; ++tri) { - var face = []; + for (let tri = 3; tri < tokens.length; ++tri) { + const face = []; - var vertexTokens = [1, tri - 1, tri]; + const vertexTokens = [1, tri - 1, tri]; - for (var tokenInd = 0; tokenInd < vertexTokens.length; ++tokenInd) { + for (let tokenInd = 0; tokenInd < vertexTokens.length; ++tokenInd) { // Now, convert the given token into an index - var vertString = tokens[vertexTokens[tokenInd]]; - var vertIndex = 0; + const vertString = tokens[vertexTokens[tokenInd]]; + let vertIndex = 0; // TODO: Faces can technically use negative numbers to refer to the // previous nth vertex. I haven't seen this used in practice, but @@ -235,8 +233,8 @@ function parseObj(model, lines) { if (indexedVerts[vertString] !== undefined) { vertIndex = indexedVerts[vertString]; } else { - var vertParts = vertString.split('/'); - for (var i = 0; i < vertParts.length; i++) { + const vertParts = vertString.split('/'); + for (let i = 0; i < vertParts.length; i++) { vertParts[i] = parseInt(vertParts[i]) - 1; } @@ -285,7 +283,7 @@ function parseSTL(model, buffer) { if (isBinary(buffer)) { parseBinarySTL(model, buffer); } else { - var reader = new DataView(buffer); + const reader = new DataView(buffer); if (!('TextDecoder' in window)) { console.warn( @@ -294,9 +292,9 @@ function parseSTL(model, buffer) { return model; } - var decoder = new TextDecoder('utf-8'); - var lines = decoder.decode(reader); - var lineArray = lines.split('\n'); + const decoder = new TextDecoder('utf-8'); + const lines = decoder.decode(reader); + const lineArray = lines.split('\n'); parseASCIISTL(model, lineArray); } return model; @@ -316,11 +314,11 @@ function parseSTL(model, buffer) { * Search for `solid` to start anywhere after those prefixes. */ function isBinary(data) { - var reader = new DataView(data); + const reader = new DataView(data); // US-ASCII ordinal values for `s`, `o`, `l`, `i`, `d` - var solid = [115, 111, 108, 105, 100]; - for (var off = 0; off < 5; off++) { + const solid = [115, 111, 108, 105, 100]; + for (let off = 0; off < 5; off++) { // If "solid" text is matched to the current offset, declare it to be an ASCII STL. if (matchDataViewAt(solid, reader, off)) return false; } @@ -334,7 +332,7 @@ function isBinary(data) { */ function matchDataViewAt(query, reader, offset) { // Check if each byte in query matches the corresponding byte from the current offset - for (var i = 0, il = query.length; i < il; i++) { + for (let i = 0, il = query.length; i < il; i++) { if (query[i] !== reader.getUint8(offset + i, false)) return false; } @@ -348,19 +346,19 @@ function matchDataViewAt(query, reader, offset) { * Currently there is no support for the colors provided in STL files. */ function parseBinarySTL(model, buffer) { - var reader = new DataView(buffer); + const reader = new DataView(buffer); // Number of faces is present following the header - var faces = reader.getUint32(80, true); - var r, + const faces = reader.getUint32(80, true); + let r, g, b, hasColors = false, colors; - var defaultR, defaultG, defaultB; + let defaultR, defaultG, defaultB; // Binary files contain 80-byte header, which is generally ignored. - for (var index = 0; index < 80 - 10; index++) { + for (let index = 0; index < 80 - 10; index++) { // Check for `COLOR=` if ( reader.getUint32(index, false) === 0x434f4c4f /*COLO*/ && @@ -377,18 +375,18 @@ function parseBinarySTL(model, buffer) { // alpha = reader.getUint8(index + 9) / 255; } } - var dataOffset = 84; - var faceLength = 12 * 4 + 2; + const dataOffset = 84; + const faceLength = 12 * 4 + 2; // Iterate the faces - for (var face = 0; face < faces; face++) { - var start = dataOffset + face * faceLength; - var normalX = reader.getFloat32(start, true); - var normalY = reader.getFloat32(start + 4, true); - var normalZ = reader.getFloat32(start + 8, true); + for (let face = 0; face < faces; face++) { + const start = dataOffset + face * faceLength; + const normalX = reader.getFloat32(start, true); + const normalY = reader.getFloat32(start + 4, true); + const normalZ = reader.getFloat32(start + 8, true); if (hasColors) { - var packedColor = reader.getUint16(start + 48, true); + const packedColor = reader.getUint16(start + 48, true); if ((packedColor & 0x8000) === 0) { // facet has its own unique color @@ -402,10 +400,10 @@ function parseBinarySTL(model, buffer) { } } - for (var i = 1; i <= 3; i++) { - var vertexstart = start + i * 12; + for (let i = 1; i <= 3; i++) { + const vertexstart = start + i * 12; - var newVertex = new p5.Vector( + const newVertex = new p5.Vector( reader.getFloat32(vertexstart, true), reader.getFloat32(vertexstart + 8, true), reader.getFloat32(vertexstart + 4, true) @@ -418,7 +416,7 @@ function parseBinarySTL(model, buffer) { } } - var newNormal = new p5.Vector(normalX, normalY, normalZ); + const newNormal = new p5.Vector(normalX, normalY, normalZ); model.vertexNormals.push(newNormal, newNormal, newNormal); @@ -441,15 +439,15 @@ function parseBinarySTL(model, buffer) { * The end of the file is indicated by `endsolid` */ function parseASCIISTL(model, lines) { - var state = ''; - var curVertexIndex = []; - var newNormal, newVertex; + let state = ''; + let curVertexIndex = []; + let newNormal, newVertex; - for (var iterator = 0; iterator < lines.length; ++iterator) { - var line = lines[iterator].trim(); - var parts = line.split(' '); + for (let iterator = 0; iterator < lines.length; ++iterator) { + const line = lines[iterator].trim(); + const parts = line.split(' '); - for (var partsiterator = 0; partsiterator < parts.length; ++partsiterator) { + for (let partsiterator = 0; partsiterator < parts.length; ++partsiterator) { if (parts[partsiterator] === '') { // Ignoring multiple whitespaces parts.splice(partsiterator, 1); @@ -466,7 +464,7 @@ function parseASCIISTL(model, lines) { if (parts[0] !== 'solid') { // Invalid state console.error(line); - console.error('Invalid state "' + parts[0] + '", should be "solid"'); + console.error(`Invalid state "${parts[0]}", should be "solid"`); return; } else { state = 'solid'; @@ -478,7 +476,7 @@ function parseASCIISTL(model, lines) { // Invalid state console.error(line); console.error( - 'Invalid state "' + parts[0] + '", should be "facet normal"' + `Invalid state "${parts[0]}", should be "facet normal"` ); return; } else { @@ -497,9 +495,7 @@ function parseASCIISTL(model, lines) { if (parts[0] !== 'outer' || parts[1] !== 'loop') { // Invalid State console.error(line); - console.error( - 'Invalid state "' + parts[0] + '", should be "outer loop"' - ); + console.error(`Invalid state "${parts[0]}", should be "outer loop"`); return; } else { // Next should be vertices @@ -526,7 +522,7 @@ function parseASCIISTL(model, lines) { // Invalid State console.error(line); console.error( - 'Invalid state "' + parts[0] + '", should be "vertex" or "endloop"' + `Invalid state "${parts[0]}", should be "vertex" or "endloop"` ); return; } @@ -536,9 +532,7 @@ function parseASCIISTL(model, lines) { if (parts[0] !== 'endfacet') { // End of face console.error(line); - console.error( - 'Invalid state "' + parts[0] + '", should be "endfacet"' - ); + console.error(`Invalid state "${parts[0]}", should be "endfacet"`); return; } else { state = 'endfacet'; @@ -561,16 +555,16 @@ function parseASCIISTL(model, lines) { // Invalid State console.error(line); console.error( - 'Invalid state "' + - parts[0] + - '", should be "endsolid" or "facet normal"' + `Invalid state "${ + parts[0] + }", should be "endsolid" or "facet normal"` ); return; } break; default: - console.error('Invalid state "' + state + '"'); + console.error(`Invalid state "${state}"`); break; } } @@ -622,4 +616,4 @@ p5.prototype.model = function(model) { } }; -module.exports = p5; +export default p5; diff --git a/src/webgl/material.js b/src/webgl/material.js index d65f57f39c..659e35907b 100644 --- a/src/webgl/material.js +++ b/src/webgl/material.js @@ -5,11 +5,9 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); -var constants = require('../core/constants'); -require('./p5.Texture'); +import p5 from '../core/main'; +import * as constants from '../core/constants'; +import './p5.Texture'; /** * Loads a custom shader from the provided vertex and fragment @@ -70,13 +68,13 @@ p5.prototype.loadShader = function( errorCallback = console.error; } - var loadedShader = new p5.Shader(); + const loadedShader = new p5.Shader(); - var self = this; - var loadedFrag = false; - var loadedVert = false; + const self = this; + let loadedFrag = false; + let loadedVert = false; - var onLoad = function() { + const onLoad = () => { self._decrementPreload(); if (callback) { callback(loadedShader); @@ -85,7 +83,7 @@ p5.prototype.loadShader = function( this.loadStrings( vertFilename, - function(result) { + result => { loadedShader._vertSrc = result.join('\n'); loadedVert = true; if (loadedFrag) { @@ -97,7 +95,7 @@ p5.prototype.loadShader = function( this.loadStrings( fragFilename, - function(result) { + result => { loadedShader._fragSrc = result.join('\n'); loadedFrag = true; if (loadedVert) { @@ -307,9 +305,9 @@ p5.prototype.resetShader = function() { * Red, green and blue gradient. * */ -p5.prototype.normalMaterial = function() { +p5.prototype.normalMaterial = function(...args) { this._assert3d('normalMaterial'); - p5._validateParameters('normalMaterial', arguments); + p5._validateParameters('normalMaterial', args); this._renderer.drawMode = constants.FILL; this._renderer._useSpecularMaterial = false; this._renderer._useEmissiveMaterial = false; @@ -493,7 +491,7 @@ p5.prototype.texture = function(tex) { p5.prototype.textureMode = function(mode) { if (mode !== constants.IMAGE && mode !== constants.NORMAL) { console.warn( - 'You tried to set ' + mode + ' textureMode only supports IMAGE & NORMAL ' + `You tried to set ${mode} textureMode only supports IMAGE & NORMAL ` ); } else { this._renderer.textureMode = mode; @@ -563,14 +561,12 @@ p5.prototype.textureMode = function(mode) { * an image of the rocky mountains repeated in mirrored tiles * */ -p5.prototype.textureWrap = function(wrapX, wrapY) { - wrapY = wrapY || wrapX; - +p5.prototype.textureWrap = function(wrapX, wrapY = wrapX) { this._renderer.textureWrapX = wrapX; this._renderer.textureWrapY = wrapY; - var textures = this._renderer.textures; - for (var i = 0; i < textures.length; i++) { + const textures = this._renderer.textures; + for (let i = 0; i < textures.length; i++) { textures[i].setWrapMode(wrapX, wrapY); } }; @@ -615,7 +611,7 @@ p5.prototype.ambientMaterial = function(v1, v2, v3, a) { this._assert3d('ambientMaterial'); p5._validateParameters('ambientMaterial', arguments); - var color = p5.prototype.color.apply(this, arguments); + const color = p5.prototype.color.apply(this, arguments); this._renderer.curFillColor = color._array; this._renderer._useSpecularMaterial = false; this._renderer._useEmissiveMaterial = false; @@ -667,7 +663,7 @@ p5.prototype.emissiveMaterial = function(v1, v2, v3, a) { this._assert3d('emissiveMaterial'); p5._validateParameters('emissiveMaterial', arguments); - var color = p5.prototype.color.apply(this, arguments); + const color = p5.prototype.color.apply(this, arguments); this._renderer.curFillColor = color._array; this._renderer._useSpecularMaterial = false; this._renderer._useEmissiveMaterial = true; @@ -719,7 +715,7 @@ p5.prototype.specularMaterial = function(v1, v2, v3, a) { this._assert3d('specularMaterial'); p5._validateParameters('specularMaterial', arguments); - var color = p5.prototype.color.apply(this, arguments); + const color = p5.prototype.color.apply(this, arguments); this._renderer.curFillColor = color._array; this._renderer._useSpecularMaterial = true; this._renderer._useEmissiveMaterial = false; @@ -783,9 +779,9 @@ p5.prototype.shininess = function(shine) { * @return {Number[]]} Normalized numbers array */ p5.RendererGL.prototype._applyColorBlend = function(colors) { - var gl = this.GL; + const gl = this.GL; - var isTexture = this.drawMode === constants.TEXTURE; + const isTexture = this.drawMode === constants.TEXTURE; if (isTexture || colors[colors.length - 1] < 1.0) { gl.depthMask(isTexture); gl.enable(gl.BLEND); @@ -803,7 +799,7 @@ p5.RendererGL.prototype._applyColorBlend = function(colors) { * @return {Number[]]} Normalized numbers array */ p5.RendererGL.prototype._applyBlendMode = function() { - var gl = this.GL; + const gl = this.GL; switch (this.curBlendMode) { case constants.BLEND: case constants.ADD: @@ -863,4 +859,4 @@ p5.RendererGL.prototype._applyBlendMode = function() { } }; -module.exports = p5; +export default p5; diff --git a/src/webgl/p5.Camera.js b/src/webgl/p5.Camera.js index 3cf0d2292b..afee06daad 100644 --- a/src/webgl/p5.Camera.js +++ b/src/webgl/p5.Camera.js @@ -4,9 +4,7 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; //////////////////////////////////////////////////////////////////////////////// // p5.Prototype Methods @@ -51,10 +49,10 @@ var p5 = require('../core/main'); * White square repeatedly grows to fill canvas and then shrinks. * */ -p5.prototype.camera = function() { +p5.prototype.camera = function(...args) { this._assert3d('camera'); - p5._validateParameters('camera', arguments); - this._renderer._curCamera.camera.apply(this._renderer._curCamera, arguments); + p5._validateParameters('camera', args); + this._renderer._curCamera.camera(...args); return this; }; @@ -113,13 +111,10 @@ p5.prototype.camera = function() { * two colored 3D boxes move back and forth, rotating as mouse is dragged. * */ -p5.prototype.perspective = function() { +p5.prototype.perspective = function(...args) { this._assert3d('perspective'); - p5._validateParameters('perspective', arguments); - this._renderer._curCamera.perspective.apply( - this._renderer._curCamera, - arguments - ); + p5._validateParameters('perspective', args); + this._renderer._curCamera.perspective(...args); return this; }; @@ -173,10 +168,10 @@ p5.prototype.perspective = function() { * two 3D boxes move back and forth along same plane, rotating as mouse is dragged. * */ -p5.prototype.ortho = function() { +p5.prototype.ortho = function(...args) { this._assert3d('ortho'); - p5._validateParameters('ortho', arguments); - this._renderer._curCamera.ortho.apply(this._renderer._curCamera, arguments); + p5._validateParameters('ortho', args); + this._renderer._curCamera.ortho(...args); return this; }; @@ -194,7 +189,7 @@ p5.prototype.ortho = function() { */ p5.prototype.createCamera = function() { this._assert3d('createCamera'); - var _cam = new p5.Camera(this._renderer); + const _cam = new p5.Camera(this._renderer); // compute default camera settings, then set a default camera _cam._computeCameraDefaultSettings(); @@ -343,8 +338,8 @@ p5.Camera.prototype.perspective = function(fovy, aspect, near, far) { this.projMatrix = p5.Matrix.identity(); - var f = 1.0 / Math.tan(this.cameraFOV / 2); - var nf = 1.0 / (this.cameraNear - this.cameraFar); + const f = 1.0 / Math.tan(this.cameraFOV / 2); + const nf = 1.0 / (this.cameraNear - this.cameraFar); // prettier-ignore this.projMatrix.set(f / aspect, 0, 0, 0, @@ -391,17 +386,17 @@ p5.Camera.prototype.ortho = function(left, right, bottom, top, near, far) { if (far === undefined) far = Math.max(this._renderer.width, this._renderer.height); - var w = right - left; - var h = top - bottom; - var d = far - near; + const w = right - left; + const h = top - bottom; + const d = far - near; - var x = +2.0 / w; - var y = +2.0 / h; - var z = -2.0 / d; + const x = +2.0 / w; + const y = +2.0 / h; + const z = -2.0 / d; - var tx = -(right + left) / w; - var ty = -(top + bottom) / h; - var tz = -(far + near) / d; + const tx = -(right + left) / w; + const ty = -(top + bottom) / h; + const tz = -(far + near) / d; this.projMatrix = p5.Matrix.identity(); @@ -446,24 +441,24 @@ p5.Camera.prototype.ortho = function(left, right, bottom, top, near, far) { * @private */ p5.Camera.prototype._rotateView = function(a, x, y, z) { - var centerX = this.centerX; - var centerY = this.centerY; - var centerZ = this.centerZ; + let centerX = this.centerX; + let centerY = this.centerY; + let centerZ = this.centerZ; // move center by eye position such that rotation happens around eye position centerX -= this.eyeX; centerY -= this.eyeY; centerZ -= this.eyeZ; - var rotation = p5.Matrix.identity(this._renderer._pInst); + const rotation = p5.Matrix.identity(this._renderer._pInst); rotation.rotate(this._renderer._pInst._toRadians(a), x, y, z); // prettier-ignore - var rotatedCenter = [ + const rotatedCenter = [ centerX * rotation.mat4[0]+ centerY * rotation.mat4[4]+ centerZ * rotation.mat4[8], centerX * rotation.mat4[1]+ centerY * rotation.mat4[5]+ centerZ * rotation.mat4[9], centerX * rotation.mat4[2]+ centerY * rotation.mat4[6]+ centerZ * rotation.mat4[10] - ] + ]; // add eye position back into center rotatedCenter[0] += this.eyeX; @@ -538,7 +533,7 @@ p5.Camera.prototype._rotateView = function(a, x, y, z) { * */ p5.Camera.prototype.pan = function(amount) { - var local = this._getLocalAxes(); + const local = this._getLocalAxes(); this._rotateView(amount, local.y[0], local.y[1], local.y[2]); }; @@ -596,7 +591,7 @@ p5.Camera.prototype.pan = function(amount) { * camera view tilts up and down across a series of rotating 3D boxes. */ p5.Camera.prototype.tilt = function(amount) { - var local = this._getLocalAxes(); + const local = this._getLocalAxes(); this._rotateView(amount, local.x[0], local.x[1], local.x[2]); }; @@ -708,7 +703,7 @@ p5.Camera.prototype.camera = function( this.upY = upY; this.upZ = upZ; - var local = this._getLocalAxes(); + const local = this._getLocalAxes(); // the camera affects the model view matrix, insofar as it // inverse translates the world to the eye position of the camera @@ -719,9 +714,9 @@ p5.Camera.prototype.camera = function( local.x[2], local.y[2], local.z[2], 0, 0, 0, 0, 1); - var tx = -eyeX; - var ty = -eyeY; - var tz = -eyeZ; + const tx = -eyeX; + const ty = -eyeY; + const tz = -eyeZ; this.cameraMatrix.translate([tx, ty, tz]); @@ -799,13 +794,13 @@ p5.Camera.prototype.camera = function( * orientation throughout the move */ p5.Camera.prototype.move = function(x, y, z) { - var local = this._getLocalAxes(); + const local = this._getLocalAxes(); // scale local axes by movement amounts // based on http://learnwebgl.brown37.net/07_cameras/camera_linear_motion.html - var dx = [local.x[0] * x, local.x[1] * x, local.x[2] * x]; - var dy = [local.y[0] * y, local.y[1] * y, local.y[2] * y]; - var dz = [local.z[0] * z, local.z[1] * z, local.z[2] * z]; + const dx = [local.x[0] * x, local.x[1] * x, local.x[2] * x]; + const dy = [local.y[0] * y, local.y[1] * y, local.y[2] * y]; + const dz = [local.z[0] * z, local.z[1] * z, local.z[2] * z]; this.camera( this.eyeX + dx[0] + dy[0] + dz[0], @@ -865,9 +860,9 @@ p5.Camera.prototype.move = function(x, y, z) { * camera position changes as the user presses keys, altering view of a 3D box */ p5.Camera.prototype.setPosition = function(x, y, z) { - var diffX = x - this.eyeX; - var diffY = y - this.eyeY; - var diffZ = z - this.eyeZ; + const diffX = x - this.eyeX; + const diffY = y - this.eyeY; + const diffZ = z - this.eyeZ; this.camera( x, @@ -944,7 +939,7 @@ p5.Camera.prototype._resize = function() { * @private */ p5.Camera.prototype.copy = function() { - var _cam = new p5.Camera(this._renderer); + const _cam = new p5.Camera(this._renderer); _cam.cameraFOV = this.cameraFOV; _cam.aspectRatio = this.aspectRatio; _cam.eyeX = this.eyeX; @@ -972,12 +967,12 @@ p5.Camera.prototype.copy = function() { */ p5.Camera.prototype._getLocalAxes = function() { // calculate camera local Z vector - var z0 = this.eyeX - this.centerX; - var z1 = this.eyeY - this.centerY; - var z2 = this.eyeZ - this.centerZ; + let z0 = this.eyeX - this.centerX; + let z1 = this.eyeY - this.centerY; + let z2 = this.eyeZ - this.centerZ; // normalize camera local Z vector - var eyeDist = Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); + const eyeDist = Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); if (eyeDist !== 0) { z0 /= eyeDist; z1 /= eyeDist; @@ -985,14 +980,14 @@ p5.Camera.prototype._getLocalAxes = function() { } // calculate camera Y vector - var y0 = this.upX; - var y1 = this.upY; - var y2 = this.upZ; + let y0 = this.upX; + let y1 = this.upY; + let y2 = this.upZ; // compute camera local X vector as up vector (local Y) cross local Z - var x0 = y1 * z2 - y2 * z1; - var x1 = -y0 * z2 + y2 * z0; - var x2 = y0 * z1 - y1 * z0; + let x0 = y1 * z2 - y2 * z1; + let x1 = -y0 * z2 + y2 * z0; + let x2 = y0 * z1 - y1 * z0; // recompute y = z cross x y0 = z1 * x2 - z2 * x1; @@ -1001,14 +996,14 @@ p5.Camera.prototype._getLocalAxes = function() { // cross product gives area of parallelogram, which is < 1.0 for // non-perpendicular unit-length vectors; so normalize x, y here: - var xmag = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); + const xmag = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); if (xmag !== 0) { x0 /= xmag; x1 /= xmag; x2 /= xmag; } - var ymag = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); + const ymag = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); if (ymag !== 0) { y0 /= ymag; y1 /= ymag; @@ -1031,15 +1026,15 @@ p5.Camera.prototype._getLocalAxes = function() { * @param {Number} dRadius change in radius */ p5.Camera.prototype._orbit = function(dTheta, dPhi, dRadius) { - var diffX = this.eyeX - this.centerX; - var diffY = this.eyeY - this.centerY; - var diffZ = this.eyeZ - this.centerZ; + const diffX = this.eyeX - this.centerX; + const diffY = this.eyeY - this.centerY; + const diffZ = this.eyeZ - this.centerZ; // get spherical coorinates for current camera position about origin - var camRadius = Math.sqrt(diffX * diffX + diffY * diffY + diffZ * diffZ); + let camRadius = Math.sqrt(diffX * diffX + diffY * diffY + diffZ * diffZ); // from https://github.com/mrdoob/three.js/blob/dev/src/math/Spherical.js#L72-L73 - var camTheta = Math.atan2(diffX, diffZ); // equatorial angle - var camPhi = Math.acos(Math.max(-1, Math.min(1, diffY / camRadius))); // polar angle + let camTheta = Math.atan2(diffX, diffZ); // equatorial angle + let camPhi = Math.acos(Math.max(-1, Math.min(1, diffY / camRadius))); // polar angle // add change camTheta += dTheta; @@ -1059,9 +1054,9 @@ p5.Camera.prototype._orbit = function(dTheta, dPhi, dRadius) { } // from https://github.com/mrdoob/three.js/blob/dev/src/math/Vector3.js#L628-L632 - var _x = Math.sin(camPhi) * camRadius * Math.sin(camTheta); - var _y = Math.cos(camPhi) * camRadius; - var _z = Math.sin(camPhi) * camRadius * Math.cos(camTheta); + const _x = Math.sin(camPhi) * camRadius * Math.sin(camTheta); + const _y = Math.cos(camPhi) * camRadius; + const _z = Math.sin(camPhi) * camRadius * Math.cos(camTheta); this.camera( _x + this.centerX, @@ -1180,4 +1175,4 @@ p5.prototype.setCamera = function(cam) { ); }; -module.exports = p5.Camera; +export default p5.Camera; diff --git a/src/webgl/p5.Geometry.js b/src/webgl/p5.Geometry.js index 71786baa1b..ca183f4a91 100644 --- a/src/webgl/p5.Geometry.js +++ b/src/webgl/p5.Geometry.js @@ -1,8 +1,6 @@ //some of the functions are adjusted from Three.js(http://threejs.org) -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * p5 Geometry class * @class p5.Geometry @@ -69,10 +67,10 @@ p5.Geometry.prototype.reset = function() { */ p5.Geometry.prototype.computeFaces = function() { this.faces.length = 0; - var sliceCount = this.detailX + 1; - var a, b, c, d; - for (var i = 0; i < this.detailY; i++) { - for (var j = 0; j < this.detailX; j++) { + const sliceCount = this.detailX + 1; + let a, b, c, d; + for (let i = 0; i < this.detailY; i++) { + for (let j = 0; j < this.detailX; j++) { a = i * sliceCount + j; // + offset; b = i * sliceCount + j + 1; // + offset; c = (i + 1) * sliceCount + j + 1; // + offset; @@ -86,15 +84,15 @@ p5.Geometry.prototype.computeFaces = function() { p5.Geometry.prototype._getFaceNormal = function(faceId) { //This assumes that vA->vB->vC is a counter-clockwise ordering - var face = this.faces[faceId]; - var vA = this.vertices[face[0]]; - var vB = this.vertices[face[1]]; - var vC = this.vertices[face[2]]; - var ab = p5.Vector.sub(vB, vA); - var ac = p5.Vector.sub(vC, vA); - var n = p5.Vector.cross(ab, ac); - var ln = p5.Vector.mag(n); - var sinAlpha = ln / (p5.Vector.mag(ab) * p5.Vector.mag(ac)); + const face = this.faces[faceId]; + const vA = this.vertices[face[0]]; + const vB = this.vertices[face[1]]; + const vC = this.vertices[face[2]]; + const ab = p5.Vector.sub(vB, vA); + const ac = p5.Vector.sub(vC, vA); + const n = p5.Vector.cross(ab, ac); + const ln = p5.Vector.mag(n); + let sinAlpha = ln / (p5.Vector.mag(ab) * p5.Vector.mag(ac)); if (sinAlpha === 0 || isNaN(sinAlpha)) { console.warn( 'p5.Geometry.prototype._getFaceNormal:', @@ -112,10 +110,10 @@ p5.Geometry.prototype._getFaceNormal = function(faceId) { * @chainable */ p5.Geometry.prototype.computeNormals = function() { - var vertexNormals = this.vertexNormals; - var vertices = this.vertices; - var faces = this.faces; - var iv; + const vertexNormals = this.vertexNormals; + const vertices = this.vertices; + const faces = this.faces; + let iv; // initialize the vertexNormals array with empty vectors vertexNormals.length = 0; @@ -125,13 +123,13 @@ p5.Geometry.prototype.computeNormals = function() { // loop through all the faces adding its normal to the normal // of each of its vertices - for (var f = 0; f < faces.length; ++f) { - var face = faces[f]; - var faceNormal = this._getFaceNormal(f); + for (let f = 0; f < faces.length; ++f) { + const face = faces[f]; + const faceNormal = this._getFaceNormal(f); // all three vertices get the normal added - for (var fv = 0; fv < 3; ++fv) { - var vertexIndex = face[fv]; + for (let fv = 0; fv < 3; ++fv) { + const vertexIndex = face[fv]; vertexNormals[vertexIndex].add(faceNormal); } } @@ -151,9 +149,9 @@ p5.Geometry.prototype.computeNormals = function() { * @chainable */ p5.Geometry.prototype.averageNormals = function() { - for (var i = 0; i <= this.detailY; i++) { - var offset = this.detailX + 1; - var temp = p5.Vector.add( + for (let i = 0; i <= this.detailY; i++) { + const offset = this.detailX + 1; + let temp = p5.Vector.add( this.vertexNormals[i * offset], this.vertexNormals[i * offset + this.detailX] ); @@ -172,20 +170,20 @@ p5.Geometry.prototype.averageNormals = function() { */ p5.Geometry.prototype.averagePoleNormals = function() { //average the north pole - var sum = new p5.Vector(0, 0, 0); - for (var i = 0; i < this.detailX; i++) { + let sum = new p5.Vector(0, 0, 0); + for (let i = 0; i < this.detailX; i++) { sum.add(this.vertexNormals[i]); } sum = p5.Vector.div(sum, this.detailX); - for (i = 0; i < this.detailX; i++) { + for (let i = 0; i < this.detailX; i++) { this.vertexNormals[i] = sum; } //average the south pole sum = new p5.Vector(0, 0, 0); for ( - i = this.vertices.length - 1; + let i = this.vertices.length - 1; i > this.vertices.length - 1 - this.detailX; i-- ) { @@ -194,7 +192,7 @@ p5.Geometry.prototype.averagePoleNormals = function() { sum = p5.Vector.div(sum, this.detailX); for ( - i = this.vertices.length - 1; + let i = this.vertices.length - 1; i > this.vertices.length - 1 - this.detailX; i-- ) { @@ -211,11 +209,11 @@ p5.Geometry.prototype.averagePoleNormals = function() { p5.Geometry.prototype._makeTriangleEdges = function() { this.edges.length = 0; if (Array.isArray(this.strokeIndices)) { - for (var i = 0, max = this.strokeIndices.length; i < max; i++) { + for (let i = 0, max = this.strokeIndices.length; i < max; i++) { this.edges.push(this.strokeIndices[i]); } } else { - for (var j = 0; j < this.faces.length; j++) { + for (let j = 0; j < this.faces.length; j++) { this.edges.push([this.faces[j][0], this.faces[j][1]]); this.edges.push([this.faces[j][1], this.faces[j][2]]); this.edges.push([this.faces[j][2], this.faces[j][0]]); @@ -235,19 +233,19 @@ p5.Geometry.prototype._edgesToVertices = function() { this.lineVertices.length = 0; this.lineNormals.length = 0; - for (var i = 0; i < this.edges.length; i++) { - var begin = this.vertices[this.edges[i][0]]; - var end = this.vertices[this.edges[i][1]]; - var dir = end + for (let i = 0; i < this.edges.length; i++) { + const begin = this.vertices[this.edges[i][0]]; + const end = this.vertices[this.edges[i][1]]; + const dir = end .copy() .sub(begin) .normalize(); - var a = begin.array(); - var b = begin.array(); - var c = end.array(); - var d = end.array(); - var dirAdd = dir.array(); - var dirSub = dir.array(); + const a = begin.array(); + const b = begin.array(); + const c = end.array(); + const d = end.array(); + const dirAdd = dir.array(); + const dirSub = dir.array(); // below is used to displace the pair of vertices at beginning and end // in opposite directions dirAdd.push(1); @@ -266,10 +264,10 @@ p5.Geometry.prototype._edgesToVertices = function() { p5.Geometry.prototype.normalize = function() { if (this.vertices.length > 0) { // Find the corners of our bounding box - var maxPosition = this.vertices[0].copy(); - var minPosition = this.vertices[0].copy(); + const maxPosition = this.vertices[0].copy(); + const minPosition = this.vertices[0].copy(); - for (var i = 0; i < this.vertices.length; i++) { + for (let i = 0; i < this.vertices.length; i++) { maxPosition.x = Math.max(maxPosition.x, this.vertices[i].x); minPosition.x = Math.min(minPosition.x, this.vertices[i].x); maxPosition.y = Math.max(maxPosition.y, this.vertices[i].y); @@ -278,12 +276,12 @@ p5.Geometry.prototype.normalize = function() { minPosition.z = Math.min(minPosition.z, this.vertices[i].z); } - var center = p5.Vector.lerp(maxPosition, minPosition, 0.5); - var dist = p5.Vector.sub(maxPosition, minPosition); - var longestDist = Math.max(Math.max(dist.x, dist.y), dist.z); - var scale = 200 / longestDist; + const center = p5.Vector.lerp(maxPosition, minPosition, 0.5); + const dist = p5.Vector.sub(maxPosition, minPosition); + const longestDist = Math.max(Math.max(dist.x, dist.y), dist.z); + const scale = 200 / longestDist; - for (i = 0; i < this.vertices.length; i++) { + for (let i = 0; i < this.vertices.length; i++) { this.vertices[i].sub(center); this.vertices[i].mult(scale); } @@ -291,4 +289,4 @@ p5.Geometry.prototype.normalize = function() { return this; }; -module.exports = p5.Geometry; +export default p5.Geometry; diff --git a/src/webgl/p5.Matrix.js b/src/webgl/p5.Matrix.js index 05effe2fe1..7317669c7d 100644 --- a/src/webgl/p5.Matrix.js +++ b/src/webgl/p5.Matrix.js @@ -7,19 +7,13 @@ * Reference/Global_Objects/SIMD */ -'use strict'; +import p5 from '../core/main'; -var p5 = require('../core/main'); - -var GLMAT_ARRAY_TYPE = Array; -var isMatrixArray = function(x) { - return x instanceof Array; -}; +let GLMAT_ARRAY_TYPE = Array; +let isMatrixArray = x => x instanceof Array; if (typeof Float32Array !== 'undefined') { GLMAT_ARRAY_TYPE = Float32Array; - isMatrixArray = function(x) { - return x instanceof Array || x instanceof Float32Array; - }; + isMatrixArray = x => x instanceof Array || x instanceof Float32Array; } /** @@ -31,8 +25,8 @@ if (typeof Float32Array !== 'undefined') { * @param {Array} [mat4] array literal of our 4x4 matrix */ p5.Matrix = function() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; ++i) { + const args = new Array(arguments.length); + for (let i = 0; i < args.length; ++i) { args[i] = arguments[i]; } @@ -114,7 +108,7 @@ p5.Matrix.prototype.get = function() { * @return {p5.Matrix} the result matrix */ p5.Matrix.prototype.copy = function() { - var copied = new p5.Matrix(this.p5); + const copied = new p5.Matrix(this.p5); copied.mat4[0] = this.mat4[0]; copied.mat4[1] = this.mat4[1]; copied.mat4[2] = this.mat4[2]; @@ -139,9 +133,7 @@ p5.Matrix.prototype.copy = function() { * @method identity * @return {p5.Matrix} the result matrix */ -p5.Matrix.identity = function(pInst) { - return new p5.Matrix(pInst); -}; +p5.Matrix.identity = pInst => new p5.Matrix(pInst); /** * transpose according to a given matrix @@ -151,7 +143,7 @@ p5.Matrix.identity = function(pInst) { * @chainable */ p5.Matrix.prototype.transpose = function(a) { - var a01, a02, a03, a12, a13, a23; + let a01, a02, a03, a12, a13, a23; if (a instanceof p5.Matrix) { a01 = a.mat4[1]; a02 = a.mat4[2]; @@ -212,8 +204,8 @@ p5.Matrix.prototype.transpose = function(a) { * @chainable */ p5.Matrix.prototype.invert = function(a) { - var a00, a01, a02, a03, a10, a11, a12, a13; - var a20, a21, a22, a23, a30, a31, a32, a33; + let a00, a01, a02, a03, a10, a11, a12, a13; + let a20, a21, a22, a23, a30, a31, a32, a33; if (a instanceof p5.Matrix) { a00 = a.mat4[0]; a01 = a.mat4[1]; @@ -249,21 +241,21 @@ p5.Matrix.prototype.invert = function(a) { a32 = a[14]; a33 = a[15]; } - var b00 = a00 * a11 - a01 * a10; - var b01 = a00 * a12 - a02 * a10; - var b02 = a00 * a13 - a03 * a10; - var b03 = a01 * a12 - a02 * a11; - var b04 = a01 * a13 - a03 * a11; - var b05 = a02 * a13 - a03 * a12; - var b06 = a20 * a31 - a21 * a30; - var b07 = a20 * a32 - a22 * a30; - var b08 = a20 * a33 - a23 * a30; - var b09 = a21 * a32 - a22 * a31; - var b10 = a21 * a33 - a23 * a31; - var b11 = a22 * a33 - a23 * a32; + const b00 = a00 * a11 - a01 * a10; + const b01 = a00 * a12 - a02 * a10; + const b02 = a00 * a13 - a03 * a10; + const b03 = a01 * a12 - a02 * a11; + const b04 = a01 * a13 - a03 * a11; + const b05 = a02 * a13 - a03 * a12; + const b06 = a20 * a31 - a21 * a30; + const b07 = a20 * a32 - a22 * a30; + const b08 = a20 * a33 - a23 * a30; + const b09 = a21 * a32 - a22 * a31; + const b10 = a21 * a33 - a23 * a31; + const b11 = a22 * a33 - a23 * a32; // Calculate the determinant - var det = + let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (!det) { @@ -297,21 +289,21 @@ p5.Matrix.prototype.invert = function(a) { * @chainable */ p5.Matrix.prototype.invert3x3 = function() { - var a00 = this.mat3[0]; - var a01 = this.mat3[1]; - var a02 = this.mat3[2]; - var a10 = this.mat3[3]; - var a11 = this.mat3[4]; - var a12 = this.mat3[5]; - var a20 = this.mat3[6]; - var a21 = this.mat3[7]; - var a22 = this.mat3[8]; - var b01 = a22 * a11 - a12 * a21; - var b11 = -a22 * a10 + a12 * a20; - var b21 = a21 * a10 - a11 * a20; + const a00 = this.mat3[0]; + const a01 = this.mat3[1]; + const a02 = this.mat3[2]; + const a10 = this.mat3[3]; + const a11 = this.mat3[4]; + const a12 = this.mat3[5]; + const a20 = this.mat3[6]; + const a21 = this.mat3[7]; + const a22 = this.mat3[8]; + const b01 = a22 * a11 - a12 * a21; + const b11 = -a22 * a10 + a12 * a20; + const b21 = a21 * a10 - a11 * a20; // Calculate the determinant - var det = a00 * b01 + a01 * b11 + a02 * b21; + let det = a00 * b01 + a01 * b11 + a02 * b21; if (!det) { return null; } @@ -335,7 +327,7 @@ p5.Matrix.prototype.invert3x3 = function() { * @chainable */ p5.Matrix.prototype.transpose3x3 = function(mat3) { - var a01 = mat3[1], + const a01 = mat3[1], a02 = mat3[2], a12 = mat3[5]; this.mat3[1] = mat3[3]; @@ -371,13 +363,13 @@ p5.Matrix.prototype.inverseTranspose = function(matrix) { this.mat3[8] = matrix.mat4[10]; } - var inverse = this.invert3x3(); + const inverse = this.invert3x3(); // check inverse succeeded if (inverse) { inverse.transpose3x3(this.mat3); } else { // in case of singularity, just zero the matrix - for (var i = 0; i < 9; i++) { + for (let i = 0; i < 9; i++) { this.mat3[i] = 0; } } @@ -390,7 +382,7 @@ p5.Matrix.prototype.inverseTranspose = function(matrix) { * @return {Number} Determinant of our 4x4 matrix */ p5.Matrix.prototype.determinant = function() { - var d00 = this.mat4[0] * this.mat4[5] - this.mat4[1] * this.mat4[4], + const d00 = this.mat4[0] * this.mat4[5] - this.mat4[1] * this.mat4[4], d01 = this.mat4[0] * this.mat4[6] - this.mat4[2] * this.mat4[4], d02 = this.mat4[0] * this.mat4[7] - this.mat4[3] * this.mat4[4], d03 = this.mat4[1] * this.mat4[6] - this.mat4[2] * this.mat4[5], @@ -415,7 +407,7 @@ p5.Matrix.prototype.determinant = function() { * @chainable */ p5.Matrix.prototype.mult = function(multMatrix) { - var _src; + let _src; if (multMatrix === this || multMatrix === this.mat4) { _src = this.copy().mat4; // only need to allocate in this rare case @@ -430,7 +422,7 @@ p5.Matrix.prototype.mult = function(multMatrix) { } // each row is used for the multiplier - var b0 = this.mat4[0], + let b0 = this.mat4[0], b1 = this.mat4[1], b2 = this.mat4[2], b3 = this.mat4[3]; @@ -470,7 +462,7 @@ p5.Matrix.prototype.mult = function(multMatrix) { }; p5.Matrix.prototype.apply = function(multMatrix) { - var _src; + let _src; if (multMatrix === this || multMatrix === this.mat4) { _src = this.copy().mat4; // only need to allocate in this rare case @@ -484,40 +476,40 @@ p5.Matrix.prototype.apply = function(multMatrix) { return; // nothing to do. } - var mat4 = this.mat4; + const mat4 = this.mat4; // each row is used for the multiplier - var m0 = mat4[0]; - var m4 = mat4[4]; - var m8 = mat4[8]; - var m12 = mat4[12]; + const m0 = mat4[0]; + const m4 = mat4[4]; + const m8 = mat4[8]; + const m12 = mat4[12]; mat4[0] = _src[0] * m0 + _src[1] * m4 + _src[2] * m8 + _src[3] * m12; mat4[4] = _src[4] * m0 + _src[5] * m4 + _src[6] * m8 + _src[7] * m12; mat4[8] = _src[8] * m0 + _src[9] * m4 + _src[10] * m8 + _src[11] * m12; mat4[12] = _src[12] * m0 + _src[13] * m4 + _src[14] * m8 + _src[15] * m12; - var m1 = mat4[1]; - var m5 = mat4[5]; - var m9 = mat4[9]; - var m13 = mat4[13]; + const m1 = mat4[1]; + const m5 = mat4[5]; + const m9 = mat4[9]; + const m13 = mat4[13]; mat4[1] = _src[0] * m1 + _src[1] * m5 + _src[2] * m9 + _src[3] * m13; mat4[5] = _src[4] * m1 + _src[5] * m5 + _src[6] * m9 + _src[7] * m13; mat4[9] = _src[8] * m1 + _src[9] * m5 + _src[10] * m9 + _src[11] * m13; mat4[13] = _src[12] * m1 + _src[13] * m5 + _src[14] * m9 + _src[15] * m13; - var m2 = mat4[2]; - var m6 = mat4[6]; - var m10 = mat4[10]; - var m14 = mat4[14]; + const m2 = mat4[2]; + const m6 = mat4[6]; + const m10 = mat4[10]; + const m14 = mat4[14]; mat4[2] = _src[0] * m2 + _src[1] * m6 + _src[2] * m10 + _src[3] * m14; mat4[6] = _src[4] * m2 + _src[5] * m6 + _src[6] * m10 + _src[7] * m14; mat4[10] = _src[8] * m2 + _src[9] * m6 + _src[10] * m10 + _src[11] * m14; mat4[14] = _src[12] * m2 + _src[13] * m6 + _src[14] * m10 + _src[15] * m14; - var m3 = mat4[3]; - var m7 = mat4[7]; - var m11 = mat4[11]; - var m15 = mat4[15]; + const m3 = mat4[3]; + const m7 = mat4[7]; + const m11 = mat4[11]; + const m15 = mat4[15]; mat4[3] = _src[0] * m3 + _src[1] * m7 + _src[2] * m11 + _src[3] * m15; mat4[7] = _src[4] * m3 + _src[5] * m7 + _src[6] * m11 + _src[7] * m15; mat4[11] = _src[8] * m3 + _src[9] * m7 + _src[10] * m11 + _src[11] * m15; @@ -582,38 +574,38 @@ p5.Matrix.prototype.rotate = function(a, x, y, z) { x = x[0]; //must be last } - var len = Math.sqrt(x * x + y * y + z * z); + const len = Math.sqrt(x * x + y * y + z * z); x *= 1 / len; y *= 1 / len; z *= 1 / len; - var a00 = this.mat4[0]; - var a01 = this.mat4[1]; - var a02 = this.mat4[2]; - var a03 = this.mat4[3]; - var a10 = this.mat4[4]; - var a11 = this.mat4[5]; - var a12 = this.mat4[6]; - var a13 = this.mat4[7]; - var a20 = this.mat4[8]; - var a21 = this.mat4[9]; - var a22 = this.mat4[10]; - var a23 = this.mat4[11]; + const a00 = this.mat4[0]; + const a01 = this.mat4[1]; + const a02 = this.mat4[2]; + const a03 = this.mat4[3]; + const a10 = this.mat4[4]; + const a11 = this.mat4[5]; + const a12 = this.mat4[6]; + const a13 = this.mat4[7]; + const a20 = this.mat4[8]; + const a21 = this.mat4[9]; + const a22 = this.mat4[10]; + const a23 = this.mat4[11]; //sin,cos, and tan of respective angle - var sA = Math.sin(a); - var cA = Math.cos(a); - var tA = 1 - cA; + const sA = Math.sin(a); + const cA = Math.cos(a); + const tA = 1 - cA; // Construct the elements of the rotation matrix - var b00 = x * x * tA + cA; - var b01 = y * x * tA + z * sA; - var b02 = z * x * tA - y * sA; - var b10 = x * y * tA - z * sA; - var b11 = y * y * tA + cA; - var b12 = z * y * tA + x * sA; - var b20 = x * z * tA + y * sA; - var b21 = y * z * tA - x * sA; - var b22 = z * z * tA + cA; + const b00 = x * x * tA + cA; + const b01 = y * x * tA + z * sA; + const b02 = z * x * tA - y * sA; + const b10 = x * y * tA - z * sA; + const b11 = y * y * tA + cA; + const b12 = z * y * tA + x * sA; + const b20 = x * z * tA + y * sA; + const b21 = y * z * tA - x * sA; + const b22 = z * z * tA + cA; // rotation-specific matrix multiplication this.mat4[0] = a00 * b00 + a10 * b01 + a20 * b02; @@ -640,7 +632,7 @@ p5.Matrix.prototype.rotate = function(a, x, y, z) { * @chainable */ p5.Matrix.prototype.translate = function(v) { - var x = v[0], + const x = v[0], y = v[1], z = v[2] || 0; this.mat4[12] += this.mat4[0] * x + this.mat4[4] * y + this.mat4[8] * z; @@ -669,7 +661,7 @@ p5.Matrix.prototype.rotateZ = function(a) { * @chainable */ p5.Matrix.prototype.perspective = function(fovy, aspect, near, far) { - var f = 1.0 / Math.tan(fovy / 2), + const f = 1.0 / Math.tan(fovy / 2), nf = 1 / (near - far); this.mat4[0] = f / aspect; @@ -704,7 +696,7 @@ p5.Matrix.prototype.perspective = function(fovy, aspect, near, far) { * @chainable */ p5.Matrix.prototype.ortho = function(left, right, bottom, top, near, far) { - var lr = 1 / (left - right), + const lr = 1 / (left - right), bt = 1 / (bottom - top), nf = 1 / (near - far); this.mat4[0] = -2 * lr; @@ -735,10 +727,10 @@ p5.Matrix.prototype.ortho = function(left, right, bottom, top, near, far) { // gluPerspective // // function _makePerspective(fovy, aspect, znear, zfar){ -// var ymax = znear * Math.tan(fovy * Math.PI / 360.0); -// var ymin = -ymax; -// var xmin = ymin * aspect; -// var xmax = ymax * aspect; +// const ymax = znear * Math.tan(fovy * Math.PI / 360.0); +// const ymin = -ymax; +// const xmin = ymin * aspect; +// const xmax = ymax * aspect; // return _makeFrustum(xmin, xmax, ymin, ymax, znear, zfar); // } @@ -746,13 +738,13 @@ p5.Matrix.prototype.ortho = function(left, right, bottom, top, near, far) { //// glFrustum //// //function _makeFrustum(left, right, bottom, top, znear, zfar){ -// var X = 2*znear/(right-left); -// var Y = 2*znear/(top-bottom); -// var A = (right+left)/(right-left); -// var B = (top+bottom)/(top-bottom); -// var C = -(zfar+znear)/(zfar-znear); -// var D = -2*zfar*znear/(zfar-znear); -// var frustrumMatrix =[ +// const X = 2*znear/(right-left); +// const Y = 2*znear/(top-bottom); +// const A = (right+left)/(right-left); +// const B = (top+bottom)/(top-bottom); +// const C = -(zfar+znear)/(zfar-znear); +// const D = -2*zfar*znear/(zfar-znear); +// const frustrumMatrix =[ // X, 0, A, 0, // 0, Y, B, 0, // 0, 0, C, D, @@ -765,7 +757,7 @@ p5.Matrix.prototype.ortho = function(left, right, bottom, top, near, far) { ////an identity matrix ////@TODO use the p5.Matrix class to abstract away our MV matrices and ///other math -//var _mvMatrix = +//const _mvMatrix = //[ // 1.0,0.0,0.0,0.0, // 0.0,1.0,0.0,0.0, @@ -773,4 +765,4 @@ p5.Matrix.prototype.ortho = function(left, right, bottom, top, near, far) { // 0.0,0.0,0.0,1.0 //]; -module.exports = p5.Matrix; +export default p5.Matrix; diff --git a/src/webgl/p5.RendererGL.Immediate.js b/src/webgl/p5.RendererGL.Immediate.js index 66436d76e4..e6c5041510 100644 --- a/src/webgl/p5.RendererGL.Immediate.js +++ b/src/webgl/p5.RendererGL.Immediate.js @@ -11,10 +11,8 @@ * however, Immediate Mode is useful for sketching quick * geometric ideas. */ -'use strict'; - -var p5 = require('../core/main'); -var constants = require('../core/constants'); +import p5 from '../core/main'; +import * as constants from '../core/constants'; /** * Begin shape drawing. This is a helpful way of generating @@ -76,7 +74,7 @@ p5.RendererGL.prototype.beginShape = function(mode) { * @TODO implement handling of p5.Vector args */ p5.RendererGL.prototype.vertex = function(x, y) { - var z, u, v; + let z, u, v; // default to (x, y) mode: all other arugments assumed to be 0. z = u = v = 0; @@ -99,9 +97,9 @@ p5.RendererGL.prototype.vertex = function(x, y) { } else if (this.immediateMode._testIfCoplanar !== z) { this.immediateMode._isCoplanar = false; } - var vert = new p5.Vector(x, y, z); + const vert = new p5.Vector(x, y, z); this.immediateMode.vertices.push(vert); - var vertexColor = this.curFillColor || [0.5, 0.5, 0.5, 1.0]; + const vertexColor = this.curFillColor || [0.5, 0.5, 0.5, 1.0]; this.immediateMode.vertexColors.push( vertexColor[0], vertexColor[1], @@ -157,24 +155,24 @@ p5.RendererGL.prototype.endShape = function( } else if (this.immediateMode.vertices.length > 1) { if (this._doStroke && this.drawMode !== constants.TEXTURE) { if (this.immediateMode.shapeMode === constants.TRIANGLE_STRIP) { - var i; + let i; for (i = 0; i < this.immediateMode.vertices.length - 2; i++) { this.immediateMode.edges.push([i, i + 1]); this.immediateMode.edges.push([i, i + 2]); } this.immediateMode.edges.push([i, i + 1]); } else if (this.immediateMode.shapeMode === constants.TRIANGLES) { - for (i = 0; i < this.immediateMode.vertices.length - 2; i = i + 3) { + for (let i = 0; i < this.immediateMode.vertices.length - 2; i = i + 3) { this.immediateMode.edges.push([i, i + 1]); this.immediateMode.edges.push([i + 1, i + 2]); this.immediateMode.edges.push([i + 2, i]); } } else if (this.immediateMode.shapeMode === constants.LINES) { - for (i = 0; i < this.immediateMode.vertices.length - 1; i = i + 2) { + for (let i = 0; i < this.immediateMode.vertices.length - 1; i = i + 2) { this.immediateMode.edges.push([i, i + 1]); } } else { - for (i = 0; i < this.immediateMode.vertices.length - 1; i++) { + for (let i = 0; i < this.immediateMode.vertices.length - 1; i++) { this.immediateMode.edges.push([i, i + 1]); } } @@ -199,13 +197,13 @@ p5.RendererGL.prototype.endShape = function( this.immediateMode._isCoplanar === true) ) { this.immediateMode.shapeMode = constants.TRIANGLES; - var contours = [ + const contours = [ new Float32Array(this._vToNArray(this.immediateMode.vertices)) ]; - var polyTriangles = this._triangulate(contours); + const polyTriangles = this._triangulate(contours); this.immediateMode.vertices = []; for ( - var j = 0, polyTriLength = polyTriangles.length; + let j = 0, polyTriLength = polyTriangles.length; j < polyTriLength; j = j + 3 ) { @@ -254,8 +252,8 @@ p5.RendererGL.prototype._drawFillImmediateMode = function( isContour, shapeKind ) { - var gl = this.GL; - var shader = this._getImmediateFillShader(); + const gl = this.GL; + const shader = this._getImmediateFillShader(); this._setFillUniforms(shader); // initialize the fill shader's 'aPosition' buffer @@ -323,9 +321,9 @@ p5.RendererGL.prototype._drawFillImmediateMode = function( this.immediateMode.shapeMode === constants.QUAD_STRIP ) { throw new Error( - 'sorry, ' + - this.immediateMode.shapeMode + - ' not yet implemented in webgl mode.' + `sorry, ${ + this.immediateMode.shapeMode + } not yet implemented in webgl mode.` ); } else { this._applyColorBlend(this.curFillColor); @@ -343,8 +341,8 @@ p5.RendererGL.prototype._drawFillImmediateMode = function( }; p5.RendererGL.prototype._drawStrokeImmediateMode = function() { - var gl = this.GL; - var shader = this._getImmediateStrokeShader(); + const gl = this.GL; + const shader = this._getImmediateStrokeShader(); this._setStrokeUniforms(shader); // initialize the stroke shader's 'aPosition' buffer @@ -380,4 +378,4 @@ p5.RendererGL.prototype._drawStrokeImmediateMode = function() { shader.unbindShader(); }; -module.exports = p5.RendererGL; +export default p5.RendererGL; diff --git a/src/webgl/p5.RendererGL.Retained.js b/src/webgl/p5.RendererGL.Retained.js index d650df48ff..e323e31fc0 100644 --- a/src/webgl/p5.RendererGL.Retained.js +++ b/src/webgl/p5.RendererGL.Retained.js @@ -1,9 +1,7 @@ //Retained Mode. The default mode for rendering 3D primitives //in WEBGL. -'use strict'; - -var p5 = require('../core/main'); -require('./p5.RendererGL'); +import p5 from '../core/main'; +import './p5.RendererGL'; // a render buffer definition function BufferDef(size, src, dst, attr, map) { @@ -14,15 +12,15 @@ function BufferDef(size, src, dst, attr, map) { this.map = map; // optional, a transformation function to apply to src } -var _flatten = p5.RendererGL.prototype._flatten; -var _vToNArray = p5.RendererGL.prototype._vToNArray; +const _flatten = p5.RendererGL.prototype._flatten; +const _vToNArray = p5.RendererGL.prototype._vToNArray; -var strokeBuffers = [ +const strokeBuffers = [ new BufferDef(3, 'lineVertices', 'lineVertexBuffer', 'aPosition', _flatten), new BufferDef(4, 'lineNormals', 'lineNormalBuffer', 'aDirection', _flatten) ]; -var fillBuffers = [ +const fillBuffers = [ new BufferDef(3, 'vertices', 'vertexBuffer', 'aPosition', _vToNArray), new BufferDef(3, 'vertexNormals', 'normalBuffer', 'aNormal', _vToNArray), new BufferDef(4, 'vertexColors', 'colorBuffer', 'aMaterialColor'), @@ -36,7 +34,7 @@ p5.RendererGL._textBuffers = [ new BufferDef(2, 'uvs', 'uvBuffer', 'aTexCoord', _flatten) ]; -var hashCount = 0; +let hashCount = 0; /** * _initBufferDefaults * @private @@ -51,7 +49,7 @@ p5.RendererGL.prototype._initBufferDefaults = function(gId) { //@TODO remove this limit on hashes in gHash hashCount++; if (hashCount > 1000) { - var key = Object.keys(this.gHash)[0]; + const key = Object.keys(this.gHash)[0]; delete this.gHash[key]; hashCount--; } @@ -61,7 +59,7 @@ p5.RendererGL.prototype._initBufferDefaults = function(gId) { }; p5.RendererGL.prototype._freeBuffers = function(gId) { - var buffers = this.gHash[gId]; + const buffers = this.gHash[gId]; if (!buffers) { return; } @@ -69,14 +67,13 @@ p5.RendererGL.prototype._freeBuffers = function(gId) { delete this.gHash[gId]; hashCount--; - var gl = this.GL; + const gl = this.GL; if (buffers.indexBuffer) { gl.deleteBuffer(buffers.indexBuffer); } function freeBuffers(defs) { - for (var i = 0; i < defs.length; i++) { - var def = defs[i]; + for (const def of defs) { if (buffers[def.dst]) { gl.deleteBuffer(buffers[def.dst]); buffers[def.dst] = null; @@ -90,24 +87,22 @@ p5.RendererGL.prototype._freeBuffers = function(gId) { }; p5.RendererGL.prototype._prepareBuffers = function(buffers, shader, defs) { - var model = buffers.model; - var attributes = shader.attributes; - var gl = this.GL; + const model = buffers.model; + const attributes = shader.attributes; + const gl = this.GL; // loop through each of the buffer definitions - for (var i = 0; i < defs.length; i++) { - var def = defs[i]; - - var attr = attributes[def.attr]; + for (const def of defs) { + const attr = attributes[def.attr]; if (!attr) continue; - var buffer = buffers[def.dst]; + let buffer = buffers[def.dst]; // check if the model has the appropriate source array - var src = model[def.src]; + const src = model[def.src]; if (src) { // check if we need to create the GL buffer - var createBuffer = !buffer; + const createBuffer = !buffer; if (createBuffer) { // create and remember the buffer buffers[def.dst] = buffer = gl.createBuffer(); @@ -117,9 +112,9 @@ p5.RendererGL.prototype._prepareBuffers = function(buffers, shader, defs) { // check if we need to fill the buffer with data if (createBuffer || model.dirtyFlags[def.src] !== false) { - var map = def.map; + const map = def.map; // get the values from the model, possibly transformed - var values = map ? map(src) : src; + const values = map ? map(src) : src; // fill the buffer with the values this._bindBuffer(buffer, gl.ARRAY_BUFFER, values); @@ -149,17 +144,17 @@ p5.RendererGL.prototype._prepareBuffers = function(buffers, shader, defs) { * @param {p5.Geometry} model contains geometry data */ p5.RendererGL.prototype.createBuffers = function(gId, model) { - var gl = this.GL; + const gl = this.GL; //initialize the gl buffers for our geom groups - var buffers = this._initBufferDefaults(gId); + const buffers = this._initBufferDefaults(gId); buffers.model = model; - var indexBuffer = buffers.indexBuffer; + let indexBuffer = buffers.indexBuffer; if (model.faces.length) { // allocate space for faces if (!indexBuffer) indexBuffer = buffers.indexBuffer = gl.createBuffer(); - var vals = p5.RendererGL.prototype._flatten(model.faces); + const vals = p5.RendererGL.prototype._flatten(model.faces); this._bindBuffer(indexBuffer, gl.ELEMENT_ARRAY_BUFFER, vals, Uint16Array); // the vertex count is based on the number of faces @@ -186,11 +181,11 @@ p5.RendererGL.prototype.createBuffers = function(gId, model) { * @chainable */ p5.RendererGL.prototype.drawBuffers = function(gId) { - var gl = this.GL; - var buffers = this.gHash[gId]; + const gl = this.GL; + const buffers = this.gHash[gId]; if (this._doStroke && buffers.lineVertexCount > 0) { - var strokeShader = this._getRetainedStrokeShader(); + const strokeShader = this._getRetainedStrokeShader(); this._setStrokeUniforms(strokeShader); this._prepareBuffers(buffers, strokeShader, strokeBuffers); this._applyColorBlend(this.curStrokeColor); @@ -199,7 +194,7 @@ p5.RendererGL.prototype.drawBuffers = function(gId) { } if (this._doFill) { - var fillShader = this._getRetainedFillShader(); + const fillShader = this._getRetainedFillShader(); this._setFillUniforms(fillShader); this._prepareBuffers(buffers, fillShader, fillBuffers); if (buffers.indexBuffer) { @@ -234,7 +229,7 @@ p5.RendererGL.prototype.drawBuffersScaled = function( scaleY, scaleZ ) { - var uMVMatrix = this.uMVMatrix.copy(); + const uMVMatrix = this.uMVMatrix.copy(); try { this.uMVMatrix.scale(scaleX, scaleY, scaleZ); this.drawBuffers(gId); @@ -250,8 +245,8 @@ p5.RendererGL.prototype._drawArrays = function(drawMode, gId) { }; p5.RendererGL.prototype._drawElements = function(drawMode, gId) { - var buffers = this.gHash[gId]; - var gl = this.GL; + const buffers = this.gHash[gId]; + const gl = this.GL; // render the fill if (buffers.indexBuffer) { // we're drawing faces @@ -264,8 +259,8 @@ p5.RendererGL.prototype._drawElements = function(drawMode, gId) { }; p5.RendererGL.prototype._drawPoints = function(vertices, vertexBuffer) { - var gl = this.GL; - var pointShader = this._getImmediatePointShader(); + const gl = this.GL; + const pointShader = this._getImmediatePointShader(); this._setPointUniforms(pointShader); this._bindBuffer( @@ -284,4 +279,4 @@ p5.RendererGL.prototype._drawPoints = function(vertices, vertexBuffer) { this._pixelsState._pixelsDirty = true; }; -module.exports = p5.RendererGL; +export default p5.RendererGL; diff --git a/src/webgl/p5.RendererGL.js b/src/webgl/p5.RendererGL.js index 14ecc1d31b..1ca756d6cc 100755 --- a/src/webgl/p5.RendererGL.js +++ b/src/webgl/p5.RendererGL.js @@ -1,52 +1,51 @@ -'use strict'; - -var p5 = require('../core/main'); -var constants = require('../core/constants'); -var libtess = require('libtess'); -require('./p5.Shader'); -require('./p5.Camera'); -require('../core/p5.Renderer'); -require('./p5.Matrix'); -var fs = require('fs'); - -var lightingShader = fs.readFileSync( - __dirname + '/shaders/lighting.glsl', +import p5 from '../core/main'; +import * as constants from '../core/constants'; +import libtess from 'libtess'; +import './p5.Shader'; +import './p5.Camera'; +import '../core/p5.Renderer'; +import './p5.Matrix'; +import { readFileSync } from 'fs'; +import { join } from 'path'; + +const lightingShader = readFileSync( + join(__dirname, '/shaders/lighting.glsl'), 'utf-8' ); -var defaultShaders = { - immediateVert: fs.readFileSync( - __dirname + '/shaders/immediate.vert', +const defaultShaders = { + immediateVert: readFileSync( + join(__dirname, '/shaders/immediate.vert'), 'utf-8' ), - vertexColorVert: fs.readFileSync( - __dirname + '/shaders/vertexColor.vert', + vertexColorVert: readFileSync( + join(__dirname, '/shaders/vertexColor.vert'), 'utf-8' ), - vertexColorFrag: fs.readFileSync( - __dirname + '/shaders/vertexColor.frag', + vertexColorFrag: readFileSync( + join(__dirname, '/shaders/vertexColor.frag'), 'utf-8' ), - normalVert: fs.readFileSync(__dirname + '/shaders/normal.vert', 'utf-8'), - normalFrag: fs.readFileSync(__dirname + '/shaders/normal.frag', 'utf-8'), - basicFrag: fs.readFileSync(__dirname + '/shaders/basic.frag', 'utf-8'), + normalVert: readFileSync(join(__dirname, '/shaders/normal.vert'), 'utf-8'), + normalFrag: readFileSync(join(__dirname, '/shaders/normal.frag'), 'utf-8'), + basicFrag: readFileSync(join(__dirname, '/shaders/basic.frag'), 'utf-8'), lightVert: lightingShader + - fs.readFileSync(__dirname + '/shaders/light.vert', 'utf-8'), - lightTextureFrag: fs.readFileSync( - __dirname + '/shaders/light_texture.frag', + readFileSync(join(__dirname, '/shaders/light.vert'), 'utf-8'), + lightTextureFrag: readFileSync( + join(__dirname, '/shaders/light_texture.frag'), 'utf-8' ), - phongVert: fs.readFileSync(__dirname + '/shaders/phong.vert', 'utf-8'), + phongVert: readFileSync(join(__dirname, '/shaders/phong.vert'), 'utf-8'), phongFrag: lightingShader + - fs.readFileSync(__dirname + '/shaders/phong.frag', 'utf-8'), - fontVert: fs.readFileSync(__dirname + '/shaders/font.vert', 'utf-8'), - fontFrag: fs.readFileSync(__dirname + '/shaders/font.frag', 'utf-8'), - lineVert: fs.readFileSync(__dirname + '/shaders/line.vert', 'utf-8'), - lineFrag: fs.readFileSync(__dirname + '/shaders/line.frag', 'utf-8'), - pointVert: fs.readFileSync(__dirname + '/shaders/point.vert', 'utf-8'), - pointFrag: fs.readFileSync(__dirname + '/shaders/point.frag', 'utf-8') + readFileSync(join(__dirname, '/shaders/phong.frag'), 'utf-8'), + fontVert: readFileSync(join(__dirname, '/shaders/font.vert'), 'utf-8'), + fontFrag: readFileSync(join(__dirname, '/shaders/font.frag'), 'utf-8'), + lineVert: readFileSync(join(__dirname, '/shaders/line.vert'), 'utf-8'), + lineFrag: readFileSync(join(__dirname, '/shaders/line.frag'), 'utf-8'), + pointVert: readFileSync(join(__dirname, '/shaders/point.vert'), 'utf-8'), + pointFrag: readFileSync(join(__dirname, '/shaders/point.frag'), 'utf-8') }; /** @@ -163,8 +162,8 @@ p5.RendererGL.prototype = Object.create(p5.Renderer.prototype); // Setting ////////////////////////////////////////////// -p5.RendererGL.prototype._setAttributeDefaults = function(pInst) { - var defaults = { +p5.RendererGL.prototype._setAttributeDefaults = pInst => { + const defaults = { alpha: true, depth: true, stencil: true, @@ -189,7 +188,7 @@ p5.RendererGL.prototype._initContext = function() { if (this.drawingContext === null) { throw new Error('Error creating webgl context'); } else { - var gl = this.drawingContext; + const gl = this.drawingContext; gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); @@ -206,22 +205,22 @@ p5.RendererGL.prototype._initContext = function() { //are changed with setAttributes() p5.RendererGL.prototype._resetContext = function(options, callback) { - var w = this.width; - var h = this.height; - var defaultId = this.canvas.id; - var isPGraphics = this._pInst instanceof p5.Graphics; + const w = this.width; + const h = this.height; + const defaultId = this.canvas.id; + const isPGraphics = this._pInst instanceof p5.Graphics; if (isPGraphics) { - var pg = this._pInst; + const pg = this._pInst; pg.canvas.parentNode.removeChild(pg.canvas); pg.canvas = document.createElement('canvas'); - var node = pg._pInst._userNode || document.body; + const node = pg._pInst._userNode || document.body; node.appendChild(pg.canvas); p5.Element.call(pg, pg.canvas, pg._pInst); pg.width = w; pg.height = h; } else { - var c = this.canvas; + let c = this.canvas; if (c) { c.parentNode.removeChild(c); } @@ -235,7 +234,7 @@ p5.RendererGL.prototype._resetContext = function(options, callback) { this._pInst.canvas = c; } - var renderer = new p5.RendererGL( + const renderer = new p5.RendererGL( this._pInst.canvas, this._pInst, !isPGraphics @@ -251,7 +250,7 @@ p5.RendererGL.prototype._resetContext = function(options, callback) { if (typeof callback === 'function') { //setTimeout with 0 forces the task to the back of the queue, this ensures that //we finish switching out the renderer - setTimeout(function() { + setTimeout(() => { callback.apply(window._renderer, options); }, 0); } @@ -354,7 +353,7 @@ p5.RendererGL.prototype._resetContext = function(options, callback) { * fill(255); * } * - * var lights = [ + * const lights = [ * { c: '#f00', t: 1.12, p: 1.91, r: 0.2 }, * { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 }, * { c: '#00f', t: 1.37, p: 1.57, r: 0.2 }, @@ -364,12 +363,12 @@ p5.RendererGL.prototype._resetContext = function(options, callback) { * ]; * * function draw() { - * var t = millis() / 1000 + 1000; + * let t = millis() / 1000 + 1000; * background(0); * directionalLight(color('#222'), 1, 1, 1); * - * for (var i = 0; i < lights.length; i++) { - * var light = lights[i]; + * for (let i = 0; i < lights.length; i++) { + * let light = lights[i]; * pointLight( * color(light.c), * p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r) @@ -414,7 +413,7 @@ p5.prototype.setAttributes = function(key, value) { ); return; } - var unchanged = true; + let unchanged = true; if (typeof value !== 'undefined') { //first time modifying the attributes if (this._glAttributes === null) { @@ -438,7 +437,7 @@ p5.prototype.setAttributes = function(key, value) { } if (!this._setupDone) { - for (var x in this._renderer.gHash) { + for (const x in this._renderer.gHash) { if (this._renderer.gHash.hasOwnProperty(x)) { console.error( 'Sorry, Could not set the attributes, you need to call setAttributes() ' + @@ -505,12 +504,12 @@ p5.RendererGL.prototype._update = function() { /** * [background description] */ -p5.RendererGL.prototype.background = function() { - var _col = this._pInst.color.apply(this._pInst, arguments); - var _r = _col.levels[0] / 255; - var _g = _col.levels[1] / 255; - var _b = _col.levels[2] / 255; - var _a = _col.levels[3] / 255; +p5.RendererGL.prototype.background = function(...args) { + const _col = this._pInst.color(...args); + const _r = _col.levels[0] / 255; + const _g = _col.levels[1] / 255; + const _b = _col.levels[2] / 255; + const _a = _col.levels[3] / 255; this.GL.clearColor(_r, _g, _b, _a); this.GL.depthMask(true); this.GL.clear(this.GL.COLOR_BUFFER_BIT | this.GL.DEPTH_BUFFER_BIT); @@ -555,7 +554,7 @@ p5.RendererGL.prototype.background = function() { */ p5.RendererGL.prototype.fill = function(v1, v2, v3, a) { //see material.js for more info on color blending in webgl - var color = p5.prototype.color.apply(this._pInst, arguments); + const color = p5.prototype.color.apply(this._pInst, arguments); this.curFillColor = color._array; this.drawMode = constants.FILL; this._useNormalMaterial = false; @@ -597,11 +596,11 @@ p5.RendererGL.prototype.stroke = function(r, g, b, a) { //@todo allow transparency in stroking currently doesn't have //any impact and causes problems with specularMaterial arguments[3] = 255; - var color = p5.prototype.color.apply(this._pInst, arguments); + const color = p5.prototype.color.apply(this._pInst, arguments); this.curStrokeColor = color._array; }; -p5.RendererGL.prototype.strokeCap = function(cap) { +p5.RendererGL.prototype.strokeCap = cap => { // @TODO : to be implemented console.error('Sorry, strokeCap() is not yet implemented in WEBGL mode'); }; @@ -681,8 +680,8 @@ p5.RendererGL.prototype.strokeWeight = function(w) { // x,y are canvas-relative (pre-scaled by _pixelDensity) p5.RendererGL.prototype._getPixel = function(x, y) { - var pixelsState = this._pixelsState; - var imageData, index; + const pixelsState = this._pixelsState; + let imageData, index; if (pixelsState._pixelsDirty) { imageData = new Uint8Array(4); // prettier-ignore @@ -715,7 +714,7 @@ p5.RendererGL.prototype._getPixel = function(x, y) { */ p5.RendererGL.prototype.loadPixels = function() { - var pixelsState = this._pixelsState; + const pixelsState = this._pixelsState; if (!pixelsState._pixelsDirty) return; pixelsState._pixelsDirty = false; @@ -729,14 +728,14 @@ p5.RendererGL.prototype.loadPixels = function() { //if there isn't a renderer-level temporary pixels buffer //make a new one - var pixels = pixelsState.pixels; - var len = this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4; + let pixels = pixelsState.pixels; + const len = this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4; if (!(pixels instanceof Uint8Array) || pixels.length !== len) { pixels = new Uint8Array(len); this._pixelsState._setProperty('pixels', pixels); } - var pd = this._pInst._pixelDensity; + const pd = this._pInst._pixelDensity; // prettier-ignore this.GL.readPixels( 0, 0, this.width * pd, this.height * pd, @@ -772,7 +771,7 @@ p5.RendererGL.prototype.resize = function(w, h) { this._curCamera._resize(); //resize pixels buffer - var pixelsState = this._pixelsState; + const pixelsState = this._pixelsState; pixelsState._pixelsDirty = true; if (typeof pixelsState.pixels !== 'undefined') { pixelsState._setProperty( @@ -793,11 +792,11 @@ p5.RendererGL.prototype.resize = function(w, h) { * @param {Number} b normalized blue val. * @param {Number} a normalized alpha val. */ -p5.RendererGL.prototype.clear = function() { - var _r = arguments[0] || 0; - var _g = arguments[1] || 0; - var _b = arguments[2] || 0; - var _a = arguments[3] || 0; +p5.RendererGL.prototype.clear = function(...args) { + const _r = args[0] || 0; + const _g = args[1] || 0; + const _b = args[2] || 0; + const _a = args[3] || 0; this.GL.clearColor(_r, _g, _b, _a); this.GL.clear(this.GL.COLOR_BUFFER_BIT | this.GL.DEPTH_BUFFER_BIT); this._pixelsState._pixelsDirty = true; @@ -874,10 +873,10 @@ p5.RendererGL.prototype.rotateZ = function(rad) { p5.RendererGL.prototype.push = function() { // get the base renderer style - var style = p5.Renderer.prototype.push.apply(this); + const style = p5.Renderer.prototype.push.apply(this); // add webgl-specific style properties - var properties = style.properties; + const properties = style.properties; properties.uMVMatrix = this.uMVMatrix.copy(); properties.uPMatrix = this.uPMatrix.copy(); @@ -937,7 +936,7 @@ p5.RendererGL.prototype.resetMatrix = function() { p5.RendererGL.prototype._getImmediateStrokeShader = function() { // select the stroke shader to use - var stroke = this.userStrokeShader; + const stroke = this.userStrokeShader; if (!stroke || !stroke.isStrokeShader()) { return this._getLineShader(); } @@ -960,7 +959,7 @@ p5.RendererGL.prototype._getImmediateFillShader = function() { return this._getImmediateModeShader(); } - var fill = this.userFillShader; + const fill = this.userFillShader; if (this._enableLighting) { if (!fill || !fill.isLightShader()) { return this._getLightShader(); @@ -984,7 +983,7 @@ p5.RendererGL.prototype._getRetainedFillShader = function() { return this._getNormalShader(); } - var fill = this.userFillShader; + const fill = this.userFillShader; if (this._enableLighting) { if (!fill || !fill.isLightShader()) { return this._getLightShader(); @@ -1001,7 +1000,7 @@ p5.RendererGL.prototype._getRetainedFillShader = function() { p5.RendererGL.prototype._getImmediatePointShader = function() { // select the point shader to use - var point = this.userPointShader; + const point = this.userPointShader; if (!point || !point.isPointShader()) { return this._getPointShader(); } @@ -1105,7 +1104,7 @@ p5.RendererGL.prototype._getFontShader = function() { p5.RendererGL.prototype._getEmptyTexture = function() { if (!this._emptyTexture) { // a plain white texture RGBA, full alpha, single pixel. - var im = new p5.Image(1, 1); + const im = new p5.Image(1, 1); im.set(0, 0, 255); this._emptyTexture = new p5.Texture(this, im); } @@ -1113,13 +1112,13 @@ p5.RendererGL.prototype._getEmptyTexture = function() { }; p5.RendererGL.prototype.getTexture = function(img) { - var textures = this.textures; - for (var it = 0; it < textures.length; ++it) { - var texture = textures[it]; + const textures = this.textures; + + for (const texture of textures) { if (texture.src === img) return texture; } - var tex = new p5.Texture(this, img); + const tex = new p5.Texture(this, img); textures.push(tex); return tex; }; @@ -1149,18 +1148,18 @@ p5.RendererGL.prototype._setFillUniforms = function(fillShader) { fillShader.setUniform('uUseLighting', this._enableLighting); - var pointLightCount = this.pointLightColors.length / 3; + const pointLightCount = this.pointLightColors.length / 3; fillShader.setUniform('uPointLightCount', pointLightCount); fillShader.setUniform('uPointLightLocation', this.pointLightPositions); fillShader.setUniform('uPointLightColor', this.pointLightColors); - var directionalLightCount = this.directionalLightColors.length / 3; + const directionalLightCount = this.directionalLightColors.length / 3; fillShader.setUniform('uDirectionalLightCount', directionalLightCount); fillShader.setUniform('uLightingDirection', this.directionalLightDirections); fillShader.setUniform('uDirectionalColor', this.directionalLightColors); // TODO: sum these here... - var ambientLightCount = this.ambientLightColors.length / 3; + const ambientLightCount = this.ambientLightColors.length / 3; fillShader.setUniform('uAmbientLightCount', ambientLightCount); fillShader.setUniform('uAmbientColor', this.ambientLightColors); @@ -1195,7 +1194,7 @@ p5.RendererGL.prototype._bindBuffer = function( if (!target) target = this.GL.ARRAY_BUFFER; this.GL.bindBuffer(target, buffer); if (values !== undefined) { - var data = new (type || Float32Array)(values); + const data = new (type || Float32Array)(values); this.GL.bufferData(target, data, usage || this.GL.STATIC_DRAW); } }; @@ -1210,7 +1209,7 @@ p5.RendererGL.prototype._bindBuffer = function( * @return {Array} 1-dimensional array * [[1, 2, 3],[4, 5, 6]] -> [1, 2, 3, 4, 5, 6] */ -p5.RendererGL.prototype._flatten = function(arr) { +p5.RendererGL.prototype._flatten = arr => { //when empty, return empty if (arr.length === 0) { return []; @@ -1218,15 +1217,15 @@ p5.RendererGL.prototype._flatten = function(arr) { //big models , load slower to avoid stack overflow //faster non-recursive flatten via axelduch //stackoverflow.com/questions/27266550/how-to-flatten-nested-array-in-javascript - var toString = Object.prototype.toString; - var arrayTypeStr = '[object Array]'; - var result = []; - var nodes = arr.slice(); - var node; + const toString = Object.prototype.toString; + const arrayTypeStr = '[object Array]'; + const result = []; + const nodes = arr.slice(); + let node; node = nodes.pop(); do { if (toString.call(node) === arrayTypeStr) { - nodes.push.apply(nodes, node); + nodes.push(...node); } else { result.push(node); } @@ -1236,7 +1235,7 @@ p5.RendererGL.prototype._flatten = function(arr) { } else { //otherwise if model within limits for browser //use faster recursive loading - return [].concat.apply([], arr); + return [].concat(...arr); } }; @@ -1248,12 +1247,13 @@ p5.RendererGL.prototype._flatten = function(arr) { * [p5.Vector(1, 2, 3), p5.Vector(4, 5, 6)] -> * [1, 2, 3, 4, 5, 6] */ -p5.RendererGL.prototype._vToNArray = function(arr) { - var ret = []; - for (var i = 0; i < arr.length; i++) { - var item = arr[i]; +p5.RendererGL.prototype._vToNArray = arr => { + const ret = []; + + for (const item of arr) { ret.push(item.x, item.y, item.z); } + return ret; }; @@ -1263,10 +1263,7 @@ p5.RendererGL.prototype._vToNArray = function(arr) { p5.prototype._assert3d = function(name) { if (!this._renderer.isP3D) throw new Error( - name + - "() is only supported in WEBGL mode. If you'd like to use 3D graphics" + - ' and WebGL, see https://p5js.org/examples/form-3d-primitives.html' + - ' for more information.' + `${name}() is only supported in WEBGL mode. If you'd like to use 3D graphics and WebGL, see https://p5js.org/examples/form-3d-primitives.html for more information.` ); }; @@ -1282,13 +1279,13 @@ p5.RendererGL.prototype._initTessy = function initTesselator() { function begincallback(type) { if (type !== libtess.primitiveType.GL_TRIANGLES) { - console.log('expected TRIANGLES but got type: ' + type); + console.log(`expected TRIANGLES but got type: ${type}`); } } function errorcallback(errno) { console.log('error callback'); - console.log('error number: ' + errno); + console.log(`error number: ${errno}`); } // callback for when segments intersect and must be split function combinecallback(coords, data, weight) { @@ -1299,7 +1296,7 @@ p5.RendererGL.prototype._initTessy = function initTesselator() { // don't really care about the flag, but need no-strip/no-fan behavior } - var tessy = new libtess.GluTesselator(); + const tessy = new libtess.GluTesselator(); tessy.gluTessCallback(libtess.gluEnum.GLU_TESS_VERTEX_DATA, vertexCallback); tessy.gluTessCallback(libtess.gluEnum.GLU_TESS_BEGIN, begincallback); tessy.gluTessCallback(libtess.gluEnum.GLU_TESS_ERROR, errorcallback); @@ -1316,14 +1313,14 @@ p5.RendererGL.prototype._triangulate = function(contours) { // comment out to test normal-generation code this._tessy.gluTessNormal(0, 0, 1); - var triangleVerts = []; + const triangleVerts = []; this._tessy.gluTessBeginPolygon(triangleVerts); - for (var i = 0; i < contours.length; i++) { + for (let i = 0; i < contours.length; i++) { this._tessy.gluTessBeginContour(); - var contour = contours[i]; - for (var j = 0; j < contour.length; j += 3) { - var coords = [contour[j], contour[j + 1], contour[j + 2]]; + const contour = contours[i]; + for (let j = 0; j < contour.length; j += 3) { + const coords = [contour[j], contour[j + 1], contour[j + 2]]; this._tessy.gluTessVertex(coords, coords); } this._tessy.gluTessEndContour(); @@ -1336,31 +1333,31 @@ p5.RendererGL.prototype._triangulate = function(contours) { }; // function to calculate BezierVertex Coefficients -p5.RendererGL.prototype._bezierCoefficients = function(t) { - var t2 = t * t; - var t3 = t2 * t; - var mt = 1 - t; - var mt2 = mt * mt; - var mt3 = mt2 * mt; +p5.RendererGL.prototype._bezierCoefficients = t => { + const t2 = t * t; + const t3 = t2 * t; + const mt = 1 - t; + const mt2 = mt * mt; + const mt3 = mt2 * mt; return [mt3, 3 * mt2 * t, 3 * mt * t2, t3]; }; // function to calculate QuadraticVertex Coefficients -p5.RendererGL.prototype._quadraticCoefficients = function(t) { - var t2 = t * t; - var mt = 1 - t; - var mt2 = mt * mt; +p5.RendererGL.prototype._quadraticCoefficients = t => { + const t2 = t * t; + const mt = 1 - t; + const mt2 = mt * mt; return [mt2, 2 * mt * t, t2]; }; // function to convert Bezier coordinates to Catmull Rom Splines p5.RendererGL.prototype._bezierToCatmull = function(w) { - var p1 = w[1]; - var p2 = w[1] + (w[2] - w[0]) / this._curveTightness; - var p3 = w[2] - (w[3] - w[1]) / this._curveTightness; - var p4 = w[2]; - var p = [p1, p2, p3, p4]; + const p1 = w[1]; + const p2 = w[1] + (w[2] - w[0]) / this._curveTightness; + const p3 = w[2] - (w[3] - w[1]) / this._curveTightness; + const p4 = w[2]; + const p = [p1, p2, p3, p4]; return p; }; -module.exports = p5.RendererGL; +export default p5.RendererGL; diff --git a/src/webgl/p5.Shader.js b/src/webgl/p5.Shader.js index c75753e5e2..373cdb0d1b 100644 --- a/src/webgl/p5.Shader.js +++ b/src/webgl/p5.Shader.js @@ -6,9 +6,7 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); +import p5 from '../core/main'; /** * Shader class for WEBGL Mode @@ -47,7 +45,7 @@ p5.Shader = function(renderer, vertSrc, fragSrc) { */ p5.Shader.prototype.init = function() { if (this._glProgram === 0 /* or context is stale? */) { - var gl = this._renderer.GL; + const gl = this._renderer.GL; // @todo: once custom shading is allowed, // friendly error messages should be used here to share @@ -64,8 +62,9 @@ p5.Shader.prototype.init = function() { // if our vertex shader failed compilation? if (!gl.getShaderParameter(this._vertShader, gl.COMPILE_STATUS)) { console.error( - 'Yikes! An error occurred compiling the vertex shader:' + - gl.getShaderInfoLog(this._vertShader) + `Yikes! An error occurred compiling the vertex shader:${gl.getShaderInfoLog( + this._vertShader + )}` ); return null; } @@ -77,8 +76,9 @@ p5.Shader.prototype.init = function() { // if our frag shader failed compilation? if (!gl.getShaderParameter(this._fragShader, gl.COMPILE_STATUS)) { console.error( - 'Darn! An error occurred compiling the fragment shader:' + - gl.getShaderInfoLog(this._fragShader) + `Darn! An error occurred compiling the fragment shader:${gl.getShaderInfoLog( + this._fragShader + )}` ); return null; } @@ -89,8 +89,9 @@ p5.Shader.prototype.init = function() { gl.linkProgram(this._glProgram); if (!gl.getProgramParameter(this._glProgram, gl.LINK_STATUS)) { console.error( - 'Snap! Error linking shader program: ' + - gl.getProgramInfoLog(this._glProgram) + `Snap! Error linking shader program: ${gl.getProgramInfoLog( + this._glProgram + )}` ); } @@ -113,17 +114,17 @@ p5.Shader.prototype._loadAttributes = function() { this.attributes = {}; - var gl = this._renderer.GL; + const gl = this._renderer.GL; - var numAttributes = gl.getProgramParameter( + const numAttributes = gl.getProgramParameter( this._glProgram, gl.ACTIVE_ATTRIBUTES ); - for (var i = 0; i < numAttributes; ++i) { - var attributeInfo = gl.getActiveAttrib(this._glProgram, i); - var name = attributeInfo.name; - var location = gl.getAttribLocation(this._glProgram, name); - var attribute = {}; + for (let i = 0; i < numAttributes; ++i) { + const attributeInfo = gl.getActiveAttrib(this._glProgram, i); + const name = attributeInfo.name; + const location = gl.getAttribLocation(this._glProgram, name); + const attribute = {}; attribute.name = name; attribute.location = location; attribute.index = i; @@ -146,18 +147,21 @@ p5.Shader.prototype._loadUniforms = function() { return; } - var gl = this._renderer.GL; + const gl = this._renderer.GL; // Inspect shader and cache uniform info - var numUniforms = gl.getProgramParameter(this._glProgram, gl.ACTIVE_UNIFORMS); + const numUniforms = gl.getProgramParameter( + this._glProgram, + gl.ACTIVE_UNIFORMS + ); - var samplerIndex = 0; - for (var i = 0; i < numUniforms; ++i) { - var uniformInfo = gl.getActiveUniform(this._glProgram, i); - var uniform = {}; + let samplerIndex = 0; + for (let i = 0; i < numUniforms; ++i) { + const uniformInfo = gl.getActiveUniform(this._glProgram, i); + const uniform = {}; uniform.location = gl.getUniformLocation(this._glProgram, uniformInfo.name); uniform.size = uniformInfo.size; - var uniformName = uniformInfo.name; + let uniformName = uniformInfo.name; //uniforms thats are arrays have their name returned as //someUniform[0] which is a bit silly so we trim it //off here. The size property tells us that its an array @@ -177,7 +181,7 @@ p5.Shader.prototype._loadUniforms = function() { this._loadedUniforms = true; }; -p5.Shader.prototype.compile = function() { +p5.Shader.prototype.compile = () => { // TODO }; @@ -213,10 +217,10 @@ p5.Shader.prototype.unbindShader = function() { }; p5.Shader.prototype.bindTextures = function() { - var gl = this._renderer.GL; - for (var i = 0; i < this.samplers.length; i++) { - var uniform = this.samplers[i]; - var tex = uniform.texture; + const gl = this._renderer.GL; + + for (const uniform of this.samplers) { + let tex = uniform.texture; if (tex === undefined) { // user hasn't yet supplied a texture for this slot. // (or there may not be one--maybe just lighting), @@ -231,16 +235,15 @@ p5.Shader.prototype.bindTextures = function() { }; p5.Shader.prototype.updateTextures = function() { - for (var i = 0; i < this.samplers.length; i++) { - var uniform = this.samplers[i]; - var tex = uniform.texture; + for (const uniform of this.samplers) { + const tex = uniform.texture; if (tex) { tex.update(); } } }; -p5.Shader.prototype.unbindTextures = function() { +p5.Shader.prototype.unbindTextures = () => { // TODO: migrate stuff from material.js here // - OR - have material.js define this function }; @@ -261,7 +264,7 @@ p5.Shader.prototype._setMatrixUniforms = function() { * @private */ p5.Shader.prototype.useProgram = function() { - var gl = this._renderer.GL; + const gl = this._renderer.GL; gl.useProgram(this._glProgram); return this; }; @@ -331,14 +334,14 @@ p5.Shader.prototype.useProgram = function() { p5.Shader.prototype.setUniform = function(uniformName, data) { //@todo update all current gl.uniformXX calls - var uniform = this.uniforms[uniformName]; + const uniform = this.uniforms[uniformName]; if (!uniform) { return; } - var location = uniform.location; + const location = uniform.location; - var gl = this._renderer.GL; + const gl = this._renderer.GL; this.useProgram(); switch (uniform.type) { @@ -485,14 +488,14 @@ p5.Shader.prototype.enableAttrib = function( this.attributes[attr.name] !== attr ) { console.warn( - 'The attribute "' + - attr.name + - '"passed to enableAttrib does not belong to this shader.' + `The attribute "${ + attr.name + }"passed to enableAttrib does not belong to this shader.` ); } - var loc = attr.location; + const loc = attr.location; if (loc !== -1) { - var gl = this._renderer.GL; + const gl = this._renderer.GL; gl.enableVertexAttribArray(loc); gl.vertexAttribPointer( loc, @@ -507,4 +510,4 @@ p5.Shader.prototype.enableAttrib = function( return this; }; -module.exports = p5.Shader; +export default p5.Shader; diff --git a/src/webgl/p5.Texture.js b/src/webgl/p5.Texture.js index 272203492b..830b1a3e70 100644 --- a/src/webgl/p5.Texture.js +++ b/src/webgl/p5.Texture.js @@ -6,10 +6,8 @@ * @requires core */ -'use strict'; - -var p5 = require('../core/main'); -var constants = require('../core/constants'); +import p5 from '../core/main'; +import * as constants from '../core/constants'; /** * Texture class for WEBGL Mode @@ -23,7 +21,7 @@ var constants = require('../core/constants'); p5.Texture = function(renderer, obj) { this._renderer = renderer; - var gl = this._renderer.GL; + const gl = this._renderer.GL; this.src = obj; this.glTex = undefined; @@ -49,7 +47,7 @@ p5.Texture = function(renderer, obj) { this.isImageData = typeof ImageData !== 'undefined' && obj instanceof ImageData; - var textureData = this._getTextureDataFromSource(); + const textureData = this._getTextureDataFromSource(); this.width = textureData.width; this.height = textureData.height; @@ -58,7 +56,7 @@ p5.Texture = function(renderer, obj) { }; p5.Texture.prototype._getTextureDataFromSource = function() { - var textureData; + let textureData; if (this.isSrcP5Image) { // param is a p5.Image textureData = this.src.canvas; @@ -83,7 +81,7 @@ p5.Texture.prototype._getTextureDataFromSource = function() { * @method init */ p5.Texture.prototype.init = function(data) { - var gl = this._renderer.GL; + const gl = this._renderer.GL; this.glTex = gl.createTexture(); this.glWrapS = this._renderer.textureWrapX; @@ -103,7 +101,7 @@ p5.Texture.prototype.init = function(data) { ) { // assign a 1x1 empty texture initially, because data is not yet ready, // so that no errors occur in gl console! - var tmpdata = new Uint8Array([1, 1, 1, 1]); + const tmpdata = new Uint8Array([1, 1, 1, 1]); gl.texImage2D( this.glTarget, 0, @@ -136,15 +134,15 @@ p5.Texture.prototype.init = function(data) { * @method update */ p5.Texture.prototype.update = function() { - var data = this.src; + const data = this.src; if (data.width === 0 || data.height === 0) { return false; // nothing to do! } - var textureData = this._getTextureDataFromSource(); - var updated = false; + const textureData = this._getTextureDataFromSource(); + let updated = false; - var gl = this._renderer.GL; + const gl = this._renderer.GL; // pull texture from data, make sure width & height are appropriate if (textureData.width !== this.width || textureData.height !== this.height) { updated = true; @@ -228,7 +226,7 @@ p5.Texture.prototype.update = function() { p5.Texture.prototype.bindTexture = function() { // bind texture using gl context + glTarget and // generated gl texture object - var gl = this._renderer.GL; + const gl = this._renderer.GL; gl.bindTexture(this.glTarget, this.glTex); return this; @@ -240,7 +238,7 @@ p5.Texture.prototype.bindTexture = function() { */ p5.Texture.prototype.unbindTexture = function() { // unbind per above, disable texturing on glTarget - var gl = this._renderer.GL; + const gl = this._renderer.GL; gl.bindTexture(this.glTarget, null); }; @@ -256,7 +254,7 @@ p5.Texture.prototype.unbindTexture = function() { * @todo implement mipmapping filters */ p5.Texture.prototype.setInterpolation = function(downScale, upScale) { - var gl = this._renderer.GL; + const gl = this._renderer.GL; if (downScale === constants.NEAREST) { this.glMinFilter = gl.NEAREST; @@ -286,17 +284,15 @@ p5.Texture.prototype.setInterpolation = function(downScale, upScale) { * @param {String} wrapY Controls the vertical texture wrapping behavior */ p5.Texture.prototype.setWrapMode = function(wrapX, wrapY) { - var gl = this._renderer.GL; + const gl = this._renderer.GL; // for webgl 1 we need to check if the texture is power of two // if it isn't we will set the wrap mode to CLAMP // webgl2 will support npot REPEAT and MIRROR but we don't check for it yet - var isPowerOfTwo = function(x) { - return (x & (x - 1)) === 0; - }; + const isPowerOfTwo = x => (x & (x - 1)) === 0; - var widthPowerOfTwo = isPowerOfTwo(this.width); - var heightPowerOfTwo = isPowerOfTwo(this.height); + const widthPowerOfTwo = isPowerOfTwo(this.width); + const heightPowerOfTwo = isPowerOfTwo(this.height); if (wrapX === constants.REPEAT) { if (widthPowerOfTwo && heightPowerOfTwo) { @@ -350,4 +346,4 @@ p5.Texture.prototype.setWrapMode = function(wrapX, wrapY) { this.unbindTexture(); }; -module.exports = p5.Texture; +export default p5.Texture; diff --git a/src/webgl/text.js b/src/webgl/text.js index db5f0f32f7..d0129e6251 100644 --- a/src/webgl/text.js +++ b/src/webgl/text.js @@ -1,13 +1,11 @@ -'use strict'; - -var p5 = require('../core/main'); -var constants = require('../core/constants'); -require('./p5.Shader'); -require('./p5.RendererGL.Retained'); +import p5 from '../core/main'; +import * as constants from '../core/constants'; +import './p5.Shader'; +import './p5.RendererGL.Retained'; // Text/Typography // @TODO: -p5.RendererGL.prototype._applyTextProperties = function() { +p5.RendererGL.prototype._applyTextProperties = () => { //@TODO finish implementation //console.error('text commands not yet implemented in webgl'); }; @@ -23,20 +21,20 @@ p5.RendererGL.prototype.textWidth = function(s) { // rendering constants // the number of rows/columns dividing each glyph -var charGridWidth = 9; -var charGridHeight = charGridWidth; +const charGridWidth = 9; +const charGridHeight = charGridWidth; // size of the image holding the bezier stroke info -var strokeImageWidth = 64; -var strokeImageHeight = 64; +const strokeImageWidth = 64; +const strokeImageHeight = 64; // size of the image holding the stroke indices for each row/col -var gridImageWidth = 64; -var gridImageHeight = 64; +const gridImageWidth = 64; +const gridImageHeight = 64; // size of the image holding the offset/length of each row/col stripe -var cellImageWidth = 64; -var cellImageHeight = 64; +const cellImageWidth = 64; +const cellImageHeight = 64; /** * @private @@ -61,15 +59,15 @@ function ImageInfos(width, height) { * finds free space of a given size in the ImageData list */ this.findImage = function(space) { - var imageSize = this.width * this.height; + const imageSize = this.width * this.height; if (space > imageSize) throw new Error('font is too complex to render in 3D'); // search through the list of images, looking for one with // anough unused space. - var imageInfo, imageData; - for (var ii = this.infos.length - 1; ii >= 0; --ii) { - var imageInfoTest = this.infos[ii]; + let imageInfo, imageData; + for (let ii = this.infos.length - 1; ii >= 0; --ii) { + const imageInfoTest = this.infos[ii]; if (imageInfoTest.index + space < imageSize) { // found one imageInfo = imageInfoTest; @@ -85,15 +83,15 @@ function ImageInfos(width, height) { } catch (err) { // for browsers that don't support ImageData constructors (ie IE11) // create an ImageData using the old method - var canvas = document.getElementsByTagName('canvas')[0]; - var created = !canvas; + let canvas = document.getElementsByTagName('canvas')[0]; + const created = !canvas; if (!canvas) { // create a temporary canvas canvas = document.createElement('canvas'); canvas.style.display = 'none'; document.body.appendChild(canvas); } - var ctx = canvas.getContext('2d'); + const ctx = canvas.getContext('2d'); if (ctx) { imageData = ctx.createImageData(this.width, this.height); } @@ -103,14 +101,14 @@ function ImageInfos(width, height) { } } // construct & dd the new image info - imageInfo = { index: 0, imageData: imageData }; + imageInfo = { index: 0, imageData }; this.infos.push(imageInfo); } - var index = imageInfo.index; + const index = imageInfo.index; imageInfo.index += space; // move to the start of the next image imageData._dirty = true; - return { imageData: imageData, index: index }; + return { imageData, index }; }; } @@ -125,16 +123,16 @@ function ImageInfos(width, height) { * writes the next pixel into an indexed ImageData */ function setPixel(imageInfo, r, g, b, a) { - var imageData = imageInfo.imageData; - var pixels = imageData.data; - var index = imageInfo.index++ * 4; + const imageData = imageInfo.imageData; + const pixels = imageData.data; + let index = imageInfo.index++ * 4; pixels[index++] = r; pixels[index++] = g; pixels[index++] = b; pixels[index++] = a; } -var SQRT3 = Math.sqrt(3); +const SQRT3 = Math.sqrt(3); /** * @private @@ -143,7 +141,7 @@ var SQRT3 = Math.sqrt(3); * * contains cached images and glyph information for an opentype font */ -var FontInfo = function(font) { +const FontInfo = function(font) { this.font = font; // the bezier curve coordinates this.strokeImageInfos = new ImageInfos(strokeImageWidth, strokeImageHeight); @@ -168,25 +166,25 @@ var FontInfo = function(font) { this.getGlyphInfo = function(glyph) { // check the cache - var gi = this.glyphInfos[glyph.index]; + let gi = this.glyphInfos[glyph.index]; if (gi) return gi; // get the bounding box of the glyph from opentype.js - var bb = glyph.getBoundingBox(); - var xMin = bb.x1; - var yMin = bb.y1; - var gWidth = bb.x2 - xMin; - var gHeight = bb.y2 - yMin; - var cmds = glyph.path.commands; + const bb = glyph.getBoundingBox(); + const xMin = bb.x1; + const yMin = bb.y1; + const gWidth = bb.x2 - xMin; + const gHeight = bb.y2 - yMin; + const cmds = glyph.path.commands; // don't bother rendering invisible glyphs if (gWidth === 0 || gHeight === 0 || !cmds.length) { return (this.glyphInfos[glyph.index] = {}); } - var i; - var strokes = []; // the strokes in this glyph - var rows = []; // the indices of strokes in each row - var cols = []; // the indices of strokes in each column + let i; + const strokes = []; // the strokes in this glyph + const rows = []; // the indices of strokes in each row + const cols = []; // the indices of strokes in each column for (i = charGridWidth - 1; i >= 0; --i) cols.push([]); for (i = charGridHeight - 1; i >= 0; --i) rows.push([]); @@ -199,7 +197,7 @@ var FontInfo = function(font) { * adds a curve to the rows & columns that it intersects with */ function push(xs, ys, v) { - var index = strokes.length; // the index of this stroke + const index = strokes.length; // the index of this stroke strokes.push(v); // add this stroke to the list /** @@ -211,25 +209,28 @@ var FontInfo = function(font) { * find the minimum & maximum value in a list of values */ function minMax(rg, min, max) { - for (var i = rg.length; i-- > 0; ) { - var v = rg[i]; + for (let i = rg.length; i-- > 0; ) { + const v = rg[i]; if (min > v) min = v; if (max < v) max = v; } - return { min: min, max: max }; + return { min, max }; } // loop through the rows & columns that the curve intersects // adding the curve to those slices - var mmX = minMax(xs, 1, 0); - var ixMin = Math.max(Math.floor(mmX.min * charGridWidth), 0); - var ixMax = Math.min(Math.ceil(mmX.max * charGridWidth), charGridWidth); - for (var iCol = ixMin; iCol < ixMax; ++iCol) cols[iCol].push(index); - - var mmY = minMax(ys, 1, 0); - var iyMin = Math.max(Math.floor(mmY.min * charGridHeight), 0); - var iyMax = Math.min(Math.ceil(mmY.max * charGridHeight), charGridHeight); - for (var iRow = iyMin; iRow < iyMax; ++iRow) rows[iRow].push(index); + const mmX = minMax(xs, 1, 0); + const ixMin = Math.max(Math.floor(mmX.min * charGridWidth), 0); + const ixMax = Math.min(Math.ceil(mmX.max * charGridWidth), charGridWidth); + for (let iCol = ixMin; iCol < ixMax; ++iCol) cols[iCol].push(index); + + const mmY = minMax(ys, 1, 0); + const iyMin = Math.max(Math.floor(mmY.min * charGridHeight), 0); + const iyMax = Math.min( + Math.ceil(mmY.max * charGridHeight), + charGridHeight + ); + for (let iRow = iyMin; iRow < iyMax; ++iRow) rows[iRow].push(index); } /** @@ -316,14 +317,14 @@ var FontInfo = function(font) { * point at 't'. the 'end half is returned. */ this.split = function(t) { - var m1 = p5.Vector.lerp(this.p0, this.c0, t); - var m2 = p5.Vector.lerp(this.c0, this.c1, t); - var mm1 = p5.Vector.lerp(m1, m2, t); + const m1 = p5.Vector.lerp(this.p0, this.c0, t); + const m2 = p5.Vector.lerp(this.c0, this.c1, t); + const mm1 = p5.Vector.lerp(m1, m2, t); this.c1 = p5.Vector.lerp(this.c1, this.p1, t); this.c0 = p5.Vector.lerp(m2, this.c1, t); - var pt = p5.Vector.lerp(mm1, this.c0, t); - var part1 = new Cubic(this.p0, m1, mm1, pt); + const pt = p5.Vector.lerp(mm1, this.c0, t); + const part1 = new Cubic(this.p0, m1, mm1, pt); this.p0 = pt; return part1; }; @@ -337,21 +338,21 @@ var FontInfo = function(font) { * this cubic is (potentially) altered and returned in the list. */ this.splitInflections = function() { - var a = p5.Vector.sub(this.c0, this.p0); - var b = p5.Vector.sub(p5.Vector.sub(this.c1, this.c0), a); - var c = p5.Vector.sub( + const a = p5.Vector.sub(this.c0, this.p0); + const b = p5.Vector.sub(p5.Vector.sub(this.c1, this.c0), a); + const c = p5.Vector.sub( p5.Vector.sub(p5.Vector.sub(this.p1, this.c1), a), p5.Vector.mult(b, 2) ); - var cubics = []; + const cubics = []; // find the derivative coefficients - var A = b.x * c.y - b.y * c.x; + let A = b.x * c.y - b.y * c.x; if (A !== 0) { - var B = a.x * c.y - a.y * c.x; - var C = a.x * b.y - a.y * b.x; - var disc = B * B - 4 * A * C; + let B = a.x * c.y - a.y * c.x; + let C = a.x * b.y - a.y * b.x; + const disc = B * B - 4 * A * C; if (disc >= 0) { if (A < 0) { A = -A; @@ -359,9 +360,9 @@ var FontInfo = function(font) { C = -C; } - var Q = Math.sqrt(disc); - var t0 = (-B - Q) / (2 * A); // the first inflection point - var t1 = (-B + Q) / (2 * A); // the second inflection point + const Q = Math.sqrt(disc); + const t0 = (-B - Q) / (2 * A); // the first inflection point + let t1 = (-B + Q) / (2 * A); // the second inflection point // test if the first inflection point lies on the curve if (t0 > 0 && t0 < 1) { @@ -401,27 +402,25 @@ var FontInfo = function(font) { */ function cubicToQuadratics(x0, y0, cx0, cy0, cx1, cy1, x1, y1) { // create the Cubic object and split it at its inflections - var cubics = new Cubic( + const cubics = new Cubic( new p5.Vector(x0, y0), new p5.Vector(cx0, cy0), new p5.Vector(cx1, cy1), new p5.Vector(x1, y1) ).splitInflections(); - var qs = []; // the final list of quadratics - var precision = 30 / SQRT3; + const qs = []; // the final list of quadratics + const precision = 30 / SQRT3; // for each of the non-inflected pieces of the original cubic - for (var i = 0; i < cubics.length; i++) { - var cubic = cubics[i]; - + for (let cubic of cubics) { // the cubic is iteratively split in 3 pieces: // the first piece is accumulated in 'qs', the result. // the last piece is accumulated in 'tail', temporarily. // the middle piece is repeatedly split again, while necessary. - var tail = []; + const tail = []; - var t3; + let t3; for (;;) { // calculate this cubic's precision t3 = precision / cubic.quadError(); @@ -430,10 +429,10 @@ var FontInfo = function(font) { } // find a split point based on the error - var t = Math.pow(t3, 1.0 / 3.0); + const t = Math.pow(t3, 1.0 / 3.0); // split the cubic in 3 - var start = cubic.split(t); - var middle = cubic.split(1 - t / (1 - t)); + const start = cubic.split(t); + const middle = cubic.split(1 - t / (1 - t)); qs.push(start); // the first part tail.push(cubic); // the last part @@ -464,8 +463,8 @@ var FontInfo = function(font) { * add a straight line to the row/col grid of a glyph */ function pushLine(x0, y0, x1, y1) { - var mx = (x0 + x1) / 2; - var my = (y0 + y1) / 2; + const mx = (x0 + x1) / 2; + const my = (y0 + y1) / 2; push([x0, x1], [y0, y1], { x: x0, y: y0, cx: mx, cy: my }); } @@ -483,30 +482,37 @@ var FontInfo = function(font) { return Math.abs(x1 - x0) < 0.00001 && Math.abs(y1 - y0) < 0.00001; } - var x0, y0, xs, ys; - for (var iCmd = 0; iCmd < cmds.length; ++iCmd) { - var cmd = cmds[iCmd]; + let x0, y0, xs, ys; + + for (const cmd of cmds) { // scale the coordinates to the range 0-1 - var x1 = (cmd.x - xMin) / gWidth; - var y1 = (cmd.y - yMin) / gHeight; + const x1 = (cmd.x - xMin) / gWidth; + const y1 = (cmd.y - yMin) / gHeight; // don't bother if this point is the same as the last if (samePoint(x0, y0, x1, y1)) continue; switch (cmd.type) { - case 'M': // move + case 'M': { + // move xs = x1; ys = y1; break; - case 'L': // line + } + case 'L': { + // line pushLine(x0, y0, x1, y1); break; - case 'Q': // quadratic - var cx = (cmd.x1 - xMin) / gWidth; - var cy = (cmd.y1 - yMin) / gHeight; - push([x0, x1, cx], [y0, y1, cy], { x: x0, y: y0, cx: cx, cy: cy }); + } + case 'Q': { + // quadratic + const cx = (cmd.x1 - xMin) / gWidth; + const cy = (cmd.y1 - yMin) / gHeight; + push([x0, x1, cx], [y0, y1, cy], { x: x0, y: y0, cx, cy }); break; - case 'Z': // end + } + case 'Z': { + // end if (!samePoint(x0, y0, xs, ys)) { // add an extra line closing the loop, if necessary pushLine(x0, y0, xs, ys); @@ -515,32 +521,35 @@ var FontInfo = function(font) { strokes.push({ x: x0, y: y0 }); } break; - case 'C': // cubic - var cx1 = (cmd.x1 - xMin) / gWidth; - var cy1 = (cmd.y1 - yMin) / gHeight; - var cx2 = (cmd.x2 - xMin) / gWidth; - var cy2 = (cmd.y2 - yMin) / gHeight; - var qs = cubicToQuadratics(x0, y0, cx1, cy1, cx2, cy2, x1, y1); - for (var iq = 0; iq < qs.length; iq++) { - var q = qs[iq].toQuadratic(); + } + case 'C': { + // cubic + const cx1 = (cmd.x1 - xMin) / gWidth; + const cy1 = (cmd.y1 - yMin) / gHeight; + const cx2 = (cmd.x2 - xMin) / gWidth; + const cy2 = (cmd.y2 - yMin) / gHeight; + const qs = cubicToQuadratics(x0, y0, cx1, cy1, cx2, cy2, x1, y1); + for (let iq = 0; iq < qs.length; iq++) { + const q = qs[iq].toQuadratic(); push([q.x, q.x1, q.cx], [q.y, q.y1, q.cy], q); } break; + } default: - throw new Error('unknown command type: ' + cmd.type); + throw new Error(`unknown command type: ${cmd.type}`); } x0 = x1; y0 = y1; } // allocate space for the strokes - var strokeCount = strokes.length; - var strokeImageInfo = this.strokeImageInfos.findImage(strokeCount); - var strokeOffset = strokeImageInfo.index; + const strokeCount = strokes.length; + const strokeImageInfo = this.strokeImageInfos.findImage(strokeCount); + const strokeOffset = strokeImageInfo.index; // fill the stroke image - for (var il = 0; il < strokeCount; ++il) { - var s = strokes[il]; + for (let il = 0; il < strokeCount; ++il) { + const s = strokes[il]; setPixel(strokeImageInfo, byte(s.x), byte(s.y), byte(s.cx), byte(s.cy)); } @@ -556,23 +565,23 @@ var FontInfo = function(font) { * one containing the offset and length of those index spans. */ function layout(dim, dimImageInfos, cellImageInfos) { - var dimLength = dim.length; // the number of slices in this dimension - var dimImageInfo = dimImageInfos.findImage(dimLength); - var dimOffset = dimImageInfo.index; + const dimLength = dim.length; // the number of slices in this dimension + const dimImageInfo = dimImageInfos.findImage(dimLength); + const dimOffset = dimImageInfo.index; // calculate the total number of stroke indices in this dimension - var totalStrokes = 0; - for (var id = 0; id < dimLength; ++id) { + let totalStrokes = 0; + for (let id = 0; id < dimLength; ++id) { totalStrokes += dim[id].length; } // allocate space for the stroke indices - var cellImageInfo = cellImageInfos.findImage(totalStrokes); + const cellImageInfo = cellImageInfos.findImage(totalStrokes); // for each slice in the glyph - for (var i = 0; i < dimLength; ++i) { - var strokeIndices = dim[i]; - var strokeCount = strokeIndices.length; - var cellLineIndex = cellImageInfo.index; + for (let i = 0; i < dimLength; ++i) { + const strokeIndices = dim[i]; + const strokeCount = strokeIndices.length; + const cellLineIndex = cellImageInfo.index; // write the offset and count into the glyph slice image setPixel( @@ -584,26 +593,26 @@ var FontInfo = function(font) { ); // for each stroke index in that slice - for (var iil = 0; iil < strokeCount; ++iil) { + for (let iil = 0; iil < strokeCount; ++iil) { // write the stroke index into the slice's image - var strokeIndex = strokeIndices[iil] + strokeOffset; + const strokeIndex = strokeIndices[iil] + strokeOffset; setPixel(cellImageInfo, strokeIndex >> 7, strokeIndex & 0x7f, 0, 0); } } return { - cellImageInfo: cellImageInfo, - dimOffset: dimOffset, - dimImageInfo: dimImageInfo + cellImageInfo, + dimOffset, + dimImageInfo }; } // initialize the info for this glyph gi = this.glyphInfos[glyph.index] = { - glyph: glyph, + glyph, uGlyphRect: [bb.x1, -bb.y1, bb.x2, -bb.y2], - strokeImageInfo: strokeImageInfo, - strokes: strokes, + strokeImageInfo, + strokes, colInfo: layout(cols, this.colDimImageInfos, this.colCellImageInfos), rowInfo: layout(rows, this.rowDimImageInfos, this.rowCellImageInfos) }; @@ -631,30 +640,30 @@ p5.RendererGL.prototype._renderText = function(p, line, x, y, maxY) { p.push(); // fix to #803 // remember this state, so it can be restored later - var doStroke = this._doStroke; - var drawMode = this.drawMode; + const doStroke = this._doStroke; + const drawMode = this.drawMode; this._doStroke = false; this.drawMode = constants.TEXTURE; // get the cached FontInfo object - var font = this._textFont.font; - var fontInfo = this._textFont._fontInfo; + const font = this._textFont.font; + let fontInfo = this._textFont._fontInfo; if (!fontInfo) { fontInfo = this._textFont._fontInfo = new FontInfo(font); } // calculate the alignment and move/scale the view accordingly - var pos = this._textFont._handleAlignment(this, line, x, y); - var fontSize = this._textSize; - var scale = fontSize / font.unitsPerEm; + const pos = this._textFont._handleAlignment(this, line, x, y); + const fontSize = this._textSize; + const scale = fontSize / font.unitsPerEm; this.translate(pos.x, pos.y, 0); this.scale(scale, scale, 1); // initialize the font shader - var gl = this.GL; - var initializeShader = !this._defaultFontShader; - var sh = this._getFontShader(); + const gl = this.GL; + const initializeShader = !this._defaultFontShader; + const sh = this._getFontShader(); sh.init(); sh.bindShader(); // first time around, bind the shader fully @@ -667,12 +676,12 @@ p5.RendererGL.prototype._renderText = function(p, line, x, y, maxY) { } this._applyColorBlend(this.curFillColor); - var g = this.gHash['glyph']; + let g = this.gHash['glyph']; if (!g) { // create the geometry for rendering a quad - var geom = (this._textGeom = new p5.Geometry(1, 1, function() { - for (var i = 0; i <= 1; i++) { - for (var j = 0; j <= 1; j++) { + const geom = (this._textGeom = new p5.Geometry(1, 1, function() { + for (let i = 0; i <= 1; i++) { + for (let j = 0; j <= 1; j++) { this.vertices.push(new p5.Vector(j, i, 0)); this.uvs.push(j, i); } @@ -690,19 +699,19 @@ p5.RendererGL.prototype._renderText = function(p, line, x, y, maxY) { sh.setUniform('uMaterialColor', this.curFillColor); try { - var dx = 0; // the x position in the line - var glyphPrev = null; // the previous glyph, used for kerning + let dx = 0; // the x position in the line + let glyphPrev = null; // the previous glyph, used for kerning // fetch the glyphs in the line of text - var glyphs = font.stringToGlyphs(line); - for (var ig = 0; ig < glyphs.length; ++ig) { - var glyph = glyphs[ig]; + const glyphs = font.stringToGlyphs(line); + + for (const glyph of glyphs) { // kern if (glyphPrev) dx += font.getKerningValue(glyphPrev, glyph); - var gi = fontInfo.getGlyphInfo(glyph); + const gi = fontInfo.getGlyphInfo(glyph); if (gi.uGlyphRect) { - var rowInfo = gi.rowInfo; - var colInfo = gi.colInfo; + const rowInfo = gi.rowInfo; + const colInfo = gi.colInfo; sh.setUniform('uSamplerStrokes', gi.strokeImageInfo.imageData); sh.setUniform('uSamplerRowStrokes', rowInfo.cellImageInfo.imageData); sh.setUniform('uSamplerRows', rowInfo.dimImageInfo.imageData); diff --git a/tasks/build/browserify.js b/tasks/build/browserify.js index 281969392a..b1901b5231 100644 --- a/tasks/build/browserify.js +++ b/tasks/build/browserify.js @@ -39,16 +39,13 @@ module.exports = function(grunt) { browseified = browseified.exclude('../../docs/reference/data.json'); } - const babelifyOpts = {}; + const babelifyOpts = { plugins: ['static-fs'] }; if (isTest) { babelifyOpts.envName = 'test'; } - const bundle = browseified - .transform('brfs') - .transform('babelify', babelifyOpts) - .bundle(); + const bundle = browseified.transform('babelify', babelifyOpts).bundle(); // Start the generated output with the banner comment, let code = banner + '\n'; diff --git a/tasks/build/combineModules.js b/tasks/build/combineModules.js index 3eb6c5e75a..507bb93c8f 100644 --- a/tasks/build/combineModules.js +++ b/tasks/build/combineModules.js @@ -28,10 +28,12 @@ module.exports = function(grunt) { // Make a list of sources from app.js in that sequence only const sources = []; const dump = fs.readFileSync('./src/app.js', 'utf8'); - const regexp = /\('.+'/g; + const regexp = /import\s.*('.+')/g; // Used for ES6 import syntax + // const regexp = /\('.+'/g; // Used for require syntax let match; while ((match = regexp.exec(dump)) != null) { - let text = match[0]; + let text = match[1]; // Used for ES6 import syntax + // let text = match[0]; // Used for require syntax text = text.substring(text.indexOf('./') + 2, text.length - 1); sources.push(text); } @@ -59,7 +61,7 @@ module.exports = function(grunt) { const bundle = browserify(srcFilePath, { standalone: 'p5' }) - .transform('brfs') + .transform('babelify', { plugins: ['static-fs'] }) .bundle(); // Start the generated output with the banner comment, diff --git a/test/node/helpers.js b/test/node/helpers.js index 19d2da73a1..8830971bee 100644 --- a/test/node/helpers.js +++ b/test/node/helpers.js @@ -1,6 +1,6 @@ var { expect } = require('chai'); var constants = require('../../src/core/constants.js'); -var helpers = require('../../src/core/helpers.js'); +import helpers from '../../src/core/helpers.js'; var a = 100; var b = 200;