7#ifdef MAYAFLUX_USE_SHADERC
8#include <shaderc/shaderc.hpp>
11#include <spirv_cross/spirv_cross.hpp>
16 std::vector<std::string> get_shader_search_paths()
18 std::vector<std::string> paths {
19 SHADER_BUILD_OUTPUT_DIR,
29 if (std::string_view(SHADER_EXAMPLE_DIR).length() > 0) {
30 paths.emplace_back(SHADER_EXAMPLE_DIR);
33#ifdef MAYAFLUX_PROJECT_SHADER_DIR
34 paths.emplace_back(MAYAFLUX_PROJECT_SHADER_DIR);
40 std::string resolve_shader_path(
const std::string& filename)
42 namespace fs = std::filesystem;
44 if (fs::path(filename).is_absolute() || fs::exists(filename)) {
48 for (
const auto& search_path : get_shader_search_paths()) {
49 fs::path full_path = fs::path(search_path) / filename;
50 if (fs::exists(full_path)) {
52 "Resolved shader '{}' -> '{}'", filename, full_path.string());
53 return full_path.string();
60 vk::DescriptorType spirv_to_vk_descriptor_type(spirv_cross::SPIRType::BaseType base_type,
61 const spirv_cross::SPIRType& type,
64 if (type.image.dim != spv::DimMax) {
65 if (type.image.sampled == 2) {
66 return vk::DescriptorType::eStorageImage;
69 if (type.image.sampled == 1) {
70 return is_storage ? vk::DescriptorType::eSampledImage
71 : vk::DescriptorType::eCombinedImageSampler;
76 return vk::DescriptorType::eStorageBuffer;
79 return vk::DescriptorType::eUniformBuffer;
91 "VKShaderModule destroyed without cleanup() - potential leak");
96 : m_module(other.m_module)
97 , m_stage(other.m_stage)
98 , m_entry_point(std::move(other.m_entry_point))
99 , m_reflection(std::move(other.m_reflection))
100 , m_spirv_code(std::move(other.m_spirv_code))
101 , m_preserve_spirv(other.m_preserve_spirv)
102 , m_specialization_map(std::move(other.m_specialization_map))
103 , m_specialization_entries(std::move(other.m_specialization_entries))
104 , m_specialization_data(std::move(other.m_specialization_data))
105 , m_specialization_info(other.m_specialization_info)
107 other.m_module =
nullptr;
112 if (
this != &other) {
115 "VKShaderModule move-assigned without cleanup() - potential leak");
118 m_module = other.m_module;
119 m_stage = other.m_stage;
120 m_entry_point = std::move(other.m_entry_point);
121 m_reflection = std::move(other.m_reflection);
122 m_spirv_code = std::move(other.m_spirv_code);
123 m_preserve_spirv = other.m_preserve_spirv;
124 m_specialization_map = std::move(other.m_specialization_map);
125 m_specialization_entries = std::move(other.m_specialization_entries);
126 m_specialization_data = std::move(other.m_specialization_data);
127 m_specialization_info = other.m_specialization_info;
129 other.m_module =
nullptr;
137 device.destroyShaderModule(
m_module);
141 "Shader module cleaned up ({} stage)", vk::to_string(
m_stage));
157 const std::vector<uint32_t>& spirv_code,
158 vk::ShaderStageFlagBits stage,
159 const std::string& entry_point,
160 bool enable_reflection)
162 if (spirv_code.empty()) {
164 "Cannot create shader module from empty SPIR-V code");
168 if (spirv_code[0] != 0x07230203) {
170 "Invalid SPIR-V magic number: 0x{:08X} (expected 0x07230203)",
175 vk::ShaderModuleCreateInfo create_info;
176 create_info.codeSize = spirv_code.size() *
sizeof(uint32_t);
177 create_info.pCode = spirv_code.data();
180 m_module = device.createShaderModule(create_info);
181 }
catch (
const vk::SystemError& e) {
183 "Failed to create shader module: {}", e.what());
194 if (enable_reflection) {
197 "Shader reflection failed - descriptor layouts must be manually specified");
202 "Shader module created ({} stage, {} bytes SPIR-V, entry='{}')",
203 vk::to_string(stage), spirv_code.size() * 4, entry_point);
210 const std::string& spirv_path,
211 vk::ShaderStageFlagBits stage,
212 const std::string& entry_point,
213 bool enable_reflection)
215 std::string resolved_path = resolve_shader_path(spirv_path);
218 if (spirv_code.empty()) {
220 "Failed to read SPIR-V file: '{}'", spirv_path);
225 "Loaded SPIR-V from file: '{}'", spirv_path);
227 return create_from_spirv(device, spirv_code, stage, entry_point, enable_reflection);
236 const std::string& glsl_source,
237 vk::ShaderStageFlagBits stage,
238 const std::string& entry_point,
239 bool enable_reflection,
240 const std::vector<std::string>& include_directories,
241 const std::unordered_map<std::string, std::string>& defines)
244 if (spirv_code.empty()) {
246 "Failed to compile GLSL to SPIR-V ({} stage)", vk::to_string(stage));
251 "Compiled GLSL to SPIR-V ({} stage, {} bytes)",
252 vk::to_string(stage), spirv_code.size() * 4);
254 return create_from_spirv(device, spirv_code, stage, entry_point, enable_reflection);
259 const std::string& glsl_path,
260 std::optional<vk::ShaderStageFlagBits> stage,
261 const std::string& entry_point,
262 bool enable_reflection,
263 const std::vector<std::string>& include_directories,
264 const std::unordered_map<std::string, std::string>& defines)
266 std::string resolved_path = resolve_shader_path(glsl_path);
268 if (!stage.has_value()) {
270 if (!stage.has_value()) {
272 "Cannot auto-detect shader stage from file extension: '{}'", glsl_path);
276 "Auto-detected {} stage from file extension", vk::to_string(*stage));
280 if (glsl_source.empty()) {
282 "Failed to read GLSL file: '{}'", glsl_path);
287 "Loaded GLSL from file: '{}' ({} bytes)", glsl_path, glsl_source.size());
290 enable_reflection, include_directories, defines);
301 "Cannot get stage create info from invalid shader module");
305 vk::PipelineShaderStageCreateInfo stage_info;
323 const std::unordered_map<uint32_t, uint32_t>& constants)
328 "Set {} specialization constants for {} stage",
329 constants.size(), vk::to_string(
m_stage));
349 vk::SpecializationMapEntry entry;
350 entry.constantID = constant_id;
351 entry.offset = offset;
352 entry.size =
sizeof(uint32_t);
356 offset +=
sizeof(uint32_t);
372 spirv_cross::Compiler compiler(spirv_code);
373 spirv_cross::ShaderResources resources = compiler.get_shader_resources();
375 auto reflect_resources = [&](
const spirv_cross::SmallVector<spirv_cross::Resource>& res_vec,
376 bool is_storage =
false) {
377 for (
const auto& resource : res_vec) {
379 desc.
set = compiler.get_decoration(resource.id, spv::DecorationDescriptorSet);
380 desc.
binding = compiler.get_decoration(resource.id, spv::DecorationBinding);
382 desc.
name = resource.name;
384 const auto& type = compiler.get_type(resource.type_id);
385 desc.
count = type.array.empty() ? 1 : type.array[0];
386 desc.
type = spirv_to_vk_descriptor_type(type.basetype, type, is_storage);
392 reflect_resources(resources.uniform_buffers,
false);
394 reflect_resources(resources.storage_buffers,
true);
396 reflect_resources(resources.sampled_images,
false);
398 reflect_resources(resources.storage_images,
true);
400 reflect_resources(resources.separate_images,
false);
401 reflect_resources(resources.separate_samplers,
false);
408 for (
const auto& pc_buffer : resources.push_constant_buffers) {
409 const auto& type = compiler.get_type(pc_buffer.type_id);
414 range.size =
static_cast<uint32_t
>(compiler.get_declared_struct_size(type));
424 auto spec_constants = compiler.get_specialization_constants();
425 for (
const auto& spec : spec_constants) {
428 sc.
name = compiler.get_name(spec.id);
430 const auto& type = compiler.get_type(compiler.get_constant(spec.id).constant_type);
431 sc.
size =
static_cast<uint32_t
>(compiler.get_declared_struct_size(type));
438 "Reflected {} specialization constants",
442 if (
m_stage == vk::ShaderStageFlagBits::eCompute
443 ||
m_stage == vk::ShaderStageFlagBits::eMeshEXT
444 ||
m_stage == vk::ShaderStageFlagBits::eTaskEXT) {
445 auto entry_points = compiler.get_entry_points_and_stages();
447 for (
const auto& ep : entry_points) {
448 if (ep.name ==
m_entry_point && ep.execution_model == spv::ExecutionModelGLCompute) {
450 std::array<uint32_t, 3> workgroup_size {
451 compiler.get_execution_mode_argument(spv::ExecutionModeLocalSize, 0),
452 compiler.get_execution_mode_argument(spv::ExecutionModeLocalSize, 1),
453 compiler.get_execution_mode_argument(spv::ExecutionModeLocalSize, 2)
456 if (!workgroup_size.empty() && workgroup_size.size() >= 3) {
464 "Compute shader workgroup size: [{}, {}, {}]",
465 workgroup_size[0], workgroup_size[1], workgroup_size[2]);
472 if (
m_stage == vk::ShaderStageFlagBits::eVertex) {
473 for (
const auto& input : resources.stage_inputs) {
474 uint32_t location = compiler.get_decoration(input.id, spv::DecorationLocation);
475 const auto& type = compiler.get_type(input.type_id);
477 vk::VertexInputAttributeDescription attr;
478 attr.location = location;
488 "Reflected {} vertex input attributes",
495 }
catch (
const spirv_cross::CompilerError& e) {
497 "SPIRV-Cross reflection failed: {}", e.what());
504 using BaseType = spirv_cross::SPIRType::BaseType;
506 if (type.columns > 1) {
508 "Matrix types are not valid vertex attributes (columns={})",
510 return vk::Format::eUndefined;
513 if (type.width != 32) {
515 "Unsupported SPIR-V vertex attribute width {} (only 32-bit supported)",
517 return vk::Format::eUndefined;
520 const uint32_t vec_size = type.vecsize;
521 if (type.basetype == BaseType::Float) {
524 return vk::Format::eR32Sfloat;
526 return vk::Format::eR32G32Sfloat;
528 return vk::Format::eR32G32B32Sfloat;
530 return vk::Format::eR32G32B32A32Sfloat;
532 }
else if (type.basetype == BaseType::Int) {
535 return vk::Format::eR32Sint;
537 return vk::Format::eR32G32Sint;
539 return vk::Format::eR32G32B32Sint;
541 return vk::Format::eR32G32B32A32Sint;
543 }
else if (type.basetype == BaseType::UInt) {
546 return vk::Format::eR32Uint;
548 return vk::Format::eR32G32Uint;
550 return vk::Format::eR32G32B32Uint;
552 return vk::Format::eR32G32B32A32Uint;
557 "Unsupported SPIR-V vertex attribute type (basetype={}, vecsize={})",
558 static_cast<int>(type.basetype), vec_size);
560 return vk::Format::eUndefined;
568 const std::string& filepath)
570 std::filesystem::path path(filepath);
571 std::string ext = path.extension().string();
573 std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
575 static const std::unordered_map<std::string, vk::ShaderStageFlagBits> extension_map = {
576 {
".comp", vk::ShaderStageFlagBits::eCompute },
577 {
".vert", vk::ShaderStageFlagBits::eVertex },
578 {
".frag", vk::ShaderStageFlagBits::eFragment },
579 {
".geom", vk::ShaderStageFlagBits::eGeometry },
580 {
".tesc", vk::ShaderStageFlagBits::eTessellationControl },
581 {
".tese", vk::ShaderStageFlagBits::eTessellationEvaluation },
582 {
".rgen", vk::ShaderStageFlagBits::eRaygenKHR },
583 {
".rint", vk::ShaderStageFlagBits::eIntersectionKHR },
584 {
".rahit", vk::ShaderStageFlagBits::eAnyHitKHR },
585 {
".rchit", vk::ShaderStageFlagBits::eClosestHitKHR },
586 {
".rmiss", vk::ShaderStageFlagBits::eMissKHR },
587 {
".rcall", vk::ShaderStageFlagBits::eCallableKHR },
588 {
".mesh", vk::ShaderStageFlagBits::eMeshEXT },
589 {
".task", vk::ShaderStageFlagBits::eTaskEXT }
592 auto it = extension_map.find(ext);
593 if (it != extension_map.end()) {
601 const std::string& glsl_source,
602 vk::ShaderStageFlagBits stage,
603 const std::vector<std::string>& include_directories,
604 const std::unordered_map<std::string, std::string>& defines)
606#ifdef MAYAFLUX_USE_SHADERC
607 shaderc::Compiler compiler;
608 shaderc::CompileOptions options;
610 options.SetOptimizationLevel(shaderc_optimization_level_performance);
612 for (
const auto& dir : include_directories) {
616 for (
const auto& [name, value] : defines) {
617 options.AddMacroDefinition(name, value);
620 shaderc_shader_kind shader_kind;
622 case vk::ShaderStageFlagBits::eVertex:
623 shader_kind = shaderc_glsl_vertex_shader;
625 case vk::ShaderStageFlagBits::eFragment:
626 shader_kind = shaderc_glsl_fragment_shader;
628 case vk::ShaderStageFlagBits::eCompute:
629 shader_kind = shaderc_glsl_compute_shader;
631 case vk::ShaderStageFlagBits::eGeometry:
632 shader_kind = shaderc_glsl_geometry_shader;
634 case vk::ShaderStageFlagBits::eTessellationControl:
635 shader_kind = shaderc_glsl_tess_control_shader;
637 case vk::ShaderStageFlagBits::eTessellationEvaluation:
638 shader_kind = shaderc_glsl_tess_evaluation_shader;
640 case vk::ShaderStageFlagBits::eMeshEXT:
641 shader_kind = shaderc_glsl_mesh_shader;
643 case vk::ShaderStageFlagBits::eTaskEXT:
644 shader_kind = shaderc_glsl_task_shader;
648 "Unsupported shader stage for GLSL compilation: {}", vk::to_string(stage));
652 shaderc::SpvCompilationResult result = compiler.CompileGlslToSpv(
658 if (result.GetCompilationStatus() != shaderc_compilation_status_success) {
660 "GLSL compilation failed:\n{}", result.GetErrorMessage());
664 std::vector<uint32_t> spirv(result.cbegin(), result.cend());
667 "Compiled GLSL ({} stage) -> {} bytes SPIR-V",
668 vk::to_string(stage), spirv.size() * 4);
679 std::ifstream file(filepath, std::ios::binary | std::ios::ate);
680 if (!file.is_open()) {
682 "Failed to open SPIR-V file: '{}'", filepath);
686 size_t file_size =
static_cast<size_t>(file.tellg());
687 if (file_size == 0) {
689 "SPIR-V file is empty: '{}'", filepath);
693 if (file_size %
sizeof(uint32_t) != 0) {
695 "SPIR-V file size ({} bytes) is not multiple of 4: '{}'",
696 file_size, filepath);
700 std::vector<uint32_t> buffer(file_size /
sizeof(uint32_t));
702 file.read(
reinterpret_cast<char*
>(buffer.data()), file_size);
706 "Failed to read SPIR-V file: '{}'", filepath);
715 std::ifstream file(filepath);
716 if (!file.is_open()) {
718 "Failed to open file: '{}'", filepath);
723 (std::istreambuf_iterator<char>(file)),
724 std::istreambuf_iterator<char>());
726 if (content.empty()) {
728 "File is empty: '{}'", filepath);
734#ifndef MAYAFLUX_USE_SHADERC
736 bool is_command_available(
const std::string& command)
738#if defined(MAYAFLUX_PLATFORM_WINDOWS)
739 std::string check_cmd =
"where " + command +
" >nul 2>&1";
741 std::string check_cmd =
"command -v " + command +
" >/dev/null 2>&1";
743 return std::system(check_cmd.c_str()) == 0;
746 std::string get_null_device()
748#if defined(MAYAFLUX_PLATFORM_WINDOWS)
757 const std::string& glsl_source,
758 vk::ShaderStageFlagBits stage,
759 const std::vector<std::string>& include_directories,
760 const std::unordered_map<std::string, std::string>& defines)
762 namespace fs = std::filesystem;
764 if (!is_command_available(
"glslc")) {
766 "glslc compiler not found in PATH. Install Vulkan SDK or enable MAYAFLUX_USE_SHADERC");
770 fs::path temp_dir = fs::temp_directory_path();
771 fs::path glsl_temp = temp_dir /
"mayaflux_shader_temp.glsl";
772 fs::path spirv_temp = temp_dir /
"mayaflux_shader_temp.spv";
775 std::ofstream out(glsl_temp);
776 if (!out.is_open()) {
778 "Failed to create temporary GLSL file: '{}'", glsl_temp.string());
784 std::string stage_flag;
786 case vk::ShaderStageFlagBits::eVertex:
787 stage_flag =
"-fshader-stage=vertex";
789 case vk::ShaderStageFlagBits::eFragment:
790 stage_flag =
"-fshader-stage=fragment";
792 case vk::ShaderStageFlagBits::eCompute:
793 stage_flag =
"-fshader-stage=compute";
795 case vk::ShaderStageFlagBits::eGeometry:
796 stage_flag =
"-fshader-stage=geometry";
798 case vk::ShaderStageFlagBits::eTessellationControl:
799 stage_flag =
"-fshader-stage=tesscontrol";
801 case vk::ShaderStageFlagBits::eTessellationEvaluation:
802 stage_flag =
"-fshader-stage=tesseval";
804 case vk::ShaderStageFlagBits::eMeshEXT:
805 stage_flag =
"-fshader-stage=mesh";
807 case vk::ShaderStageFlagBits::eTaskEXT:
808 stage_flag =
"-fshader-stage=task";
812 "Unsupported shader stage for external compilation: {}", vk::to_string(stage));
813 fs::remove(glsl_temp);
817#if defined(MAYAFLUX_PLATFORM_WINDOWS)
818 std::string cmd =
"glslc " + stage_flag +
" \"" + glsl_temp.string() +
"\" -o \"" + spirv_temp.string() +
"\"";
820 std::string cmd =
"glslc " + stage_flag +
" '" + glsl_temp.string() +
"' -o '" + spirv_temp.string() +
"'";
823 for (
const auto& dir : include_directories) {
824#if defined(MAYAFLUX_PLATFORM_WINDOWS)
825 cmd +=
" -I\"" + dir +
"\"";
827 cmd +=
" -I'" + dir +
"'";
831 for (
const auto& [name, value] : defines) {
833 if (!value.empty()) {
838 std::string null_device = get_null_device();
841 "Invoking external glslc : {}", cmd);
843 int result = std::system(cmd.c_str());
845 fs::remove(glsl_temp);
849 "External glslc compilation failed (exit code: {})", result);
851 "Make sure Vulkan SDK is installed or enable MAYAFLUX_USE_SHADERC for runtime compilation");
852 fs::remove(spirv_temp);
858 fs::remove(spirv_temp);
860 if (!spirv_code.empty()) {
862 "Compiled GLSL ({} stage) via external glslc -> {} bytes SPIR-V",
863 vk::to_string(stage), spirv_code.size() * 4);
873 case vk::ShaderStageFlagBits::eCompute:
875 case vk::ShaderStageFlagBits::eVertex:
877 case vk::ShaderStageFlagBits::eFragment:
879 case vk::ShaderStageFlagBits::eGeometry:
881 case vk::ShaderStageFlagBits::eTessellationControl:
883 case vk::ShaderStageFlagBits::eTessellationEvaluation:
885 case vk::ShaderStageFlagBits::eMeshEXT:
887 case vk::ShaderStageFlagBits::eTaskEXT:
891 "Unknown shader stage: {}", vk::to_string(
m_stage));
#define MF_INFO(comp, ctx,...)
#define MF_ERROR(comp, ctx,...)
#define MF_WARN(comp, ctx,...)
#define MF_DEBUG(comp, ctx,...)
vk::SpecializationInfo m_specialization_info
bool create_from_glsl_file(vk::Device device, const std::string &glsl_path, std::optional< vk::ShaderStageFlagBits > stage=std::nullopt, const std::string &entry_point="main", bool enable_reflection=true, const std::vector< std::string > &include_directories={}, const std::unordered_map< std::string, std::string > &defines={})
Create shader module from GLSL file.
bool create_from_glsl(vk::Device device, const std::string &glsl_source, vk::ShaderStageFlagBits stage, const std::string &entry_point="main", bool enable_reflection=true, const std::vector< std::string > &include_directories={}, const std::unordered_map< std::string, std::string > &defines={})
Create shader module from GLSL source string.
static std::optional< vk::ShaderStageFlagBits > detect_stage_from_extension(const std::string &filepath)
Auto-detect shader stage from file extension.
bool reflect_spirv(const std::vector< uint32_t > &spirv_code)
Perform reflection on SPIR-V bytecode.
bool create_from_spirv(vk::Device device, const std::vector< uint32_t > &spirv_code, vk::ShaderStageFlagBits stage, const std::string &entry_point="main", bool enable_reflection=true)
Create shader module from SPIR-V binary.
vk::PipelineShaderStageCreateInfo get_stage_create_info() const
Get pipeline shader stage create info.
static std::vector< uint32_t > compile_glsl_to_spirv_external(const std::string &glsl_source, vk::ShaderStageFlagBits stage, const std::vector< std::string > &include_directories={}, const std::unordered_map< std::string, std::string > &defines={})
std::vector< vk::SpecializationMapEntry > m_specialization_entries
VKShaderModule & operator=(const VKShaderModule &)=delete
vk::ShaderStageFlagBits m_stage
bool create_from_spirv_file(vk::Device device, const std::string &spirv_path, vk::ShaderStageFlagBits stage, const std::string &entry_point="main", bool enable_reflection=true)
Create shader module from SPIR-V file.
void update_specialization_info()
Update specialization info from current map Called before get_stage_create_info() to ensure fresh dat...
std::vector< uint32_t > compile_glsl_to_spirv(const std::string &glsl_source, vk::ShaderStageFlagBits stage, const std::vector< std::string > &include_directories, const std::unordered_map< std::string, std::string > &defines)
Compile GLSL to SPIR-V using shaderc.
static std::string read_text_file(const std::string &filepath)
Read text file into string.
void set_specialization_constants(const std::unordered_map< uint32_t, uint32_t > &constants)
Set specialization constants.
ShaderReflection m_reflection
static std::vector< uint32_t > read_spirv_file(const std::string &filepath)
Read binary file into vector.
static vk::Format spirv_type_to_vk_format(const spirv_cross::SPIRType &type)
Convert SPIRV-Cross type to Vulkan vertex attribute format.
std::vector< uint32_t > m_specialization_data
vk::ShaderModule m_module
std::string m_entry_point
void cleanup(vk::Device device)
Cleanup shader module.
std::unordered_map< uint32_t, uint32_t > m_specialization_map
Stage get_stage_type() const
Get shader stage type.
std::vector< uint32_t > m_spirv_code
Preserved SPIR-V (if enabled)
Wrapper for Vulkan shader module with lifecycle and reflection.
@ GraphicsBackend
Graphics/visual rendering backend (Vulkan, OpenGL)
@ Core
Core engine, backend, subsystems.
std::string name
Variable name in shader.
vk::ShaderStageFlags stage
Stage visibility.
uint32_t set
Descriptor set index.
uint32_t count
Array size (1 for non-arrays)
uint32_t binding
Binding point within set.
vk::DescriptorType type
Type (uniform buffer, storage buffer, etc.)
uint32_t constant_id
Specialization constant ID.
std::string name
Variable name in shader.
uint32_t size
Size in bytes.
std::vector< SpecializationConstant > specialization_constants
std::vector< DescriptorBinding > bindings
std::vector< PushConstantRange > push_constants
std::vector< vk::VertexInputAttributeDescription > vertex_attributes
std::optional< std::array< uint32_t, 3 > > workgroup_size
local_size_x/y/z
Metadata extracted from shader module.