forked from processing/p5.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShaderGenerator.js
878 lines (790 loc) · 29.5 KB
/
ShaderGenerator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
/**
* @module 3D
* @submodule ShaderGenerator
* @for p5
* @requires core
*/
import { parse } from 'acorn';
import { ancestor } from 'acorn-walk';
import escodegen from 'escodegen';
function shadergenerator(p5, fn) {
let GLOBAL_SHADER;
const oldModify = p5.Shader.prototype.modify
p5.Shader.prototype.modify = function(shaderModifier, options = { parser: true, srcLocations: false }) {
if (shaderModifier instanceof Function) {
let generatorFunction;
if (options.parser) {
const sourceString = shaderModifier.toString()
const ast = parse(sourceString, {
ecmaVersion: 2021,
locations: options.srcLocations
});
ancestor(ast, ASTCallbacks);
const transpiledSource = escodegen.generate(ast);
generatorFunction = new Function(
transpiledSource.slice(
transpiledSource.indexOf("{") + 1,
transpiledSource.lastIndexOf("}")
)
);
} else {
generatorFunction = shaderModifier;
}
const generator = new ShaderGenerator(generatorFunction, this, options.srcLocations)
const generatedModifyArgument = generator.generate();
return oldModify.call(this, generatedModifyArgument);
}
else {
return oldModify.call(this, shaderModifier)
}
}
// AST Transpiler Callbacks and their helpers
function replaceBinaryOperator(codeSource) {
switch (codeSource) {
case '+': return 'add';
case '-': return 'sub';
case '*': return 'mult';
case '/': return 'div';
case '%': return 'mod';
}
}
const ASTCallbacks = {
VariableDeclarator(node, _state, _ancestors) {
if (node.init.callee && node.init.callee.name?.startsWith('uniform')) {
const uniformNameLiteral = {
type: 'Literal',
value: node.id.name
}
node.init.arguments.unshift(uniformNameLiteral);
}
},
// The callbacks for AssignmentExpression and BinaryExpression handle
// operator overloading including +=, *= assignment expressions
AssignmentExpression(node, _state, _ancestors) {
if (node.operator !== '=') {
const methodName = replaceBinaryOperator(node.operator.replace('=',''));
const rightReplacementNode = {
type: 'CallExpression',
callee: {
type: "MemberExpression",
object: node.left,
property: {
type: "Identifier",
name: methodName,
},
computed: false,
},
arguments: [node.right]
}
node.operator = '=';
node.right = rightReplacementNode;
}
},
BinaryExpression(node, _state, ancestors) {
// Don't convert uniform default values to node methods, as
// they should be evaluated at runtime, not compiled.
const isUniform = (ancestor) => {
return ancestor.type === 'CallExpression'
&& ancestor.callee?.type === 'Identifier'
&& ancestor.callee?.name.startsWith('uniform');
}
if (ancestors.some(isUniform)) {
return;
}
// If the left hand side of an expression is one of these types,
// we should construct a node from it.
const unsafeTypes = ["Literal", "ArrayExpression"]
if (unsafeTypes.includes(node.left.type)) {
const leftReplacementNode = {
type: "CallExpression",
callee: {
type: "Identifier",
name: "makeNode",
},
arguments: [node.left, node.right]
}
node.left = leftReplacementNode;
}
// Replace the binary operator with a call expression
// in other words a call to BaseNode.mult(), .div() etc.
node.type = 'CallExpression';
node.callee = {
type: "MemberExpression",
object: node.left,
property: {
type: "Identifier",
name: replaceBinaryOperator(node.operator),
},
};
node.arguments = [node.right];
},
}
// This unfinished function lets you do 1 * 10
// and turns it into float.mult(10)
fn.makeNode = function(leftValue, rightValue) {
if (typeof leftValue === 'number') {
return new FloatNode(leftValue);
}
}
// Javascript Node API.
// These classes are for expressing GLSL functions in Javascript without
// needing to transpile the user's code.
class BaseNode {
constructor(isInternal, type) {
if (new.target === BaseNode) {
throw new TypeError("Cannot construct BaseNode instances directly. This is an abstract class.");
}
this.type = type;
this.componentNames = [];
this.swizzleChanged = false;
// For tracking recursion depth and creating temporary variables
this.isInternal = isInternal;
this.usedIn = [];
this.dependsOn = [];
this.srcLine = null;
// Stack Capture is used to get the original line of user code for Debug purposes
if (GLOBAL_SHADER.srcLocations === true && isInternal === false) {
try {
throw new Error("StackCapture");
} catch (e) {
const lines = e.stack.split("\n");
let userSketchLineIndex = 5;
if (isBinaryOperatorNode(this)) { userSketchLineIndex--; };
this.srcLine = lines[userSketchLineIndex].trim();
}
}
}
// get type() {
// return this._type;
// }
// set type(value) {
// this._type = value;
// }
addVectorComponents() {
if (this.type.startsWith('vec')) {
const vectorDimensions = +this.type.slice(3);
this.componentNames = ['x', 'y', 'z', 'w'].slice(0, vectorDimensions);
for (let componentName of this.componentNames) {
// let value = new FloatNode()
let value = new ComponentNode(this, componentName, 'float', true);
Object.defineProperty(this, componentName, {
get() {
return value;
},
set(newValue) {
this.swizzleChanged = true;
value = newValue;
}
})
}
}
}
// The base node implements a version of toGLSL which determines whether the generated code should be stored in a temporary variable.
toGLSLBase(context){
if (this.shouldUseTemporaryVariable()) {
return this.getTemporaryVariable(context);
}
else {
return this.toGLSL(context);
}
}
shouldUseTemporaryVariable() {
if (this.swizzleChanged) { return true; }
if (this.isInternal || isVariableNode(this)) { return false; }
let score = 0;
score += isBinaryOperatorNode(this);
score += isVectorNode(this) * 2;
score += this.usedIn.length;
return score > 3;
}
getTemporaryVariable(context) {
if (!this.temporaryVariable) {
this.temporaryVariable = `temp_${context.getNextID()}`;
let line = "";
if (this.srcLine) {
line += `\n// From ${this.srcLine}\n`;
}
if (this.swizzleChanged) {
const valueArgs = [];
for (let componentName of this.componentNames) {
valueArgs.push(this[componentName])
}
const replacement = nodeConstructors[this.type](valueArgs)
line += this.type + " " + this.temporaryVariable + " = " + this.toGLSL(context) + ";";
line += `\n` + this.temporaryVariable + " = " + replacement.toGLSL(context) + ";";
} else {
line += this.type + " " + this.temporaryVariable + " = " + this.toGLSL(context) + ";";
}
context.declarations.push(line);
}
return this.temporaryVariable;
};
// Binary Operators
add(other) { return new BinaryOperatorNode(this, this.enforceType(other), '+'); }
sub(other) { return new BinaryOperatorNode(this, this.enforceType(other), '-'); }
mult(other) { return new BinaryOperatorNode(this, this.enforceType(other), '*'); }
div(other) { return new BinaryOperatorNode(this, this.enforceType(other), '/'); }
mod(other) { return new ModulusNode(this, this.enforceType(other)); }
// Check that the types of the operands are compatible.
enforceType(other){
if (isShaderNode(other)){
if (!isGLSLNativeType(other.type)) {
throw new TypeError (`You've tried to perform an operation on a struct of type: ${other.type}. Try accessing a member on that struct with '.'`)
}
if (!isGLSLNativeType(other.type)) {
throw new TypeError (`You've tried to perform an operation on a struct of type: ${other.type}. Try accessing a member on that struct with '.'`)
}
if ((isFloatNode(this) || isVectorNode(this)) && isIntNode(other)) {
return new FloatNode(other)
}
return other;
}
else if(typeof other === 'number') {
if (isIntNode(this)) {
return new IntNode(other);
}
return new FloatNode(other);
}
else if(Array.isArray(other)) {
return new VectorNode(other, `vec${other.length}`)
}
else {
return new this.constructor(other);
}
}
toFloat() {
if (isFloatNode(this)) {
return this;
} else if (isIntNode(this)) {
return new FloatNode(this);
} else {
throw new TypeError(`Can't convert from type '${this.type}' to 'float'.`)
}
}
toGLSL(context){
throw new TypeError("Not supposed to call this function on BaseNode, which is an abstract class.");
}
}
// Primitive Types
class IntNode extends BaseNode {
constructor(x = 0, isInternal = false) {
super(isInternal, 'int');
this.x = x;
}
toGLSL(context) {
if (isShaderNode(this.x)) {
let code = this.x.toGLSLBase(context);
return isIntNode(this.x.type) ? code : `int(${code})`;
}
else if (typeof this.x === "number") {
return `${Math.floor(this.x)}`;
}
else {
return `int(${this.x})`;
}
}
}
class FloatNode extends BaseNode {
constructor(x = 0, isInternal = false){
super(isInternal, 'float');
this.x = x;
}
toGLSL(context) {
if (isShaderNode(this.x)) {
let code = this.x.toGLSLBase(context);
return isFloatNode(this.x) ? code : `float(${code})`;
}
else if (typeof this.x === "number") {
return `${this.x.toFixed(4)}`;
}
else {
return `float(${this.x})`;
}
}
}
class VectorNode extends BaseNode {
constructor(values, type, isInternal = false) {
super(isInternal, type);
this.componentNames = ['x', 'y', 'z', 'w'].slice(0, values.length);
this.componentNames.forEach((component, i) => {
this[component] = new FloatNode(values[i], true);
});
}
toGLSL(context) {
let glslArgs = ``;
this.componentNames.forEach((component, i) => {
const comma = i === this.componentNames.length - 1 ? `` : `, `;
glslArgs += `${this[component].toGLSLBase(context)}${comma}`;
})
return `${this.type}(${glslArgs})`;
}
}
// Function Call Nodes
class FunctionCallNode extends BaseNode {
constructor(name, args, properties, isInternal = false) {
let inferredType = args.find((arg, i) => {
properties.args[i] === 'genType'
&& isShaderNode(arg)
})?.type;
if (!inferredType) {
let arrayArg = args.find(arg => Array.isArray(arg));
inferredType = arrayArg ? `vec${arrayArg.length}` : undefined;
}
if (!inferredType) {
inferredType = 'float';
}
args = args.map((arg, i) => {
if (!isShaderNode(arg)) {
const typeName = properties.args[i] === 'genType' ? inferredType : properties.args[i];
arg = nodeConstructors[typeName](arg);
}
return arg;
})
if (properties.returnType === 'genType') {
properties.returnType = inferredType;
}
super(isInternal, properties.returnType);
this.name = name;
this.args = args;
this.argumentTypes = properties.args;
this.addVectorComponents();
}
deconstructArgs(context) {
let argsString = this.args.map((argNode, i) => {
if (isIntNode(argNode) && this.argumentTypes[i] != 'float') {
argNode = argNode.toFloat();
}
return argNode.toGLSLBase(context);
}).join(', ');
return argsString;
}
toGLSL(context) {
return `${this.name}(${this.deconstructArgs(context)})`;
}
}
// Variables and member variable nodes
class VariableNode extends BaseNode {
constructor(name, type, isInternal = false) {
super(isInternal, type);
this.name = name;
this.addVectorComponents();
}
toGLSL(context) {
return `${this.name}`;
}
}
class ComponentNode extends BaseNode {
constructor(parent, componentName, type, isInternal = false) {
super(isInternal, type);
this.parent = parent;
this.componentName = componentName;
this.type = type;
}
toGLSL(context) {
const parentName = this.parent.toGLSLBase(context);
// const parentName = this.parent.temporaryVariable ? this.parent.temporaryVariable : this.parent.name;
return `${parentName}.${this.componentName}`;
}
}
// Binary Operator Nodes
class BinaryOperatorNode extends BaseNode {
constructor(a, b, operator, isInternal = false) {
super(isInternal, null);
this.op = operator;
this.a = a;
this.b = b;
for (const operand of [a, b]) {
operand.usedIn.push(this);
}
this.type = this.determineType();
this.addVectorComponents();
}
// We know that both this.a and this.b are nodes because of BaseNode.enforceType
determineType() {
if (this.a.type === this.b.type) {
return this.a.type;
}
else if (isVectorNode(this.a) && isFloatNode(this.b)) {
return this.a.type;
}
else if (isVectorNode(this.b) && isFloatNode(this.a)) {
return this.b.type;
}
else if (isFloatNode(this.a) && isIntNode(this.b)
|| isIntNode(this.a) && isFloatNode(this.b)
) {
return 'float';
}
else {
throw new Error("Incompatible types for binary operator");
}
}
processOperand(operand, context) {
if (operand.temporaryVariable) { return operand.temporaryVariable; }
let code = operand.toGLSLBase(context);
if (isBinaryOperatorNode(operand) && !operand.temporaryVariable) {
code = `(${code})`;
}
if (this.type === 'float' && isIntNode(operand)) {
code = `float(${code})`;
}
return code;
}
toGLSL(context) {
const a = this.processOperand(this.a, context);
const b = this.processOperand(this.b, context);
return `${a} ${this.op} ${b}`;
}
}
class ModulusNode extends BinaryOperatorNode {
constructor(a, b) {
super(a, b);
}
toGLSL(context) {
// Switch on type between % or mod()
if (isVectorNode(this) || isFloatNode(this)) {
return `mod(${this.a.toGLSLBase(context)}, ${this.b.toGLSLBase(context)})`;
}
return `${this.processOperand(context, this.a)} % ${this.processOperand(context, this.b)}`;
}
}
// TODO: finish If Node
class ConditionalNode extends BaseNode {
constructor(value) {
super(value);
this.value = value;
this.condition = null;
this.thenBranch = null;
this.elseBranch = null;
}
// conditions
equalTo(value){}
greaterThan(value) {}
greaterThanEqualTo(value) {}
lessThan(value) {}
lessThanEqualTo(value) {}
// modifiers
not() {}
or() {}
and() {}
// returns
thenReturn(value) {}
elseReturn(value) {}
//
thenDiscard() {
new ConditionalDiscard(this.condition);
};
};
class ConditionalDiscard extends BaseNode {
constructor(condition){
this.condition = condition;
}
toGLSL(context) {
context.discardConditions.push(`if(${this.condition}{discard;})`);
}
}
fn.if = function (value) {
return new ConditionalNode(value);
}
// Node Helper functions
function isShaderNode(node) {
return (node instanceof BaseNode);
}
function isIntNode(node) {
return (isShaderNode(node) && (node.type === 'int'));
}
function isFloatNode(node) {
return (isShaderNode(node) && (node.type === 'float'));
}
function isVectorNode(node) {
return (isShaderNode(node) && (node.type === 'vec2'|| node.type === 'vec3' || node.type === 'vec4'));
}
function isBinaryOperatorNode(node) {
return (node instanceof BinaryOperatorNode);
}
function isVariableNode(node) {
return (node instanceof VariableNode || node instanceof ComponentNode || typeof(node.temporaryVariable) != 'undefined');
}
// Helper function to check if a type is a user defined struct or native type
function isGLSLNativeType(typeName) {
// Supported types for now
const glslNativeTypes = ['int', 'float', 'vec2', 'vec3', 'vec4', 'sampler2D'];
return glslNativeTypes.includes(typeName);
}
// Helper function to check if a type is a user defined struct or native type
function isGLSLNativeType(typeName) {
// Supported types for now
const glslNativeTypes = ['int', 'float', 'vec2', 'vec3', 'vec4', 'sampler2D'];
return glslNativeTypes.includes(typeName);
}
// Shader Generator
// This class is responsible for converting the nodes into an object containing GLSL code, to be used by p5.Shader.modify
class ShaderGenerator {
constructor(userCallback, originalShader, srcLocations) {
GLOBAL_SHADER = this;
this.userCallback = userCallback;
this.userCallback = userCallback;
this.srcLocations = srcLocations;
this.cleanup = () => {};
this.generateHookOverrides(originalShader);
this.output = {
uniforms: {},
}
this.resetGLSLContext();
this.isGenerating = false;
}
generate() {
const prevFESDisabled = p5.disableFriendlyErrors;
// We need a custom error handling system within shader generation
p5.disableFriendlyErrors = true;
this.isGenerating = true;
this.userCallback();
this.isGenerating = false;
this.cleanup();
p5.disableFriendlyErrors = prevFESDisabled;
return this.output;
}
// This method generates the hook overrides which the user calls in their modify function.
generateHookOverrides(originalShader) {
const availableHooks = {
...originalShader.hooks.vertex,
...originalShader.hooks.fragment,
}
const windowOverrides = {};
Object.keys(availableHooks).forEach((hookName) => {
const hookTypes = originalShader.hookTypes(hookName);
this[hookTypes.name] = function(userCallback) {
// Create the initial nodes which are passed to the user callback
// Also generate a string of the arguments for the code generation
const argNodes = []
const argsArray = [];
hookTypes.parameters.forEach((parameter) => {
// For hooks with structs as input we should pass an object populated with variable nodes
if (!isGLSLNativeType(parameter.type.typeName)) {
const structArg = {};
parameter.type.properties.forEach((property) => {
structArg[property.name] = new VariableNode(`${parameter.name}.${property.name}`, property.type.typeName, true);
});
argNodes.push(structArg);
} else {
argNodes.push(
new VariableNode(parameter.name, parameter.type.typeName, true)
);
}
const qualifiers = parameter.type.qualifiers.length > 0 ? parameter.type.qualifiers.join(' ') : '';
argsArray.push(`${qualifiers} ${parameter.type.typeName} ${parameter.name}`.trim())
})
let returnedValue = userCallback(...argNodes);
const expectedReturnType = hookTypes.returnType;
const toGLSLResults = {};
// If the expected return type is a struct we need to evaluate each of its properties
if (!isGLSLNativeType(expectedReturnType.typeName)) {
Object.entries(returnedValue).forEach(([propertyName, propertyNode]) => {
toGLSLResults[propertyName] = propertyNode.toGLSLBase(this.context);
})
} else {
// We can accept raw numbers or arrays otherwise
if (!isShaderNode(returnedValue)) {
returnedValue = nodeConstructors[expectedReturnType.typeName](returnedValue)
}
toGLSLResults['notAProperty'] = returnedValue.toGLSLBase(this.context);
}
// Build the final GLSL string.
// The order of this code is a bit confusing, we need to call toGLSLBase
let codeLines = [
`(${argsArray.join(', ')}) {`,
...this.context.declarations,
`${hookTypes.returnType.typeName} finalReturnValue;`
];
Object.entries(toGLSLResults).forEach(([propertyName, result]) => {
const propString = expectedReturnType.properties ? `.${propertyName}` : '';
codeLines.push(`finalReturnValue${propString} = ${result};`)
})
codeLines.push('return finalReturnValue;', '}');
this.output[hookName] = codeLines.join('\n');
this.resetGLSLContext();
}
windowOverrides[hookTypes.name] = window[hookTypes.name];
// Expose the Functions to global scope for users to use
window[hookTypes.name] = function(userOverride) {
GLOBAL_SHADER[hookTypes.name](userOverride);
};
});
this.cleanup = () => {
for (const key in windowOverrides) {
window[key] = windowOverrides[key];
}
};
}
resetGLSLContext() {
this.context = {
id: 0,
getNextID: function() { return this.id++ },
declarations: [],
}
}
}
// User function helpers
function conformVectorParameters(value, vectorDimensions) {
// Allow arguments as arrays ([0,0,0,0]) or not (0,0,0,0)
value = value.flat();
// Populate arguments so uniformVector3(0) becomes [0,0,0]
if (value.length === 1) {
value = Array(vectorDimensions).fill(value[0]);
}
return value;
}
// User functions
fn.instanceID = function() {
return new VariableNode('gl_InstanceID', 'int');
}
fn.discard = function() {
return new VariableNode('discard', 'keyword');
}
// Generating uniformFloat, uniformVec, createFloat, etc functions
// Maps a GLSL type to the name suffix for method names
const GLSLTypesToIdentifiers = {
int: 'Int',
float: 'Float',
vec2: 'Vector2',
vec3: 'Vector3',
vec4: 'Vector4',
sampler2D: 'Texture',
};
const nodeConstructors = {
int: (value) => new IntNode(value),
float: (value) => new FloatNode(value),
vec2: (value) => new VectorNode(value, 'vec2'),
vec3: (value) => new VectorNode(value, 'vec3'),
vec4: (value) => new VectorNode(value, 'vec4'),
};
for (const glslType in GLSLTypesToIdentifiers) {
// Generate uniform*() Methods for creating uniforms
const typeIdentifier = GLSLTypesToIdentifiers[glslType];
const uniformMethodName = `uniform${typeIdentifier}`;
ShaderGenerator.prototype[uniformMethodName] = function(...args) {
let [name, ...defaultValue] = args;
if(glslType.startsWith('vec')) {
defaultValue = conformVectorParameters(defaultValue, +glslType.slice(3));
this.output.uniforms[`${glslType} ${name}`] = defaultValue;
}
else {
this.output.uniforms[`${glslType} ${name}`] = defaultValue[0];
}
const uniform = new VariableNode(name, glslType, false);
return uniform;
};
fn[uniformMethodName] = function (...args) {
return GLOBAL_SHADER[uniformMethodName](...args);
};
// We don't need a createTexture method.
if (glslType === 'sampler2D') { continue; }
// Generate the create*() Methods for creating variables in shaders
const createMethodName = `create${typeIdentifier}`;
fn[createMethodName] = function (...value) {
if(glslType.startsWith('vec')) {
value = conformVectorParameters(value, +glslType.slice(3));
} else {
value = value[0];
}
return nodeConstructors[glslType](value);
}
}
// GLSL Built in functions
// Add a whole lot of these functions.
// https://docs.gl/el3/abs
const builtInGLSLFunctions = {
//////////// Trigonometry //////////
'acos': { args: ['genType'], returnType: 'genType', isp5Function: true},
'acosh': { args: ['genType'], returnType: 'genType', isp5Function: false},
'asin': { args: ['genType'], returnType: 'genType', isp5Function: true},
'asinh': { args: ['genType'], returnType: 'genType', isp5Function: false},
'atan': { args: ['genType', 'genType'], returnType: 'genType', isp5Function: false},
'atanh': { args: ['genType'], returnType: 'genType', isp5Function: false},
'cos': { args: ['genType'], returnType: 'genType', isp5Function: true},
'cosh': { args: ['genType'], returnType: 'genType', isp5Function: false},
'degrees': { args: ['genType'], returnType: 'genType', isp5Function: true},
'radians': { args: ['genType'], returnType: 'genType', isp5Function: true},
'sin': { args: ['genType'], returnType: 'genType' , isp5Function: true},
'sinh': { args: ['genType'], returnType: 'genType', isp5Function: false},
'tan': { args: ['genType'], returnType: 'genType', isp5Function: true},
'tanh': { args: ['genType'], returnType: 'genType', isp5Function: false},
////////// Mathematics //////////
'abs': { args: ['genType'], returnType: 'genType', isp5Function: true},
'ceil': { args: ['genType'], returnType: 'genType', isp5Function: true},
'clamp': { args: ['genType', 'genType', 'genType'], returnType: 'genType', isp5Function: false},
'dFdx': { args: ['genType'], returnType: 'genType', isp5Function: false},
'dFdy': { args: ['genType'], returnType: 'genType', isp5Function: false},
'exp': { args: ['genType'], returnType: 'genType', isp5Function: true},
'exp2': { args: ['genType'], returnType: 'genType', isp5Function: false},
'floor': { args: ['genType'], returnType: 'genType', isp5Function: true},
'fma': { args: ['genType', 'genType', 'genType'], returnType: 'genType', isp5Function: false},
'fract': { args: ['genType'], returnType: 'genType', isp5Function: true},
'fwidth': { args: ['genType'], returnType: 'genType', isp5Function: false},
'inversesqrt': { args: ['genType'], returnType: 'genType', isp5Function: true},
// 'isinf': {},
// 'isnan': {},
'log': { args: ['genType'], returnType: 'genType', isp5Function: true},
'log2': { args: ['genType'], returnType: 'genType', isp5Function: false},
'max': { args: ['genType', 'genType'], returnType: 'genType', isp5Function: true},
'min': { args: ['genType', 'genType'], returnType: 'genType', isp5Function: true},
'mix': { args: ['genType', 'genType', 'genType'], returnType: 'genType', isp5Function: false},
// 'mod': {},
// 'modf': {},
'pow': { args: ['genType', 'genType'], returnType: 'genType', isp5Function: true},
'round': { args: ['genType'], returnType: 'genType', isp5Function: true},
'roundEven': { args: ['genType'], returnType: 'genType', isp5Function: false},
// 'sign': {},
'smoothstep': { args: ['genType', 'genType', 'genType'], returnType: 'genType', isp5Function: false},
'sqrt': { args: ['genType'], returnType: 'genType', isp5Function: true},
'step': { args: ['genType', 'genType'], returnType: 'genType', isp5Function: false},
'trunc': { args: ['genType'], returnType: 'genType', isp5Function: false},
////////// Vector //////////
'cross': { args: ['vec3', 'vec3'], returnType: 'vec3', isp5Function: true},
'distance': { args: ['genType', 'genType'], returnType: 'float', isp5Function: true},
'dot': { args: ['genType', 'genType'], returnType: 'float', isp5Function: true},
// 'equal': {},
'faceforward': { args: ['genType', 'genType', 'genType'], returnType: 'genType', isp5Function: false},
'length': { args: ['genType'], returnType: 'float', isp5Function: false},
'normalize': { args: ['genType'], returnType: 'genType', isp5Function: true},
// 'notEqual': {},
'reflect': { args: ['genType', 'genType'], returnType: 'genType', isp5Function: false},
'refract': { args: ['genType', 'genType', 'float'], returnType: 'genType', isp5Function: false},
// Texture sampling
'texture': {args: ['sampler2D', 'vec2'], returnType: 'vec4', isp5Function: true},
}
Object.entries(builtInGLSLFunctions).forEach(([functionName, properties]) => {
if (properties.isp5Function) {
const originalFn = fn[functionName];
fn[functionName] = function (...args) {
if (GLOBAL_SHADER?.isGenerating) {
return new FunctionCallNode(functionName, args, properties)
} else {
return originalFn.apply(this, args);
}
}
} else {
fn[functionName] = function (...args) {
if (GLOBAL_SHADER?.isGenerating) {
return new FunctionCallNode(functionName, args, properties);
} else {
p5._friendlyError(
`It looks like you've called ${functionName} outside of a shader's modify() function.`
);
}
}
}
})
// const oldTexture = p5.prototype.texture;
// p5.prototype.texture = function(...args) {
// if (isShaderNode(args[0])) {
// return new FunctionCallNode('texture', args, 'vec4');
// } else {
// return oldTexture.apply(this, args);
// }
// }
}
export default shadergenerator;
if (typeof p5 !== 'undefined') {
p5.registerAddon(shadergenerator)
}