-
-
Notifications
You must be signed in to change notification settings - Fork 584
/
Copy patheffect_codegen_glsl.cpp
2354 lines (1973 loc) · 70.3 KB
/
effect_codegen_glsl.cpp
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
/*
* Copyright (C) 2014 Patrick Mours
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "effect_parser.hpp"
#include "effect_codegen.hpp"
#include <cmath> // std::isinf, std::isnan, std::signbit
#include <cassert>
#include <cstring> // std::memcmp
#include <charconv> // std::from_chars, std::to_chars
#include <algorithm> // std::find, std::find_if, std::max
#include <unordered_set>
using namespace reshadefx;
inline char to_digit(unsigned int value)
{
assert(value < 10);
return '0' + static_cast<char>(value);
}
inline uint32_t align_up(uint32_t size, uint32_t alignment)
{
alignment -= 1;
return ((size + alignment) & ~alignment);
}
class codegen_glsl final : public codegen
{
public:
codegen_glsl(bool vulkan_semantics, bool debug_info, bool uniforms_to_spec_constants, bool enable_16bit_types, bool flip_vert_y) :
_debug_info(debug_info),
_vulkan_semantics(vulkan_semantics),
_uniforms_to_spec_constants(uniforms_to_spec_constants),
_enable_16bit_types(enable_16bit_types),
_flip_vert_y(flip_vert_y)
{
// Create default block and reserve a memory block to avoid frequent reallocations
std::string &block = _blocks.emplace(0, std::string()).first->second;
block.reserve(8192);
}
private:
enum class naming
{
// After escaping, name should already be unique, so no additional steps are taken
unique,
// After escaping, will be numbered when clashing with another name
general,
// This is a special name that is not modified and should be unique
reserved,
// Replace name with a code snippet
expression,
};
bool _debug_info = false;
bool _vulkan_semantics = false;
bool _uniforms_to_spec_constants = false;
bool _enable_16bit_types = false;
bool _flip_vert_y = false;
std::unordered_map<id, std::string> _names;
std::unordered_map<id, std::string> _blocks;
std::string _ubo_block;
std::string _compute_block;
std::string _current_function_declaration;
std::unordered_map<id, id> _remapped_sampler_variables;
std::unordered_map<std::string, uint32_t> _semantic_to_location;
std::vector<std::tuple<type, constant, id>> _constant_lookup;
// Only write compatibility intrinsics to result if they are actually in use
bool _uses_fmod = false;
bool _uses_componentwise_or = false;
bool _uses_componentwise_and = false;
bool _uses_componentwise_cond = false;
bool _uses_control_flow_attributes = false;
bool _uses_derivative_control = false;
std::string finalize_preamble() const
{
std::string preamble = "#version 430\n";
if (_enable_16bit_types)
// GL_NV_gpu_shader5, GL_AMD_gpu_shader_half_float or GL_EXT_shader_16bit_storage
preamble += "#extension GL_NV_gpu_shader5 : require\n";
if (_uses_control_flow_attributes)
preamble += "#extension GL_EXT_control_flow_attributes : enable\n";
if (_uses_derivative_control)
// Core only starting in GLSL version 4.5
preamble += "#extension GL_ARB_derivative_control : enable\n";
if (_uses_fmod)
preamble += "float fmodHLSL(float x, float y) { return x - y * trunc(x / y); }\n"
"vec2 fmodHLSL(vec2 x, vec2 y) { return x - y * trunc(x / y); }\n"
"vec3 fmodHLSL(vec3 x, vec3 y) { return x - y * trunc(x / y); }\n"
"vec4 fmodHLSL(vec4 x, vec4 y) { return x - y * trunc(x / y); }\n"
"mat2 fmodHLSL(mat2 x, mat2 y) { return x - matrixCompMult(y, mat2(trunc(x[0] / y[0]), trunc(x[1] / y[1]))); }\n"
"mat3 fmodHLSL(mat3 x, mat3 y) { return x - matrixCompMult(y, mat3(trunc(x[0] / y[0]), trunc(x[1] / y[1]), trunc(x[2] / y[2]))); }\n"
"mat4 fmodHLSL(mat4 x, mat4 y) { return x - matrixCompMult(y, mat4(trunc(x[0] / y[0]), trunc(x[1] / y[1]), trunc(x[2] / y[2]), trunc(x[3] / y[3]))); }\n";
if (_uses_componentwise_or)
preamble +=
"bvec2 compOr(bvec2 a, bvec2 b) { return bvec2(a.x || b.x, a.y || b.y); }\n"
"bvec3 compOr(bvec3 a, bvec3 b) { return bvec3(a.x || b.x, a.y || b.y, a.z || b.z); }\n"
"bvec4 compOr(bvec4 a, bvec4 b) { return bvec4(a.x || b.x, a.y || b.y, a.z || b.z, a.w || b.w); }\n";
if (_uses_componentwise_and)
preamble +=
"bvec2 compAnd(bvec2 a, bvec2 b) { return bvec2(a.x && b.x, a.y && b.y); }\n"
"bvec3 compAnd(bvec3 a, bvec3 b) { return bvec3(a.x && b.x, a.y && b.y, a.z && b.z); }\n"
"bvec4 compAnd(bvec4 a, bvec4 b) { return bvec4(a.x && b.x, a.y && b.y, a.z && b.z, a.w && b.w); }\n";
if (_uses_componentwise_cond)
preamble +=
"vec2 compCond(bvec2 cond, vec2 a, vec2 b) { return vec2(cond.x ? a.x : b.x, cond.y ? a.y : b.y); }\n"
"vec3 compCond(bvec3 cond, vec3 a, vec3 b) { return vec3(cond.x ? a.x : b.x, cond.y ? a.y : b.y, cond.z ? a.z : b.z); }\n"
"vec4 compCond(bvec4 cond, vec4 a, vec4 b) { return vec4(cond.x ? a.x : b.x, cond.y ? a.y : b.y, cond.z ? a.z : b.z, cond.w ? a.w : b.w); }\n"
"bvec2 compCond(bvec2 cond, bvec2 a, bvec2 b) { return bvec2(cond.x ? a.x : b.x, cond.y ? a.y : b.y); }\n"
"bvec3 compCond(bvec3 cond, bvec3 a, bvec3 b) { return bvec3(cond.x ? a.x : b.x, cond.y ? a.y : b.y, cond.z ? a.z : b.z); }\n"
"bvec4 compCond(bvec4 cond, bvec4 a, bvec4 b) { return bvec4(cond.x ? a.x : b.x, cond.y ? a.y : b.y, cond.z ? a.z : b.z, cond.w ? a.w : b.w); }\n"
"ivec2 compCond(bvec2 cond, ivec2 a, ivec2 b) { return ivec2(cond.x ? a.x : b.x, cond.y ? a.y : b.y); }\n"
"ivec3 compCond(bvec3 cond, ivec3 a, ivec3 b) { return ivec3(cond.x ? a.x : b.x, cond.y ? a.y : b.y, cond.z ? a.z : b.z); }\n"
"ivec4 compCond(bvec4 cond, ivec4 a, ivec4 b) { return ivec4(cond.x ? a.x : b.x, cond.y ? a.y : b.y, cond.z ? a.z : b.z, cond.w ? a.w : b.w); }\n"
"uvec2 compCond(bvec2 cond, uvec2 a, uvec2 b) { return uvec2(cond.x ? a.x : b.x, cond.y ? a.y : b.y); }\n"
"uvec3 compCond(bvec3 cond, uvec3 a, uvec3 b) { return uvec3(cond.x ? a.x : b.x, cond.y ? a.y : b.y, cond.z ? a.z : b.z); }\n"
"uvec4 compCond(bvec4 cond, uvec4 a, uvec4 b) { return uvec4(cond.x ? a.x : b.x, cond.y ? a.y : b.y, cond.z ? a.z : b.z, cond.w ? a.w : b.w); }\n";
if (!_ubo_block.empty())
// Read matrices in column major layout, even though they are actually row major, to avoid transposing them on every access (since GLSL uses column matrices)
// TODO: This technically only works with square matrices
preamble += "layout(std140, column_major, binding = 0) uniform _Globals {\n" + _ubo_block + "};\n";
return preamble;
}
std::string finalize_code() const override
{
std::string code = finalize_preamble();
// Add sampler definitions
for (const sampler &info : _module.samplers)
code += _blocks.at(info.id);
// Add storage definitions
for (const storage &info : _module.storages)
code += _blocks.at(info.id);
// Add global definitions (struct types, global variables, ...)
code += _blocks.at(0);
// Add function definitions
for (const std::unique_ptr<function> &func : _functions)
{
assert(func->unique_name[0] == 'F' || func->unique_name[0] == 'E');
const bool is_entry_point = func->unique_name[0] == 'E';
if (is_entry_point)
code += "#ifdef " + func->unique_name + '\n';
code += _blocks.at(func->id);
if (is_entry_point)
code += "#endif\n";
}
return code;
}
std::string finalize_code_for_entry_point(const std::string &entry_point_name) const override
{
const function *const entry_point = find_function(entry_point_name);
if (entry_point == nullptr)
return {};
std::string code = finalize_preamble();
if (entry_point->type != shader_type::pixel)
code +=
// OpenGL does not allow using 'discard' in the vertex shader profile
"#define discard\n"
// 'dFdx', 'dFdx' and 'fwidth' too are only available in fragment shaders
"#define dFdx(x) x\n"
"#define dFdy(y) y\n"
"#define fwidth(p) p\n";
if (entry_point->type != shader_type::compute)
code +=
// OpenGL does not allow using 'shared' in vertex/fragment shader profile
"#define shared\n"
"#define atomicAdd(a, b) a\n"
"#define atomicAnd(a, b) a\n"
"#define atomicOr(a, b) a\n"
"#define atomicXor(a, b) a\n"
"#define atomicMin(a, b) a\n"
"#define atomicMax(a, b) a\n"
"#define atomicExchange(a, b) a\n"
"#define atomicCompSwap(a, b, c) a\n"
// Barrier intrinsics are only available in compute shaders
"#define barrier()\n"
"#define memoryBarrier()\n"
"#define groupMemoryBarrier()\n";
const auto replace_binding =
[](std::string &code, uint32_t binding) {
const size_t beg = code.find("layout(binding = ") + 17;
const size_t end = code.find_first_of("),", beg);
code.replace(beg, end - beg, std::to_string(binding));
};
// Add referenced sampler definitions
for (uint32_t binding = 0; binding < entry_point->referenced_samplers.size(); ++binding)
{
if (entry_point->referenced_samplers[binding] == 0)
continue;
std::string block_code = _blocks.at(entry_point->referenced_samplers[binding]);
replace_binding(block_code, binding);
code += block_code;
}
// Add referenced storage definitions
for (uint32_t binding = 0; binding < entry_point->referenced_storages.size(); ++binding)
{
if (entry_point->referenced_storages[binding] == 0)
continue;
std::string block_code = _blocks.at(entry_point->referenced_storages[binding]);
replace_binding(block_code, binding);
code += block_code;
}
// Add global definitions (struct types, global variables, ...)
code += _blocks.at(0);
// Add referenced function definitions
for (const std::unique_ptr<function> &func : _functions)
{
if (func->id != entry_point->id &&
std::find(entry_point->referenced_functions.begin(), entry_point->referenced_functions.end(), func->id) == entry_point->referenced_functions.end())
continue;
code += _blocks.at(func->id);
}
return code;
}
template <bool is_param = false, bool is_decl = true, bool is_interface = false>
void write_type(std::string &s, const type &type) const
{
if constexpr (is_decl)
{
// Global variables are implicitly 'static' in GLSL, so the keyword does not exist
if (type.has(type::q_precise))
s += "precise ";
if (type.has(type::q_groupshared))
s += "shared ";
}
if constexpr (is_interface)
{
if (type.has(type::q_linear))
s += "smooth ";
if (type.has(type::q_noperspective))
s += "noperspective ";
if (type.has(type::q_centroid))
s += "centroid ";
if (type.has(type::q_nointerpolation))
s += "flat ";
}
if constexpr (is_interface || is_param)
{
if (type.has(type::q_inout))
s += "inout ";
else if (type.has(type::q_in))
s += "in ";
else if (type.has(type::q_out))
s += "out ";
}
switch (type.base)
{
case type::t_void:
s += "void";
break;
case type::t_bool:
if (type.cols > 1)
s += "mat", s += to_digit(type.rows), s += 'x', s += to_digit(type.cols);
else if (type.rows > 1)
s += "bvec", s += to_digit(type.rows);
else
s += "bool";
break;
case type::t_min16int:
if (_enable_16bit_types)
{
assert(type.cols == 1);
if (type.rows > 1)
s += "i16vec", s += to_digit(type.rows);
else
s += "int16_t";
break;
}
else if constexpr (is_decl)
s += "mediump ";
[[fallthrough]];
case type::t_int:
if (type.cols > 1)
s += "mat", s += to_digit(type.rows), s += 'x', s += to_digit(type.cols);
else if (type.rows > 1)
s += "ivec", s += to_digit(type.rows);
else
s += "int";
break;
case type::t_min16uint:
if (_enable_16bit_types)
{
assert(type.cols == 1);
if (type.rows > 1)
s += "u16vec", s += to_digit(type.rows);
else
s += "uint16_t";
break;
}
else if constexpr (is_decl)
s += "mediump ";
[[fallthrough]];
case type::t_uint:
if (type.cols > 1)
s += "mat", s += to_digit(type.rows), s += 'x', s += to_digit(type.cols);
else if (type.rows > 1)
s += "uvec", s += to_digit(type.rows);
else
s += "uint";
break;
case type::t_min16float:
if (_enable_16bit_types)
{
assert(type.cols == 1);
if (type.rows > 1)
s += "f16vec", s += to_digit(type.rows);
else
s += "float16_t";
break;
}
else if constexpr (is_decl)
s += "mediump ";
[[fallthrough]];
case type::t_float:
if (type.cols > 1)
s += "mat", s += to_digit(type.rows), s += 'x', s += to_digit(type.cols);
else if (type.rows > 1)
s += "vec", s += to_digit(type.rows);
else
s += "float";
break;
case type::t_struct:
s += id_to_name(type.struct_definition);
break;
case type::t_sampler1d_int:
s += "isampler1D";
break;
case type::t_sampler2d_int:
s += "isampler2D";
break;
case type::t_sampler3d_int:
s += "isampler3D";
break;
case type::t_sampler1d_uint:
s += "usampler1D";
break;
case type::t_sampler3d_uint:
s += "usampler3D";
break;
case type::t_sampler2d_uint:
s += "usampler2D";
break;
case type::t_sampler1d_float:
s += "sampler1D";
break;
case type::t_sampler2d_float:
s += "sampler2D";
break;
case type::t_sampler3d_float:
s += "sampler3D";
break;
case type::t_storage1d_int:
if constexpr (is_param)
s += "writeonly ";
s += "iimage1D";
break;
case type::t_storage2d_int:
if constexpr (is_param)
s += "writeonly ";
s += "iimage2D";
break;
case type::t_storage3d_int:
if constexpr (is_param)
s += "writeonly ";
s += "iimage3D";
break;
case type::t_storage1d_uint:
if constexpr (is_param)
s += "writeonly ";
s += "uimage1D";
break;
case type::t_storage2d_uint:
if constexpr (is_param)
s += "writeonly ";
s += "uimage2D";
break;
case type::t_storage3d_uint:
if constexpr (is_param)
s += "writeonly ";
s += "uimage3D";
break;
case type::t_storage1d_float:
if constexpr (is_param)
s += "writeonly ";
s += "image1D";
break;
case type::t_storage2d_float:
if constexpr (is_param) // Images need a format to be readable, but declaring that on function parameters is not well supported, so can only support write-only images there
s += "writeonly ";
s += "image2D";
break;
case type::t_storage3d_float:
if constexpr (is_param)
s += "writeonly ";
s += "image3D";
break;
default:
assert(false);
}
}
void write_constant(std::string &s, const type &data_type, const constant &data) const
{
if (data_type.is_array())
{
assert(data_type.is_bounded_array());
type elem_type = data_type;
elem_type.array_length = 0;
write_type<false, false>(s, elem_type);
s += '[' + std::to_string(data_type.array_length) + "](";
for (unsigned int a = 0; a < data_type.array_length; ++a)
{
write_constant(s, elem_type, a < static_cast<unsigned int>(data.array_data.size()) ? data.array_data[a] : constant {});
s += ", ";
}
// Remove trailing ", "
s.erase(s.size() - 2);
s += ')';
return;
}
// There can only be numeric constants
assert(data_type.is_numeric());
if (!data_type.is_scalar())
write_type<false, false>(s, data_type), s += '(';
for (unsigned int i = 0; i < data_type.components(); ++i)
{
switch (data_type.base)
{
case type::t_bool:
s += data.as_uint[i] ? "true" : "false";
break;
case type::t_min16int:
case type::t_int:
s += std::to_string(data.as_int[i]);
break;
case type::t_min16uint:
case type::t_uint:
s += std::to_string(data.as_uint[i]) + 'u';
break;
case type::t_min16float:
case type::t_float:
if (std::isnan(data.as_float[i])) {
s += "0.0/0.0/*nan*/";
break;
}
if (std::isinf(data.as_float[i])) {
s += std::signbit(data.as_float[i]) ? "1.0/0.0/*inf*/" : "-1.0/0.0/*-inf*/";
break;
}
{
char temp[64];
const std::to_chars_result res = std::to_chars(temp, temp + sizeof(temp), data.as_float[i]
#if !defined(_HAS_COMPLETE_CHARCONV) || _HAS_COMPLETE_CHARCONV
, std::chars_format::scientific, 8
#endif
);
if (res.ec == std::errc())
s.append(temp, res.ptr);
else
assert(false);
}
break;
default:
assert(false);
}
s += ", ";
}
// Remove trailing ", "
s.erase(s.size() - 2);
if (!data_type.is_scalar())
s += ')';
}
void write_location(std::string &s, const location &loc) const
{
if (loc.source.empty() || !_debug_info)
return;
s += "#line " + std::to_string(loc.line) + '\n';
}
void write_texture_format(std::string &s, texture_format format)
{
switch (format)
{
case texture_format::r8:
s += "r8";
break;
case texture_format::r16:
s += "r16";
break;
case texture_format::r16f:
s += "r16f";
break;
case texture_format::r32i:
s += "r32i";
break;
case texture_format::r32u:
s += "r32ui";
break;
case texture_format::r32f:
s += "r32f";
break;
case texture_format::rg8:
s += "rg8";
break;
case texture_format::rg16:
s += "rg16";
break;
case texture_format::rg16f:
s += "rg16f";
break;
case texture_format::rg32f:
s += "rg32f";
break;
case texture_format::rgba8:
s += "rgba8";
break;
case texture_format::rgba16:
s += "rgba16";
break;
case texture_format::rgba16f:
s += "rgba16f";
break;
case texture_format::rgba32i:
s += "rgba32i";
break;
case texture_format::rgba32u:
s += "rgba32ui";
break;
case texture_format::rgba32f:
s += "rgba32f";
break;
case texture_format::rgb10a2:
s += "rgb10_a2";
break;
default:
assert(false);
}
}
std::string id_to_name(id id) const
{
if (const auto it = _remapped_sampler_variables.find(id);
it != _remapped_sampler_variables.end())
id = it->second;
assert(id != 0);
if (const auto names_it = _names.find(id);
names_it != _names.end())
return names_it->second;
return '_' + std::to_string(id);
}
template <naming naming_type = naming::general>
void define_name(const id id, std::string name)
{
assert(!name.empty());
if constexpr (naming_type != naming::expression)
if (name[0] == '_')
return; // Filter out names that may clash with automatic ones
if constexpr (naming_type != naming::reserved)
name = escape_name(std::move(name));
if constexpr (naming_type == naming::general)
if (std::find_if(_names.begin(), _names.end(),
[&name](const auto &names_it) { return names_it.second == name; }) != _names.end())
name += '_' + std::to_string(id); // Append a numbered suffix if the name already exists
_names[id] = std::move(name);
}
uint32_t semantic_to_location(const std::string &semantic, uint32_t max_attributes = 1)
{
if (const auto location_it = _semantic_to_location.find(semantic);
location_it != _semantic_to_location.end())
return location_it->second;
// Extract the semantic index from the semantic name (e.g. 2 for "TEXCOORD2")
size_t digit_index = semantic.size() - 1;
while (digit_index != 0 && semantic[digit_index] >= '0' && semantic[digit_index] <= '9')
digit_index--;
digit_index++;
const std::string semantic_base = semantic.substr(0, digit_index);
uint32_t semantic_digit = 0;
std::from_chars(semantic.c_str() + digit_index, semantic.c_str() + semantic.size(), semantic_digit);
if (semantic_base == "COLOR" || semantic_base == "SV_TARGET")
return semantic_digit;
uint32_t location = static_cast<uint32_t>(_semantic_to_location.size());
// Now create adjoining location indices for all possible semantic indices belonging to this semantic name
for (uint32_t a = 0; a < semantic_digit + max_attributes; ++a)
{
const auto insert = _semantic_to_location.emplace(semantic_base + std::to_string(a), location + a);
if (!insert.second)
{
assert(a == 0 || (insert.first->second - a) == location);
// Semantic was already created with a different location index, so need to remap to that
location = insert.first->second - a;
}
}
return location + semantic_digit;
}
std::string escape_name(std::string name) const
{
static const std::unordered_set<std::string> s_reserverd_names = {
"common", "partition", "input", "output", "active", "filter", "superp", "invariant",
"attribute", "varying", "buffer", "resource", "coherent", "readonly", "writeonly",
"layout", "flat", "smooth", "lowp", "mediump", "highp", "precision", "patch", "subroutine",
"atomic_uint", "fixed",
"vec2", "vec3", "vec4", "ivec2", "dvec2", "dvec3", "dvec4", "ivec3", "ivec4", "uvec2", "uvec3", "uvec4", "bvec2", "bvec3", "bvec4", "fvec2", "fvec3", "fvec4", "hvec2", "hvec3", "hvec4",
"mat2", "mat3", "mat4", "dmat2", "dmat3", "dmat4", "mat2x2", "mat2x3", "mat2x4", "dmat2x2", "dmat2x3", "dmat2x4", "mat3x2", "mat3x3", "mat3x4", "dmat3x2", "dmat3x3", "dmat3x4", "mat4x2", "mat4x3", "mat4x4", "dmat4x2", "dmat4x3", "dmat4x4",
"sampler1DShadow", "sampler1DArrayShadow", "isampler1D", "isampler1DArray", "usampler1D", "usampler1DArray",
"sampler2DShadow", "sampler2DArrayShadow", "isampler2D", "isampler2DArray", "usampler2D", "usampler2DArray", "sampler2DRect", "sampler2DRectShadow", "isampler2DRect", "usampler2DRect", "isampler2DMS", "usampler2DMS", "isampler2DMSArray", "usampler2DMSArray",
"isampler3D", "usampler3D", "sampler3DRect",
"samplerCubeShadow", "samplerCubeArrayShadow", "isamplerCube", "isamplerCubeArray", "usamplerCube", "usamplerCubeArray",
"samplerBuffer", "isamplerBuffer", "usamplerBuffer",
"image1D", "iimage1D", "uimage1D", "image1DArray", "iimage1DArray", "uimage1DArray",
"image2D", "iimage2D", "uimage2D", "image2DArray", "iimage2DArray", "uimage2DArray", "image2DRect", "iimage2DRect", "uimage2DRect", "image2DMS", "iimage2DMS", "uimage2DMS", "image2DMSArray", "iimage2DMSArray", "uimage2DMSArray",
"image3D", "iimage3D", "uimage3D",
"imageCube", "iimageCube", "uimageCube", "imageCubeArray", "iimageCubeArray", "uimageCubeArray",
"imageBuffer", "iimageBuffer", "uimageBuffer",
"abs", "sign", "all", "any", "sin", "sinh", "cos", "cosh", "tan", "tanh", "asin", "acos", "atan",
"exp", "exp2", "log", "log2", "sqrt", "inversesqrt", "ceil", "floor", "fract", "trunc", "round",
"radians", "degrees", "length", "normalize", "transpose", "determinant", "intBitsToFloat", "uintBitsToFloat",
"floatBitsToInt", "floatBitsToUint", "matrixCompMult", "not", "lessThan", "greaterThan", "lessThanEqual",
"greaterThanEqual", "equal", "notEqual", "dot", "cross", "distance", "pow", "modf", "frexp", "ldexp",
"min", "max", "step", "reflect", "texture", "textureOffset", "fma", "mix", "clamp", "smoothstep", "refract",
"faceforward", "textureLod", "textureLodOffset", "texelFetch", "main"
};
// Escape reserved names so that they do not fail to compile
if (name.compare(0, 3, "gl_") == 0 || s_reserverd_names.count(name))
// Append an underscore at start instead of the end, since another one may get added in 'define_name' when there is a suffix
// This is guaranteed to not clash with user defined names, since those starting with an underscore are filtered out in 'define_name'
name = '_' + name;
// Remove duplicated underscore symbols from name which can occur due to namespaces but are not allowed in GLSL
for (size_t pos = 0; (pos = name.find("__", pos)) != std::string::npos;)
name.replace(pos, 2, "_x");
return name;
}
std::string semantic_to_builtin(std::string name, const std::string &semantic, shader_type stype) const
{
if (semantic == "SV_POSITION")
return stype == shader_type::pixel ? "gl_FragCoord" : "gl_Position";
if (semantic == "SV_POINTSIZE")
return "gl_PointSize";
if (semantic == "SV_DEPTH")
return "gl_FragDepth";
if (semantic == "SV_VERTEXID")
return _vulkan_semantics ? "gl_VertexIndex" : "gl_VertexID";
if (semantic == "SV_ISFRONTFACE")
return "gl_FrontFacing";
if (semantic == "SV_GROUPID")
return "gl_WorkGroupID";
if (semantic == "SV_GROUPINDEX")
return "gl_LocalInvocationIndex";
if (semantic == "SV_GROUPTHREADID")
return "gl_LocalInvocationID";
if (semantic == "SV_DISPATCHTHREADID")
return "gl_GlobalInvocationID";
return escape_name(std::move(name));
}
static void increase_indentation_level(std::string &block)
{
if (block.empty())
return;
for (size_t pos = 0; (pos = block.find("\n\t", pos)) != std::string::npos; pos += 3)
block.replace(pos, 2, "\n\t\t");
block.insert(block.begin(), '\t');
}
id define_struct(const location &loc, struct_type &info) override
{
const id res = info.id = make_id();
define_name<naming::unique>(res, info.unique_name);
_structs.push_back(info);
std::string &code = _blocks.at(_current_block);
write_location(code, loc);
code += "struct " + id_to_name(res) + "\n{\n";
for (const member_type &member : info.member_list)
{
code += '\t';
write_type(code, member.type); // GLSL does not allow interpolation attributes on struct members
code += ' ';
code += escape_name(member.name);
if (member.type.is_array())
code += '[' + std::to_string(member.type.array_length) + ']';
code += ";\n";
}
if (info.member_list.empty())
code += "float _dummy;\n";
code += "};\n";
return res;
}
id define_texture(const location &, texture &info) override
{
const id res = info.id = make_id();
_module.textures.push_back(info);
return res;
}
id define_sampler(const location &loc, const texture &, sampler &info) override
{
const id res = info.id = create_block();
define_name<naming::unique>(res, info.unique_name);
std::string &code = _blocks.at(res);
write_location(code, loc);
// Default to a binding index equivalent to the entry in the sampler list (this is later overwritten in 'finalize_code_for_entry_point' to a more optimal placement)
const uint32_t default_binding = static_cast<uint32_t>(_module.samplers.size());
code += "layout(binding = " + std::to_string(default_binding);
code += ") uniform ";
write_type(code, info.type);
code += ' ' + id_to_name(res) + ";\n";
_module.samplers.push_back(info);
return res;
}
id define_storage(const location &loc, const texture &tex_info, storage &info) override
{
const id res = info.id = create_block();
define_name<naming::unique>(res, info.unique_name);
std::string &code = _blocks.at(res);
write_location(code, loc);
// Default to a binding index equivalent to the entry in the storage list (this is later overwritten in 'finalize_code_for_entry_point' to a more optimal placement)
const uint32_t default_binding = static_cast<uint32_t>(_module.storages.size());
code += "layout(binding = " + std::to_string(default_binding) + ", ";
write_texture_format(code, tex_info.format);
code += ") uniform ";
write_type(code, info.type);
code += ' ' + id_to_name(res) + ";\n";
_module.storages.push_back(info);
return res;
}
id define_uniform(const location &loc, uniform &info) override
{
const id res = make_id();
define_name<naming::unique>(res, info.name);
if (_uniforms_to_spec_constants && info.has_initializer_value)
{
info.size = info.type.components() * 4;
if (info.type.is_array())
info.size *= info.type.array_length;
std::string &code = _blocks.at(_current_block);
write_location(code, loc);
assert(!info.type.has(type::q_static) && !info.type.has(type::q_const));
code += "const ";
write_type(code, info.type);
code += ' ' + id_to_name(res) + " = ";
if (!info.type.is_scalar())
write_type<false, false>(code, info.type);
code += "(SPEC_CONSTANT_" + info.name + ");\n";
_module.spec_constants.push_back(info);
}
else
{
// GLSL specification on std140 layout:
// 1. If the member is a scalar consuming N basic machine units, the base alignment is N.
// 2. If the member is a two- or four-component vector with components consuming N basic machine units, the base alignment is 2N or 4N, respectively.
// 3. If the member is a three-component vector with components consuming N basic machine units, the base alignment is 4N.
// 4. If the member is an array of scalars or vectors, the base alignment and array stride are set to match the base alignment of a single array element,
// according to rules (1), (2), and (3), and rounded up to the base alignment of a four-component vector.
// 7. If the member is a row-major matrix with C columns and R rows, the matrix is stored identically to an array of R row vectors with C components each, according to rule (4).
// 8. If the member is an array of S row-major matrices with C columns and R rows, the matrix is stored identically to a row of S*R row vectors with C components each, according to rule (4).
uint32_t alignment = (info.type.rows == 3 ? 4 /* (3) */ : info.type.rows /* (2) */) * 4 /* (1) */;
info.size = info.type.rows * 4;
if (info.type.is_matrix())
{
alignment = 16 /* (4) */;
info.size = info.type.rows * alignment /* (7), (8) */;
}
if (info.type.is_array())
{
alignment = 16 /* (4) */;
info.size = align_up(info.size, alignment) * info.type.array_length;
}
// Adjust offset according to alignment rules from above
info.offset = _module.total_uniform_size;
info.offset = align_up(info.offset, alignment);
_module.total_uniform_size = info.offset + info.size;
write_location(_ubo_block, loc);
_ubo_block += '\t';
// Note: All matrices are floating-point, even if the uniform type says different!!
write_type(_ubo_block, info.type);
_ubo_block += ' ' + id_to_name(res);
if (info.type.is_array())
_ubo_block += '[' + std::to_string(info.type.array_length) + ']';
_ubo_block += ";\n";
_module.uniforms.push_back(info);
}
return res;
}
id define_variable(const location &loc, const type &type, std::string name, bool global, id initializer_value) override
{
// Constant variables with a constant initializer can just point to the initializer SSA variable, since they cannot be modified anyway, thus saving an unnecessary assignment
if (initializer_value != 0 && type.has(type::q_const) &&
std::find_if(_constant_lookup.begin(), _constant_lookup.end(),
[initializer_value](const auto &x) {
return initializer_value == std::get<2>(x);
}) != _constant_lookup.end())
return initializer_value;
const id res = make_id();
// GLSL does not allow local sampler variables, so try to remap those
if (!global && type.is_sampler())
{
_remapped_sampler_variables[res] = 0;
return res;
}
if (!name.empty())
define_name<naming::general>(res, name);
std::string &code = _blocks.at(_current_block);
write_location(code, loc);
if (!global)
code += '\t';
write_type(code, type);
code += ' ' + id_to_name(res);
if (type.is_array())
code += '[' + std::to_string(type.array_length) + ']';
if (initializer_value != 0)
code += " = " + id_to_name(initializer_value);
code += ";\n";
return res;
}
id define_function(const location &loc, function &info) override
{
const id res = info.id = make_id();
// Name is used in other places like the entry point defines, so escape it here
info.unique_name = escape_name(info.unique_name);
assert(!info.unique_name.empty() && (info.unique_name[0] == 'F' || info.unique_name[0] == 'E'));
const bool is_entry_point = info.unique_name[0] == 'E';
if (!is_entry_point)
define_name<naming::unique>(res, info.unique_name);
else
define_name<naming::reserved>(res, "main");
assert(_current_block == 0 && (_current_function_declaration.empty() || is_entry_point));
std::string &code = _current_function_declaration;
write_location(code, loc);
write_type(code, info.return_type);
code += ' ' + id_to_name(res) + '(';
assert(info.parameter_list.empty() || !is_entry_point);
for (member_type ¶m : info.parameter_list)
{
param.id = make_id();
define_name<naming::unique>(param.id, param.name);
code += '\n';
write_location(code, param.location);
code += '\t';
write_type<true>(code, param.type); // GLSL does not allow interpolation attributes on function parameters
code += ' ' + id_to_name(param.id);
if (param.type.is_array())
code += '[' + std::to_string(param.type.array_length) + ']';
code += ',';
}
// Remove trailing comma
if (!info.parameter_list.empty())
code.pop_back();
code += ")\n";
_functions.push_back(std::make_unique<function>(info));
_current_function = _functions.back().get();
return res;
}
void define_entry_point(function &func) override
{
assert(!func.unique_name.empty() && func.unique_name[0] == 'F');
func.unique_name[0] = 'E';
// Modify entry point name so each thread configuration is made separate
if (func.type == shader_type::compute)
func.unique_name +=
'_' + std::to_string(func.num_threads[0]) +
'_' + std::to_string(func.num_threads[1]) +
'_' + std::to_string(func.num_threads[2]);
if (std::find_if(_module.entry_points.begin(), _module.entry_points.end(),
[&func](const std::pair<std::string, shader_type> &entry_point) {
return entry_point.first == func.unique_name;
}) != _module.entry_points.end())
return;
_module.entry_points.emplace_back(func.unique_name, func.type);
assert(_current_function_declaration.empty());
if (func.type == shader_type::compute)
_current_function_declaration +=
"layout(local_size_x = " + std::to_string(func.num_threads[0]) +
", local_size_y = " + std::to_string(func.num_threads[1]) +
", local_size_z = " + std::to_string(func.num_threads[2]) + ") in;\n";