-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
p5.Framebuffer.js
1856 lines (1775 loc) · 54 KB
/
p5.Framebuffer.js
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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @module Rendering
* @requires constants
*/
import p5 from '../core/main';
import * as constants from '../core/constants';
import { checkWebGLCapabilities } from './p5.Texture';
import { readPixelsWebGL, readPixelWebGL } from './p5.RendererGL';
class FramebufferCamera extends p5.Camera {
/**
* A <a href="#/p5.Camera">p5.Camera</a> attached to a
* <a href="#/p5.Framebuffer">p5.Framebuffer</a>.
*
* @class p5.FramebufferCamera
* @constructor
* @param {p5.Framebuffer} framebuffer The framebuffer this camera is
* attached to
* @private
*/
constructor(framebuffer) {
super(framebuffer.target._renderer);
this.fbo = framebuffer;
// WebGL textures are upside-down compared to textures that come from
// images and graphics. Framebuffer cameras need to invert their y
// axes when being rendered to so that the texture comes out rightway up
// when read in shaders or image().
this.yScale = -1;
}
_computeCameraDefaultSettings() {
super._computeCameraDefaultSettings();
this.defaultAspectRatio = this.fbo.width / this.fbo.height;
this.defaultCameraFOV =
2 * Math.atan(this.fbo.height / 2 / this.defaultEyeZ);
}
}
p5.FramebufferCamera = FramebufferCamera;
class FramebufferTexture {
/**
* A <a href="#/p5.Texture">p5.Texture</a> corresponding to a property of a
* <a href="#/p5.Framebuffer">p5.Framebuffer</a>.
*
* @class p5.FramebufferTexture
* @param {p5.Framebuffer} framebuffer The framebuffer represented by this
* texture
* @param {String} property The property of the framebuffer represented by
* this texture, either `color` or `depth`
* @private
*/
constructor(framebuffer, property) {
this.framebuffer = framebuffer;
this.property = property;
}
get width() {
return this.framebuffer.width * this.framebuffer.density;
}
get height() {
return this.framebuffer.height * this.framebuffer.density;
}
rawTexture() {
return this.framebuffer[this.property];
}
}
p5.FramebufferTexture = FramebufferTexture;
class Framebuffer {
/**
* A class to describe a high-performance drawing surface for textures.
*
* Each `p5.Framebuffer` object provides a dedicated drawing surface called
* a *framebuffer*. They're similar to
* <a href="#/p5.Graphics">p5.Graphics</a> objects but can run much faster.
* Performance is improved because the framebuffer shares the same WebGL
* context as the canvas used to create it.
*
* `p5.Framebuffer` objects have all the drawing features of the main
* canvas. Drawing instructions meant for the framebuffer must be placed
* between calls to
* <a href="#/p5.Framebuffer/begin">myBuffer.begin()</a> and
* <a href="#/p5.Framebuffer/end">myBuffer.end()</a>. The resulting image
* can be applied as a texture by passing the `p5.Framebuffer` object to the
* <a href="#/p5/texture">texture()</a> function, as in `texture(myBuffer)`.
* It can also be displayed on the main canvas by passing it to the
* <a href="#/p5/image">image()</a> function, as in `image(myBuffer, 0, 0)`.
*
* Note: <a href="#/p5/createFramebuffer">createFramebuffer()</a> is the
* recommended way to create an instance of this class.
*
* @class p5.Framebuffer
* @constructor
* @param {p5.Graphics|p5} target sketch instance or
* <a href="#/p5.Graphics">p5.Graphics</a>
* object.
* @param {Object} [settings] configuration options.
*/
constructor(target, settings = {}) {
this.target = target;
this.target._renderer.framebuffers.add(this);
this._isClipApplied = false;
/**
* An array containing the color of each pixel in the framebuffer.
*
* <a href="#/p5.Framebuffer/loadPixels">myBuffer.loadPixels()</a> must be
* called before accessing the `myBuffer.pixels` array.
* <a href="#/p5.Framebuffer/updatePixels">myBuffer.updatePixels()</a>
* must be called after any changes are made.
*
* Note: Updating pixels via this property is slower than drawing to the
* framebuffer directly. Consider using a
* <a href="#/p5.Shader">p5.Shader</a> object instead of looping over
* `myBuffer.pixels`.
*
* @property {Number[]} pixels
*
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* background(200);
*
* // Create a p5.Framebuffer object.
* let myBuffer = createFramebuffer();
*
* // Load the pixels array.
* myBuffer.loadPixels();
*
* // Get the number of pixels in the
* // top half of the framebuffer.
* let numPixels = myBuffer.pixels.length / 2;
*
* // Set the framebuffer's top half to pink.
* for (let i = 0; i < numPixels; i += 4) {
* myBuffer.pixels[i] = 255;
* myBuffer.pixels[i + 1] = 102;
* myBuffer.pixels[i + 2] = 204;
* myBuffer.pixels[i + 3] = 255;
* }
*
* // Update the pixels array.
* myBuffer.updatePixels();
*
* // Draw the p5.Framebuffer object to the canvas.
* image(myBuffer, -50, -50);
*
* describe('A pink rectangle above a gray rectangle.');
* }
* </code>
* </div>
*/
this.pixels = [];
this.format = settings.format || constants.UNSIGNED_BYTE;
this.channels = settings.channels || (
target._renderer._pInst._glAttributes.alpha
? constants.RGBA
: constants.RGB
);
this.useDepth = settings.depth === undefined ? true : settings.depth;
this.depthFormat = settings.depthFormat || constants.FLOAT;
this.textureFiltering = settings.textureFiltering || constants.LINEAR;
if (settings.antialias === undefined) {
this.antialiasSamples = target._renderer._pInst._glAttributes.antialias
? 2
: 0;
} else if (typeof settings.antialias === 'number') {
this.antialiasSamples = settings.antialias;
} else {
this.antialiasSamples = settings.antialias ? 2 : 0;
}
this.antialias = this.antialiasSamples > 0;
if (this.antialias && target.webglVersion !== constants.WEBGL2) {
console.warn('Antialiasing is unsupported in a WebGL 1 context');
this.antialias = false;
}
this.density = settings.density || target.pixelDensity();
const gl = target._renderer.GL;
this.gl = gl;
if (settings.width && settings.height) {
const dimensions =
target._renderer._adjustDimensions(settings.width, settings.height);
this.width = dimensions.adjustedWidth;
this.height = dimensions.adjustedHeight;
this._autoSized = false;
} else {
if ((settings.width === undefined) !== (settings.height === undefined)) {
console.warn(
'Please supply both width and height for a framebuffer to give it a ' +
'size. Only one was given, so the framebuffer will match the size ' +
'of its canvas.'
);
}
this.width = target.width;
this.height = target.height;
this._autoSized = true;
}
this._checkIfFormatsAvailable();
if (settings.stencil && !this.useDepth) {
console.warn('A stencil buffer can only be used if also using depth. Since the framebuffer has no depth buffer, the stencil buffer will be ignored.');
}
this.useStencil = this.useDepth &&
(settings.stencil === undefined ? true : settings.stencil);
this.framebuffer = gl.createFramebuffer();
if (!this.framebuffer) {
throw new Error('Unable to create a framebuffer');
}
if (this.antialias) {
this.aaFramebuffer = gl.createFramebuffer();
if (!this.aaFramebuffer) {
throw new Error('Unable to create a framebuffer for antialiasing');
}
}
this._recreateTextures();
const prevCam = this.target._renderer._curCamera;
this.defaultCamera = this.createCamera();
this.filterCamera = this.createCamera();
this.target._renderer._curCamera = prevCam;
this.draw(() => this.target.clear());
}
/**
* Resizes the framebuffer to a given width and height.
*
* The parameters, `width` and `height`, set the dimensions of the
* framebuffer. For example, calling `myBuffer.resize(300, 500)` resizes
* the framebuffer to 300×500 pixels, then sets `myBuffer.width` to 300
* and `myBuffer.height` 500.
*
* @method resize
* @param {Number} width width of the framebuffer.
* @param {Number} height height of the framebuffer.
*
* @example
* <div>
* <code>
* let myBuffer;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* // Create a p5.Framebuffer object.
* myBuffer = createFramebuffer();
*
* describe('A multicolor sphere on a white surface. The image grows larger or smaller when the user moves the mouse, revealing a gray background.');
* }
*
* function draw() {
* background(200);
*
* // Draw to the p5.Framebuffer object.
* myBuffer.begin();
* background(255);
* normalMaterial();
* sphere(20);
* myBuffer.end();
*
* // Display the p5.Framebuffer object.
* image(myBuffer, -50, -50);
* }
*
* // Resize the p5.Framebuffer object when the
* // user moves the mouse.
* function mouseMoved() {
* myBuffer.resize(mouseX, mouseY);
* }
* </code>
* </div>
*/
resize(width, height) {
this._autoSized = false;
const dimensions =
this.target._renderer._adjustDimensions(width, height);
width = dimensions.adjustedWidth;
height = dimensions.adjustedHeight;
this.width = width;
this.height = height;
this._handleResize();
}
/**
* Sets the framebuffer's pixel density or returns its current density.
*
* Computer displays are grids of little lights called pixels. A display's
* pixel density describes how many pixels it packs into an area. Displays
* with smaller pixels have a higher pixel density and create sharper
* images.
*
* The parameter, `density`, is optional. If a number is passed, as in
* `myBuffer.pixelDensity(1)`, it sets the framebuffer's pixel density. By
* default, the framebuffer's pixel density will match that of the canvas
* where it was created. All canvases default to match the display's pixel
* density.
*
* Calling `myBuffer.pixelDensity()` without an argument returns its current
* pixel density.
*
* @method pixelDensity
* @param {Number} [density] pixel density to set.
* @returns {Number} current pixel density.
*
* @example
* <div>
* <code>
* let myBuffer;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* // Create a p5.Framebuffer object.
* myBuffer = createFramebuffer();
*
* describe("A white circle on a gray canvas. The circle's edge become fuzzy while the user presses and holds the mouse.");
* }
*
* function draw() {
* // Draw to the p5.Framebuffer object.
* myBuffer.begin();
* background(200);
* circle(0, 0, 40);
* myBuffer.end();
*
* // Display the p5.Framebuffer object.
* image(myBuffer, -50, -50);
* }
*
* // Decrease the pixel density when the user
* // presses the mouse.
* function mousePressed() {
* myBuffer.pixelDensity(1);
* }
*
* // Increase the pixel density when the user
* // releases the mouse.
* function mouseReleased() {
* myBuffer.pixelDensity(2);
* }
* </code>
* </div>
*
* <div>
* <code>
* let myBuffer;
* let myFont;
*
* // Load a font and create a p5.Font object.
* function preload() {
* myFont = loadFont('assets/inconsolata.otf');
* }
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* background(200);
*
* // Create a p5.Framebuffer object.
* myBuffer = createFramebuffer();
*
* // Get the p5.Framebuffer object's pixel density.
* let d = myBuffer.pixelDensity();
*
* // Style the text.
* textAlign(CENTER, CENTER);
* textFont(myFont);
* textSize(16);
* fill(0);
*
* // Display the pixel density.
* text(`Density: ${d}`, 0, 0);
*
* describe(`The text "Density: ${d}" written in black on a gray background.`);
* }
* </code>
* </div>
*/
pixelDensity(density) {
if (density) {
this._autoSized = false;
this.density = density;
this._handleResize();
} else {
return this.density;
}
}
/**
* Toggles the framebuffer's autosizing mode or returns the current mode.
*
* By default, the framebuffer automatically resizes to match the canvas
* that created it. Calling `myBuffer.autoSized(false)` disables this
* behavior and calling `myBuffer.autoSized(true)` re-enables it.
*
* Calling `myBuffer.autoSized()` without an argument returns `true` if
* the framebuffer automatically resizes and `false` if not.
*
* @method autoSized
* @param {Boolean} [autoSized] whether to automatically resize the framebuffer to match the canvas.
* @returns {Boolean} current autosize setting.
*
* @example
* <div>
* <code>
* // Double-click to toggle the autosizing mode.
*
* let myBuffer;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* // Create a p5.Framebuffer object.
* myBuffer = createFramebuffer();
*
* describe('A multicolor sphere on a gray background. The image resizes when the user moves the mouse.');
* }
*
* function draw() {
* background(50);
*
* // Draw to the p5.Framebuffer object.
* myBuffer.begin();
* background(200);
* normalMaterial();
* sphere(width / 4);
* myBuffer.end();
*
* // Display the p5.Framebuffer object.
* image(myBuffer, -width / 2, -height / 2);
* }
*
* // Resize the canvas when the user moves the mouse.
* function mouseMoved() {
* let w = constrain(mouseX, 0, 100);
* let h = constrain(mouseY, 0, 100);
* resizeCanvas(w, h);
* }
*
* // Toggle autoSizing when the user double-clicks.
* // Note: opened an issue to fix(?) this.
* function doubleClicked() {
* let isAuto = myBuffer.autoSized();
* myBuffer.autoSized(!isAuto);
* }
* </code>
* </div>
*/
autoSized(autoSized) {
if (autoSized === undefined) {
return this._autoSized;
} else {
this._autoSized = autoSized;
this._handleResize();
}
}
/**
* Checks the capabilities of the current WebGL environment to see if the
* settings supplied by the user are capable of being fulfilled. If they
* are not, warnings will be logged and the settings will be changed to
* something close that can be fulfilled.
*
* @private
*/
_checkIfFormatsAvailable() {
const gl = this.gl;
if (
this.useDepth &&
this.target.webglVersion === constants.WEBGL &&
!gl.getExtension('WEBGL_depth_texture')
) {
console.warn(
'Unable to create depth textures in this environment. Falling back ' +
'to a framebuffer without depth.'
);
this.useDepth = false;
}
if (
this.useDepth &&
this.target.webglVersion === constants.WEBGL &&
this.depthFormat === constants.FLOAT
) {
console.warn(
'FLOAT depth format is unavailable in WebGL 1. ' +
'Defaulting to UNSIGNED_INT.'
);
this.depthFormat = constants.UNSIGNED_INT;
}
if (![
constants.UNSIGNED_BYTE,
constants.FLOAT,
constants.HALF_FLOAT
].includes(this.format)) {
console.warn(
'Unknown Framebuffer format. ' +
'Please use UNSIGNED_BYTE, FLOAT, or HALF_FLOAT. ' +
'Defaulting to UNSIGNED_BYTE.'
);
this.format = constants.UNSIGNED_BYTE;
}
if (this.useDepth && ![
constants.UNSIGNED_INT,
constants.FLOAT
].includes(this.depthFormat)) {
console.warn(
'Unknown Framebuffer depth format. ' +
'Please use UNSIGNED_INT or FLOAT. Defaulting to FLOAT.'
);
this.depthFormat = constants.FLOAT;
}
const support = checkWebGLCapabilities(this.target._renderer);
if (!support.float && this.format === constants.FLOAT) {
console.warn(
'This environment does not support FLOAT textures. ' +
'Falling back to UNSIGNED_BYTE.'
);
this.format = constants.UNSIGNED_BYTE;
}
if (
this.useDepth &&
!support.float &&
this.depthFormat === constants.FLOAT
) {
console.warn(
'This environment does not support FLOAT depth textures. ' +
'Falling back to UNSIGNED_INT.'
);
this.depthFormat = constants.UNSIGNED_INT;
}
if (!support.halfFloat && this.format === constants.HALF_FLOAT) {
console.warn(
'This environment does not support HALF_FLOAT textures. ' +
'Falling back to UNSIGNED_BYTE.'
);
this.format = constants.UNSIGNED_BYTE;
}
if (
this.channels === constants.RGB &&
[constants.FLOAT, constants.HALF_FLOAT].includes(this.format)
) {
console.warn(
'FLOAT and HALF_FLOAT formats do not work cross-platform with only ' +
'RGB channels. Falling back to RGBA.'
);
this.channels = constants.RGBA;
}
}
/**
* Creates new textures and renderbuffers given the current size of the
* framebuffer.
*
* @private
*/
_recreateTextures() {
const gl = this.gl;
this._updateSize();
const prevBoundTexture = gl.getParameter(gl.TEXTURE_BINDING_2D);
const prevBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
const colorTexture = gl.createTexture();
if (!colorTexture) {
throw new Error('Unable to create color texture');
}
gl.bindTexture(gl.TEXTURE_2D, colorTexture);
const colorFormat = this._glColorFormat();
gl.texImage2D(
gl.TEXTURE_2D,
0,
colorFormat.internalFormat,
this.width * this.density,
this.height * this.density,
0,
colorFormat.format,
colorFormat.type,
null
);
this.colorTexture = colorTexture;
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
gl.COLOR_ATTACHMENT0,
gl.TEXTURE_2D,
colorTexture,
0
);
if (this.useDepth) {
// Create the depth texture
const depthTexture = gl.createTexture();
if (!depthTexture) {
throw new Error('Unable to create depth texture');
}
const depthFormat = this._glDepthFormat();
gl.bindTexture(gl.TEXTURE_2D, depthTexture);
gl.texImage2D(
gl.TEXTURE_2D,
0,
depthFormat.internalFormat,
this.width * this.density,
this.height * this.density,
0,
depthFormat.format,
depthFormat.type,
null
);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
this.useStencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT,
gl.TEXTURE_2D,
depthTexture,
0
);
this.depthTexture = depthTexture;
}
// Create separate framebuffer for antialiasing
if (this.antialias) {
this.colorRenderbuffer = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, this.colorRenderbuffer);
gl.renderbufferStorageMultisample(
gl.RENDERBUFFER,
Math.max(
0,
Math.min(this.antialiasSamples, gl.getParameter(gl.MAX_SAMPLES))
),
colorFormat.internalFormat,
this.width * this.density,
this.height * this.density
);
if (this.useDepth) {
const depthFormat = this._glDepthFormat();
this.depthRenderbuffer = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, this.depthRenderbuffer);
gl.renderbufferStorageMultisample(
gl.RENDERBUFFER,
Math.max(
0,
Math.min(this.antialiasSamples, gl.getParameter(gl.MAX_SAMPLES))
),
depthFormat.internalFormat,
this.width * this.density,
this.height * this.density
);
}
gl.bindFramebuffer(gl.FRAMEBUFFER, this.aaFramebuffer);
gl.framebufferRenderbuffer(
gl.FRAMEBUFFER,
gl.COLOR_ATTACHMENT0,
gl.RENDERBUFFER,
this.colorRenderbuffer
);
if (this.useDepth) {
gl.framebufferRenderbuffer(
gl.FRAMEBUFFER,
this.useStencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT,
gl.RENDERBUFFER,
this.depthRenderbuffer
);
}
}
if (this.useDepth) {
this.depth = new FramebufferTexture(this, 'depthTexture');
const depthFilter = gl.NEAREST;
this.depthP5Texture = new p5.Texture(
this.target._renderer,
this.depth,
{
minFilter: depthFilter,
magFilter: depthFilter
}
);
this.target._renderer.textures.set(this.depth, this.depthP5Texture);
}
this.color = new FramebufferTexture(this, 'colorTexture');
const filter = this.textureFiltering === constants.LINEAR
? gl.LINEAR
: gl.NEAREST;
this.colorP5Texture = new p5.Texture(
this.target._renderer,
this.color,
{
minFilter: filter,
magFilter: filter
}
);
this.target._renderer.textures.set(this.color, this.colorP5Texture);
gl.bindTexture(gl.TEXTURE_2D, prevBoundTexture);
gl.bindFramebuffer(gl.FRAMEBUFFER, prevBoundFramebuffer);
}
/**
* To create a WebGL texture, one needs to supply three pieces of information:
* the type (the data type each channel will be stored as, e.g. int or float),
* the format (the color channels that will each be stored in the previously
* specified type, e.g. rgb or rgba), and the internal format (the specifics
* of how data for each channel, in the aforementioned type, will be packed
* together, such as how many bits to use, e.g. RGBA32F or RGB565.)
*
* The format and channels asked for by the user hint at what these values
* need to be, and the WebGL version affects what options are avaiable.
* This method returns the values for these three properties, given the
* framebuffer's settings.
*
* @private
*/
_glColorFormat() {
let type, format, internalFormat;
const gl = this.gl;
if (this.format === constants.FLOAT) {
type = gl.FLOAT;
} else if (this.format === constants.HALF_FLOAT) {
type = this.target.webglVersion === constants.WEBGL2
? gl.HALF_FLOAT
: gl.getExtension('OES_texture_half_float').HALF_FLOAT_OES;
} else {
type = gl.UNSIGNED_BYTE;
}
if (this.channels === constants.RGBA) {
format = gl.RGBA;
} else {
format = gl.RGB;
}
if (this.target.webglVersion === constants.WEBGL2) {
// https://webgl2fundamentals.org/webgl/lessons/webgl-data-textures.html
const table = {
[gl.FLOAT]: {
[gl.RGBA]: gl.RGBA32F
// gl.RGB32F is not available in Firefox without an alpha channel
},
[gl.HALF_FLOAT]: {
[gl.RGBA]: gl.RGBA16F
// gl.RGB16F is not available in Firefox without an alpha channel
},
[gl.UNSIGNED_BYTE]: {
[gl.RGBA]: gl.RGBA8, // gl.RGBA4
[gl.RGB]: gl.RGB8 // gl.RGB565
}
};
internalFormat = table[type][format];
} else if (this.format === constants.HALF_FLOAT) {
internalFormat = gl.RGBA;
} else {
internalFormat = format;
}
return { internalFormat, format, type };
}
/**
* To create a WebGL texture, one needs to supply three pieces of information:
* the type (the data type each channel will be stored as, e.g. int or float),
* the format (the color channels that will each be stored in the previously
* specified type, e.g. rgb or rgba), and the internal format (the specifics
* of how data for each channel, in the aforementioned type, will be packed
* together, such as how many bits to use, e.g. RGBA32F or RGB565.)
*
* This method takes into account the settings asked for by the user and
* returns values for these three properties that can be used for the
* texture storing depth information.
*
* @private
*/
_glDepthFormat() {
let type, format, internalFormat;
const gl = this.gl;
if (this.useStencil) {
if (this.depthFormat === constants.FLOAT) {
type = gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
} else if (this.target.webglVersion === constants.WEBGL2) {
type = gl.UNSIGNED_INT_24_8;
} else {
type = gl.getExtension('WEBGL_depth_texture').UNSIGNED_INT_24_8_WEBGL;
}
} else {
if (this.depthFormat === constants.FLOAT) {
type = gl.FLOAT;
} else {
type = gl.UNSIGNED_INT;
}
}
if (this.useStencil) {
format = gl.DEPTH_STENCIL;
} else {
format = gl.DEPTH_COMPONENT;
}
if (this.useStencil) {
if (this.depthFormat === constants.FLOAT) {
internalFormat = gl.DEPTH32F_STENCIL8;
} else if (this.target.webglVersion === constants.WEBGL2) {
internalFormat = gl.DEPTH24_STENCIL8;
} else {
internalFormat = gl.DEPTH_STENCIL;
}
} else if (this.target.webglVersion === constants.WEBGL2) {
if (this.depthFormat === constants.FLOAT) {
internalFormat = gl.DEPTH_COMPONENT32F;
} else {
internalFormat = gl.DEPTH_COMPONENT24;
}
} else {
internalFormat = gl.DEPTH_COMPONENT;
}
return { internalFormat, format, type };
}
/**
* A method that will be called when recreating textures. If the framebuffer
* is auto-sized, it will update its width, height, and density properties.
*
* @private
*/
_updateSize() {
if (this._autoSized) {
this.width = this.target.width;
this.height = this.target.height;
this.density = this.target.pixelDensity();
}
}
/**
* Called when the canvas that the framebuffer is attached to resizes. If the
* framebuffer is auto-sized, it will update its textures to match the new
* size.
*
* @private
*/
_canvasSizeChanged() {
if (this._autoSized) {
this._handleResize();
}
}
/**
* Called when the size of the framebuffer has changed (either by being
* manually updated or from auto-size updates when its canvas changes size.)
* Old textures and renderbuffers will be deleted, and then recreated with the
* new size.
*
* @private
*/
_handleResize() {
const oldColor = this.color;
const oldDepth = this.depth;
const oldColorRenderbuffer = this.colorRenderbuffer;
const oldDepthRenderbuffer = this.depthRenderbuffer;
this._deleteTexture(oldColor);
if (oldDepth) this._deleteTexture(oldDepth);
const gl = this.gl;
if (oldColorRenderbuffer) gl.deleteRenderbuffer(oldColorRenderbuffer);
if (oldDepthRenderbuffer) gl.deleteRenderbuffer(oldDepthRenderbuffer);
this._recreateTextures();
this.defaultCamera._resize();
}
/**
* Creates a new
* <a href="#/p5.Camera">p5.Camera</a> object to use with the framebuffer.
*
* The new camera is initialized with a default position `(0, 0, 800)` and a
* default perspective projection. Its properties can be controlled with
* <a href="#/p5.Camera">p5.Camera</a> methods such as `myCamera.lookAt(0, 0, 0)`.
*
* Framebuffer cameras should be created between calls to
* <a href="#/p5.Framebuffer/begin">myBuffer.begin()</a> and
* <a href="#/p5.Framebuffer/end">myBuffer.end()</a> like so:
*
* ```js
* let myCamera;
*
* myBuffer.begin();
*
* // Create the camera for the framebuffer.
* myCamera = myBuffer.createCamera();
*
* myBuffer.end();
* ```
*
* Calling <a href="#/p5/setCamera">setCamera()</a> updates the
* framebuffer's projection using the camera.
* <a href="#/p5/resetMatrix">resetMatrix()</a> must also be called for the
* view to change properly:
*
* ```js
* myBuffer.begin();
*
* // Set the camera for the framebuffer.
* setCamera(myCamera);
*
* // Reset all transformations.
* resetMatrix();
*
* // Draw stuff...
*
* myBuffer.end();
* ```
*
* @method createCamera
* @returns {p5.Camera} new camera.
*
* @example
* <div>
* <code>
* // Double-click to toggle between cameras.
*
* let myBuffer;
* let cam1;
* let cam2;
* let usingCam1 = true;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* // Create a p5.Framebuffer object.
* myBuffer = createFramebuffer();
*
* // Create the cameras between begin() and end().
* myBuffer.begin();
*
* // Create the first camera.
* // Keep its default settings.
* cam1 = myBuffer.createCamera();
*
* // Create the second camera.
* // Place it at the top-left.
* // Point it at the origin.
* cam2 = myBuffer.createCamera();
* cam2.setPosition(400, -400, 800);
* cam2.lookAt(0, 0, 0);
*
* myBuffer.end();
*
* describe(
* 'A white cube on a gray background. The camera toggles between frontal and aerial views when the user double-clicks.'
* );
* }
*
* function draw() {
* // Draw to the p5.Framebuffer object.
* myBuffer.begin();
* background(200);
*
* // Set the camera.
* if (usingCam1 === true) {
* setCamera(cam1);
* } else {
* setCamera(cam2);
* }
*
* // Reset all transformations.
* resetMatrix();
*
* // Draw the box.
* box();
*
* myBuffer.end();
*
* // Display the p5.Framebuffer object.
* image(myBuffer, -50, -50);
* }
*
* // Toggle the current camera when the user double-clicks.
* function doubleClicked() {
* if (usingCam1 === true) {