forked from mrdoob/three.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGLSLNodeBuilder.js
1355 lines (883 loc) · 31.3 KB
/
GLSLNodeBuilder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { GLSLNodeParser, NodeBuilder, TextureNode, vectorComponents } from '../../../nodes/Nodes.js';
import NodeUniformBuffer from '../../common/nodes/NodeUniformBuffer.js';
import NodeUniformsGroup from '../../common/nodes/NodeUniformsGroup.js';
import { NodeSampledTexture, NodeSampledCubeTexture, NodeSampledTexture3D } from '../../common/nodes/NodeSampledTexture.js';
import { NoColorSpace, ByteType, ShortType, RGBAIntegerFormat, RGBIntegerFormat, RedIntegerFormat, RGIntegerFormat, UnsignedByteType, UnsignedIntType, UnsignedShortType, RedFormat, RGFormat, IntType, RGBFormat, RGBAFormat, FloatType } from '../../../constants.js';
import { DataTexture } from '../../../textures/DataTexture.js';
const glslMethods = {
textureDimensions: 'textureSize',
equals: 'equal'
};
const precisionLib = {
low: 'lowp',
medium: 'mediump',
high: 'highp'
};
const supports = {
swizzleAssign: true,
storageBuffer: false
};
const defaultPrecisions = `
precision highp float;
precision highp int;
precision highp sampler2D;
precision highp sampler3D;
precision highp samplerCube;
precision highp sampler2DArray;
precision highp usampler2D;
precision highp usampler3D;
precision highp usamplerCube;
precision highp usampler2DArray;
precision highp isampler2D;
precision highp isampler3D;
precision highp isamplerCube;
precision highp isampler2DArray;
precision lowp sampler2DShadow;
`;
/**
* A node builder targeting GLSL.
*
* This module generates GLSL shader code from node materials and also
* generates the respective bindings and vertex buffer definitions. These
* data are later used by the renderer to create render and compute pipelines
* for render objects.
*
* @augments NodeBuilder
*/
class GLSLNodeBuilder extends NodeBuilder {
/**
* Constructs a new GLSL node builder renderer.
*
* @param {Object3D} object - The 3D object.
* @param {Renderer} renderer - The renderer.
*/
constructor( object, renderer ) {
super( object, renderer, new GLSLNodeParser() );
/**
* A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
* another dictionary which manages UBOs per group ('render','frame','object').
*
* @type {Object<string,Object<string,NodeUniformsGroup>>}
*/
this.uniformGroups = {};
/**
* An array that holds objects defining the varying and attribute data in
* context of Transform Feedback.
*
* @type {Array<Object<string,AttributeNode|string>>}
*/
this.transforms = [];
/**
* A dictionary that holds for each shader stage a Map of used extensions.
*
* @type {Object<string,Map<string,Object>>}
*/
this.extensions = {};
/**
* A dictionary that holds for each shader stage an Array of used builtins.
*
* @type {Object<string,Array<string>>}
*/
this.builtins = { vertex: [], fragment: [], compute: [] };
}
/**
* Checks if the given texture requires a manual conversion to the working color space.
*
* @param {Texture} texture - The texture to check.
* @return {boolean} Whether the given texture requires a conversion to working color space or not.
*/
needsToWorkingColorSpace( texture ) {
return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
}
/**
* Returns the native shader method name for a given generic name.
*
* @param {string} method - The method name to resolve.
* @return {string} The resolved GLSL method name.
*/
getMethod( method ) {
return glslMethods[ method ] || method;
}
/**
* Returns the output struct name. Not relevant for GLSL.
*
* @return {string}
*/
getOutputStructName() {
return '';
}
/**
* Builds the given shader node.
*
* @param {ShaderNodeInternal} shaderNode - The shader node.
* @return {string} The GLSL function code.
*/
buildFunctionCode( shaderNode ) {
const layout = shaderNode.layout;
const flowData = this.flowShaderNode( shaderNode );
const parameters = [];
for ( const input of layout.inputs ) {
parameters.push( this.getType( input.type ) + ' ' + input.name );
}
//
const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
${ flowData.vars }
${ flowData.code }
return ${ flowData.result };
}`;
//
return code;
}
/**
* Setups the Pixel Buffer Object (PBO) for the given storage
* buffer node.
*
* @param {StorageBufferNode} storageBufferNode - The storage buffer node.
*/
setupPBO( storageBufferNode ) {
const attribute = storageBufferNode.value;
if ( attribute.pbo === undefined ) {
const originalArray = attribute.array;
const numElements = attribute.count * attribute.itemSize;
const { itemSize } = attribute;
const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
let format = isInteger ? RedIntegerFormat : RedFormat;
if ( itemSize === 2 ) {
format = isInteger ? RGIntegerFormat : RGFormat;
} else if ( itemSize === 3 ) {
format = isInteger ? RGBIntegerFormat : RGBFormat;
} else if ( itemSize === 4 ) {
format = isInteger ? RGBAIntegerFormat : RGBAFormat;
}
const typeMap = {
Float32Array: FloatType,
Uint8Array: UnsignedByteType,
Uint16Array: UnsignedShortType,
Uint32Array: UnsignedIntType,
Int8Array: ByteType,
Int16Array: ShortType,
Int32Array: IntType,
Uint8ClampedArray: UnsignedByteType,
};
const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
let height = Math.ceil( ( numElements / itemSize ) / width );
if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
const newSize = width * height * itemSize;
const newArray = new originalArray.constructor( newSize );
newArray.set( originalArray, 0 );
attribute.array = newArray;
const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
pboTexture.needsUpdate = true;
pboTexture.isPBOTexture = true;
const pbo = new TextureNode( pboTexture, null, null );
pbo.setPrecision( 'high' );
attribute.pboNode = pbo;
attribute.pbo = pbo.value;
this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
}
}
/**
* Returns a GLSL snippet that represents the property name of the given node.
*
* @param {Node} node - The node.
* @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
* @return {string} The property name.
*/
getPropertyName( node, shaderStage = this.shaderStage ) {
if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
return shaderStage.charAt( 0 ) + '_' + node.name;
}
return super.getPropertyName( node, shaderStage );
}
/**
* Setups the Pixel Buffer Object (PBO) for the given storage
* buffer node.
*
* @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
* @return {string} The property name.
*/
generatePBO( storageArrayElementNode ) {
const { node, indexNode } = storageArrayElementNode;
const attribute = node.value;
if ( this.renderer.backend.has( attribute ) ) {
const attributeData = this.renderer.backend.get( attribute );
attributeData.pbo = attribute.pbo;
}
const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
const textureName = this.getPropertyName( nodeUniform );
this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
const indexSnippet = indexNode.build( this, 'uint' );
const elementNodeData = this.getDataFromNode( storageArrayElementNode );
let propertyName = elementNodeData.propertyName;
if ( propertyName === undefined ) {
// property element
const nodeVar = this.getVarFromNode( storageArrayElementNode );
propertyName = this.getPropertyName( nodeVar );
// property size
const bufferNodeData = this.getDataFromNode( node );
let propertySizeName = bufferNodeData.propertySizeName;
if ( propertySizeName === undefined ) {
propertySizeName = propertyName + 'Size';
this.getVarFromNode( node, propertySizeName, 'uint' );
this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
bufferNodeData.propertySizeName = propertySizeName;
}
//
const { itemSize } = attribute;
const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
//
let prefix = 'vec4';
if ( attribute.pbo.type === UnsignedIntType ) {
prefix = 'uvec4';
} else if ( attribute.pbo.type === IntType ) {
prefix = 'ivec4';
}
this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
elementNodeData.propertyName = propertyName;
}
return propertyName;
}
/**
* Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
*
* @param {Texture} texture - The texture.
* @param {string} textureProperty - The name of the texture uniform in the shader.
* @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
* @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
* @param {string} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
* @return {string} The GLSL snippet.
*/
generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
if ( depthSnippet ) {
return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
} else {
return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
}
}
/**
* Generates the GLSL snippet for sampling/loading the given texture.
*
* @param {Texture} texture - The texture.
* @param {string} textureProperty - The name of the texture uniform in the shader.
* @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
* @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
* @return {string} The GLSL snippet.
*/
generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
if ( texture.isDepthTexture ) {
return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
} else {
if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
return `texture( ${ textureProperty }, ${ uvSnippet } )`;
}
}
/**
* Generates the GLSL snippet when sampling textures with explicit mip level.
*
* @param {Texture} texture - The texture.
* @param {string} textureProperty - The name of the texture uniform in the shader.
* @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
* @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
* @return {string} The GLSL snippet.
*/
generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
}
/**
* Generates the GLSL snippet when sampling textures with a bias to the mip level.
*
* @param {Texture} texture - The texture.
* @param {string} textureProperty - The name of the texture uniform in the shader.
* @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
* @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
* @return {string} The GLSL snippet.
*/
generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
}
/**
* Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
*
* @param {Texture} texture - The texture.
* @param {string} textureProperty - The name of the texture uniform in the shader.
* @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
* @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
* @return {string} The GLSL snippet.
*/
generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
}
/**
* Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
* against a reference value.
*
* @param {Texture} texture - The texture.
* @param {string} textureProperty - The name of the texture uniform in the shader.
* @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
* @param {string} compareSnippet - A GLSL snippet that represents the reference value.
* @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
* @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
* @return {string} The GLSL snippet.
*/
generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
if ( shaderStage === 'fragment' ) {
return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
} else {
console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
}
}
/**
* Returns the variables of the given shader stage as a GLSL string.
*
* @param {string} shaderStage - The shader stage.
* @return {string} The GLSL snippet that defines the variables.
*/
getVars( shaderStage ) {
const snippets = [];
const vars = this.vars[ shaderStage ];
if ( vars !== undefined ) {
for ( const variable of vars ) {
snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
}
}
return snippets.join( '\n\t' );
}
/**
* Returns the uniforms of the given shader stage as a GLSL string.
*
* @param {string} shaderStage - The shader stage.
* @return {string} The GLSL snippet that defines the uniforms.
*/
getUniforms( shaderStage ) {
const uniforms = this.uniforms[ shaderStage ];
const bindingSnippets = [];
const uniformGroups = {};
for ( const uniform of uniforms ) {
let snippet = null;
let group = false;
if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
const texture = uniform.node.value;
let typePrefix = '';
if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
if ( texture.type === UnsignedIntType ) {
typePrefix = 'u';
} else if ( texture.type === IntType ) {
typePrefix = 'i';
}
}
if ( uniform.type === 'texture3D' ) {
snippet = `${typePrefix}sampler3D ${ uniform.name };`;
} else if ( texture.compareFunction ) {
snippet = `sampler2DShadow ${ uniform.name };`;
} else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
} else {
snippet = `${typePrefix}sampler2D ${ uniform.name };`;
}
} else if ( uniform.type === 'cubeTexture' ) {
snippet = `samplerCube ${ uniform.name };`;
} else if ( uniform.type === 'buffer' ) {
const bufferNode = uniform.node;
const bufferType = this.getType( bufferNode.bufferType );
const bufferCount = bufferNode.bufferCount;
const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
} else {
const vectorType = this.getVectorType( uniform.type );
snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
group = true;
}
const precision = uniform.node.precision;
if ( precision !== null ) {
snippet = precisionLib[ precision ] + ' ' + snippet;
}
if ( group ) {
snippet = '\t' + snippet;
const groupName = uniform.groupNode.name;
const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
groupSnippets.push( snippet );
} else {
snippet = 'uniform ' + snippet;
bindingSnippets.push( snippet );
}
}
let output = '';
for ( const name in uniformGroups ) {
const groupSnippets = uniformGroups[ name ];
output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
}
output += bindingSnippets.join( '\n' );
return output;
}
/**
* Returns the type for a given buffer attribute.
*
* @param {BufferAttribute} attribute - The buffer attribute.
* @return {string} The type.
*/
getTypeFromAttribute( attribute ) {
let nodeType = super.getTypeFromAttribute( attribute );
if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
let dataAttribute = attribute;
if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
const array = dataAttribute.array;
if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
nodeType = nodeType.slice( 1 );
}
}
return nodeType;
}
/**
* Returns the shader attributes of the given shader stage as a GLSL string.
*
* @param {string} shaderStage - The shader stage.
* @return {string} The GLSL snippet that defines the shader attributes.
*/
getAttributes( shaderStage ) {
let snippet = '';
if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
const attributes = this.getAttributesArray();
let location = 0;
for ( const attribute of attributes ) {
snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
}
}
return snippet;
}
/**
* Returns the members of the given struct type node as a GLSL string.
*
* @param {StructTypeNode} struct - The struct type node.
* @return {string} The GLSL snippet that defines the struct members.
*/
getStructMembers( struct ) {
const snippets = [];
for ( const member of struct.members ) {
snippets.push( `\t${ member.type } ${ member.name };` );
}
return snippets.join( '\n' );
}
/**
* Returns the structs of the given shader stage as a GLSL string.
*
* @param {string} shaderStage - The shader stage.
* @return {string} The GLSL snippet that defines the structs.
*/
getStructs( shaderStage ) {
const snippets = [];
const structs = this.structs[ shaderStage ];
const outputSnippet = [];
for ( const struct of structs ) {
if ( struct.output ) {
for ( const member of struct.members ) {
outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
}
} else {
let snippet = 'struct ' + struct.name + ' {\n';
snippet += this.getStructMembers( struct );
snippet += '\n};\n';
snippets.push( snippet );
}
}
if ( outputSnippet.length === 0 ) {
outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
}
return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
}
/**
* Returns the varyings of the given shader stage as a GLSL string.
*
* @param {string} shaderStage - The shader stage.
* @return {string} The GLSL snippet that defines the varyings.
*/
getVaryings( shaderStage ) {
let snippet = '';
const varyings = this.varyings;
if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
for ( const varying of varyings ) {
if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
const type = this.getType( varying.type );
if ( varying.needsInterpolation ) {
const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
snippet += `${flat}out ${type} ${varying.name};\n`;
} else {
snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
}
}
} else if ( shaderStage === 'fragment' ) {
for ( const varying of varyings ) {
if ( varying.needsInterpolation ) {
const type = this.getType( varying.type );
const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
snippet += `${flat}in ${type} ${varying.name};\n`;
}
}
}
for ( const builtin of this.builtins[ shaderStage ] ) {
snippet += `${builtin};\n`;
}
return snippet;
}
/**
* Returns the vertex index builtin.
*
* @return {string} The vertex index.
*/
getVertexIndex() {
return 'uint( gl_VertexID )';
}
/**
* Returns the instance index builtin.
*
* @return {string} The instance index.
*/
getInstanceIndex() {
return 'uint( gl_InstanceID )';
}
/**
* Returns the invocation local index builtin.
*
* @return {string} The invocation local index.
*/
getInvocationLocalIndex() {
const workgroupSize = this.object.workgroupSize;
const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
return `uint( gl_InstanceID ) % ${size}u`;
}
/**
* Returns the draw index builtin.
*
* @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
*/
getDrawIndex() {
const extensions = this.renderer.backend.extensions;
if ( extensions.has( 'WEBGL_multi_draw' ) ) {
return 'uint( gl_DrawID )';
}
return null;
}
/**
* Returns the front facing builtin.
*
* @return {string} The front facing builtin.
*/
getFrontFacing() {
return 'gl_FrontFacing';
}
/**
* Returns the frag coord builtin.
*
* @return {string} The frag coord builtin.
*/
getFragCoord() {
return 'gl_FragCoord.xy';
}
/**
* Returns the frag depth builtin.
*
* @return {string} The frag depth builtin.
*/
getFragDepth() {
return 'gl_FragDepth';
}
/**
* Enables the given extension.
*
* @param {string} name - The extension name.
* @param {string} behavior - The extension behavior.
* @param {string} [shaderStage=this.shaderStage] - The shader stage.
*/
enableExtension( name, behavior, shaderStage = this.shaderStage ) {
const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
if ( map.has( name ) === false ) {
map.set( name, {
name,
behavior
} );
}
}
/**
* Returns the enabled extensions of the given shader stage as a GLSL string.
*
* @param {string} shaderStage - The shader stage.
* @return {string} The GLSL snippet that defines the enabled extensions.
*/
getExtensions( shaderStage ) {
const snippets = [];
if ( shaderStage === 'vertex' ) {
const ext = this.renderer.backend.extensions;
const isBatchedMesh = this.object.isBatchedMesh;
if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
}
}
const extensions = this.extensions[ shaderStage ];
if ( extensions !== undefined ) {
for ( const { name, behavior } of extensions.values() ) {
snippets.push( `#extension ${name} : ${behavior}` );
}
}
return snippets.join( '\n' );
}
/**
* Returns the clip distances builtin.
*
* @return {string} The clip distances builtin.
*/
getClipDistance() {
return 'gl_ClipDistance';
}
/**
* Whether the requested feature is available or not.
*
* @param {string} name - The requested feature.
* @return {boolean} Whether the requested feature is supported or not.
*/
isAvailable( name ) {
let result = supports[ name ];
if ( result === undefined ) {
let extensionName;
result = false;
switch ( name ) {
case 'float32Filterable':
extensionName = 'OES_texture_float_linear';
break;
case 'clipDistance':
extensionName = 'WEBGL_clip_cull_distance';
break;
}
if ( extensionName !== undefined ) {
const extensions = this.renderer.backend.extensions;
if ( extensions.has( extensionName ) ) {