Blender V5.3
mtl_shader_generate.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2025 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <fmt/format.h>
10#include <sstream>
11#include <string>
12
13#include "BLI_math_bits.hh"
14
15#include "mtl_backend.hh"
17
18namespace blender {
19
20using namespace blender::gpu;
21using namespace blender::gpu::shader;
22
23namespace gpu {
24
25struct Separator {};
26
27/* Same as a string stream but insert a separator before each new argument after the first one. */
28struct ArgumentStream : public std::stringstream {
29 bool is_first_arg = true;
30
31 std::stringstream &operator<<(Separator /*separator*/)
32 {
33 if (is_first_arg) {
34 is_first_arg = false;
35 *this << "\n ";
36 }
37 else {
38 *this << ",\n ";
39 }
40 return *this;
41 }
42};
43
53
54using Sep = Separator;
55
57{
58 /* Add Types as needed. */
59 static Set<StringRefNull> glsl_builtin_types = {
60 {"float"},
61 {"vec2"},
62 {"vec3"},
63 {"vec4"},
64 {"float2"},
65 {"float3"},
66 {"float4"},
67 {"int"},
68 {"ivec2"},
69 {"ivec3"},
70 {"ivec4"},
71 {"int2"},
72 {"int3"},
73 {"int4"},
74 {"uint32_t"},
75 {"uvec2"},
76 {"uvec3"},
77 {"uvec4"},
78 {"uint"},
79 {"uint2"},
80 {"uint3"},
81 {"uint4"},
82 {"mat3"},
83 {"mat4"},
84 {"float3x3"},
85 {"float4x4"},
86 {"bool"},
87 {"uchar"},
88 {"uchar2"},
89 {"uchar2"},
90 {"uchar4"},
91 {"vec3_1010102_Unorm"},
92 {"vec3_1010102_Inorm"},
93 {"packed_float2"},
94 {"packed_float3"},
95 };
96 return glsl_builtin_types.contains(type);
97}
98
100{
101 bool supports_native_atomics = MTLBackend::get_capabilities().supports_texture_atomics;
102 switch (type) {
103 case ImageType::Float1D:
104 return "texture1d";
105 case ImageType::Float2D:
106 return "texture2d";
107 case ImageType::Float3D:
108 return "texture3d";
109 case ImageType::FloatCube:
110 return "texturecube";
111 case ImageType::Float1DArray:
112 return "texture1d_array";
113 case ImageType::Float2DArray:
114 return "texture2d_array";
115 case ImageType::FloatCubeArray:
116 return "texturecube_array";
117 case ImageType::FloatBuffer:
118 return "texture_buffer";
119 case ImageType::Depth2D:
120 return "depth2d";
121 case ImageType::Shadow2D:
122 return "depth2d";
123 case ImageType::Depth2DArray:
124 return "depth2d_array";
125 case ImageType::Shadow2DArray:
126 return "depth2d_array";
127 case ImageType::DepthCube:
128 return "depthcube";
129 case ImageType::ShadowCube:
130 return "depthcube";
131 case ImageType::DepthCubeArray:
132 return "depthcube_array";
133 case ImageType::ShadowCubeArray:
134 return "depthcube_array";
135 case ImageType::Int1D:
136 return "texture1d";
137 case ImageType::Int2D:
138 return "texture2d";
139 case ImageType::Int3D:
140 return "texture3d";
141 case ImageType::IntCube:
142 return "texturecube";
143 case ImageType::Int1DArray:
144 return "texture1d_array";
145 case ImageType::Int2DArray:
146 return "texture2d_array";
147 case ImageType::IntCubeArray:
148 return "texturecube_array";
149 case ImageType::IntBuffer:
150 return "texture_buffer";
151 case ImageType::Uint1D:
152 return "texture1d";
153 case ImageType::Uint2D:
154 return "texture2d";
155 case ImageType::Uint3D:
156 return "texture3d";
157 case ImageType::UintCube:
158 return "texturecube";
159 case ImageType::Uint1DArray:
160 return "texture1d_array";
161 case ImageType::Uint2DArray:
162 return "texture2d_array";
163 case ImageType::UintCubeArray:
164 return "texturecube_array";
165 case ImageType::UintBuffer:
166 return "texture_buffer";
167 case ImageType::AtomicInt2D:
168 case ImageType::AtomicUint2D:
169 return "texture2d";
170 case ImageType::AtomicInt2DArray:
171 case ImageType::AtomicUint2DArray:
172 /* If texture atomics are natively supported, we use the native texture type, otherwise all
173 * other formats are implemented via texture2d. */
174 return supports_native_atomics ? "texture2d_array" : "texture2d";
175 case ImageType::AtomicInt3D:
176 case ImageType::AtomicUint3D:
177 /* If texture atomics are natively supported, we use the native texture type, otherwise all
178 * other formats are implemented via texture2d. */
179 return supports_native_atomics ? "texture3d" : "texture2d";
180 default: {
181 /* Unrecognized type. */
183 return "ERROR";
184 }
185 };
186}
187
189{
190 bool supports_native_atomics = MTLBackend::get_capabilities().supports_texture_atomics;
191 /* Add Types as needed. */
192 switch (type) {
193 case ImageType::Float1D:
194 case ImageType::Int1D:
195 case ImageType::Uint1D:
196 return "sampler1D";
197 case ImageType::Float1DArray:
198 case ImageType::Int1DArray:
199 case ImageType::Uint1DArray:
200 return "sampler1DArray";
201 case ImageType::Float2D:
202 case ImageType::Int2D:
203 case ImageType::Uint2D:
204 return "sampler2D";
205 case ImageType::Float2DArray:
206 case ImageType::Int2DArray:
207 case ImageType::Uint2DArray:
208 return "sampler2DArray";
209 case ImageType::Float3D:
210 case ImageType::Int3D:
211 case ImageType::Uint3D:
212 return "sampler3D";
213 case ImageType::FloatBuffer:
214 case ImageType::IntBuffer:
215 case ImageType::UintBuffer:
216 return "samplerBuffer";
217 case ImageType::FloatCube:
218 case ImageType::IntCube:
219 case ImageType::UintCube:
220 return "samplerCube";
221 case ImageType::FloatCubeArray:
222 case ImageType::IntCubeArray:
223 case ImageType::UintCubeArray:
224 return "samplerCubeArray";
225 case ImageType::Depth2D:
226 case ImageType::Shadow2D:
227 return "sampler2DDepth";
228 case ImageType::Depth2DArray:
229 case ImageType::Shadow2DArray:
230 return "sampler2DArrayDepth";
231 case ImageType::DepthCube:
232 case ImageType::ShadowCube:
233 return "depthCube";
234 case ImageType::DepthCubeArray:
235 case ImageType::ShadowCubeArray:
236 return "depthCubeArray";
237 /* If native texture atomics are unsupported, map types to fallback atomic structures which
238 * contain a buffer pointer and metadata members for size and alignment. */
239 case ImageType::AtomicInt2D:
240 case ImageType::AtomicUint2D:
241 return supports_native_atomics ? "sampler2D" : "sampler2DAtomic";
242 case ImageType::AtomicInt3D:
243 case ImageType::AtomicUint3D:
244 return supports_native_atomics ? "sampler3D" : "sampler3DAtomic";
245 case ImageType::AtomicInt2DArray:
246 case ImageType::AtomicUint2DArray:
247 return supports_native_atomics ? "sampler2DArray" : "sampler2DArrayAtomic";
248 default: {
249 /* Unrecognized type. */
251 return "ERROR";
252 }
253 };
254}
255
257{
258 /* Add Types as needed */
259 switch (type) {
260 /* Floating point return. */
261 case ImageType::Float1D:
262 case ImageType::Float2D:
263 case ImageType::Float3D:
264 case ImageType::FloatCube:
265 case ImageType::Float1DArray:
266 case ImageType::Float2DArray:
267 case ImageType::FloatCubeArray:
268 case ImageType::FloatBuffer:
269 case ImageType::Depth2D:
270 case ImageType::Shadow2D:
271 case ImageType::Depth2DArray:
272 case ImageType::Shadow2DArray:
273 case ImageType::DepthCube:
274 case ImageType::ShadowCube:
275 case ImageType::DepthCubeArray:
276 case ImageType::ShadowCubeArray: {
277 return "float";
278 }
279 /* Integer return. */
280 case ImageType::Int1D:
281 case ImageType::Int2D:
282 case ImageType::Int3D:
283 case ImageType::IntCube:
284 case ImageType::Int1DArray:
285 case ImageType::Int2DArray:
286 case ImageType::IntCubeArray:
287 case ImageType::IntBuffer:
288 case ImageType::AtomicInt2D:
289 case ImageType::AtomicInt2DArray:
290 case ImageType::AtomicInt3D: {
291 return "int";
292 }
293
294 /* Unsigned Integer return. */
295 case ImageType::Uint1D:
296 case ImageType::Uint2D:
297 case ImageType::Uint3D:
298 case ImageType::UintCube:
299 case ImageType::Uint1DArray:
300 case ImageType::Uint2DArray:
301 case ImageType::UintCubeArray:
302 case ImageType::UintBuffer:
303 case ImageType::AtomicUint2D:
304 case ImageType::AtomicUint2DArray:
305 case ImageType::AtomicUint3D: {
306 return "uint32_t";
307 }
308
309 default: {
310 /* Unrecognized type. */
312 return "ERROR";
313 }
314 };
315}
316
317static const char *get_stage_class_name(ShaderStage stage)
318{
319 switch (stage) {
321 return "mtl_Vert";
323 return "mtl_Frag";
325 return "mtl_Comp";
326 default:
328 return "";
329 }
330 return "";
331}
332
333static const char *get_stage_out_class_name(ShaderStage stage, const ShaderCreateInfo &info)
334{
335 switch (stage) {
337 return "mtl_VertOut";
339 return (info.fragment_outputs_.is_empty() && info.depth_write_ == DepthWrite::UNCHANGED &&
340 flag_is_set(info.builtins_combined(), BuiltinBits::STENCIL_REF) == false) ?
341 "void" :
342 "mtl_FragOut";
344 return "void";
345 default:
347 return "";
348 }
349 return "";
350}
351static const char *get_stage_in_class_name(ShaderStage stage)
352{
353 switch (stage) {
355 return "mtl_VertIn";
357 return "mtl_VertOut";
359 return "mtl_CompIn";
360 default:
362 return "";
363 }
364 return "";
365}
366
368{
369 switch (stage) {
371 return "mtl_vert_out";
373 return "mtl_frag_out";
375 return "";
376 default:
378 return "";
379 }
380 return "";
381}
382
384{
385 switch (stage) {
387 return "mtl_vert_in";
389 return "mtl_frag_in";
391 return "";
392 default:
394 return "";
395 }
396 return "";
397}
398
399static const char *get_stage_instance_name(ShaderStage stage)
400{
401 switch (stage) {
403 return "vert_inst";
405 return "frag_inst";
407 return "comp_inst";
408 default:
410 return "";
411 }
412 return "";
413}
414
415static const char *get_stage_type(ShaderStage stage)
416{
417 switch (stage) {
419 return "vertex";
421 return "fragment";
423 return "kernel";
424 default:
426 return "";
427 }
428 return "";
429}
430
432{
433 switch (type) {
434 case Type::uint_t:
435 return std::to_string(value.u);
436 case Type::int_t:
437 return std::to_string(value.i);
438 case Type::bool_t:
439 return value.u ? "true" : "false";
440 default:
442 return "";
443 }
444}
445
446static const char *to_string(const Interpolation &interp)
447{
448 switch (interp) {
450 return " [[center_perspective]]";
452 return " [[flat]]";
454 return " [[center_no_perspective]]";
455 default:
457 return " error";
458 }
459}
460
461#if 0
462# define LINE ""
463#else
464# define LINE "\n#line " STRINGIFY(__LINE__) "\n"
465#endif
466
467std::string wrap_type(StringRefNull type_name, const ShaderStage stage)
468{
469 if (is_builtin_type(type_name)) {
470 return type_name;
471 }
472 return std::string(get_stage_class_name(stage)) + "::" + type_name;
473}
474
475std::string ref_type(const ResourceString &str, const std::string &attribute = "")
476{
477 if (!str.is_array()) {
478 return " &" + str + attribute;
479 }
480 return " (&" + str.str_no_array() + attribute + ")" + str.str_only_array();
481}
482
483std::string ptr_type(const ResourceString &str)
484{
485 if (!str.is_array()) {
486 return " &" + str;
487 }
488 return " *" + str.str_no_array();
489}
490
491static void generate_uniforms(GeneratedStreams &generated,
493 const ShaderStage stage)
494{
495 /* Only generate PushConstantBlock if we have uniforms. */
496 if (uniforms.is_empty()) {
497 return;
498 }
499 {
500 /* Block definition. */
501 auto &out = generated.wrapper_class_members;
502 out << " struct PushConstantBlock {\n";
503 for (const ShaderCreateInfo::PushConst &uni : uniforms) {
504 /* Subtle workaround to follow sane alignment rules.
505 * Always use 4 bytes boolean like in GLSL. */
506 Type type = (uni.type == Type::bool_t) ? Type::int_t : uni.type;
507 out << " " << type << " " << uni.name << uni.array_str() << ";\n";
508 }
509 out << " };\n";
510
511 /* References definition for global access. */
512 for (const ShaderCreateInfo::PushConst &uni : uniforms) {
513 Type type = (uni.type == Type::bool_t) ? Type::int_t : uni.type;
514 out << " const constant " << type << " (&" << uni.name << ")" << uni.array_str() << ";\n";
515 }
516 }
517 {
518 /* Constructor parameters. */
519 auto &out = generated.wrapper_constructor_parameters;
520 out << Sep() << "const constant PushConstantBlock &mtl_pc";
521 }
522 {
523 /* Constructor assignments. */
524 auto &out = generated.wrapper_constructor_assign;
525 for (const ShaderCreateInfo::PushConst &uni : uniforms) {
526 out << Sep() << uni.name << "(mtl_pc." << uni.name << ")";
527 }
528 }
529 {
530 /* Constructor arguments. */
531 auto &out = generated.wrapper_instance_init;
532 out << Sep() << "*mtl_pc";
533 }
534 {
535 /* Entry point arguments. */
536 auto &out = generated.entry_point_parameters;
537 out << Sep() << "constant " << wrap_type("PushConstantBlock", stage) << " *mtl_pc";
538 out << " [[buffer(" << MTL_PUSH_CONSTANT_BUFFER_SLOT << ")]]";
539 }
540}
541
542static void generate_buffer(GeneratedStreams &generated,
543 const bool writeable,
544 std::string type,
545 ResourceString name,
546 int slot,
547 const ShaderStage stage)
548{
549 const char *memory_scope = (writeable) ? "device " : "constant ";
550 const char *const_qual = bool(stage & ShaderStage::VERTEX) ? "const " : "";
551
552 {
553 /* References definition for global access. */
554 auto &out = generated.wrapper_class_members;
555 out << " " << memory_scope << type << ref_type(name) << ";\n";
556 }
557 {
558 /* Constructor parameters. */
559 auto &out = generated.wrapper_constructor_parameters;
560 out << Sep() << const_qual << memory_scope << type << ref_type(name);
561 }
562 {
563 /* Constructor assignments. */
564 auto &out = generated.wrapper_constructor_assign;
565 out << Sep() << name.str_no_array() << "(";
566 /* Remove the const qualifier. Its only there to avoid a compiler warning. */
567 /* The reason the warning exists is because the vertex shader might be executed more than once
568 * per vertex, which could lead to weird situation when working with atomic counter for
569 * instance. Given this is only used by the debug line shader (to decrement the primitives
570 * lifetime) it is not a huge issue to silence the warning. In the future, it might be better
571 * to add a flag on the create info to allow non-const resource in the vertex shader. */
572 out << "const_cast<" << memory_scope << type << " (&)" << name.str_only_array() << ">(";
573 out << name.str_no_array();
574 out << ")";
575 out << ")";
576 }
577 {
578 /* Constructor arguments. */
579 auto &out = generated.wrapper_instance_init;
580 out << Sep() << name.str_no_array();
581 }
582 {
583 /* Entry point arguments. */
584 auto &out = generated.entry_point_parameters;
585 out << Sep() << const_qual << memory_scope << wrap_type(type, stage);
586 out << ref_type(name, " [[buffer(" + std::to_string(slot) + ")]]");
587 }
588}
589
590StringRefNull to_access(const bool is_sampler, const shader::Qualifier qualifier)
591{
592 if (is_sampler) {
593 return "access::sample";
594 }
595
596 switch (qualifier) {
598 return "access::read";
600 return "access::write";
602 return "access::read_write";
603 default:
604 BLI_assert(false);
605 return "";
606 }
607 return "";
608}
609
610static void generate_texture(GeneratedStreams &generated,
611 bool is_sampler,
612 shader::Qualifier qualifier,
613 const shader::ImageType type,
614 ResourceString name,
615 int slot,
616 const ShaderStage stage,
617 const bool use_sampler_argument_buffer = false)
618{
619 const bool supports_native_atomics = MTLBackend::get_capabilities().supports_texture_atomics;
620
621 if (ELEM(type, ImageType::FloatBuffer, ImageType::IntBuffer, ImageType::UintBuffer)) {
622 /* These cannot be declared with sample access. */
623 is_sampler = false;
624 }
625 if (bool(stage & ShaderStage::VERTEX)) {
626 /* Forcing sampling only access for vertex shaders.
627 * Avoid this warning: "writable resources in non-void vertex function". */
628 qualifier = shader::Qualifier::read;
629 }
630 /* Samplers use a different bind space and start at 0. */
631 const std::string sampler_slot = std::to_string(slot - MTL_SAMPLER_SLOT_OFFSET);
632 const std::string sampler_name = use_sampler_argument_buffer ?
633 ("mtl_samplers.samplers[" + sampler_slot + "]") :
634 (name + "_samp_");
635 const std::string temp_args = to_component_type(type) + ", " + to_access(is_sampler, qualifier);
636 const std::string type_str = to_raw_type(type) + "<" + temp_args + "> ";
637 const std::string wrapper_str = "_" + to_wrapper_type(type) + "<" + temp_args + "> ";
638 {
639 /* References definition for global access. */
640 auto &out = generated.wrapper_class_members;
641 out << " " << wrapper_str << name << ";\n";
642 }
643 {
644 /* Constructor parameters. */
645 auto &out = generated.wrapper_constructor_parameters;
646 out << Sep() << wrapper_str << name;
647 }
648 {
649 /* Constructor assignments. */
650 auto &out = generated.wrapper_constructor_assign;
651 out << Sep() << name << "(" << name << ")";
652 }
653 {
654 /* Constructor arguments. */
655 auto &out = generated.wrapper_instance_init;
656 std::string atomic_args;
657 if (!supports_native_atomics) {
658 std::string prefix;
659 std::string suffix;
660 if (stage == ShaderStage::VERTEX) {
661 /* Keep buffer declaration as const to avoid warning. */
662 prefix = "const_cast<device " + to_component_type(type) + " *>(";
663 suffix = ")";
664 }
665
666 /* Pass the additional buffer and the metadata. */
667 if (ELEM(type,
668 ImageType::AtomicUint2DArray,
669 ImageType::AtomicUint3D,
670 ImageType::AtomicInt2DArray,
671 ImageType::AtomicInt3D))
672 {
673 /* Buffer-backed 2D Array and 3D texture types are not natively supported so texture size
674 * is passed in as uniform metadata for 3D to 2D coordinate remapping. */
675 atomic_args += ", {";
676 atomic_args += prefix + name + "_buf_" + suffix + ", ";
677 atomic_args += "ushort3(mtl_pc->" + name + "_metadata_.xyz), ";
678 atomic_args += "ushort(mtl_pc->" + name + "_metadata_.w)";
679 atomic_args += "}";
680 }
681 else if (ELEM(type, ImageType::AtomicUint2D, ImageType::AtomicInt2D)) {
682 /* Only pass buffer and alignment. */
683 atomic_args += ", {";
684 atomic_args += prefix + name + "_buf_" + suffix + ", ";
685 atomic_args += "ushort(mtl_pc->" + name + "_metadata_.w)";
686 atomic_args += "}";
687 }
688 }
689 if (is_sampler) {
690 out << Sep() << wrapper_str << "{&" << name << ", &" << sampler_name << atomic_args << "}";
691 }
692 else {
693 out << Sep() << wrapper_str << "{&" << name << ", nullptr " << atomic_args << "}";
694 }
695 }
696 {
697 /* Entry point arguments. */
698 auto &out = generated.entry_point_parameters;
699 out << Sep() << type_str << name << " [[texture(" << slot << ")]]";
700
701 if (is_sampler && !use_sampler_argument_buffer) {
702 out << Sep() << "sampler " << sampler_name << " [[sampler(" << sampler_slot << ")]]";
703 }
704 }
705}
706
708 StringRefNull name,
709 int slot)
710{
711 {
712 /* Reference definition for global access. */
713 auto &out = generated.wrapper_class_members;
714 out << " instance_acceleration_structure " << name << ";\n";
715 }
716 {
717 /* Constructor parameters. */
718 auto &out = generated.wrapper_constructor_parameters;
719 out << Sep() << "instance_acceleration_structure " << name;
720 }
721 {
722 /* Constructor assignments. */
723 auto &out = generated.wrapper_constructor_assign;
724 out << Sep() << name << "(" << name << ")";
725 }
726 {
727 /* Constructor arguments. */
728 auto &out = generated.wrapper_instance_init;
729 out << Sep() << name;
730 }
731 {
732 /* Entry point arguments. */
733 auto &out = generated.entry_point_parameters;
734 out << Sep() << "instance_acceleration_structure " << name;
735 out << " [[buffer(" << slot << ")]]";
736 }
737}
738
739static void generate_resource(GeneratedStreams &generated,
741 const ShaderStage stage,
742 const ShaderCreateInfo & /*info*/,
743 const bool use_sampler_argument_buffer)
744{
745 switch (res.bind_type) {
747 generate_texture(generated,
748 true,
750 res.sampler.type,
751 res.sampler.name,
753 stage,
754 use_sampler_argument_buffer);
755 break;
757 generate_texture(generated,
758 false,
759 res.image.qualifiers,
760 res.image.type,
761 res.image.name,
763 stage);
764 break;
766 generate_buffer(generated,
767 false,
768 res.uniformbuf.type_name,
769 res.uniformbuf.name,
771 stage);
772 break;
774 generate_buffer(generated,
775 bool(res.storagebuf.qualifiers & shader::Qualifier::write),
776 res.storagebuf.type_name,
777 res.storagebuf.name,
779 stage);
780 break;
783 generated, res.acceleration_structure.name, MTL_ACCELERATION_STRUCTURE_SLOT + res.slot);
784 break;
785 }
786}
787
789 const CompilationConstant &constant)
790{
791 /* Global scope definition before the wrapper class. */
792 auto &out = generated.wrapper_class_prefix;
793 out << "constant " << constant.type << " " << constant.name;
794 out << " [[maybe_unused]] = " << to_string(constant.type, constant.value) << ";\n";
795}
796
798 const SpecializationConstant &constant,
799 int index)
800{
801 /* Global scope definition before the wrapper class. */
802 auto &out = generated.wrapper_class_prefix;
803 out << "constant " << constant.type << " " << constant.name;
804 out << " [[function_constant(" << index << ")]];\n";
805}
806
809{
810 {
811 /* References definition for global access. */
812 auto &out = generated.wrapper_class_members;
813 out << " threadgroup " << sv.type << ref_type(sv.name) << ";\n";
814 }
815 {
816 /* Constructor parameters. */
817 auto &out = generated.wrapper_constructor_parameters;
818 out << Sep() << "threadgroup " << sv.type << ref_type(sv.name);
819 }
820 {
821 /* Constructor assignments. */
822 auto &out = generated.wrapper_constructor_assign;
823 out << Sep() << sv.name.str_no_array() << "(" << sv.name.str_no_array() << ")";
824 }
825 {
826 /* Entry point body start. */
827 auto &out = generated.entry_point_start;
828 out << " threadgroup " << sv.type << " " << sv.name << ";\n";
829 }
830 {
831 /* Constructor arguments. */
832 auto &out = generated.wrapper_instance_init;
833 out << Sep() << sv.name.str_no_array();
834 }
835}
836
837static void generate_sampler_argument_buffer(GeneratedStreams &generated, int sampler_count)
838{
839 {
840 /* Global scope definition before the wrapper class. */
841 auto &out = generated.wrapper_class_prefix;
842 out << "struct BindlessSamplers {\n";
843 out << " array<sampler, " << sampler_count << "> samplers [[id(0)]];\n";
844 out << "};\n";
845 }
846 {
847 /* Entry point arguments. */
848 auto &out = generated.entry_point_parameters;
849 out << Sep() << "constant BindlessSamplers &mtl_samplers";
850 out << " [[buffer(" << MTL_SAMPLER_ARGUMENT_BUFFER_SLOT << ")]]";
851 }
852}
853
855 const ShaderStage stage,
856 const ShaderCreateInfo &info)
857{
858 const bool use_sampler_argument_buffer = flag_is_set(info.builtins_combined(),
860
861 int specialization_constant_index = MTL_SPECIALIZATION_CONSTANT_OFFSET;
863 generate_specialization_constant(generated, sc, specialization_constant_index++);
864 }
865
866 for (const CompilationConstant &cc : info.compilation_constants_) {
867 generate_compilation_constant(generated, cc);
868 }
869
871 generate_shared_variable(generated, sv);
872 }
873
874 for (const ShaderCreateInfo::Resource &res : info.pass_resources_) {
875 generate_resource(generated, res, stage, info, use_sampler_argument_buffer);
876 }
877 for (const ShaderCreateInfo::Resource &res : info.batch_resources_) {
878 generate_resource(generated, res, stage, info, use_sampler_argument_buffer);
879 }
880 for (const ShaderCreateInfo::Resource &res : info.geometry_resources_) {
881 generate_resource(generated, res, stage, info, use_sampler_argument_buffer);
882 }
883
884 if (use_sampler_argument_buffer) {
886 }
887
888 generate_uniforms(generated, info.push_constants_, stage);
889}
890
892{
893 constexpr ShaderStage stage = ShaderStage::VERTEX;
894 StringRefNull in_class_local = get_stage_in_class_name(stage);
895 std::string in_class = get_stage_class_name(stage) + ("::" + in_class_local);
897
898 if (info.vertex_inputs_.is_empty()) {
899 return;
900 }
901
902 {
903 /* References definition for global access. */
904 auto &out = generated.wrapper_class_members;
905 for (const ShaderCreateInfo::VertIn &attr : info.vertex_inputs_) {
906 out << " const " << attr.type << " " << attr.name << ";\n";
907 }
908
909 out << " struct " << in_class_local << " {\n";
910 for (const ShaderCreateInfo::VertIn &attr : info.vertex_inputs_) {
911 out << " " << attr.type << " " << attr.name << " [[attribute(" << attr.index << ")]];\n";
912 }
913 out << " };\n\n";
914 }
915 {
916 /* Constructor parameters. */
917 auto &out = generated.wrapper_constructor_parameters;
918 out << Sep() << "const thread " << in_class_local << " &mtl_vert_in";
919 }
920 {
921 /* Constructor assignments. */
922 auto &out = generated.wrapper_constructor_assign;
923 for (const ShaderCreateInfo::VertIn &attr : info.vertex_inputs_) {
924 out << Sep() << attr.name << "(mtl_vert_in." << attr.name << ")";
925 }
926 }
927 {
928 /* Entry point arguments. */
929 auto &out = generated.entry_point_parameters;
930 out << Sep() << in_class << " " << in_inst << " [[stage_in]]";
931 }
932 {
933 /* Constructor arguments. */
934 auto &out = generated.wrapper_instance_init;
935 out << Sep() << in_inst;
936 }
937}
938
940 std::stringstream &declaration,
941 const StringRefNull type,
942 const StringRefNull var,
944 const StringRefNull array = "",
945 const bool is_const = false)
946{
947 StringRefNull const_qual = is_const ? "const " : "";
948 StringRefNull mem_scope = "thread ";
949 /* Declaration inside builtin class. */
950 declaration << " " << type << " " << var << " " << attribute << array << ";\n";
951 /* Global scope access. */
952 ss.wrapper_class_members << " " << mem_scope << const_qual << type << " (&" << var << ")"
953 << array << ";\n";
954 ss.wrapper_constructor_assign << Sep() << var << "(mtl_vert_out." << var << ")";
955}
956
958 const ShaderCreateInfo &info,
959 const ShaderStage stage)
960{
961 const bool is_frag = stage == ShaderStage::FRAGMENT;
962 std::stringstream decl;
963
964 /* If invariance is available, utilize this to consistently mitigate depth fighting artifacts
965 * by ensuring that vertex position is consistently calculated between subsequent passes
966 * with maximum precision. */
967 /* TODO(fclem): Maybe worth enabling only for cases where it matters (only mesh rendering). */
968 std::string pos_attr = "[[position]] [[invariant]]";
969 if (stage == ShaderStage::VERTEX) {
970 generate_raster_builtin(ss, decl, "float4", "gl_Position", pos_attr);
971 }
972 else if (flag_is_set(info.builtins_combined(), BuiltinBits::FRAG_COORD) &&
973 stage == ShaderStage::FRAGMENT)
974 {
975 generate_raster_builtin(ss, decl, "float4", "gl_FragCoord", pos_attr, "", true);
976 }
977
978 if (flag_is_set(info.builtins_combined(), BuiltinBits::LAYER)) {
980 ss, decl, "uint", "gpu_Layer", "[[render_target_array_index]]", "", is_frag);
981 }
982 if (flag_is_set(info.builtins_combined(), BuiltinBits::VIEWPORT_INDEX)) {
984 ss, decl, "uint", "gpu_ViewportIndex", "[[viewport_array_index]]", "", is_frag);
985 }
986 if (flag_is_set(info.builtins_combined(), BuiltinBits::POINT_SIZE) &&
987 stage == ShaderStage::VERTEX)
988 {
989 generate_raster_builtin(ss, decl, "float", "gl_PointSize", "[[point_size]]");
990 }
991 if (flag_is_set(info.builtins_combined(), BuiltinBits::CLIP_DISTANCES) &&
992 stage == ShaderStage::VERTEX)
993 {
994 /* WORKAROUND: BSL has currently no way to disable clip distances using compilation constant.
995 * This induce a huge performance gap with the BSL port of workbench shader (see #155865).
996 * This adds back the same preprocessor check that was previously here. However, this code is
997 * heavily tailored to workbench and assume exact match with the compilation constant name.
998 * GLSL doesn't suffer the same issue as gl_ClipDistance is only considered used if assigned.
999 */
1000 std::string start_cond =
1001 "\n#if (defined(SRT_CONSTANT_use_clipping) ? (SRT_CONSTANT_use_clipping == 1) : "
1002 "defined(USE_WORLD_CLIP_PLANES))\n";
1003 std::string end_cond = "\n#endif\n";
1004
1005 decl << start_cond;
1006 ss.wrapper_class_members << start_cond;
1007 ss.wrapper_constructor_assign << start_cond;
1008
1009 generate_raster_builtin(ss, decl, "float", "gl_ClipDistance", "[[clip_distance]]", " [6]");
1010
1011 decl << end_cond;
1012 ss.wrapper_class_members << end_cond;
1013 ss.wrapper_constructor_assign << end_cond;
1014
1015 ss.entry_point_start << start_cond;
1016
1017 /* We always create all planes and initialize them to 1 (passing). This way the shader doesn't
1018 * have to write to them for the ones it doesn't need. */
1019 StringRefNull vert_inout_inst = get_stage_out_instance_name(stage);
1020 for ([[maybe_unused]] const int i : IndexRange(6)) {
1021 ss.entry_point_start << " " << vert_inout_inst << ".gl_ClipDistance[" << i << "] = 1.0f;\n";
1022 }
1023
1024 ss.entry_point_start << end_cond;
1025 }
1026 return decl.str();
1027}
1028
1029static void generate_inout(std::stringstream &out,
1030 StringRefNull iface_name,
1032{
1033 /* TODO(fclem): Move this to the GPU level and do not assert but simply fail compilation. */
1035 !inout.name.is_array());
1036 out << " " << inout.type << " _" << iface_name << "_" << inout.name.str_no_array();
1037 out << to_string(inout.interp) << ";\n";
1038}
1039
1041 const ShaderCreateInfo &info,
1042 const ShaderStage stage)
1043{
1044 std::string out_class_local = get_stage_out_class_name(ShaderStage::VERTEX, info);
1045
1046 StringRefNull const_qual = (stage == ShaderStage::FRAGMENT) ? "const " : "";
1047 StringRefNull mem_scope = "thread ";
1048
1049 {
1050 auto &out = generated.wrapper_class_members;
1051
1052 std::string builtins_decl = generate_raster_builtins(generated, info, stage);
1053
1054 /* References definition for global access. */
1055 for (const StageInterfaceInfo *iface : info.vertex_out_interfaces_) {
1056 if (iface->instance_name.is_empty()) {
1057 for (const StageInterfaceInfo::InOut &inout : iface->inouts) {
1058 out << " " << const_qual << mem_scope << inout.type << " &" << inout.name << ";\n";
1059 }
1060 }
1061 else {
1062 out << " struct " << iface->name << " {\n";
1063 for (const StageInterfaceInfo::InOut &inout : iface->inouts) {
1064 /* Eventually, we only need one pointer per named interface. However, this require
1065 * MSL 3.0 which would mean artificially dropping support for older MacOS versions. */
1066 out << " " << const_qual << mem_scope << inout.type << " &" << inout.name << ";\n";
1067 }
1068 out << " } " << iface->instance_name << ";\n";
1069 }
1070 }
1071
1072 /* Main Block Definition. */
1073 out << " struct " << out_class_local << " {\n";
1074 out << builtins_decl;
1075 for (const StageInterfaceInfo *iface : info.vertex_out_interfaces_) {
1076 for (const StageInterfaceInfo::InOut &inout : iface->inouts) {
1078 }
1079 }
1080 out << " };\n\n";
1081 }
1082 {
1083 /* Constructor parameters. */
1084 auto &out = generated.wrapper_constructor_parameters;
1085 out << Sep() << const_qual << mem_scope << out_class_local << " &mtl_vert_out";
1086 }
1087 {
1088 /* Constructor assignments. */
1089 auto &out = generated.wrapper_constructor_assign;
1090 for (const StageInterfaceInfo *iface : info.vertex_out_interfaces_) {
1091 if (iface->instance_name.is_empty()) {
1092 for (const StageInterfaceInfo::InOut &inout : iface->inouts) {
1093 out << Sep() << inout.name << "(mtl_vert_out.__" << inout.name << ")";
1094 }
1095 }
1096 else {
1097 ArgumentStream args;
1098 for (const StageInterfaceInfo::InOut &inout : iface->inouts) {
1099 args << Sep() << " mtl_vert_out._" << iface->instance_name << "_" << inout.name;
1100 }
1101 out << Sep() << iface->instance_name << "({" << args.str() << "\n })";
1102 }
1103 }
1104 }
1105 {
1106 /* Entry point arguments. */
1107 auto &out = generated.entry_point_parameters;
1108 if (stage == ShaderStage::FRAGMENT) {
1109 std::string in_class_local = get_stage_in_class_name(stage);
1110 std::string in_class = get_stage_class_name(stage) + ("::" + in_class_local);
1111 std::string in_inst = get_stage_in_instance_name(stage);
1112
1113 out << Sep() << const_qual << in_class << " " << in_inst << " [[stage_in]]";
1114 }
1115 }
1116 {
1117 /* Constructor arguments. */
1118 auto &out = generated.wrapper_instance_init;
1119 if (stage == ShaderStage::FRAGMENT) {
1121 }
1122 else {
1124 }
1125 }
1126}
1127
1129 std::stringstream &declaration,
1130 const StringRefNull type,
1131 const StringRefNull var,
1132 const StringRefNull native_type,
1134 const bool is_const = false)
1135{
1136 StringRefNull const_qual = is_const ? "const " : "";
1137 StringRefNull mem_scope = "thread ";
1138 /* Declaration inside builtin class. */
1139 declaration << " " << native_type << " " << var << " " << attribute << ";\n";
1140 /* Global scope access. */
1141 ss.wrapper_class_members << " " << mem_scope << const_qual << type << " &" << var << ";\n";
1142 /* Normally done for uint to int cast, which is safe in this case. */
1143 std::string cast = "*reinterpret_cast<thread " + type + "*>";
1144 ss.wrapper_constructor_assign << Sep() << var << "(" << cast << "(&mtl_frag_out." << var << "))";
1145}
1146
1148{
1149 std::stringstream decl;
1150
1151 if (info.depth_write_ != DepthWrite::UNCHANGED) {
1152 auto attr = [](DepthWrite depth_write) {
1153 switch (depth_write) {
1154 case DepthWrite::ANY:
1155 return "[[depth(any)]]";
1157 return "[[depth(greater)]]";
1158 case DepthWrite::LESS:
1159 return "[[depth(less)]]";
1161 return "";
1162 }
1163 };
1164 generate_fragment_builtin(ss, decl, "float", "gl_FragDepth", "float", attr(info.depth_write_));
1165 }
1166
1167 if (flag_is_set(info.builtins_combined(), BuiltinBits::STENCIL_REF)) {
1168 generate_fragment_builtin(ss, decl, "int", "gl_FragStencilRefARB", "uint", "[[stencil]]");
1169 }
1170
1171 return decl.str();
1172}
1173
1175{
1176 constexpr ShaderStage stage = ShaderStage::FRAGMENT;
1177 StringRefNull in_class_local = "SubpassInputs";
1178 std::string in_class = wrap_type(in_class_local, stage);
1179
1180 if (info.subpass_inputs_.is_empty()) {
1181 return;
1182 }
1183
1184 StringRefNull mem_scope = "thread ";
1185
1186 {
1187 auto &out = generated.wrapper_class_members;
1188
1189 /* References definition for global access. */
1190 for (const ShaderCreateInfo::SubpassIn &input : info.subpass_inputs_) {
1191 out << " " << mem_scope << input.type << " &" << input.name << ";\n";
1192 }
1193
1194 /* Main Block Definition. */
1195 out << " struct " << in_class_local << " {\n";
1196 for (const ShaderCreateInfo::SubpassIn &input : info.subpass_inputs_) {
1197 out << " " << input.type << " " << input.name;
1198 out << " [[color(" << input.index << ")]]";
1199 if (input.raster_order_group >= 0) {
1200 out << " [[raster_order_group(" << input.raster_order_group << ")]]";
1201 }
1202 out << ";\n";
1203 }
1204 out << " };\n";
1205 }
1206 {
1207 /* Constructor parameters. */
1208 auto &out = generated.wrapper_constructor_parameters;
1209 out << Sep() << mem_scope << in_class_local << " &mtl_subpass_in";
1210 }
1211 {
1212 /* Constructor assignments. */
1213 auto &out = generated.wrapper_constructor_assign;
1214 for (const ShaderCreateInfo::SubpassIn &input : info.subpass_inputs_) {
1215 out << Sep() << input.name << "(mtl_subpass_in." << input.name << ")";
1216 }
1217 }
1218 {
1219 /* Constructor arguments. */
1220 auto &out = generated.wrapper_instance_init;
1221 out << Sep() << "mtl_subpass_in";
1222 }
1223 {
1224 /* Entry point arguments. */
1225 auto &out = generated.entry_point_parameters;
1226 out << Sep() << in_class << " mtl_subpass_in";
1227 }
1228}
1229
1230static void generate_fragment_out(GeneratedStreams &generated, const ShaderCreateInfo &info)
1231{
1232 constexpr ShaderStage stage = ShaderStage::FRAGMENT;
1233 StringRefNull out_class_local = get_stage_out_class_name(stage, info);
1234
1235 std::string builtins_decl = generate_fragment_builtins(generated, info);
1236
1237 if (info.fragment_outputs_.is_empty() && builtins_decl.empty()) {
1238 return;
1239 }
1240
1241 StringRefNull mem_scope = "thread ";
1242
1243 {
1244 auto &out = generated.wrapper_class_members;
1245
1246 /* References definition for global access. */
1248 out << " " << mem_scope << output.type << " &" << output.name << ";\n";
1249 }
1250
1251 /* Main Block Definition. */
1252 out << " struct " << out_class_local << " {\n";
1253 if (builtins_decl.empty() == false) {
1254 out << builtins_decl;
1255 }
1257 out << " " << output.type << " " << output.name;
1258 out << " [[color(" << output.index << ")]]";
1259 if (output.blend != DualBlend::NONE) {
1260 out << " [[index(" << ((output.blend == DualBlend::SRC_0) ? 0 : 1) << ")]]";
1261 }
1262 if (output.raster_order_group >= 0) {
1263 out << " [[raster_order_group(" << output.raster_order_group << ")]]";
1264 }
1265 out << ";\n";
1266 }
1267 out << " };\n";
1268 }
1269 {
1270 /* Constructor parameters. */
1271 auto &out = generated.wrapper_constructor_parameters;
1272 out << Sep() << mem_scope << out_class_local << " &mtl_frag_out";
1273 }
1274 {
1275 /* Constructor assignments. */
1276 auto &out = generated.wrapper_constructor_assign;
1278 out << Sep() << output.name << "(mtl_frag_out." << output.name << ")";
1279 }
1280 }
1281 {
1282 /* Constructor arguments. */
1283 auto &out = generated.wrapper_instance_init;
1284 out << Sep() << get_stage_out_instance_name(stage);
1285 }
1286}
1287
1289{
1290 generate_vertex_attributes(generated, info);
1291 generate_vertex_out(generated, info, ShaderStage::VERTEX);
1292}
1293
1295{
1296 generate_subpass_inputs(generated, info);
1298 generate_fragment_out(generated, info);
1299}
1300
1302 const ShaderStage stage,
1303 const ShaderCreateInfo &info)
1304{
1305 if (stage == ShaderStage::VERTEX) {
1306 generate_vertex_interface(generated, info);
1307 }
1308 else if (stage == ShaderStage::FRAGMENT) {
1309 generate_fragment_interface(generated, info);
1310 }
1311}
1312
1314 const StringRefNull wrapper_type,
1315 const StringRefNull wrapper_var,
1316 const StringRefNull native_type,
1317 const StringRefNull native_var)
1318{
1319 ss.wrapper_class_members << " const " << wrapper_type << " " << wrapper_var << ";\n";
1320 ss.wrapper_constructor_parameters << Sep() << "const thread " << wrapper_type << " &"
1321 << wrapper_var;
1322 ss.wrapper_constructor_assign << Sep() << wrapper_var << "(" << wrapper_var << ")";
1323 ss.entry_point_parameters << Sep() << native_type << " " << wrapper_var << " " << native_var;
1324 ss.wrapper_instance_init << Sep() << wrapper_type << "(" << wrapper_var << ")";
1325}
1326
1327static void generate_builtin(GeneratedStreams &generated,
1328 const StringRefNull wrapper_type,
1329 const StringRefNull wrapper_var,
1330 const StringRefNull native_var)
1331{
1332 generate_builtin(generated, wrapper_type, wrapper_var, wrapper_type, native_var);
1333}
1334
1336{
1337 generate_builtin(ss, "int", "gpu_InstanceIndex", "uint", "[[instance_id]]");
1338 generate_builtin(ss, "int", "gpu_BaseInstance", "uint", "[[base_instance]]");
1339 /* MSL matches Vulkan semantic of gpu_InstanceIndex.
1340 * Thus we have to emulate gl_InstanceID support. */
1341 {
1342 auto &out = ss.wrapper_class_members;
1343 out << " int gl_InstanceID;\n";
1344 }
1345 {
1347 out << Sep() << "gl_InstanceID(gpu_InstanceIndex - gpu_BaseInstance)";
1348 }
1349}
1350
1352 const ShaderStage stage,
1353 const ShaderCreateInfo &info)
1354{
1355 if (stage == ShaderStage::VERTEX) {
1356 if (flag_is_set(info.builtins_combined(), BuiltinBits::VERTEX_ID)) {
1357 generate_builtin(ss, "int", "gl_VertexID", "uint", "[[vertex_id]]");
1358 }
1359 if (flag_is_set(info.builtins_combined(), BuiltinBits::INSTANCE_ID)) {
1361 }
1362 }
1363 else if (stage == ShaderStage::FRAGMENT) {
1364 if (flag_is_set(info.builtins_combined(), BuiltinBits::FRONT_FACING)) {
1365 generate_builtin(ss, "bool", "gl_FrontFacing", "[[front_facing]]");
1366 }
1367 if (flag_is_set(info.builtins_combined(), BuiltinBits::PRIMITIVE_ID)) {
1368 generate_builtin(ss, "int", "gl_PrimitiveID", "uint", "[[primitive_id]]");
1369 }
1370 if (flag_is_set(info.builtins_combined(), BuiltinBits::POINT_COORD)) {
1371 generate_builtin(ss, "float2", "gl_PointCoord", "[[point_coord]]");
1372 }
1373 if (flag_is_set(info.builtins_combined(), BuiltinBits::BARYCENTRIC_COORD)) {
1374 generate_builtin(ss, "float3", "gpu_BaryCoord", "[[barycentric_coord]]");
1375 }
1376 }
1377 else if (stage == ShaderStage::COMPUTE) {
1378 /* Compute shader global variables. */
1379 if (flag_is_set(info.builtins_combined(), BuiltinBits::GLOBAL_INVOCATION_ID)) {
1380 generate_builtin(ss, "uint3", "gl_GlobalInvocationID", "[[thread_position_in_grid]]");
1381 }
1382 if (flag_is_set(info.builtins_combined(), BuiltinBits::WORK_GROUP_ID)) {
1383 generate_builtin(ss, "uint3", "gl_WorkGroupID", "[[threadgroup_position_in_grid]]");
1384 }
1385 if (flag_is_set(info.builtins_combined(), BuiltinBits::NUM_WORK_GROUP)) {
1386 generate_builtin(ss, "uint3", "gl_NumWorkGroups", "[[threadgroups_per_grid]]");
1387 }
1388 if (flag_is_set(info.builtins_combined(), BuiltinBits::LOCAL_INVOCATION_INDEX)) {
1389 generate_builtin(ss, "uint", "gl_LocalInvocationIndex", "[[thread_index_in_threadgroup]]");
1390 }
1391 if (flag_is_set(info.builtins_combined(), BuiltinBits::LOCAL_INVOCATION_ID)) {
1392 generate_builtin(ss, "uint3", "gl_LocalInvocationID", "[[thread_position_in_threadgroup]]");
1393 }
1394 }
1395 ss.wrapper_class_members << "\n";
1396}
1397
1398std::pair<std::string, std::string> generate_entry_point(const ShaderCreateInfo &info,
1399 const ShaderStage stage,
1400 const StringRefNull entry_point_name)
1401{
1402 StringRefNull stage_out_class_name = get_stage_out_class_name(stage, info);
1403 StringRefNull stage_out_inst_name = get_stage_out_instance_name(stage);
1404 StringRefNull stage_class_name = get_stage_class_name(stage);
1405 StringRefNull stage_inst_name = get_stage_instance_name(stage);
1406 StringRefNull stage_type_name = get_stage_type(stage);
1407
1408 std::string stage_out_class = "void";
1409 if (stage_out_class_name != "void") {
1410 stage_out_class = stage_class_name + "::" + stage_out_class_name;
1411 }
1412
1413 GeneratedStreams generated;
1414 generate_builtins(generated, stage, info);
1415 generate_stage_interfaces(generated, stage, info);
1416 generate_resources(generated, stage, info);
1417
1418 std::stringstream prefix;
1419 /* Note: The shader log class expect a `#line 1 "filename"` For correct filename. */
1420 prefix << "#line 1 \"" __FILE__ "\"\n";
1421 prefix << LINE;
1422 prefix << generated.wrapper_class_prefix.str() << "\n\n";
1423 prefix << "struct " << stage_class_name << " {\n";
1424
1425 /* User generated code goes here. */
1426
1427 std::stringstream out;
1428 out << "\n";
1429 /* Undefine macros that can conflict with attributes. We still need to keep other user macros in
1430 * case they are used inside resources declaration. */
1431 out << "#undef color\n";
1432 out << "#undef user\n";
1433 out << "#pragma blender dead_code_elimination off\n";
1434
1435 out << generated.wrapper_class_members.str();
1436 out << "\n";
1437 out << " " << stage_class_name << "(";
1438 out << generated.wrapper_constructor_parameters.str() << "\n";
1439 out << " ) " << (generated.wrapper_constructor_assign.is_first_arg ? "" : ":");
1440 out << generated.wrapper_constructor_assign.str();
1441 out << " {}\n";
1442 out << "};\n\n";
1443
1444 /* Entry point attribute. */
1445 if (info.early_fragment_test_ && stage == ShaderStage::FRAGMENT) {
1446 out << LINE << "[[early_fragment_tests]]";
1447 }
1448
1449 /* Entry point signature. */
1450 out << LINE << stage_type_name << " " << stage_out_class << " " << entry_point_name;
1451
1452 out << LINE;
1453 out << "(";
1454 out << generated.entry_point_parameters.str() << "\n";
1455 out << ")\n";
1456
1457 /* Entry point body. */
1458 out << "{\n";
1459 {
1460 if (stage_out_class != "void") {
1461 out << LINE;
1462 out << " " << stage_out_class << " " << stage_out_inst_name << ";";
1463 }
1464
1465 out << LINE;
1466 out << generated.entry_point_start.str();
1467
1468 out << LINE;
1469 out << " " << stage_class_name << " " << stage_inst_name;
1470 out << " {";
1471 out << generated.wrapper_instance_init.str() << "\n";
1472 out << " };\n\n";
1473
1474 out << LINE;
1475 out << " " << stage_inst_name << ".main();\n";
1476
1477 if (stage == ShaderStage::VERTEX) {
1478 /* For historical reasons vertex shader output is expected to be in OpenGL NDC coordinates:
1479 * Z in [-1..+1] and Y up. */
1480 std::string pos = stage_out_inst_name + ".gl_Position";
1481 /* Flip Y. */
1482 out << LINE << " " << pos << ".y = -" << pos << ".y;\n";
1483 /* Remap Z from [-1..+1] to [0..1]. */
1484 out << LINE << " " << pos << ".z = (" << pos << ".z + " << pos << ".w) / 2.0;\n";
1485 }
1486
1487 if (stage_out_class != "void") {
1488 out << LINE << " return " << stage_out_inst_name << ";\n";
1489 }
1490 }
1491 out << "}\n";
1492
1493 return {prefix.str(), out.str()};
1494}
1495
1496/* Return available buffer slots for vertex buffer bindings. */
1498{
1499 uint32_t free_slots = ~((~0u) << 31u);
1500
1501 auto occupy_slot = [&](const ShaderCreateInfo::Resource &res) {
1502 switch (res.bind_type) {
1504 free_slots &= ~(1u << (MTL_UBO_SLOT_OFFSET + res.slot));
1505 break;
1507 free_slots &= ~(1u << (MTL_SSBO_SLOT_OFFSET + res.slot));
1508 break;
1511 break;
1513 free_slots &= ~(1u << (MTL_ACCELERATION_STRUCTURE_SLOT + res.slot));
1514 break;
1515 };
1516 };
1517
1518 for (const ShaderCreateInfo::Resource &res : info.pass_resources_) {
1519 occupy_slot(res);
1520 }
1521 for (const ShaderCreateInfo::Resource &res : info.batch_resources_) {
1522 occupy_slot(res);
1523 }
1524 for (const ShaderCreateInfo::Resource &res : info.geometry_resources_) {
1525 occupy_slot(res);
1526 }
1527
1528 if (info.push_constants_.is_empty() == false) {
1529 free_slots &= ~(1u << MTL_PUSH_CONSTANT_BUFFER_SLOT);
1530 }
1531
1532 if (flag_is_set(info.builtins_combined(), BuiltinBits::USE_SAMPLER_ARG_BUFFER)) {
1533 free_slots &= ~(1u << MTL_SAMPLER_ARGUMENT_BUFFER_SLOT);
1534 }
1535
1536 return free_slots;
1537}
1538
1539void patch_create_info_atomic_workaround(std::unique_ptr<PatchedShaderCreateInfo> &patched_info,
1540 const shader::ShaderCreateInfo &original_info)
1541{
1542 uint32_t free_slots = 0;
1543 auto ensure_atomic_workaround = [&](ImageType type, StringRefNull name) {
1544 if (!ELEM(type,
1545 ImageType::AtomicUint2D,
1546 ImageType::AtomicUint2DArray,
1547 ImageType::AtomicUint3D,
1548 ImageType::AtomicInt2D,
1549 ImageType::AtomicInt2DArray,
1550 ImageType::AtomicInt3D))
1551 {
1552 return;
1553 }
1554
1555 if (patched_info == nullptr) {
1556 patched_info = std::make_unique<PatchedShaderCreateInfo>(original_info);
1557 free_slots = available_buffer_slots(original_info);
1558 }
1559 int slot = bitscan_forward_clear_uint(&free_slots);
1560 patched_info->names.append(std::make_unique<std::string>(name + "_buf_[]"));
1561 patched_info->info.storage_buf(
1562 slot, Qualifier::read_write, to_component_type(type), *patched_info->names.last());
1563 patched_info->names.append(std::make_unique<std::string>(name + "_metadata_"));
1564 patched_info->info.push_constant(Type::uint4_t, *patched_info->names.last());
1565 };
1566
1567 auto ensure_atomic_workaround_resource = [&](const ShaderCreateInfo::Resource &res) {
1568 switch (res.bind_type) {
1570 ensure_atomic_workaround(res.sampler.type, res.sampler.name);
1571 break;
1573 ensure_atomic_workaround(res.image.type, res.image.name);
1574 break;
1578 break;
1579 }
1580 };
1581
1582 for (const ShaderCreateInfo::Resource &res : original_info.pass_resources_) {
1583 ensure_atomic_workaround_resource(res);
1584 }
1585 for (const ShaderCreateInfo::Resource &res : original_info.batch_resources_) {
1586 ensure_atomic_workaround_resource(res);
1587 }
1588 for (const ShaderCreateInfo::Resource &res : original_info.geometry_resources_) {
1589 ensure_atomic_workaround_resource(res);
1590 }
1591}
1592
1593} // namespace gpu
1594} // namespace blender
#define BLI_assert_unreachable()
#define ELEM(...)
#define output
constexpr IndexRange()=default
bool contains(const Key &key) const
Definition BLI_set.hh:310
constexpr bool is_empty() const
Definition BLI_span.hh:264
constexpr bool is_empty() const
static MTLCapabilities & get_capabilities()
#define str(s)
#define attribute(slot)
ccl_device_inline float interp(const float a, const float b, const float t)
Definition math_base.h:549
ccl_device_inline int4 cast(const float4 a)
Definition math_float4.h:32
#define LINE
#define MTL_SAMPLER_ARGUMENT_BUFFER_SLOT
#define MTL_ACCELERATION_STRUCTURE_SLOT
#define MTL_PUSH_CONSTANT_BUFFER_SLOT
#define MTL_UBO_SLOT_OFFSET
#define MTL_IMAGE_SLOT_OFFSET
#define MTL_SAMPLER_SLOT_OFFSET
#define MTL_SSBO_SLOT_OFFSET
#define MTL_SPECIALIZATION_CONSTANT_OFFSET
static void generate_vertex_out(GeneratedStreams &generated, const ShaderCreateInfo &info, const ShaderStage stage)
std::string ptr_type(const ResourceString &str)
static const char * get_stage_class_name(ShaderStage stage)
static void generate_acceleration_structure(GeneratedStreams &generated, StringRefNull name, int slot)
const char * to_string(ShaderStage stage)
Definition mtl_shader.mm:52
static void generate_fragment_interface(GeneratedStreams &generated, const ShaderCreateInfo &info)
std::pair< std::string, std::string > generate_entry_point(const ShaderCreateInfo &info, const ShaderStage stage, const StringRefNull entry_point_name)
static StringRefNull to_raw_type(ImageType type)
static void generate_resource(GeneratedStreams &generated, const ShaderCreateInfo::Resource &res, const ShaderStage stage, const ShaderCreateInfo &, const bool use_sampler_argument_buffer)
static void generate_buffer(GeneratedStreams &generated, const bool writeable, std::string type, ResourceString name, int slot, const ShaderStage stage)
static void generate_texture(GeneratedStreams &generated, bool is_sampler, shader::Qualifier qualifier, const shader::ImageType type, ResourceString name, int slot, const ShaderStage stage, const bool use_sampler_argument_buffer=false)
static void generate_builtins(GeneratedStreams &ss, const ShaderStage stage, const ShaderCreateInfo &info)
static const char * get_stage_instance_name(ShaderStage stage)
static bool is_builtin_type(StringRefNull type)
static void generate_instance_id(GeneratedStreams &ss)
static void generate_vertex_interface(GeneratedStreams &generated, const ShaderCreateInfo &info)
static void generate_raster_builtin(GeneratedStreams &ss, std::stringstream &declaration, const StringRefNull type, const StringRefNull var, const StringRefNull attribute, const StringRefNull array="", const bool is_const=false)
static std::string generate_raster_builtins(GeneratedStreams &ss, const ShaderCreateInfo &info, const ShaderStage stage)
StringRefNull to_access(const bool is_sampler, const shader::Qualifier qualifier)
static void generate_specialization_constant(GeneratedStreams &generated, const SpecializationConstant &constant, int index)
static const char * get_stage_out_instance_name(ShaderStage stage)
static void generate_stage_interfaces(GeneratedStreams &generated, const ShaderStage stage, const ShaderCreateInfo &info)
StringRefNull to_wrapper_type(ImageType type)
static void generate_sampler_argument_buffer(GeneratedStreams &generated, int sampler_count)
static std::string generate_fragment_builtins(GeneratedStreams &ss, const ShaderCreateInfo &info)
static void generate_builtin(GeneratedStreams &ss, const StringRefNull wrapper_type, const StringRefNull wrapper_var, const StringRefNull native_type, const StringRefNull native_var)
static StringRefNull to_component_type(ImageType type)
static void generate_fragment_out(GeneratedStreams &generated, const ShaderCreateInfo &info)
std::string ref_type(const ResourceString &str, const std::string &attribute="")
static void generate_inout(std::stringstream &out, StringRefNull iface_name, const StageInterfaceInfo::InOut &inout)
static void generate_compilation_constant(GeneratedStreams &generated, const CompilationConstant &constant)
static void generate_vertex_attributes(GeneratedStreams &generated, const ShaderCreateInfo &info)
static void generate_fragment_builtin(GeneratedStreams &ss, std::stringstream &declaration, const StringRefNull type, const StringRefNull var, const StringRefNull native_type, const StringRefNull attribute, const bool is_const=false)
static const char * get_stage_in_instance_name(ShaderStage stage)
static void generate_uniforms(GeneratedStreams &generated, Span< ShaderCreateInfo::PushConst > uniforms, const ShaderStage stage)
static const char * get_stage_in_class_name(ShaderStage stage)
static const char * get_stage_type(ShaderStage stage)
static const char * get_stage_out_class_name(ShaderStage stage, const ShaderCreateInfo &info)
static void generate_subpass_inputs(GeneratedStreams &generated, const ShaderCreateInfo &info)
void patch_create_info_atomic_workaround(std::unique_ptr< PatchedShaderCreateInfo > &patched_info, const shader::ShaderCreateInfo &original_info)
uint32_t available_buffer_slots(const ShaderCreateInfo &info)
void generate_resources(GeneratedStreams &generated, const ShaderStage stage, const ShaderCreateInfo &info)
std::string wrap_type(StringRefNull type_name, const ShaderStage stage)
static void generate_shared_variable(GeneratedStreams &generated, const ShaderCreateInfo::SharedVariable &sv)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
MINLINE unsigned int bitscan_forward_clear_uint(unsigned int *a)
unsigned int uint32_t
Definition BKE_text.h:81
std::stringstream & operator<<(Separator)
Describe inputs & outputs, stage interfaces, resources and sources of a shader. If all data is correc...
Vector< SpecializationConstant, 0 > specialization_constants_
Vector< CompilationConstant, 0 > compilation_constants_
Vector< StageInterfaceInfoHandle, 0 > vertex_out_interfaces_