-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathp5.strands.js
More file actions
1094 lines (1054 loc) · 35.7 KB
/
p5.strands.js
File metadata and controls
1094 lines (1054 loc) · 35.7 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 p5.strands
* @for p5
* @requires core
*/
import { transpileStrandsToJS } from "./strands_transpiler";
import { BlockType } from "./ir_types";
import { createDirectedAcyclicGraph } from "./ir_dag";
import {
createControlFlowGraph,
createBasicBlock,
pushBlock,
popBlock,
} from "./ir_cfg";
import { generateShaderCode } from "./strands_codegen";
import {
initGlobalStrandsAPI,
createShaderHooksFunctions,
} from "./strands_api";
function strands(p5, fn) {
// Whether or not strands callbacks should be forced to be executed in global mode.
// This is turned on while loading shaders from files, when there is not a feasible
// way to pass context in.
fn._runStrandsInGlobalMode = false;
//////////////////////////////////////////////
// Global Runtime
//////////////////////////////////////////////
function initStrandsContext(
ctx,
backend,
{ active = false, renderer = null, baseShader = null } = {},
) {
ctx.dag = createDirectedAcyclicGraph();
ctx.cfg = createControlFlowGraph();
ctx.uniforms = [];
ctx.vertexDeclarations = new Set();
ctx.fragmentDeclarations = new Set();
ctx.computeDeclarations = new Set();
ctx.hooks = [];
ctx.backend = backend;
ctx.active = active;
ctx.renderer = renderer;
ctx.baseShader = baseShader;
ctx.previousFES = p5.disableFriendlyErrors;
ctx.windowOverrides = {};
ctx.fnOverrides = {};
ctx.graphicsOverrides = {};
if (active) {
p5.disableFriendlyErrors = true;
}
ctx.p5 = p5;
}
function deinitStrandsContext(ctx) {
ctx.dag = createDirectedAcyclicGraph();
ctx.cfg = createControlFlowGraph();
ctx.uniforms = [];
ctx.vertexDeclarations = new Set();
ctx.fragmentDeclarations = new Set();
ctx.computeDeclarations = new Set();
ctx.hooks = [];
ctx.active = false;
p5.disableFriendlyErrors = ctx.previousFES;
for (const key in ctx.windowOverrides) {
window[key] = ctx.windowOverrides[key];
}
for (const key in ctx.fnOverrides) {
fn[key] = ctx.fnOverrides[key];
}
// Clean up the hooks temporarily installed on p5.Graphics.prototype (#8549)
const GraphicsProto = p5.Graphics?.prototype;
if (GraphicsProto) {
for (const key in ctx.graphicsOverrides) {
if (ctx.graphicsOverrides[key] === undefined) {
delete GraphicsProto[key];
} else {
GraphicsProto[key] = ctx.graphicsOverrides[key];
}
}
}
}
const strandsContext = {};
initStrandsContext(strandsContext);
initGlobalStrandsAPI(p5, fn, strandsContext);
function withTempGlobalMode(pInst, callback) {
if (pInst._isGlobal) return callback();
const prev = {};
for (const key of Object.getOwnPropertyNames(fn)) {
const descriptor = Object.getOwnPropertyDescriptor(fn, key);
if (descriptor && !descriptor.get && typeof fn[key] === "function") {
prev[key] = window[key];
window[key] = fn[key].bind(pInst);
}
}
try {
callback();
} finally {
for (const key in prev) {
window[key] = prev[key];
}
}
}
//////////////////////////////////////////////
// Entry Point
//////////////////////////////////////////////
const oldModify = p5.Shader.prototype.modify;
p5.Shader.prototype.modify = function (shaderModifier, scope = {}, options = {}) {
const fnOverrides = {};
const windowOverrides = {};
const graphicsOverrides = {};
try {
if (
shaderModifier instanceof Function ||
typeof shaderModifier === "string"
) {
// Reset the context object every time modify is called;
// const backend = glslBackend;
initStrandsContext(strandsContext, this._renderer.strandsBackend, {
active: true,
renderer: this._renderer,
baseShader: this,
});
createShaderHooksFunctions(strandsContext, fn, this);
// TODO: expose this, is internal for debugging for now.
options.parser = true;
options.srcLocations = false;
// 1. Transpile from strands DSL to JS
let strandsCallback;
if (options.parser) {
// #7955 Wrap function declaration code in brackets so anonymous functions are not top level statements, which causes an error in acorn when parsing
// https://github.com/acornjs/acorn/issues/1385
const sourceString =
typeof shaderModifier === "string"
? `(${shaderModifier})`
: `(${shaderModifier.toString()})`;
strandsCallback = transpileStrandsToJS(
p5,
sourceString,
options.srcLocations,
scope,
);
} else {
strandsCallback = shaderModifier;
}
// 2. Build the IR from JavaScript API
const globalScope = createBasicBlock(
strandsContext.cfg,
BlockType.GLOBAL,
);
pushBlock(strandsContext.cfg, globalScope);
if (options.hook) {
strandsContext.renderer._pInst[options.hook].begin();
for (const key of strandsContext.renderer._pInst[options.hook]._properties) {
const hookProp = strandsContext.renderer._pInst[options.hook][key];
fnOverrides[key] = fn[key];
fn[key] = hookProp;
windowOverrides[key] = window[key];
window[key] = hookProp;
graphicsOverrides[key] = p5.Graphics.prototype[key];
p5.Graphics.prototype[key] = hookProp;
}
}
if (strandsContext.renderer?._pInst?._runStrandsInGlobalMode) {
withTempGlobalMode(strandsContext.renderer._pInst, strandsCallback);
} else {
strandsCallback();
}
if (options.hook) strandsContext.renderer._pInst[options.hook].end();
popBlock(strandsContext.cfg);
// 3. Generate shader code hooks object from the IR
// .......
const hooksObject = generateShaderCode(strandsContext);
// Call modify with the generated hooks object
return oldModify.call(this, hooksObject);
} else {
return oldModify.call(this, shaderModifier);
}
} finally {
for (const key in fnOverrides) {
fn[key] = fnOverrides[key];
}
for (const key in windowOverrides) {
window[key] = windowOverrides[key];
}
for (const key in graphicsOverrides) {
p5.Graphics[key] = graphicsOverrides[key];
}
// Reset the strands runtime context
deinitStrandsContext(strandsContext);
}
};
}
export default strands;
if (typeof p5 !== "undefined") {
p5.registerAddon(strands);
}
/* ------------------------------------------------------------- */
/**
* @typedef {Object} WorldInputsHook
*/
/**
* @property {WorldInputsHook} worldInputs
* @beta
* @description
* A shader hook block that modifies the world-space properties of each vertex in a shader. This hook can be used inside <a href="#/p5/buildColorShader">`buildColorShader()`</a> and similar shader <a href="#/p5.Shader/modify">`modify()`</a> calls to customize vertex positions, normals, texture coordinates, and colors before rendering. Modifications happen between the `.begin()` and `.end()` methods of the hook. "World space" refers to the coordinate system of the 3D scene, before any camera or projection transformations are applied.
*
* `worldInputs` has the following properties:
* - `position`: a three-component vector representing the original position of the vertex.
* - `normal`: a three-component vector representing the direction the surface is facing.
* - `texCoord`: a two-component vector representing the texture coordinates.
* - `color`: a four-component vector representing the color of the vertex (red, green, blue, alpha).
*
* This hook is available in:
* - <a href="#/p5/buildMaterialShader">`buildMaterialShader()`</a>
* - <a href="#/p5/buildNormalShader">`buildNormalShader()`</a>
* - <a href="#/p5/buildColorShader">`buildColorShader()`</a>
* - <a href="#/p5/buildStrokeShader">`buildStrokeShader()`</a>
*
* @example
* let myShader;
* function setup() {
* createCanvas(200, 200, WEBGL);
* myShader = buildMaterialShader(material);
* }
*
* function material() {
* let t = millis();
* worldInputs.begin();
* // Move the vertex up and down in a wave in world space
* // In world space, moving the object (e.g., with translate()) will affect these coordinates
* // The sphere is ~50 units tall here, so 20 gives a noticeable wave
* worldInputs.position.y += 20 * sin(t * 0.001 + worldInputs.position.x * 0.05);
* worldInputs.end();
* }
*
* function draw() {
* background(255);
* shader(myShader);
* lights();
* noStroke();
* fill('red');
* sphere(50);
* }
*/
/**
* @typedef {Object} CombineColorsHook
*/
/**
* @property {CombineColorsHook} combineColors
* @beta
* @description
* A shader hook block that modifies how color components are combined in the fragment shader. This hook can be used inside <a href="#/p5/buildMaterialShader">`buildMaterialShader()`</a> and similar shader <a href="#/p5.Shader/modify">`modify()`</a> calls to control the final color output of a material. Modifications happen between the `.begin()` and `.end()` methods of the hook.
*
* `combineColors` has the following properties:
*
* - `baseColor`: a three-component vector representing the base color (red, green, blue).
* - `diffuse`: a single number representing the diffuse reflection.
* - `ambientColor`: a three-component vector representing the ambient color.
* - `ambient`: a single number representing the ambient reflection.
* - `specularColor`: a three-component vector representing the specular color.
* - `specular`: a single number representing the specular reflection.
* - `emissive`: a three-component vector representing the emissive color.
* - `opacity`: a single number representing the opacity.
*
* Call `.set()` on the hook with a vector with four components (red, green, blue, alpha) for the final color.
*
* This hook is available in:
* - <a href="#/p5/buildMaterialShader">`buildMaterialShader()`</a>
*
* @example
* let myShader;
* function setup() {
* createCanvas(200, 200, WEBGL);
* myShader = buildMaterialShader(material);
* }
*
* function material() {
* combineColors.begin();
* // Custom color combination: add a green tint using vector properties
* combineColors.set([
* combineColors.baseColor * combineColors.diffuse +
* combineColors.ambientColor * combineColors.ambient +
* combineColors.specularColor * combineColors.specular +
* combineColors.emissive +
* [0, 0.2, 0], // Green tint
* combineColors.opacity
* ]);
* combineColors.end();
* }
*
* function draw() {
* background(255);
* shader(myShader);
* lights();
* noStroke();
* fill('white');
* sphere(50);
* }
*/
/**
* @method instanceID
* @beta
* @description
* Returns the index of the current instance when drawing multiple copies of a
* shape with <a href="#/p5/model">`model(count)`</a>. The first instance has an
* ID of `0`, the second has `1`, and so on.
*
* This lets each copy of a shape behave differently. For example, you can use
* the ID to place instances at different positions, give them different colors,
* or animate them at different speeds.
*
* `instanceID()` can only be used inside a p5.strands shader callback.
*
* ```js example
* let instancesShader;
* let instance;
* let count = 5;
*
* function drawInstance() {
* sphere(15);
* }
*
* function setup() {
* createCanvas(200, 200, WEBGL);
* instance = buildGeometry(drawInstance);
* instancesShader = buildMaterialShader(drawSpaced);
* describe('Five red spheres arranged in a horizontal line.');
* }
*
* function drawSpaced() {
* worldInputs.begin();
* // Spread spheres evenly across the canvas based on their index
* let spacing = width / count;
* worldInputs.position.x +=
* (instanceID() - (count - 1) / 2) * spacing;
* worldInputs.end();
* }
*
* function draw() {
* background(220);
* lights();
* noStroke();
* fill('red');
* shader(instancesShader);
* model(instance, count);
* }
* ```
*
* If you are using WebGPU mode, a common pattern is to use `instanceID()` to look up data made with
* <a href="#/p5/createStorage">`createStorage()`</a>.
* This lets you give each instance different properties.
*
* ```js example
* let instanceData;
* let instancesShader;
* let instance;
* let count = 5;
*
* async function setup() {
* await createCanvas(200, 200, WEBGPU);
*
* let data = [];
* for (let i = 0; i < count; i++) {
* data.push({
* position: createVector(
* random(-1, 1) * width / 2,
* random(-1, 1) * height / 2,
* 0,
* ),
* color: color(
* random(255),
* random(255),
* random(255)
* )
* });
* }
* instanceData = createStorage(data);
* instance = buildGeometry(drawInstance);
* instancesShader = buildMaterialShader(drawInstances);
* describe('Five spheres at random positions, each a different random color.');
* }
*
* function drawInstance() {
* sphere(15);
* }
*
* function drawInstances() {
* let data = uniformStorage(instanceData);
* let itemColor = sharedVec4();
*
* worldInputs.begin();
* let item = data[instanceID()];
* itemColor = item.color;
* worldInputs.position += item.position;
* worldInputs.end();
*
* finalColor.begin();
* finalColor.set(itemColor);
* finalColor.end();
* }
*
* function draw() {
* background(220);
* lights();
* noStroke();
* shader(instancesShader);
* model(instance, count);
* }
* ```
*
* This can be paired with <a href="#/p5/buildComputeShader">`buildComputeShader`</a>
* to update the data being read.
*
* @webgpu
* @returns {*} The index of the current instance.
*/
/**
* @method smoothstep
* @beta
* @description
* A shader function that performs smooth Hermite interpolation between `0.0`
* and `1.0`.
*
* This function is equivalent to the GLSL built-in
* `smoothstep(edge0, edge1, x)` and is available inside p5.strands shader
* callbacks. It is commonly used to create soft transitions, smooth edges,
* fades, and anti-aliased effects.
*
* Smoothstep is useful when a threshold or cutoff is needed, but with a
* gradual transition instead of a hard edge.
*
* - Returns `0.0` when `x` is less than or equal to `edge0`
* - Returns `1.0` when `x` is greater than or equal to `edge1`
* - Smoothly interpolates between `0.0` and `1.0` when `x` is between them
*
* @param {Number} edge0
* Lower edge of the transition
* @param {Number} edge1
* Upper edge of the transition
* @param {Number} x
* Input value to interpolate
*
* @returns {Number}
* A value between `0.0` and `1.0`
*
* @example
* // Example 1: A soft vertical fade using smoothstep
*
* let fadeShader;
*
* function fadeCallback() {
* getColor((inputs) => {
* // x goes from 0 → 1 across the canvas
* let x = inputs.texCoord.x;
*
* // smoothstep creates a soft transition instead of a hard edge
* let t = smoothstep(0.25, 0.35, x);
*
* // Use t directly as brightness
* return [t, t, t, 1];
* });
* }
*
* function setup() {
* createCanvas(300, 200, WEBGL);
* fadeShader = buildFilterShader(fadeCallback);
* }
*
* function draw() {
* background(0);
* filter(fadeShader);
* }
*
* @example
* // Example 2: Animate the smooth transition over time
*
* let animatedShader;
*
* function animatedFadeCallback() {
* getColor((inputs) => {
* let x = inputs.texCoord.x;
*
* // Move the smoothstep band back and forth over time
* let center = 0.5 + 0.25 * sin(millis() * 0.001);
* let t = smoothstep(center - 0.05, center + 0.05, x);
*
* return [t, t, t, 1];
* });
* }
*
* function setup() {
* createCanvas(300, 200, WEBGL);
* animatedShader = buildFilterShader(animatedFadeCallback);
* }
*
* function draw() {
* background(0);
* filter(animatedShader);
* }
*/
/**
* @method beforeVertex
* @private
* @description
* Registers a callback to run custom code at the very start of the vertex shader. This hook can be used inside <a href="#/p5/baseColorShader">baseColorShader()</a>.modify() and similar shader <a href="#/p5.Shader/modify">modify()</a> calls to set up variables or perform calculations that affect every vertex before processing begins. The callback receives no arguments.
*
* Note: This hook is currently limited to per-vertex operations; storing variables for later use is not supported.
*
* This hook is available in:
* - <a href="#/p5/baseColorShader">baseColorShader()</a>
* - <a href="#/p5/baseMaterialShader">baseMaterialShader()</a>
* - <a href="#/p5/baseNormalShader">baseNormalShader()</a>
* - <a href="#/p5/baseStrokeShader">baseStrokeShader()</a>
*
* @param {Function} callback
* A callback function which is called before each vertex is processed.
*/
/**
* @method afterVertex
* @private
* @description
* Registers a callback to run custom code at the very end of the vertex shader. This hook can be used inside <a href="#/p5/baseColorShader">baseColorShader()</a>.modify() and similar shader <a href="#/p5.Shader/modify">modify()</a> calls to perform cleanup or final calculations after all vertex processing is done. The callback receives no arguments.
*
* Note: This hook is currently limited to per-vertex operations; storing variables for later use is not supported.
*
* This hook is available in:
* - <a href="#/p5/baseColorShader">baseColorShader()</a>
* - <a href="#/p5/baseMaterialShader">baseMaterialShader()</a>
* - <a href="#/p5/baseNormalShader">baseNormalShader()</a>
* - <a href="#/p5/baseStrokeShader">baseStrokeShader()</a>
*
* @param {Function} callback
* A callback function which is called after each vertex is processed.
*/
/**
* @method beforeFragment
* @private
* @description
* Registers a callback to run custom code at the very start of the fragment shader. This hook can be used inside <a href="#/p5/baseColorShader">baseColorShader()</a>.modify() and similar shader <a href="#/p5.Shader/modify">modify()</a> calls to set up variables or perform calculations that affect every pixel before color calculations begin. The callback receives no arguments.
*
* This hook is available in:
* - <a href="#/p5/baseColorShader">baseColorShader()</a>
* - <a href="#/p5/baseMaterialShader">baseMaterialShader()</a>
* - <a href="#/p5/baseNormalShader">baseNormalShader()</a>
* - <a href="#/p5/baseStrokeShader">baseStrokeShader()</a>
*
* @param {Function} callback
* A callback function which is called before each fragment is processed.
*
* @example
* let myShader;
* function setup() {
* createCanvas(200, 200, WEBGL);
* myShader = baseColorShader().modify(() => {
* beforeFragment(() => {
* // Set a value for use in getFinalColor
* this.brightness = 0.5 + 0.5 * sin(millis() * 0.001);
* });
* getFinalColor(color => {
* // Use the value set in beforeFragment to tint the color
* color.r *= this.brightness; // Tint red channel
* return color;
* });
* });
* }
*
* function draw() {
* background(220);
* shader(myShader);
* noStroke();
* fill('teal');
* box(100);
* }
*/
/**
* @typedef {Object} PixelInputsHook
*/
/**
* @property {PixelInputsHook} pixelInputs
* @beta
* @description
* A shader hook block that modifies the properties of each pixel before the final color is calculated. This hook can be used inside <a href="#/p5/buildMaterialShader">`buildMaterialShader()`</a> and similar shader <a href="#/p5.Shader/modify">`modify()`</a> calls to adjust per-pixel data before lighting is applied. Modifications happen between the `.begin()` and `.end()` methods of the hook.
*
* The properties of `pixelInputs` depend on the shader:
*
* - In <a href="#/p5/buildMaterialShader">`buildMaterialShader()`</a>:
* - `normal`: a three-component vector representing the surface normal.
* - `texCoord`: a two-component vector representing the texture coordinates (u, v).
* - `ambientLight`: a three-component vector representing the ambient light color.
* - `ambientMaterial`: a three-component vector representing the material's ambient color.
* - `specularMaterial`: a three-component vector representing the material's specular color.
* - `emissiveMaterial`: a three-component vector representing the material's emissive color.
* - `color`: a four-component vector representing the base color (red, green, blue, alpha).
* - `shininess`: a number controlling specular highlights.
* - `metalness`: a number controlling the metalness factor.
*
* - In <a href="#/p5/buildStrokeShader">`buildStrokeShader()`</a>:
* - `color`: a four-component vector representing the stroke color (red, green, blue, alpha).
* - `tangent`: a two-component vector representing the stroke tangent.
* - `center`: a two-component vector representing the cap/join center.
* - `position`: a two-component vector representing the current fragment position.
* - `strokeWeight`: a number representing the stroke weight in pixels.
*
* This hook is available in:
* - <a href="#/p5/buildMaterialShader">`buildMaterialShader()`</a>
* - <a href="#/p5/buildStrokeShader">`buildStrokeShader()`</a>
*
* @example
* let myShader;
* function setup() {
* createCanvas(200, 200, WEBGL);
* myShader = buildMaterialShader(material);
* }
*
* function material() {
* let t = millis();
* pixelInputs.begin();
* // Animate alpha (transparency) based on x position
* pixelInputs.color.a = 0.5 + 0.5 *
* sin(pixelInputs.texCoord.x * 10.0 + t * 0.002);
* pixelInputs.end();
* }
*
* function draw() {
* background(240);
* shader(myShader);
* lights();
* noStroke();
* fill('purple');
* circle(0, 0, 100);
* }
*/
/**
* @method shouldDiscard
* @private
* @description
* Registers a callback to decide whether to discard (skip drawing) a fragment (pixel) in the fragment shader. This hook can be used inside <a href="#/p5/baseStrokeShader">baseStrokeShader()</a>.modify() and similar shader <a href="#/p5.Shader/modify">modify()</a> calls to create effects like round points or custom masking. The callback receives a boolean:
* - `willDiscard`: true if the fragment would be discarded by default
*
* Return true to discard the fragment, or false to keep it.
*
* This hook is available in:
* - <a href="#/p5/baseStrokeShader">baseStrokeShader()</a>
*
* @param {Function} callback
* A callback function which receives a boolean and should return a boolean.
*
* @example
* let myShader;
* function setup() {
* createCanvas(200, 200, WEBGL);
* myShader = baseStrokeShader().modify({
* 'bool shouldDiscard': '(bool outside) { return outside; }'
* });
* }
*
* function draw() {
* background(255);
* strokeShader(myShader);
* strokeWeight(30);
* line(-width/3, 0, width/3, 0);
* }
*/
/**
* @property finalColor
* @beta
* @description
* A shader hook block that modifies the final color of each pixel after all lighting is applied. This hook can be used inside <a href="#/p5/buildMaterialShader">`buildMaterialShader()`</a> and similar shader <a href="#/p5.Shader/modify">`modify()`</a> calls to adjust the color before it appears on the screen. Modifications happen between the `.begin()` and `.end()` methods of the hook.
*
* `finalColor` has the following properties:
* - `color`: a four-component vector representing the pixel color (red, green, blue, alpha).
*
* Call `.set()` on the hook with a vector with four components (red, green, blue, alpha) to update the final color.
*
* This hook is available in:
* - <a href="#/p5/buildColorShader">`buildColorShader()`</a>
* - <a href="#/p5/buildMaterialShader">`buildMaterialShader()`</a>
* - <a href="#/p5/buildNormalShader">`buildNormalShader()`</a>
* - <a href="#/p5/buildStrokeShader">`buildStrokeShader()`</a>
*
* @example
* let myShader;
* function setup() {
* createCanvas(200, 200, WEBGL);
* myShader = buildMaterialShader(material);
* }
*
* function material() {
* finalColor.begin();
* let color = finalColor.color;
* // Add a blue tint to the output color
* color.b += 0.4;
* finalColor.set(color);
* finalColor.end();
* }
*
* function draw() {
* background(230);
* shader(myShader);
* noStroke();
* fill('green');
* circle(0, 0, 100);
* }
*/
/**
* @method afterFragment
* @private
* @description
* Registers a callback to run custom code at the very end of the fragment shader. This hook can be used inside <a href="#/p5/baseColorShader">baseColorShader()</a>.modify() and similar shader <a href="#/p5.Shader/modify">modify()</a> calls to perform cleanup or final per-pixel effects after all color calculations are done. The callback receives no arguments.
*
* This hook is available in:
* - <a href="#/p5/baseColorShader">baseColorShader()</a>
* - <a href="#/p5/baseMaterialShader">baseMaterialShader()</a>
* - <a href="#/p5/baseNormalShader">baseNormalShader()</a>
* - <a href="#/p5/baseStrokeShader">baseStrokeShader()</a>
*
* @param {Function} callback
* A callback function which is called after each fragment is processed.
*
* @example
* let myShader;
* function setup() {
* createCanvas(200, 200, WEBGL);
* myShader = baseColorShader().modify(() => {
* getFinalColor(color => {
* // Add a purple tint to the color
* color.b += 0.2;
* return color;
* });
* afterFragment(() => {
* // This hook runs after the final color is set for each fragment.
* // You could use this for debugging or advanced effects.
* });
* });
* }
*
* function draw() {
* background(240);
* shader(myShader);
* noStroke();
* fill('purple');
* sphere(60);
* }
*/
/**
* @typedef {Object} FilterColorHook
* @property {any} texCoord
* @property {any} canvasSize
* @property {any} texelSize
* @property {any} canvasContent
* @property {function(): undefined} begin
* @property {function(): undefined} end
* @property {function(color: any): void} set
*/
/**
* @property {FilterColorHook} filterColor
* @description
* A shader hook block that sets the color for each pixel in a filter shader. This hook can be used inside <a href="#/p5/buildFilterShader">`buildFilterShader()`</a> to control the output color for each pixel.
*
* `filterColor` has the following properties:
* - `texCoord`: a two-component vector representing the texture coordinates (u, v).
* - `canvasSize`: a two-component vector representing the canvas size in pixels (width, height).
* - `texelSize`: a two-component vector representing the size of a single texel in texture space.
* - `canvasContent`: a texture containing the sketch's contents before the filter is applied.
*
* Call `.set()` on the hook with a vector with four components (red, green, blue, alpha) to update the final color.
*
* This hook is available in:
* - <a href="#/p5/buildFilterShader">`buildFilterShader()`</a>
*
* @example
* let myShader;
* function setup() {
* createCanvas(200, 200, WEBGL);
* myShader = buildFilterShader(warp);
* }
*
* function warp() {
* filterColor.begin();
* // Warp the texture coordinates for a wavy effect
* let warped = [
* filterColor.texCoord.x,
* filterColor.texCoord.y + 0.1 * sin(filterColor.texCoord.x * 10)
* ];
* let tex = filterColor.canvasContent;
* filterColor.set(getTexture(tex, warped));
* filterColor.end();
* }
*
* function draw() {
* background(180);
* // Draw something to the canvas
* fill('yellow');
* circle(0, 0, 150);
* filter(myShader);
* }
*/
/**
* @typedef {Object} ObjectInputsHook
*/
/**
* @property {ObjectInputsHook} objectInputs
* @beta
* @description
* A shader hook block to modify the properties of each vertex before any transformations are applied. This hook can be used inside <a href="#/p5/buildMaterialShader">`buildMaterialShader()`</a> and similar shader <a href="#/p5.Shader/modify">`modify()`</a> calls to customize vertex positions, normals, texture coordinates, and colors before rendering. Modifications happen between the `.begin()` and `.end()` methods of the hook. "Object space" refers to the coordinate system of the 3D scene before any transformations, cameras, or projection transformations are applied.
*
* `objectInputs` has the following properties:
* - `position`: a three-component vector representing the original position of the vertex.
* - `normal`: a three-component vector representing the direction the surface is facing.
* - `texCoord`: a two-component vector representing the texture coordinates.
* - `color`: a four-component vector representing the color of the vertex (red, green, blue, alpha).
*
* This hook is available in:
* - <a href="#/p5/buildColorShader">`buildColorShader()`</a>
* - <a href="#/p5/buildMaterialShader">`buildMaterialShader()`</a>
* - <a href="#/p5/buildNormalShader">`buildNormalShader()`</a>
* - <a href="#/p5/buildStrokeShader">`buildStrokeShader()`</a>
*
* @example
* let myShader;
* function setup() {
* createCanvas(200, 200, WEBGL);
* myShader = buildMaterialShader(material);
* }
*
* function material() {
* let t = millis();
* objectInputs.begin();
* // Create a sine wave along the object
* objectInputs.position.y += sin(t * 0.001 + objectInputs.position.x);
* objectInputs.end();
* }
*
* function draw() {
* background(220);
* shader(myShader);
* noStroke();
* fill('orange');
* sphere(50);
* }
*/
/**
* @typedef {Object} CameraInputsHook
*/
/**
* @property {CameraInputsHook} cameraInputs
* @beta
* @description
* A shader hook block that adjusts vertex properties from the perspective of the camera. This hook can be used inside <a href="#/p5/buildMaterialShader">`buildMaterialShader()`</a> and similar shader <a href="#/p5.Shader/modify">`modify()`</a> calls to customize vertex positions, normals, texture coordinates, and colors before rendering. "Camera space" refers to the coordinate system of the 3D scene after transformations have been applied, seen relative to the camera.
*
* `cameraInputs` has the following properties:
* - `position`: a three-component vector representing the position after camera transformation.
* - `normal`: a three-component vector representing the normal after camera transformation.
* - `texCoord`: a two-component vector representing the texture coordinates.
* - `color`: a four-component vector representing the color of the vertex (red, green, blue, alpha).
*
* This hook is available in:
* - <a href="#/p5/buildColorShader">`buildColorShader()`</a>
* - <a href="#/p5/buildMaterialShader">`buildMaterialShader()`</a>
* - <a href="#/p5/buildNormalShader">`buildNormalShader()`</a>
* - <a href="#/p5/buildStrokeShader">`buildStrokeShader()`</a>
*
* @example
* let myShader;
* function setup() {
* createCanvas(200, 200, WEBGL);
* myShader = buildMaterialShader(material);
* }
*
* function material() {
* let t = millis();
* cameraInputs.begin();
* // Move vertices in camera space based on their x position
* cameraInputs.position.y += 30 * sin(cameraInputs.position.x * 0.05 + t * 0.001);
* // Tint all vertices blue
* cameraInputs.color.b = 1;
* cameraInputs.end();
* }
*
* function draw() {
* background(200);
* shader(myShader);
* noStroke();
* fill('red');
* sphere(50);
* }
*/
/**
* Declares a storage buffer uniform inside a <a href="#/p5.Shader/modify">modify()</a> callback,
* making a <a href="#/p5/createStorage">createStorage()</a> buffer accessible in the shader.
*
* Pass a `p5.StorageBuffer` (or a function returning one) as the second argument
* to set it as the default value, applied automatically each frame. Pass a plain
* object with the same field layout as the buffer's struct elements to declare the
* schema without binding a specific buffer.
*
* When called without a name, p5.strands automatically uses the name of the
* variable it is assigned to as the uniform name.
*
* Note: `uniformStorage` is only available when using p5.strands.
*
* @method uniformStorage
* @beta
* @webgpu
* @webgpuOnly
* @submodule p5.strands
* @param {String} name The name of the storage buffer uniform in the shader.
* @param {p5.StorageBuffer|Function|Object} [bufferOrSchema] A storage buffer to bind,
* a function returning a storage buffer (called each frame), or a plain object
* describing the struct field layout.
* @returns {*} A strands node representing the storage buffer.
*/
/**
* @method uniformStorage
* @param {p5.StorageBuffer|Function|Object} [bufferOrSchema]
* @returns {*}
*/
/**
*
* @method getTexture
* @beta
*
* @param texture The texture to sample from.
* (e.g. a p5.Image, p5.Graphics, or p5.Framebuffer).
*
* @param coords The 2D coordinates to sample from.
* This should be between [0,0] (the top-left) and [1,1] (the bottom-right)
* of the texture. It should be compatible with a vec2.
*
* @returns {*} The color of the given texture at the given coordinates. This
* will behave as a vec4 holding components r, g, b, and a (alpha), with each component being in the range 0.0 to 1.0.
*
* @example
* // A filter shader (using p5.strands) which will
* // sample and invert the color of each pixel
* // from the canvas.
* function setup() {
* createCanvas(100, 100, WEBGL);
* let myShader = buildFilterShader(buildIt);
*
* background("white");
* fill("red");
* circle(0, 0, 50);
*
* filter(myShader); //Try commenting this out!
*
* describe("A cyan circle on black background");
* }
*
* function buildIt() {
* filterColor.begin();
*
* //Sample the color of the pixel from the
* //canvas at the same coordinate.
* let c = getTexture(filterColor.canvasContent,
* filterColor.texCoord);
*
* //Make a new color by inverting r, g, and b
* let newColor = [1 - c.r, 1 - c.g, 1 - c.b, c.a];
*
* //Finally, use it for this pixel!
* filterColor.set(newColor);
*
* filterColor.end();
* }
*