forked from processing/p5.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp5.Shader.js
More file actions
2952 lines (2612 loc) · 104 KB
/
Copy pathp5.Shader.js
File metadata and controls
2952 lines (2612 loc) · 104 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
import p5 from '../../../src/app.js';
import { beforeEach, vi } from 'vitest';
const mockUserError = vi.fn();
vi.mock('../../../src/strands/strands_FES', () => {
const userError = (...args) => {
mockUserError(...args);
const prefixedMessage = `[p5.strands ${args[0]}]: ${args[1]}`;
throw new Error(prefixedMessage);
};
return {
userError,
internalError: (msg) => { throw new Error(`[p5.strands internal error]: ${msg}`); },
dimensionMismatchError: (declaredDim, actualDim, varName) => {
userError(
'dimension mismatch',
`Cannot assign a value of dimension ${actualDim} to \`${varName}\`, which expects dimension ${declaredDim}.`
);
},
};
});
suite('p5.Shader', function() {
var myp5;
beforeAll(function() {
window.IS_MINIFIED = true;
myp5 = new p5(function(p) {
p.setup = function() {
p.createCanvas(100, 100, p.WEBGL);
p.pointLight(250, 250, 250, 100, 100, 0);
p.ambientMaterial(250);
};
});
});
var testUniforms = function(shaderName, uniforms, expectedUniforms) {
// assert(expectedUniforms.length === Object.keys(uniforms).length,
// shaderName + ' expected ' + expectedUniforms.length + ' uniforms but has ' +
// Object.keys(uniforms).length);
// test each one
for (var i = 0; i < expectedUniforms.length; i++) {
var uniform = uniforms[expectedUniforms[i]];
assert(
uniform !== undefined,
shaderName + ' missing expectedUniform: ' + expectedUniforms[i]
);
}
};
var testAttributes = function(shaderName, attributes, expectedAttributes) {
// assert(expectedAttributes.length === Object.keys(attributes).length,
// shaderName + ' expected ' + expectedAttributes.length +
// ' attributes but has ' + Object.keys(attributes).length);
// test each one
for (var i = 0; i < expectedAttributes.length; i++) {
var attribute = attributes[expectedAttributes[i]];
assert(
attribute !== undefined,
shaderName + ' missing expected attribute: ' + expectedAttributes[i]
);
}
};
var testShader = function(
shaderName,
shaderObj,
expectedAttributes,
expectedUniforms
) {
shaderObj.bindShader();
testAttributes(shaderName, shaderObj.attributes, expectedAttributes);
testUniforms(shaderName, shaderObj.uniforms, expectedUniforms);
shaderObj.unbindShader();
};
afterAll(function() {
myp5.remove();
});
suite('Shader', function() {
test('Light Shader', function() {
var expectedAttributes = ['aPosition', 'aNormal', 'aTexCoord'];
var expectedUniforms = [
'uModelViewMatrix',
'uProjectionMatrix',
'uNormalMatrix',
'uDirectionalLightCount',
'uPointLightCount',
'uAmbientColor',
'uLightingDirection',
'uDirectionalDiffuseColors',
'uDirectionalSpecularColors',
'uPointLightLocation',
'uPointLightDiffuseColors',
'uPointLightSpecularColors',
'uSpotLightCount',
'uSpotLightAngle',
'uSpotLightConc',
'uSpotLightDiffuseColors',
'uSpotLightSpecularColors',
'uSpotLightLocation',
'uSpotLightDirection',
'uSpecular',
'uShininess',
'uMaterialColor',
'uSampler',
'isTexture',
'uConstantAttenuation',
'uLinearAttenuation',
'uQuadraticAttenuation'
];
testShader(
'Light Shader',
myp5._renderer._getLightShader(),
expectedAttributes,
expectedUniforms
);
});
test('Color Shader definition', function() {
var expectedAttributes = ['aPosition'];
var expectedUniforms = [
'uModelViewMatrix',
'uProjectionMatrix',
'uMaterialColor'
];
testShader(
'Color Shader',
myp5._renderer._getColorShader(),
expectedAttributes,
expectedUniforms
);
});
test('Immediate Mode Shader definition', function() {
var expectedAttributes = ['aPosition', 'aVertexColor'];
var expectedUniforms = [
'uModelViewMatrix',
'uProjectionMatrix'
];
testShader(
'Immediate Mode Shader',
myp5._renderer._getColorShader(),
expectedAttributes,
expectedUniforms
);
});
test('Normal Shader definition', function() {
var expectedAttributes = ['aPosition', 'aNormal'];
var expectedUniforms = [
'uModelViewMatrix',
'uProjectionMatrix',
'uNormalMatrix'
];
testShader(
'Normal Shader',
myp5._renderer._getNormalShader(),
expectedAttributes,
expectedUniforms
);
});
test('Color Shader is set after fill()', function() {
myp5.fill(0);
var retainedColorShader = myp5._renderer._getColorShader();
var texLightShader = myp5._renderer._getLightShader();
var immediateColorShader = myp5._renderer._getColorShader();
var selectedRetainedShader = myp5._renderer._getFillShader();
var selectedImmediateShader = myp5._renderer._getFillShader();
// both color and light shader are valid, depending on
// conditions set earlier.
assert(
retainedColorShader === selectedRetainedShader ||
texLightShader === selectedRetainedShader,
"_renderer's retain mode shader was not color shader after fill"
);
assert(
immediateColorShader === selectedImmediateShader ||
texLightShader === selectedImmediateShader,
"_renderer's immediate mode shader was not color shader after fill"
);
});
test('Normal Shader is set after normalMaterial()', function() {
myp5.normalMaterial();
var normalShader = myp5._renderer._getNormalShader();
var selectedRetainedShader = myp5._renderer._getFillShader();
var selectedImmediateShader = myp5._renderer._getFillShader();
assert(
normalShader === selectedRetainedShader,
"_renderer's retain mode shader was not normal shader"
);
assert(
normalShader === selectedImmediateShader,
"_renderer's retain mode shader was not normal shader"
);
});
test('Light shader set after ambientMaterial()', function() {
var lightShader = myp5._renderer._getLightShader();
myp5.ambientMaterial(128);
var selectedRetainedShader = myp5._renderer._getFillShader();
var selectedImmediateShader = myp5._renderer._getFillShader();
assert(
lightShader === selectedRetainedShader,
"_renderer's retain mode shader was not light shader " +
'after call to ambientMaterial()'
);
assert(
lightShader === selectedImmediateShader,
"_renderer's immediate mode shader was not light shader" +
'after call to ambientMaterial()'
);
});
test('Light shader set after specularMaterial()', function() {
var lightShader = myp5._renderer._getLightShader();
myp5.specularMaterial(128);
var selectedRetainedShader = myp5._renderer._getFillShader();
var selectedImmediateShader = myp5._renderer._getFillShader();
assert(
lightShader === selectedRetainedShader,
"_renderer's retain mode shader was not light shader " +
'after call to specularMaterial()'
);
assert(
lightShader === selectedImmediateShader,
"_renderer's immediate mode shader was not light shader " +
'after call to specularMaterial()'
);
});
test('Light shader set after emissiveMaterial()', function() {
var lightShader = myp5._renderer._getLightShader();
myp5.emissiveMaterial(128);
var selectedRetainedShader = myp5._renderer._getFillShader();
var selectedImmediateShader = myp5._renderer._getFillShader();
assert(
lightShader === selectedRetainedShader,
"_renderer's retain mode shader was not light shader " +
'after call to emissiveMaterial()'
);
assert(
lightShader === selectedImmediateShader,
"_renderer's immediate mode shader was not light shader " +
'after call to emissiveMaterial()'
);
});
test('Able to setUniform empty arrays', function() {
myp5.shader(myp5._renderer._getLightShader());
var s = myp5._renderer.states.userFillShader;
s.setUniform('uMaterialColor', []);
s.setUniform('uLightingDirection', []);
});
test('Able to set shininess', function() {
assert.deepEqual(myp5._renderer.states._useShininess, 1);
myp5.shininess(50);
assert.deepEqual(myp5._renderer.states._useShininess, 50);
});
test('Shader is reset after resetShader is called', function() {
myp5.shader(myp5._renderer._getColorShader());
var prevShader = myp5._renderer.states.userFillShader;
assert.isTrue(prevShader !== null);
myp5.resetShader();
var curShader = myp5._renderer.states.userFillShader;
assert.isTrue(curShader === null);
});
test('version() detects a #version directive', function() {
const shader = myp5.createShader(
`
#version 300 es
precision highp float;
attribute vec3 aPosition;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
void main() {
gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, 1.0);
}
`,
`
precision highp float;
void main() {
gl_FragColor = vec4(1.0);
}
`
);
assert.strictEqual(shader.version(), '300 es');
});
suite('Hooks', function() {
let myShader;
beforeEach(function() {
myShader = myp5.createShader(
`
precision highp float;
attribute vec3 aPosition;
attribute vec2 aTexCoord;
attribute vec4 aVertexColor;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying vec2 vTexCoord;
varying vec4 vVertexColor;
void main() {
// Apply the camera transform
vec4 viewModelPosition =
uModelViewMatrix *
vec4(aPosition, 1.0);
// Tell WebGL where the vertex goes
gl_Position =
uProjectionMatrix *
viewModelPosition;
// Pass along data to the fragment shader
vTexCoord = aTexCoord;
vVertexColor = aVertexColor;
}
`,
`
precision highp float;
varying vec2 vTexCoord;
varying vec4 vVertexColor;
void main() {
// Tell WebGL what color to make the pixel
gl_FragColor = HOOK_getVertexColor(vVertexColor);
}
`,
{
fragment: {
'vec4 getVertexColor': '(vec4 color) { return color; }'
}
}
);
});
test('available hooks show up in inspectHooks()', function() {
const logs = [];
const myLog = (...data) => logs.push(data.join(', '));
const oldLog = console.log;
console.log = myLog;
myShader.inspectHooks();
console.log = oldLog;
expect(logs.join('\n')).to.match(/vec4 getVertexColor/);
});
test('unfilled hooks do not have an AUGMENTED_HOOK define', function() {
const modified = myShader.modify({});
expect(modified.fragSrc()).not.to.match(/#define AUGMENTED_HOOK_getVertexColor/);
});
test('anonymous function shaderModifier does not throw when parsed', function() {
const callModify = () => myShader.modify(function() {});
expect(callModify).not.toThrowError();
});
test('filled hooks do have an AUGMENTED_HOOK define', function() {
const modified = myShader.modify({
'vec4 getVertexColor': `(vec4 c) {
return vec4(1., 0., 0., 1.);
}`
});
expect(modified.fragSrc()).to.match(/#define AUGMENTED_HOOK_getVertexColor/);
});
});
test('framebuffer textures are unbound when you draw to the framebuffer', function() {
const sh = myp5.baseMaterialShader().modify({
uniforms: {
'sampler2D myTex': null
},
'vec4 getFinalColor': `(vec4 c, vec2 texCoord) {
return getTexture(myTex, vec2(0.,0.));
}`
});
const fbo = myp5.createFramebuffer();
myp5.shader(sh);
sh.setUniform('myTex', fbo);
fbo.draw(() => myp5.background('red'));
sh.setUniform('myTex', fbo);
myp5.noStroke();
myp5.plane(myp5.width, myp5.height);
assert.deepEqual(myp5.get(0, 0), [255, 0, 0, 255]);
});
});
suite('hookTypes', function() {
test('Produces expected types on baseFilterShader()', function() {
const types = myp5.baseFilterShader().hookTypes('vec4 getColor');
assert.deepEqual(types, {
name: 'getColor',
returnType: {
typeName: 'vec4',
qualifiers: [],
properties: undefined,
dataType: {
baseType: 'float',
dimension: 4,
fnName: 'vec4',
priority: 3
}
},
parameters: [
{
name: 'inputs',
type: {
typeName: 'FilterInputs',
qualifiers: [],
dataType: null,
properties: [
{
name: 'texCoord',
type: {
typeName: 'vec2',
qualifiers: [],
properties: undefined,
dataType: {
baseType: 'float',
dimension: 2,
fnName: 'vec2',
priority: 3
}
}
},
{
name: 'canvasSize',
type: {
typeName: 'vec2',
qualifiers: [],
properties: undefined,
dataType: {
baseType: 'float',
dimension: 2,
fnName: 'vec2',
priority: 3
}
}
},
{
name: 'texelSize',
type: {
typeName: 'vec2',
qualifiers: [],
properties: undefined,
dataType: {
baseType: 'float',
dimension: 2,
fnName: 'vec2',
priority: 3
}
}
}
]
}
},
{
name: 'canvasContent',
type: {
typeName: 'sampler2D',
qualifiers: ['in'],
properties: undefined,
dataType: {
baseType: 'sampler2D',
dimension: 1,
fnName: 'sampler2D',
priority: -10
}
}
}
]
});
});
});
suite('p5.strands', () => {
test('handles named function callbacks', () => {
myp5.createCanvas(5, 5, myp5.WEBGL);
function myMaterial() {
myp5.getPixelInputs(inputs => {
inputs.color = [
1,
0,
0,
1
];
return inputs;
});
}
const myShader = myp5.baseMaterialShader().modify(myMaterial, { myp5 });
expect(() => {
myp5.shader(myShader);
myp5.plane(myp5.width, myp5.height);
}).not.toThrowError();
});
test('does not break when arrays are in uniform callbacks', () => {
myp5.createCanvas(5, 5, myp5.WEBGL);
const myShader = myp5.baseMaterialShader().modify(() => {
const size = myp5.uniformVector2(() => [myp5.width, myp5.height]);
myp5.getPixelInputs(inputs => {
inputs.color = [
size / 1000,
0,
1
];
return inputs;
});
}, { myp5 });
expect(() => {
myp5.shader(myShader);
myp5.plane(myp5.width, myp5.height);
}).not.toThrowError();
});
test('buildFilterShader can use numeric constants from scope', () => {
myp5.createCanvas(5, 5, myp5.WEBGL);
const constants = { val: 100 };
const myShader = myp5.buildFilterShader(({ constants }) => {
filterColor.begin();
let c = 0;
c += constants.val / 255;
filterColor.set([c, c, c, 1]);
filterColor.end();
}, { constants });
expect(() => {
myp5.filter(myShader);
}).not.toThrowError();
});
test('buildMaterialShader forwards scope to modify', () => {
myp5.createCanvas(5, 5, myp5.WEBGL);
expect(() => {
const myShader = myp5.buildMaterialShader(() => {
myp5.getPixelInputs(inputs => {
inputs.color = [1, 0, 0, 1];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(myShader);
myp5.plane(myp5.width, myp5.height);
}).not.toThrowError();
});
test('returns numbers for builtin globals outside hooks and a strandNode when called inside hooks', () => {
myp5.createCanvas(5, 5, myp5.WEBGL);
myp5.baseMaterialShader().modify(() => {
myp5.getPixelInputs(inputs => {
const mxInHook = myp5.mouseX;
const wInHook = myp5.width;
assert.isTrue(mxInHook.isStrandsNode);
assert.isTrue(wInHook.isStrandsNode);
inputs.color = [1, 0, 0, 1];
return inputs;
});
}, { myp5 });
const mx = myp5.mouseX;
const w = myp5.width;
assert.isNumber(mx);
assert.isNumber(w);
assert.strictEqual(w, myp5.width);
});
test('map() works inside a strands modify callback', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
myp5.getPixelInputs(inputs => {
const v = myp5.map(0.25, 0, 1, 0, 1);
inputs.color = [v, v, v, 1.0];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);
const pixelColor = myp5.get(25, 25);
assert.approximately(pixelColor[0], 64, 5);
assert.approximately(pixelColor[1], 64, 5);
assert.approximately(pixelColor[2], 64, 5);
});
test('map() with withinBounds clamps the result inside strands', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
myp5.getPixelInputs(inputs => {
const v = myp5.map(2.0, 0, 1, 0, 1, true);
inputs.color = [v, v, v, 1.0];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);
const pixelColor = myp5.get(25, 25);
assert.approximately(pixelColor[0], 255, 5);
assert.approximately(pixelColor[1], 255, 5);
assert.approximately(pixelColor[2], 255, 5);
});
test('map() shrinks a wider input range into a narrower output range', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
myp5.getPixelInputs(inputs => {
const v = myp5.map(5, 0, 10, 0, 1);
inputs.color = [v, v, v, 1.0];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);
const pixelColor = myp5.get(25, 25);
assert.approximately(pixelColor[0], 128, 5);
assert.approximately(pixelColor[1], 128, 5);
assert.approximately(pixelColor[2], 128, 5);
});
test('map() handles offset output ranges correctly', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
myp5.getPixelInputs(inputs => {
const v = myp5.map(0.5, 0, 1, 0.2, 0.8);
inputs.color = [v, v, v, 1.0];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);
const pixelColor = myp5.get(25, 25);
assert.approximately(pixelColor[0], 128, 5);
assert.approximately(pixelColor[1], 128, 5);
assert.approximately(pixelColor[2], 128, 5);
});
test('map() handles a negative input range', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
myp5.getPixelInputs(inputs => {
const v = myp5.map(0, -1, 1, 0, 1);
inputs.color = [v, v, v, 1.0];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);
const pixelColor = myp5.get(25, 25);
assert.approximately(pixelColor[0], 128, 5);
assert.approximately(pixelColor[1], 128, 5);
assert.approximately(pixelColor[2], 128, 5);
});
test('map() remaps texCoord.x into a horizontal gradient', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
myp5.getPixelInputs(inputs => {
const v = myp5.map(inputs.texCoord.x, 0, 1, 0.2, 0.8);
inputs.color = [v, v, v, 1.0];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);
const left = myp5.get(2, 25);
const middle = myp5.get(25, 25);
const right = myp5.get(47, 25);
assert.approximately(left[0], 51, 10);
assert.approximately(middle[0], 128, 10);
assert.approximately(right[0], 204, 10);
});
test('color() with hex string returns correct vec4 in strands', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
myp5.getPixelInputs(inputs => {
const c = myp5.color('#ff0000');
inputs.color = [c.x, c.y, c.z, 1.0];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);
const pixelColor = myp5.get(25, 25);
assert.approximately(pixelColor[0], 255, 5);
assert.approximately(pixelColor[1], 0, 5);
assert.approximately(pixelColor[2], 0, 5);
});
test('color() with CSS named color returns correct vec4 in strands', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
myp5.getPixelInputs(inputs => {
const c = myp5.color('blue');
inputs.color = [c.x, c.y, c.z, 1.0];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);
const pixelColor = myp5.get(25, 25);
assert.approximately(pixelColor[0], 0, 5);
assert.approximately(pixelColor[1], 0, 5);
assert.approximately(pixelColor[2], 255, 5);
});
test('lerpColor() interpolates between two colors in strands', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
myp5.getPixelInputs(inputs => {
const c1 = myp5.color('#ff0000');
const c2 = myp5.color('#0000ff');
const mixed = myp5.lerpColor(c1, c2, 0.5);
inputs.color = [mixed.x, mixed.y, mixed.z, 1.0];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);
const pixelColor = myp5.get(25, 25);
assert.approximately(pixelColor[0], 128, 10);
assert.approximately(pixelColor[1], 0, 5);
assert.approximately(pixelColor[2], 128, 10);
});
test('red(), green(), blue(), alpha() extract correct channels in strands', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
myp5.getPixelInputs(inputs => {
const c = myp5.color('#ff8000');
const r = myp5.red(c);
const g = myp5.green(c);
const b = myp5.blue(c);
inputs.color = [r, g, b, 1.0];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);
const pixelColor = myp5.get(25, 25);
assert.approximately(pixelColor[0], 255, 5);
assert.approximately(pixelColor[1], 128, 10);
assert.approximately(pixelColor[2], 0, 5);
});
test('hue() returns normalized hue value in strands', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
myp5.getPixelInputs(inputs => {
// Pure red has hue 0
const c = myp5.color('#ff0000');
const h = myp5.hue(c);
inputs.color = [h, h, h, 1.0];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);
const pixelColor = myp5.get(25, 25);
assert.approximately(pixelColor[0], 0, 5);
});
test('handle custom uniform names with automatic values', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
// Variable name is 'brightness' but uniform name is 'customBrightness'
const brightness = myp5.uniformFloat('customBrightness', () => 0.8);
myp5.getPixelInputs(inputs => {
inputs.color = [brightness, brightness, brightness, 1.0];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);
// Check that the shader uses the automatic value (0.8)
const pixelColor = myp5.get(25, 25);
assert.approximately(pixelColor[0], 204, 5); // 0.8 * 255 = 204
assert.approximately(pixelColor[1], 204, 5);
assert.approximately(pixelColor[2], 204, 5);
});
test('handle custom uniform names with manual setUniform', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
// Variable name is 'brightness' but uniform name is 'customBrightness'
const brightness = myp5.uniformFloat('customBrightness');
myp5.getPixelInputs(inputs => {
inputs.color = [brightness, brightness, brightness, 1.0];
return inputs;
});
}, { myp5 });
// Set the uniform using the custom name
testShader.setUniform('customBrightness', 0.6);
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);
// Check that the shader uses the manual value (0.6)
const pixelColor = myp5.get(25, 25);
assert.approximately(pixelColor[0], 153, 5); // 0.6 * 255 = 153
assert.approximately(pixelColor[1], 153, 5);
assert.approximately(pixelColor[2], 153, 5);
});
suite('array indexing on non-storage vectors (#8756)', () => {
afterEach(() => {
mockUserError.mockClear();
});
test('indexing into array returned from helper function works in WebGL', () => {
myp5.createCanvas(5, 5, myp5.WEBGL);
const myShader = myp5.baseMaterialShader().modify(() => {
const brightness = myp5.uniformFloat();
function getArr() {
return [1, 2];
}
const arr = getArr();
myp5.getPixelInputs(inputs => {
inputs.color = [arr[0] * brightness, arr[1], 0, 1];
return inputs;
});
}, { myp5 });
expect(() => {
myp5.shader(myShader);
myp5.plane(myp5.width, myp5.height);
}).not.toThrowError();
});
test('inline literal indexing [1, 2][0] works in WebGL', () => {
myp5.createCanvas(5, 5, myp5.WEBGL);
const myShader = myp5.baseMaterialShader().modify(() => {
const brightness = myp5.uniformFloat();
myp5.getPixelInputs(inputs => {
inputs.color = [[1, 2][0] * brightness, 0, 0, 1];
return inputs;
});
}, { myp5 });
expect(() => {
myp5.shader(myShader);
myp5.plane(myp5.width, myp5.height);
}).not.toThrowError();
});
test('array literal with 1 element throws descriptive error in WebGL', () => {
myp5.createCanvas(5, 5, myp5.WEBGL);
expect(() => {
myp5.baseMaterialShader().modify(() => {
const arr = [1];
myp5.getPixelInputs(inputs => {
inputs.color = [arr[0], 0, 0, 1];
return inputs;
});
}, { myp5 });
}).toThrowError('and must have 2-4 elements (got 1)');
});
test('array literal with 5 elements throws descriptive error in WebGL', () => {
myp5.createCanvas(5, 5, myp5.WEBGL);
expect(() => {
myp5.baseMaterialShader().modify(() => {
const arr = [1, 2, 3, 4, 5];
myp5.getPixelInputs(inputs => {
inputs.color = [arr[0], 0, 0, 1];
return inputs;
});
}, { myp5 });
}).toThrowError('and must have 2-4 elements (got 5)');
});
test('valid array lengths 2, 3, 4 work in WebGL', () => {
myp5.createCanvas(5, 5, myp5.WEBGL);
expect(() => {
const s2 = myp5.baseMaterialShader().modify(() => {
const arr = [1, 2];
myp5.getPixelInputs(inputs => {
inputs.color = [arr[0], 0, 0, 1];
return inputs;
});
}, { myp5 });
myp5.shader(s2);
myp5.plane(myp5.width, myp5.height);
const s3 = myp5.baseMaterialShader().modify(() => {
const arr = [1, 2, 3];
myp5.getPixelInputs(inputs => {
inputs.color = [arr[0], 0, 0, 1];
return inputs;
});
}, { myp5 });
myp5.shader(s3);
myp5.plane(myp5.width, myp5.height);
const s4 = myp5.baseMaterialShader().modify(() => {
const arr = [1, 2, 3, 4];
myp5.getPixelInputs(inputs => {
inputs.color = [arr[0], 0, 0, 1];
return inputs;
});
}, { myp5 });
myp5.shader(s4);
myp5.plane(myp5.width, myp5.height);
}).not.toThrowError();
});
});
suite('if statement conditionals', () => {
test('handle simple if statement with true condition', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
const condition = myp5.uniformFloat(() => 1.0); // true condition
myp5.getPixelInputs(inputs => {
let color = myp5.float(0.5); // initial gray
if (condition > 0.5) {
color = myp5.float(1.0); // set to white in if branch
}
inputs.color = [color, color, color, 1.0];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);
// Check that the center pixel is white (condition was true)
const pixelColor = myp5.get(25, 25);
assert.approximately(pixelColor[0], 255, 5); // Red channel should be 255 (white)
assert.approximately(pixelColor[1], 255, 5); // Green channel should be 255
assert.approximately(pixelColor[2], 255, 5); // Blue channel should be 255
});
test('handle simple if statement with condition that is not a swizzle', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
const x = myp5.uniformFloat(() => 1.0); // true condition
myp5.getPixelInputs(inputs => {
let color = myp5.float(0.5); // initial gray
if (x > 0.5) {
color = myp5.float(1.0); // set to white in if branch
}
inputs.color = [color, color, color, 1.0];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);
// Check that the center pixel is white (condition was true)
const pixelColor = myp5.get(25, 25);
assert.approximately(pixelColor[0], 255, 5); // Red channel should be 255 (white)
assert.approximately(pixelColor[1], 255, 5); // Green channel should be 255
assert.approximately(pixelColor[2], 255, 5); // Blue channel should be 255
});
test('handle simple if statement with simpler assignment', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
const condition = myp5.uniformFloat(() => 1.0); // true condition
myp5.getPixelInputs(inputs => {
let color = 1; // initial gray
if (condition > 0.5) {
color = 1; // set to white in if branch
}
inputs.color = [color, color, color, 1.0];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);
// Check that the center pixel is white (condition was true)
const pixelColor = myp5.get(25, 25);
assert.approximately(pixelColor[0], 255, 5); // Red channel should be 255 (white)
assert.approximately(pixelColor[1], 255, 5); // Green channel should be 255
assert.approximately(pixelColor[2], 255, 5); // Blue channel should be 255
});
test('handle simple if statement with false condition', () => {
myp5.createCanvas(50, 50, myp5.WEBGL);
const testShader = myp5.baseMaterialShader().modify(() => {
const condition = myp5.uniformFloat(() => 0.0); // false condition
myp5.getPixelInputs(inputs => {
let color = myp5.float(0.5); // initial gray
if (condition > 0.5) {
color = myp5.float(1.0); // set to white in if branch
}
inputs.color = [color, color, color, 1.0];
return inputs;
});
}, { myp5 });
myp5.noStroke();
myp5.shader(testShader);
myp5.plane(myp5.width, myp5.height);