forked from processing/p5.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
678 lines (626 loc) · 18.8 KB
/
Copy pathmain.js
File metadata and controls
678 lines (626 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
/**
* @module Structure
* @submodule Structure
* @for p5
* @requires constants
*/
import * as constants from './constants';
/**
* This is the p5 instance constructor.
*
* A p5 instance holds all the properties and methods related to
* a p5 sketch. It expects an incoming sketch closure and it can also
* take an optional node parameter for attaching the generated p5 canvas
* to a node. The sketch closure takes the newly created p5 instance as
* its sole argument and may optionally set <a href="#/p5/preload">preload()</a>,
* <a href="#/p5/setup">setup()</a>, and/or
* <a href="#/p5/draw">draw()</a> properties on it for running a sketch.
*
* A p5 sketch can run in "global" or "instance" mode:
* "global" - all properties and methods are attached to the window
* "instance" - all properties and methods are bound to this p5 object
*
* @class p5
* @param {function(p5)} sketch a closure that can set optional <a href="#/p5/preload">preload()</a>,
* <a href="#/p5/setup">setup()</a>, and/or <a href="#/p5/draw">draw()</a> properties on the
* given p5 instance
* @param {HTMLElement} [node] element to attach canvas to
* @return {p5} a p5 instance
*/
class p5 {
static VERSION = constants.VERSION;
// This is a pointer to our global mode p5 instance, if we're in
// global mode.
static instance = null;
static lifecycleHooks = {
presetup: [],
postsetup: [],
predraw: [],
postdraw: [],
remove: []
};
// FES stub
static _checkForUserDefinedFunctions = () => {};
static _friendlyFileLoadError = () => {};
constructor(sketch, node) {
//////////////////////////////////////////////
// PRIVATE p5 PROPERTIES AND METHODS
//////////////////////////////////////////////
this._setupDone = false;
this._userNode = node;
this._curElement = null;
this._elements = [];
this._glAttributes = null;
this._requestAnimId = 0;
this._isGlobal = false;
this._loop = true;
this._startListener = null;
this._initializeInstanceVariables();
this._events = {
// keep track of user-events for unregistering later
pointerdown: null,
pointerup: null,
pointermove: null,
dragend: null,
dragover: null,
click: null,
dblclick: null,
mouseover: null,
mouseout: null,
keydown: null,
keyup: null,
keypress: null,
wheel: null,
resize: null,
blur: null
};
this._millisStart = -1;
this._recording = false;
// States used in the custom random generators
this._lcg_random_state = null; // NOTE: move to random.js
this._gaussian_previous = false; // NOTE: move to random.js
if (window.DeviceOrientationEvent) {
this._events.deviceorientation = null;
}
if (window.DeviceMotionEvent && !window._isNodeWebkit) {
this._events.devicemotion = null;
}
// ensure correct reporting of window dimensions
this._updateWindowSize();
const bindGlobal = (property) => {
Object.defineProperty(window, property, {
configurable: true,
enumerable: true,
get: () => {
if(typeof this[property] === 'function'){
return this[property].bind(this);
}else{
return this[property];
}
},
set: (newValue) => {
Object.defineProperty(window, property, {
configurable: true,
enumerable: true,
value: newValue,
writable: true
});
if (!p5.disableFriendlyErrors) {
console.log(`You just changed the value of "${property}", which was a p5 global value. This could cause problems later if you're not careful.`);
}
}
})
};
// 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
// All methods and properties with name starting with '_' will be skipped
for (const p of Object.getOwnPropertyNames(p5.prototype)) {
if(p[0] === '_') continue;
bindGlobal(p);
}
// Attach its properties to the window
for (const p in this) {
if (this.hasOwnProperty(p)) {
if(p[0] === '_') continue;
bindGlobal(p);
}
}
} else {
// Else, the user has passed in a sketch closure that may set
// user-provided 'setup', 'draw', etc. properties on this instance of p5
sketch(this);
// Run a check to see if the user has misspelled 'setup', 'draw', etc
// detects capitalization mistakes only ( Setup, SETUP, MouseClicked, etc)
p5._checkForUserDefinedFunctions(this);
}
// Bind events to window (not using container div bc key events don't work)
for (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;
}
}
const focusHandler = () => {
this.focused = true;
};
const blurHandler = () => {
this.focused = false;
};
window.addEventListener('focus', focusHandler);
window.addEventListener('blur', blurHandler);
p5.lifecycleHooks.remove.push(function() {
window.removeEventListener('focus', focusHandler);
window.removeEventListener('blur', blurHandler);
});
// Initialization complete, start runtime
if (document.readyState === 'complete') {
this.#_start();
} else {
this._startListener = this.#_start.bind(this);
window.addEventListener('load', this._startListener, false);
}
}
get pixels(){
return this._renderer.pixels;
}
static registerAddon(addon) {
const lifecycles = {};
addon(p5, p5.prototype, lifecycles);
const validLifecycles = Object.keys(p5.lifecycleHooks);
for(const name of validLifecycles){
if(typeof lifecycles[name] === 'function'){
p5.lifecycleHooks[name].push(lifecycles[name]);
}
}
}
async #_start() {
// Find node if id given
if (this._userNode) {
if (typeof this._userNode === 'string') {
this._userNode = document.getElementById(this._userNode);
}
}
await this.#_setup();
if (!this._recording) {
this._draw();
}
}
async #_setup() {
// Run `presetup` hooks
await this._runLifecycleHook('presetup');
// Always create a default canvas.
// Later on if the user calls createCanvas, this default one
// will be replaced
this.createCanvas(
100,
100,
constants.P2D
);
// Record the time when sketch starts
this._millisStart = window.performance.now();
const context = this._isGlobal ? window : this;
if (typeof context.setup === 'function') {
await context.setup();
}
// unhide any hidden canvases that were created
const canvases = document.getElementsByTagName('canvas');
// Apply touchAction = 'none' to canvases if pointer events exist
if (Object.keys(this._events).some(event => event.startsWith('pointer'))) {
for (const k of canvases) {
k.style.touchAction = 'none';
}
}
for (const k of canvases) {
if (k.dataset.hidden === 'true') {
k.style.visibility = '';
delete k.dataset.hidden;
}
}
this._lastTargetFrameTime = window.performance.now();
this._lastRealFrameTime = window.performance.now();
this._setupDone = true;
if (this._accessibleOutputs.grid || this._accessibleOutputs.text) {
this._updateAccsOutput();
}
// Run `postsetup` hooks
await this._runLifecycleHook('postsetup');
}
// While '#_draw' here is async, it is not awaited as 'requestAnimationFrame'
// does not await its callback. Thus it is not recommended for 'draw()` to be
// async and use await within as the next frame may start rendering before the
// current frame finish awaiting. The same goes for lifecycle hooks 'predraw'
// and 'postdraw'.
async _draw(requestAnimationFrameTimestamp) {
const now = requestAnimationFrameTimestamp || window.performance.now();
const timeSinceLastFrame = now - this._lastTargetFrameTime;
const targetTimeBetweenFrames = 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 ||
timeSinceLastFrame >= targetTimeBetweenFrames - epsilon
) {
//mandatory update values(matrixes and stack)
this.deltaTime = now - this._lastRealFrameTime;
this._frameRate = 1000.0 / this.deltaTime;
await this.redraw();
this._lastTargetFrameTime = Math.max(this._lastTargetFrameTime
+ targetTimeBetweenFrames, now);
this._lastRealFrameTime = now;
// If the user is actually using mouse module, then update
// coordinates, otherwise skip. We can test this by simply
// checking if any of the mouse functions are available or not.
// NOTE : This reflects only in complete build or modular build.
if (typeof this._updateMouseCoords !== 'undefined') {
this._updateMouseCoords();
//reset delta values so they reset even if there is no mouse event to set them
// for example if the mouse is outside the screen
this.movedX = 0;
this.movedY = 0;
}
}
// get notified the next time the browser gives us
// an opportunity to draw.
if (this._loop) {
this._requestAnimId = window.requestAnimationFrame(
this._draw.bind(this)
);
}
}
/**
* Removes the sketch from the web page.
*
* Calling `remove()` stops the draw loop and removes any HTML elements
* created by the sketch, including the canvas. A new sketch can be
* created by using the <a href="#/p5/p5">p5()</a> constructor, as in
* `new p5()`.
*
* @example
* <div>
* <code>
* // Double-click to remove the canvas.
*
* function setup() {
* createCanvas(100, 100);
*
* describe(
* 'A white circle on a gray background. The circle follows the mouse as the user moves. The sketch disappears when the user double-clicks.'
* );
* }
*
* function draw() {
* // Paint the background repeatedly.
* background(200);
*
* // Draw circles repeatedly.
* circle(mouseX, mouseY, 40);
* }
*
* // Remove the sketch when the user double-clicks.
* function doubleClicked() {
* remove();
* }
* </code>
* </div>
*/
async remove() {
// Remove start listener to prevent orphan canvas being created
if(this._startListener){
window.removeEventListener('load', this._startListener, false);
}
if (this._curElement) {
// stop draw
this._loop = false;
if (this._requestAnimId) {
window.cancelAnimationFrame(this._requestAnimId);
}
// 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]);
}
}
// Run `remove` hooks
await this._runLifecycleHook('remove');
}
// remove window bound properties and methods
if (this._isGlobal) {
for (const p in p5.prototype) {
try {
delete window[p];
} catch (x) {
window[p] = undefined;
}
}
for (const p2 in this) {
if (this.hasOwnProperty(p2)) {
try {
delete window[p2];
} catch (x) {
window[p2] = undefined;
}
}
}
p5.instance = null;
}
}
async _runLifecycleHook(hookName) {
for(const hook of p5.lifecycleHooks[hookName]){
await hook.call(this);
}
}
_initializeInstanceVariables() {
this._accessibleOutputs = {
text: false,
grid: false,
textLabel: false,
gridLabel: false
};
this._styles = [];
this._downKeys = {}; //Holds the key codes of currently pressed keys
this._downKeyCodes = {};
}
}
// Attach constants to p5 prototype
for (const k in constants) {
p5.prototype[k] = constants[k];
}
//////////////////////////////////////////////
// PUBLIC p5 PROPERTIES AND METHODS
//////////////////////////////////////////////
/**
* A function that's called once when the sketch begins running.
*
* Declaring the function `setup()` sets a code block to run once
* automatically when the sketch starts running. It's used to perform
* setup tasks such as creating the canvas and initializing variables:
*
* ```js
* function setup() {
* // Code to run once at the start of the sketch.
* }
* ```
*
* Code placed in `setup()` will run once before code placed in
* <a href="#/p5/draw">draw()</a> begins looping. If the
* <a href="#/p5/preload">preload()</a> is declared, then `setup()` will
* run immediately after <a href="#/p5/preload">preload()</a> finishes
* loading assets.
*
* Note: `setup()` doesn’t have to be declared, but it’s common practice to do so.
*
* @method setup
* @for p5
*
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Draw the circle.
* circle(50, 50, 40);
*
* describe('A white circle on a gray background.');
* }
* </code>
* </div>
*
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
*
* // Paint the background once.
* background(200);
*
* describe(
* 'A white circle on a gray background. The circle follows the mouse as the user moves, leaving a trail.'
* );
* }
*
* function draw() {
* // Draw circles repeatedly.
* circle(mouseX, mouseY, 40);
* }
* </code>
* </div>
*
* <div>
* <code>
* let img;
*
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
*
* function setup() {
* createCanvas(100, 100);
*
* // Draw the image.
* image(img, 0, 0);
*
* describe(
* 'A white circle on a brick wall. The circle follows the mouse as the user moves, leaving a trail.'
* );
* }
*
* function draw() {
* // Style the circle.
* noStroke();
*
* // Draw the circle.
* circle(mouseX, mouseY, 10);
* }
* </code>
* </div>
*/
/**
* A function that's called repeatedly while the sketch runs.
*
* Declaring the function `draw()` sets a code block to run repeatedly
* once the sketch starts. It’s used to create animations and respond to
* user inputs:
*
* ```js
* function draw() {
* // Code to run repeatedly.
* }
* ```
*
* This is often called the "draw loop" because p5.js calls the code in
* `draw()` in a loop behind the scenes. By default, `draw()` tries to run
* 60 times per second. The actual rate depends on many factors. The
* drawing rate, called the "frame rate", can be controlled by calling
* <a href="#/p5/frameRate">frameRate()</a>. The number of times `draw()`
* has run is stored in the system variable
* <a href="#/p5/frameCount">frameCount()</a>.
*
* Code placed within `draw()` begins looping after
* <a href="#/p5/setup">setup()</a> runs. `draw()` will run until the user
* closes the sketch. `draw()` can be stopped by calling the
* <a href="#/p5/noLoop">noLoop()</a> function. `draw()` can be resumed by
* calling the <a href="#/p5/loop">loop()</a> function.
*
* @method draw
* @for p5
*
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
*
* // Paint the background once.
* background(200);
*
* describe(
* 'A white circle on a gray background. The circle follows the mouse as the user moves, leaving a trail.'
* );
* }
*
* function draw() {
* // Draw circles repeatedly.
* circle(mouseX, mouseY, 40);
* }
* </code>
* </div>
*
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
*
* describe(
* 'A white circle on a gray background. The circle follows the mouse as the user moves.'
* );
* }
*
* function draw() {
* // Paint the background repeatedly.
* background(200);
*
* // Draw circles repeatedly.
* circle(mouseX, mouseY, 40);
* }
* </code>
* </div>
*
* <div>
* <code>
* // Double-click the canvas to change the circle's color.
*
* function setup() {
* createCanvas(100, 100);
*
* describe(
* 'A white circle on a gray background. The circle follows the mouse as the user moves. The circle changes color to pink when the user double-clicks.'
* );
* }
*
* function draw() {
* // Paint the background repeatedly.
* background(200);
*
* // Draw circles repeatedly.
* circle(mouseX, mouseY, 40);
* }
*
* // Change the fill color when the user double-clicks.
* function doubleClicked() {
* fill('deeppink');
* }
* </code>
* </div>
*/
/**
* Turns off the parts of the Friendly Error System (FES) that impact performance.
*
* The <a href="https://github.com/processing/p5.js/blob/main/contributor_docs/friendly_error_system.md" target="_blank">FES</a>
* can cause sketches to draw slowly because it does extra work behind the
* scenes. For example, the FES checks the arguments passed to functions,
* which takes time to process. Disabling the FES can significantly improve
* performance by turning off these checks.
*
* @property {Boolean} disableFriendlyErrors
*
* @example
* <div>
* <code>
* // Disable the FES.
* p5.disableFriendlyErrors = true;
*
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // The circle() function requires three arguments. The
* // next line would normally display a friendly error that
* // points this out. Instead, nothing happens and it fails
* // silently.
* circle(50, 50);
*
* describe('A gray square.');
* }
* </code>
* </div>
*/
p5.disableFriendlyErrors = false;
import transform from './transform';
import structure from './structure';
import environment from './environment';
import rendering from './rendering';
import renderer from './p5.Renderer';
import renderer2D from './p5.Renderer2D';
import graphics from './p5.Graphics';
p5.registerAddon(transform);
p5.registerAddon(structure);
p5.registerAddon(environment);
p5.registerAddon(rendering);
p5.registerAddon(renderer);
p5.registerAddon(renderer2D);
p5.registerAddon(graphics);
export default p5;