forked from processing/p5.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaterial.js
More file actions
3869 lines (3787 loc) · 112 KB
/
Copy pathmaterial.js
File metadata and controls
3869 lines (3787 loc) · 112 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
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 3D
* @submodule Material
* @for p5
* @requires core
*/
import * as constants from '../core/constants';
import { RendererGL } from './p5.RendererGL';
import { Shader } from './p5.Shader';
import { request } from '../io/files';
import { Color } from '../color/p5.Color';
function material(p5, fn){
/**
* Loads vertex and fragment shaders to create a
* <a href="#/p5.Shader">p5.Shader</a> object.
*
* Shaders are programs that run on the graphics processing unit (GPU). They
* can process many pixels at the same time, making them fast for many
* graphics tasks. They’re written in a language called
* <a href="https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_on_the_web/GLSL_Shaders" target="_blank">GLSL</a>
* and run along with the rest of the code in a sketch.
*
* Once the <a href="#/p5.Shader">p5.Shader</a> object is created, it can be
* used with the <a href="#/p5/shader">shader()</a> function, as in
* `shader(myShader)`. A shader program consists of two files, a vertex shader
* and a fragment shader. The vertex shader affects where 3D geometry is drawn
* on the screen and the fragment shader affects color.
*
* `loadShader()` loads the vertex and fragment shaders from their `.vert` and
* `.frag` files. For example, calling
* `loadShader('assets/shader.vert', 'assets/shader.frag')` loads both
* required shaders and returns a <a href="#/p5.Shader">p5.Shader</a> object.
*
* The third parameter, `successCallback`, is optional. If a function is
* passed, it will be called once the shader has loaded. The callback function
* can use the new <a href="#/p5.Shader">p5.Shader</a> object as its
* parameter. The return value of the `successCallback()` function will be used
* as the final return value of `loadShader()`.
*
* The fourth parameter, `failureCallback`, is also optional. If a function is
* passed, it will be called if the shader fails to load. The callback
* function can use the event error as its parameter. The return value of the `
* failureCallback()` function will be used as the final return value of `loadShader()`.
*
* This function returns a `Promise` and should be used in an `async` setup with
* `await`. See the examples for the usage syntax.
*
* Note: Shaders can only be used in WebGL mode.
*
* @method loadShader
* @param {String|Request} vertFilename path of the vertex shader to be loaded.
* @param {String|Request} fragFilename path of the fragment shader to be loaded.
* @param {Function} [successCallback] function to call once the shader is loaded. Can be passed the
* <a href="#/p5.Shader">p5.Shader</a> object.
* @param {Function} [failureCallback] function to call if the shader fails to load. Can be passed an
* `Error` event object.
* @return {Promise<p5.Shader>} new shader created from the vertex and fragment shader files.
*
* @example
* <div modernizr='webgl'>
* <code>
* // Note: A "uniform" is a global variable within a shader program.
*
* let mandelbrot;
*
* // Load the shader and create a p5.Shader object.
* async function setup() {
* mandelbrot = await loadShader('assets/shader.vert', 'assets/shader.frag');
*
* createCanvas(100, 100, WEBGL);
*
* // Compile and apply the p5.Shader object.
* shader(mandelbrot);
*
* // Set the shader uniform p to an array.
* mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);
*
* // Set the shader uniform r to the value 1.5.
* mandelbrot.setUniform('r', 1.5);
*
* // Add a quad as a display surface for the shader.
* quad(-1, -1, 1, -1, 1, 1, -1, 1);
*
* describe('A black fractal image on a magenta background.');
* }
* </code>
* </div>
*
* <div>
* <code>
* // Note: A "uniform" is a global variable within a shader program.
*
* let mandelbrot;
*
* // Load the shader and create a p5.Shader object.
* async function setup() {
* mandelbrot = await loadShader('assets/shader.vert', 'assets/shader.frag');
*
* createCanvas(100, 100, WEBGL);
*
* // Use the p5.Shader object.
* shader(mandelbrot);
*
* // Set the shader uniform p to an array.
* mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);
*
* describe('A fractal image zooms in and out of focus.');
* }
*
* function draw() {
* // Set the shader uniform r to a value that oscillates between 0 and 2.
* mandelbrot.setUniform('r', sin(frameCount * 0.01) + 1);
*
* // Add a quad as a display surface for the shader.
* quad(-1, -1, 1, -1, 1, 1, -1, 1);
* }
* </code>
* </div>
*/
fn.loadShader = async function (
vertFilename,
fragFilename,
successCallback,
failureCallback
) {
// p5._validateParameters('loadShader', arguments);
const loadedShader = new Shader();
try {
loadedShader._vertSrc = (await request(vertFilename, 'text')).data;
loadedShader._fragSrc = (await request(fragFilename, 'text')).data;
if (successCallback) {
return successCallback(loadedShader);
} else {
return loadedShader
}
} catch(err) {
if (failureCallback) {
return failureCallback(err);
} else {
throw err;
}
}
};
/**
* Creates a new <a href="#/p5.Shader">p5.Shader</a> object.
*
* Shaders are programs that run on the graphics processing unit (GPU). They
* can process many pixels at the same time, making them fast for many
* graphics tasks. They’re written in a language called
* <a href="https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_on_the_web/GLSL_Shaders" target="_blank">GLSL</a>
* and run along with the rest of the code in a sketch.
*
* Once the <a href="#/p5.Shader">p5.Shader</a> object is created, it can be
* used with the <a href="#/p5/shader">shader()</a> function, as in
* `shader(myShader)`. A shader program consists of two parts, a vertex shader
* and a fragment shader. The vertex shader affects where 3D geometry is drawn
* on the screen and the fragment shader affects color.
*
* The first parameter, `vertSrc`, sets the vertex shader. It’s a string that
* contains the vertex shader program written in GLSL.
*
* The second parameter, `fragSrc`, sets the fragment shader. It’s a string
* that contains the fragment shader program written in GLSL.
*
* A shader can optionally describe *hooks,* which are functions in GLSL that
* users may choose to provide to customize the behavior of the shader using the
* <a href="#/p5.Shader/modify">`modify()`</a> method of `p5.Shader`. These are added by
* describing the hooks in a third parameter, `options`, and referencing the hooks in
* your `vertSrc` or `fragSrc`. Hooks for the vertex or fragment shader are described under
* the `vertex` and `fragment` keys of `options`. Each one is an object. where each key is
* the type and name of a hook function, and each value is a string with the
* parameter list and default implementation of the hook. For example, to let users
* optionally run code at the start of the vertex shader, the options object could
* include:
*
* ```js
* {
* vertex: {
* 'void beforeVertex': '() {}'
* }
* }
* ```
*
* Then, in your vertex shader source, you can run a hook by calling a function
* with the same name prefixed by `HOOK_`. If you want to check if the default
* hook has been replaced, maybe to avoid extra overhead, you can check if the
* same name prefixed by `AUGMENTED_HOOK_` has been defined:
*
* ```glsl
* void main() {
* // In most cases, just calling the hook is fine:
* HOOK_beforeVertex();
*
* // Alternatively, for more efficiency:
* #ifdef AUGMENTED_HOOK_beforeVertex
* HOOK_beforeVertex();
* #endif
*
* // Add the rest of your shader code here!
* }
* ```
*
* Note: Only filter shaders can be used in 2D mode. All shaders can be used
* in WebGL mode.
*
* @method createShader
* @param {String} vertSrc source code for the vertex shader.
* @param {String} fragSrc source code for the fragment shader.
* @param {Object} [options] An optional object describing how this shader can
* be augmented with hooks. It can include:
* - `vertex`: An object describing the available vertex shader hooks.
* - `fragment`: An object describing the available frament shader hooks.
* @returns {p5.Shader} new shader object created from the
* vertex and fragment shaders.
*
* @example
* <div modernizr='webgl'>
* <code>
* // Note: A "uniform" is a global variable within a shader program.
*
* // Create a string with the vertex shader program.
* // The vertex shader is called for each vertex.
* let vertSrc = `
* precision highp float;
* uniform mat4 uModelViewMatrix;
* uniform mat4 uProjectionMatrix;
* attribute vec3 aPosition;
* attribute vec2 aTexCoord;
* varying vec2 vTexCoord;
*
* void main() {
* vTexCoord = aTexCoord;
* vec4 positionVec4 = vec4(aPosition, 1.0);
* gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;
* }
* `;
*
* // Create a string with the fragment shader program.
* // The fragment shader is called for each pixel.
* let fragSrc = `
* precision highp float;
*
* void main() {
* // Set each pixel's RGBA value to yellow.
* gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);
* }
* `;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* // Create a p5.Shader object.
* let shaderProgram = createShader(vertSrc, fragSrc);
*
* // Compile and apply the p5.Shader object.
* shader(shaderProgram);
*
* // Style the drawing surface.
* noStroke();
*
* // Add a plane as a drawing surface.
* plane(100, 100);
*
* describe('A yellow square.');
* }
* </code>
* </div>
*
* <div>
* <code>
* // Note: A "uniform" is a global variable within a shader program.
*
* // Create a string with the vertex shader program.
* // The vertex shader is called for each vertex.
* let vertSrc = `
* precision highp float;
* uniform mat4 uModelViewMatrix;
* uniform mat4 uProjectionMatrix;
* attribute vec3 aPosition;
* attribute vec2 aTexCoord;
* varying vec2 vTexCoord;
*
* void main() {
* vTexCoord = aTexCoord;
* vec4 positionVec4 = vec4(aPosition, 1.0);
* gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;
* }
* `;
*
* // Create a string with the fragment shader program.
* // The fragment shader is called for each pixel.
* let fragSrc = `
* precision highp float;
* uniform vec2 p;
* uniform float r;
* const int numIterations = 500;
* varying vec2 vTexCoord;
*
* void main() {
* vec2 c = p + gl_FragCoord.xy * r;
* vec2 z = c;
* float n = 0.0;
*
* for (int i = numIterations; i > 0; i--) {
* if (z.x * z.x + z.y * z.y > 4.0) {
* n = float(i) / float(numIterations);
* break;
* }
* z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c;
* }
*
* gl_FragColor = vec4(
* 0.5 - cos(n * 17.0) / 2.0,
* 0.5 - cos(n * 13.0) / 2.0,
* 0.5 - cos(n * 23.0) / 2.0,
* 1.0
* );
* }
* `;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* // Create a p5.Shader object.
* let mandelbrot = createShader(vertSrc, fragSrc);
*
* // Compile and apply the p5.Shader object.
* shader(mandelbrot);
*
* // Set the shader uniform p to an array.
* // p is the center point of the Mandelbrot image.
* mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);
*
* // Set the shader uniform r to 0.005.
* // r is the size of the image in Mandelbrot-space.
* mandelbrot.setUniform('r', 0.005);
*
* // Style the drawing surface.
* noStroke();
*
* // Add a plane as a drawing surface.
* plane(100, 100);
*
* describe('A black fractal image on a magenta background.');
* }
* </code>
* </div>
*
* <div>
* <code>
* // Note: A "uniform" is a global variable within a shader program.
*
* // Create a string with the vertex shader program.
* // The vertex shader is called for each vertex.
* let vertSrc = `
* precision highp float;
* uniform mat4 uModelViewMatrix;
* uniform mat4 uProjectionMatrix;
*
* attribute vec3 aPosition;
* attribute vec2 aTexCoord;
* varying vec2 vTexCoord;
*
* void main() {
* vTexCoord = aTexCoord;
* vec4 positionVec4 = vec4(aPosition, 1.0);
* gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;
* }
* `;
*
* // Create a string with the fragment shader program.
* // The fragment shader is called for each pixel.
* let fragSrc = `
* precision highp float;
* uniform vec2 p;
* uniform float r;
* const int numIterations = 500;
* varying vec2 vTexCoord;
*
* void main() {
* vec2 c = p + gl_FragCoord.xy * r;
* vec2 z = c;
* float n = 0.0;
*
* for (int i = numIterations; i > 0; i--) {
* if (z.x * z.x + z.y * z.y > 4.0) {
* n = float(i) / float(numIterations);
* break;
* }
*
* z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c;
* }
*
* gl_FragColor = vec4(
* 0.5 - cos(n * 17.0) / 2.0,
* 0.5 - cos(n * 13.0) / 2.0,
* 0.5 - cos(n * 23.0) / 2.0,
* 1.0
* );
* }
* `;
*
* let mandelbrot;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* // Create a p5.Shader object.
* mandelbrot = createShader(vertSrc, fragSrc);
*
* // Apply the p5.Shader object.
* shader(mandelbrot);
*
* // Set the shader uniform p to an array.
* // p is the center point of the Mandelbrot image.
* mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);
*
* describe('A fractal image zooms in and out of focus.');
* }
*
* function draw() {
* // Set the shader uniform r to a value that oscillates
* // between 0 and 0.005.
* // r is the size of the image in Mandelbrot-space.
* let radius = 0.005 * (sin(frameCount * 0.01) + 1);
* mandelbrot.setUniform('r', radius);
*
* // Style the drawing surface.
* noStroke();
*
* // Add a plane as a drawing surface.
* plane(100, 100);
* }
* </code>
* </div>
*
* <div>
* <code>
* // A shader with hooks.
* let myShader;
*
* // A shader with modified hooks.
* let modifiedShader;
*
* // Create a string with the vertex shader program.
* // The vertex shader is called for each vertex.
* let vertSrc = `
* precision highp float;
* uniform mat4 uModelViewMatrix;
* uniform mat4 uProjectionMatrix;
*
* attribute vec3 aPosition;
* attribute vec2 aTexCoord;
*
* void main() {
* vec4 positionVec4 = vec4(aPosition, 1.0);
* gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;
* }
* `;
*
* // Create a fragment shader that uses a hook.
* let fragSrc = `
* precision highp float;
* void main() {
* // Let users override the color
* gl_FragColor = HOOK_getColor(vec4(1., 0., 0., 1.));
* }
* `;
*
* function setup() {
* createCanvas(50, 50, WEBGL);
*
* // Create a shader with hooks
* myShader = createShader(vertSrc, fragSrc, {
* fragment: {
* 'vec4 getColor': '(vec4 color) { return color; }'
* }
* });
*
* // Make a version of the shader with a hook overridden
* modifiedShader = myShader.modify({
* 'vec4 getColor': `(vec4 color) {
* return vec4(0., 0., 1., 1.);
* }`
* });
* }
*
* function draw() {
* noStroke();
*
* push();
* shader(myShader);
* translate(-width/3, 0);
* sphere(10);
* pop();
*
* push();
* shader(modifiedShader);
* translate(width/3, 0);
* sphere(10);
* pop();
* }
* </code>
* </div>
*/
fn.createShader = function (vertSrc, fragSrc, options) {
// p5._validateParameters('createShader', arguments);
return new Shader(this._renderer, vertSrc, fragSrc, options);
};
/**
* Creates and loads a filter shader from an external file.
*
* @method loadFilterShader
* @param {String} fragFilename path to the fragment shader file
* @param {Function} [successCallback] callback to be called once the shader is
* loaded. Will be passed the
* <a href="#/p5.Shader">p5.Shader</a> object.
* @param {Function} [failureCallback] callback to be called if there is an error
* loading the shader. Will be passed the
* error event.
* @return {Promise<p5.Shader>} a promise that resolves with a shader object
*
* @example
* <div modernizr='webgl'>
* <code>
* let myShader;
*
* async function setup() {
* myShader = await loadFilterShader('assets/basic.frag');
* createCanvas(100, 100, WEBGL);
* noStroke();
* }
*
* function draw() {
* // shader() sets the active shader with our shader
* shader(myShader);
*
* // rect gives us some geometry on the screen
* rect(-50, -50, width, height);
* }
* </code>
* </div>
* @alt
* A rectangle with a shader applied to it.
*/
fn.loadFilterShader = async function (fragFilename, successCallback, failureCallback) {
// p5._validateParameters('loadFilterShader', arguments);
try {
// Load the fragment shader
const fragSrc = await this.loadStrings(fragFilename);
const fragString = await fragSrc.join('\n');
// Create the shader using createFilterShader
const loadedShader = this.createFilterShader(fragString, true);
if (successCallback) {
successCallback(loadedShader);
}
return loadedShader;
} catch (err) {
if (failureCallback) {
failureCallback(err);
} else {
console.error(err);
}
}
};
/**
* Creates a <a href="#/p5.Shader">p5.Shader</a> object to be used with the
* <a href="#/p5/filter">filter()</a> function.
*
* `createFilterShader()` works like
* <a href="#/p5/createShader">createShader()</a> but has a default vertex
* shader included. `createFilterShader()` is intended to be used along with
* <a href="#/p5/filter">filter()</a> for filtering the contents of a canvas.
* A filter shader will be applied to the whole canvas instead of just
* <a href="#/p5.Geometry">p5.Geometry</a> objects.
*
* The parameter, `fragSrc`, sets the fragment shader. It’s a string that
* contains the fragment shader program written in
* <a href="https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_on_the_web/GLSL_Shaders" target="_blank">GLSL</a>.
*
* The <a href="#/p5.Shader">p5.Shader</a> object that's created has some
* uniforms that can be set:
* - `sampler2D tex0`, which contains the canvas contents as a texture.
* - `vec2 canvasSize`, which is the width and height of the canvas, not including pixel density.
* - `vec2 texelSize`, which is the size of a physical pixel including pixel density. This is calculated as `1.0 / (width * density)` for the pixel width and `1.0 / (height * density)` for the pixel height.
*
* The <a href="#/p5.Shader">p5.Shader</a> that's created also provides
* `varying vec2 vTexCoord`, a coordinate with values between 0 and 1.
* `vTexCoord` describes where on the canvas the pixel will be drawn.
*
* For more info about filters and shaders, see Adam Ferriss' <a href="https://github.com/aferriss/p5jsShaderExamples">repo of shader examples</a>
* or the <a href="https://p5js.org/learn/getting-started-in-webgl-shaders.html">Introduction to Shaders</a> tutorial.
*
* @method createFilterShader
* @param {String} fragSrc source code for the fragment shader.
* @returns {p5.Shader} new shader object created from the fragment shader.
*
* @example
* <div modernizr='webgl'>
* <code>
* function setup() {
* let fragSrc = `precision highp float;
* void main() {
* gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);
* }`;
*
* createCanvas(100, 100, WEBGL);
* let s = createFilterShader(fragSrc);
* filter(s);
* describe('a yellow canvas');
* }
* </code>
* </div>
*
* <div modernizr='webgl'>
* <code>
* let img, s;
* async function setup() {
* img = await loadImage('assets/bricks.jpg');
* let fragSrc = `precision highp float;
*
* // x,y coordinates, given from the vertex shader
* varying vec2 vTexCoord;
*
* // the canvas contents, given from filter()
* uniform sampler2D tex0;
* // other useful information from the canvas
* uniform vec2 texelSize;
* uniform vec2 canvasSize;
* // a custom variable from this sketch
* uniform float darkness;
*
* void main() {
* // get the color at current pixel
* vec4 color = texture2D(tex0, vTexCoord);
* // set the output color
* color.b = 1.0;
* color *= darkness;
* gl_FragColor = vec4(color.rgb, 1.0);
* }`;
*
* createCanvas(100, 100, WEBGL);
* s = createFilterShader(fragSrc);
* }
*
* function draw() {
* image(img, -50, -50);
* s.setUniform('darkness', 0.5);
* filter(s);
* describe('a image of bricks tinted dark blue');
* }
* </code>
* </div>
*/
fn.createFilterShader = function (fragSrc, skipContextCheck = false) {
// p5._validateParameters('createFilterShader', arguments);
let defaultVertV1 = `
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
attribute vec3 aPosition;
// texcoords only come from p5 to vertex shader
// so pass texcoords on to the fragment shader in a varying variable
attribute vec2 aTexCoord;
varying vec2 vTexCoord;
void main() {
// transferring texcoords for the frag shader
vTexCoord = aTexCoord;
// copy position with a fourth coordinate for projection (1.0 is normal)
vec4 positionVec4 = vec4(aPosition, 1.0);
// project to 3D space
gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;
}
`;
let defaultVertV2 = `#version 300 es
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
in vec3 aPosition;
in vec2 aTexCoord;
out vec2 vTexCoord;
void main() {
// transferring texcoords for the frag shader
vTexCoord = aTexCoord;
// copy position with a fourth coordinate for projection (1.0 is normal)
vec4 positionVec4 = vec4(aPosition, 1.0);
// project to 3D space
gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;
}
`;
let vertSrc = fragSrc.includes('#version 300 es') ? defaultVertV2 : defaultVertV1;
const shader = new Shader(this._renderer, vertSrc, fragSrc);
if (!skipContextCheck) {
if (this._renderer.GL) {
shader.ensureCompiledOnContext(this._renderer);
} else {
shader.ensureCompiledOnContext(this);
}
}
return shader;
};
/**
* Sets the <a href="#/p5.Shader">p5.Shader</a> object to apply while drawing.
*
* Shaders are programs that run on the graphics processing unit (GPU). They
* can process many pixels or vertices at the same time, making them fast for
* many graphics tasks. They’re written in a language called
* <a href="https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_on_the_web/GLSL_Shaders" target="_blank">GLSL</a>
* and run along with the rest of the code in a sketch.
* <a href="#/p5.Shader">p5.Shader</a> objects can be created using the
* <a href="#/p5/createShader">createShader()</a> and
* <a href="#/p5/loadShader">loadShader()</a> functions.
*
* The parameter, `s`, is the <a href="#/p5.Shader">p5.Shader</a> object to
* apply. For example, calling `shader(myShader)` applies `myShader` to
* process each pixel on the canvas. This only changes the fill (the inner part of shapes),
* but does not affect the outlines (strokes) or any images drawn using the `image()` function.
* The source code from a <a href="#/p5.Shader">p5.Shader</a> object's
* fragment and vertex shaders will be compiled the first time it's passed to
* `shader()`. See
* <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/compileShader" target="_blank">MDN</a>
* for more information about compiling shaders.
*
* Calling <a href="#/p5/resetShader">resetShader()</a> restores a sketch’s
* default shaders.
*
* Note: Shaders can only be used in WebGL mode.
*
* <div>
* <p>
*
* If you want to apply shaders to strokes or images, use the following methods:
* - **[strokeShader()](#/p5/strokeShader)**: Applies a shader to the stroke (outline) of shapes, allowing independent control over the stroke rendering using shaders.
* - **[imageShader()](#/p5/imageShader)**: Applies a shader to images or textures, controlling how the shader modifies their appearance during rendering.
*
* </p>
* </div>
*
*
* @method shader
* @chainable
* @param {p5.Shader} s <a href="#/p5.Shader">p5.Shader</a> object
* to apply.
*
* @example
* <div modernizr='webgl'>
* <code>
* let fillShader;
*
* let vertSrc = `
* precision highp float;
* attribute vec3 aPosition;
* uniform mat4 uModelViewMatrix;
* uniform mat4 uProjectionMatrix;
* varying vec3 vPosition;
*
* void main() {
* vPosition = aPosition;
* gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, 1.0);
* }
* `;
*
* let fragSrc = `
* precision highp float;
* uniform vec3 uLightDir;
* varying vec3 vPosition;
*
* void main() {
* vec3 lightDir = normalize(uLightDir);
* float brightness = dot(lightDir, normalize(vPosition));
* brightness = clamp(brightness, 0.4, 1.0);
* vec3 color = vec3(0.3, 0.5, 1.0);
* color = color * brightness * 3.0;
* gl_FragColor = vec4(color, 1.0);
* }
* `;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
* fillShader = createShader(vertSrc, fragSrc);
* noStroke();
* describe('A rotating torus with simulated directional lighting.');
* }
*
* function draw() {
* background(20, 20, 40);
* let lightDir = [0.5, 0.5, -1.0];
* fillShader.setUniform('uLightDir', lightDir);
* shader(fillShader);
* rotateY(frameCount * 0.02);
* rotateX(frameCount * 0.02);
* //lights();
* torus(25, 10, 30, 30);
* }
* </code>
* </div>
*
* @example
* <div modernizr='webgl'>
* <code>
* let fillShader;
*
* let vertSrc = `
* precision highp float;
* attribute vec3 aPosition;
* uniform mat4 uProjectionMatrix;
* uniform mat4 uModelViewMatrix;
* varying vec3 vPosition;
* void main() {
* vPosition = aPosition;
* gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, 1.0);
* }
* `;
*
* let fragSrc = `
* precision highp float;
* uniform vec3 uLightPos;
* uniform vec3 uFillColor;
* varying vec3 vPosition;
* void main() {
* float brightness = dot(normalize(uLightPos), normalize(vPosition));
* brightness = clamp(brightness, 0.0, 1.0);
* vec3 color = uFillColor * brightness;
* gl_FragColor = vec4(color, 1.0);
* }
* `;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
* fillShader = createShader(vertSrc, fragSrc);
* shader(fillShader);
* noStroke();
* describe('A square affected by both fill color and lighting, with lights controlled by mouse.');
* }
*
* function draw() {
* let lightPos = [(mouseX - width / 2) / width,
* (mouseY - height / 2) / height, 1.0];
* fillShader.setUniform('uLightPos', lightPos);
* let fillColor = [map(mouseX, 0, width, 0, 1),
* map(mouseY, 0, height, 0, 1), 0.5];
* fillShader.setUniform('uFillColor', fillColor);
* plane(100, 100);
* }
* </code>
* </div>
*
* @example
* <div modernizr='webgl'>
* <code>
* let myShader;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* myShader = baseMaterialShader().modify({
* declarations: 'uniform float time;',
* 'vec4 getFinalColor': `(vec4 color) {
* float r = 0.2 + 0.5 * abs(sin(time + 0.0));
* float g = 0.2 + 0.5 * abs(sin(time + 1.0));
* float b = 0.2 + 0.5 * abs(sin(time + 2.0));
* color.rgb = vec3(r, g, b);
* return color;
* }`
* });
*
* noStroke();
* describe('A 3D cube with dynamically changing colors on a beige background.');
* }
*
* function draw() {
* background(245, 245, 220);
* shader(myShader);
* myShader.setUniform('time', millis() / 1000.0);
*
* box(50);
* }
* </code>
* </div>
*
*/
fn.shader = function (s) {
this._assert3d('shader');
// p5._validateParameters('shader', arguments);
this._renderer.shader(s);
return this;
};
/**
* Sets the <a href="#/p5.Shader">p5.Shader</a> object to apply for strokes.
*
* This method applies the given shader to strokes, allowing customization of
* how lines and outlines are drawn in 3D space. The shader will be used for
* strokes until <a href="#/p5/resetShader">resetShader()</a> is called or another
* strokeShader is applied.
*
* The shader will be used for:
* - Strokes only, regardless of whether the uniform `uStrokeWeight` is present.
*
* To further customize its behavior, refer to the various hooks provided by
* the <a href="#/p5/baseStrokeShader">baseStrokeShader()</a> method, which allow
* control over stroke weight, vertex positions, colors, and more.
*
* @method strokeShader
* @chainable
* @param {p5.Shader} s <a href="#/p5.Shader">p5.Shader</a> object
* to apply for strokes.
*
*
* @example
* <div modernizr='webgl'>
* <code>
* let animatedStrokeShader;
*
* let vertSrc = `
* precision mediump int;
*
* uniform mat4 uModelViewMatrix;
* uniform mat4 uProjectionMatrix;
* uniform float uStrokeWeight;
*
* uniform bool uUseLineColor;
* uniform vec4 uMaterialColor;
*
* uniform vec4 uViewport;
* uniform int uPerspective;
* uniform int uStrokeJoin;
*
* attribute vec4 aPosition;
* attribute vec3 aTangentIn;
* attribute vec3 aTangentOut;
* attribute float aSide;
* attribute vec4 aVertexColor;
*
* void main() {
* vec4 posp = uModelViewMatrix * aPosition;
* vec4 posqIn = uModelViewMatrix * (aPosition + vec4(aTangentIn, 0));
* vec4 posqOut = uModelViewMatrix * (aPosition + vec4(aTangentOut, 0));
*
* float facingCamera = pow(
* abs(normalize(posqIn-posp).z),
* 0.25
* );
*
* float scale = mix(1., 0.995, facingCamera);
*
* posp.xyz = posp.xyz * scale;
* posqIn.xyz = posqIn.xyz * scale;
* posqOut.xyz = posqOut.xyz * scale;
*
* vec4 p = uProjectionMatrix * posp;
* vec4 qIn = uProjectionMatrix * posqIn;
* vec4 qOut = uProjectionMatrix * posqOut;
*
* vec2 tangentIn = normalize((qIn.xy*p.w - p.xy*qIn.w) * uViewport.zw);
* vec2 tangentOut = normalize((qOut.xy*p.w - p.xy*qOut.w) * uViewport.zw);
*
* vec2 curPerspScale;
* if(uPerspective == 1) {
* curPerspScale = (uProjectionMatrix * vec4(1, sign(uProjectionMatrix[1][1]), 0, 0)).xy;
* } else {
* curPerspScale = p.w / (0.5 * uViewport.zw);
* }
*
* vec2 offset;
* vec2 tangent = aTangentIn == vec3(0.) ? tangentOut : tangentIn;
* vec2 normal = vec2(-tangent.y, tangent.x);
* float normalOffset = sign(aSide);
* float tangentOffset = abs(aSide) - 1.;
* offset = (normal * normalOffset + tangent * tangentOffset) *
* uStrokeWeight * 0.5;
*
* gl_Position.xy = p.xy + offset.xy * curPerspScale;
* gl_Position.zw = p.zw;
* }
* `;
*
* let fragSrc = `
* precision mediump float;
* uniform float uTime;