7#ifdef MAYAFLUX_USE_SHADERC
8#include <shaderc/shaderc.hpp>
11#ifdef MAYAFLUX_USE_SPIRV_REFLECT
12#include <spirv_reflect.h>
18 std::vector<std::string> get_shader_search_paths()
21 SHADER_BUILD_OUTPUT_DIR,
29 std::string resolve_shader_path(
const std::string& filename)
31 namespace fs = std::filesystem;
33 if (fs::path(filename).is_absolute() || fs::exists(filename)) {
37 for (
const auto& search_path : get_shader_search_paths()) {
38 fs::path full_path = fs::path(search_path) / filename;
39 if (fs::exists(full_path)) {
41 "Resolved shader '{}' -> '{}'", filename, full_path.string());
42 return full_path.string();
58 "VKShaderModule destroyed without cleanup() - potential leak");
63 : m_module(other.m_module)
64 , m_stage(other.m_stage)
65 , m_entry_point(std::move(other.m_entry_point))
66 , m_reflection(std::move(other.m_reflection))
67 , m_spirv_code(std::move(other.m_spirv_code))
68 , m_preserve_spirv(other.m_preserve_spirv)
69 , m_specialization_map(std::move(other.m_specialization_map))
70 , m_specialization_entries(std::move(other.m_specialization_entries))
71 , m_specialization_data(std::move(other.m_specialization_data))
72 , m_specialization_info(other.m_specialization_info)
74 other.m_module =
nullptr;
82 "VKShaderModule move-assigned without cleanup() - potential leak");
85 m_module = other.m_module;
86 m_stage = other.m_stage;
87 m_entry_point = std::move(other.m_entry_point);
88 m_reflection = std::move(other.m_reflection);
89 m_spirv_code = std::move(other.m_spirv_code);
90 m_preserve_spirv = other.m_preserve_spirv;
91 m_specialization_map = std::move(other.m_specialization_map);
92 m_specialization_entries = std::move(other.m_specialization_entries);
93 m_specialization_data = std::move(other.m_specialization_data);
94 m_specialization_info = other.m_specialization_info;
96 other.m_module =
nullptr;
104 device.destroyShaderModule(
m_module);
108 "Shader module cleaned up ({} stage)", vk::to_string(
m_stage));
124 const std::vector<uint32_t>& spirv_code,
125 vk::ShaderStageFlagBits stage,
126 const std::string& entry_point,
127 bool enable_reflection)
129 if (spirv_code.empty()) {
131 "Cannot create shader module from empty SPIR-V code");
142 if (spirv_code[0] != 0x07230203) {
144 "Invalid SPIR-V magic number: 0x{:08X} (expected 0x07230203)",
149 vk::ShaderModuleCreateInfo create_info;
150 create_info.codeSize = spirv_code.size() *
sizeof(uint32_t);
151 create_info.pCode = spirv_code.data();
154 m_module = device.createShaderModule(create_info);
155 }
catch (
const vk::SystemError& e) {
157 "Failed to create shader module: {}", e.what());
168 if (enable_reflection) {
171 "Shader reflection failed - descriptor layouts must be manually specified");
176 "Shader module created ({} stage, {} bytes SPIR-V, entry='{}')",
177 vk::to_string(stage), spirv_code.size() * 4, entry_point);
184 const std::string& spirv_path,
185 vk::ShaderStageFlagBits stage,
186 const std::string& entry_point,
187 bool enable_reflection)
189 std::string resolved_path = resolve_shader_path(spirv_path);
192 if (spirv_code.empty()) {
194 "Failed to read SPIR-V file: '{}'", spirv_path);
199 "Loaded SPIR-V from file: '{}'", spirv_path);
201 return create_from_spirv(device, spirv_code, stage, entry_point, enable_reflection);
210 const std::string& glsl_source,
211 vk::ShaderStageFlagBits stage,
212 const std::string& entry_point,
213 bool enable_reflection,
214 const std::vector<std::string>& include_directories,
215 const std::unordered_map<std::string, std::string>& defines)
218 if (spirv_code.empty()) {
220 "Failed to compile GLSL to SPIR-V ({} stage)", vk::to_string(stage));
225 "Compiled GLSL to SPIR-V ({} stage, {} bytes)",
226 vk::to_string(stage), spirv_code.size() * 4);
228 return create_from_spirv(device, spirv_code, stage, entry_point, enable_reflection);
233 const std::string& glsl_path,
234 std::optional<vk::ShaderStageFlagBits> stage,
235 const std::string& entry_point,
236 bool enable_reflection,
237 const std::vector<std::string>& include_directories,
238 const std::unordered_map<std::string, std::string>& defines)
240 std::string resolved_path = resolve_shader_path(glsl_path);
242 if (!stage.has_value()) {
244 if (!stage.has_value()) {
246 "Cannot auto-detect shader stage from file extension: '{}'", glsl_path);
250 "Auto-detected {} stage from file extension", vk::to_string(*stage));
254 if (glsl_source.empty()) {
256 "Failed to read GLSL file: '{}'", glsl_path);
261 "Loaded GLSL from file: '{}' ({} bytes)", glsl_path, glsl_source.size());
264 enable_reflection, include_directories, defines);
275 "Cannot get stage create info from invalid shader module");
279 vk::PipelineShaderStageCreateInfo stage_info;
297 const std::unordered_map<uint32_t, uint32_t>& constants)
302 "Set {} specialization constants for {} stage",
303 constants.size(), vk::to_string(
m_stage));
323 vk::SpecializationMapEntry entry;
324 entry.constantID = constant_id;
325 entry.offset = offset;
326 entry.size =
sizeof(uint32_t);
330 offset +=
sizeof(uint32_t);
345#ifdef MAYAFLUX_USE_SPIRV_REFLECT
346 SpvReflectShaderModule
module;
347 SpvReflectResult result = spvReflectCreateShaderModule(
348 spirv_code.size() *
sizeof(uint32_t),
352 if (result != SPV_REFLECT_RESULT_SUCCESS) {
354 "SPIRV-Reflect failed: {}",
static_cast<int>(result));
358 uint32_t binding_count = 0;
359 result = spvReflectEnumerateDescriptorBindings(&module, &binding_count,
nullptr);
360 if (result == SPV_REFLECT_RESULT_SUCCESS && binding_count > 0) {
361 std::vector<SpvReflectDescriptorBinding*> bindings(binding_count);
362 spvReflectEnumerateDescriptorBindings(&module, &binding_count, bindings.data());
364 for (
const auto* binding : bindings) {
366 desc.
set = binding->set;
367 desc.
binding = binding->binding;
368 desc.
type =
static_cast<vk::DescriptorType
>(binding->descriptor_type);
370 desc.
count = binding->count;
371 desc.
name = binding->name ? binding->name :
"";
377 "Reflected {} descriptor bindings", binding_count);
380 uint32_t push_constant_count = 0;
381 result = spvReflectEnumeratePushConstantBlocks(&module, &push_constant_count,
nullptr);
382 if (result == SPV_REFLECT_RESULT_SUCCESS && push_constant_count > 0) {
383 std::vector<SpvReflectBlockVariable*> push_constants(push_constant_count);
384 spvReflectEnumeratePushConstantBlocks(&module, &push_constant_count, push_constants.data());
386 for (
const auto* block : push_constants) {
389 range.
offset = block->offset;
390 range.
size = block->size;
396 "Reflected {} push constant blocks", push_constant_count);
399 if (
m_stage == vk::ShaderStageFlagBits::eCompute) {
401 module.entry_points[0].local_size.x,
402 module.entry_points[0].local_size.y,
403 module.entry_points[0].local_size.z
407 "Compute shader workgroup size: [{}, {}, {}]",
413 spvReflectDestroyShaderModule(&module);
418 "SPIRV-Reflect not available - shader reflection disabled");
420 if (
m_stage == vk::ShaderStageFlagBits::eCompute) {
423 for (
size_t i = 0; i < spirv_code.size() - 4; ++i) {
424 if ((spirv_code[i] & 0xFFFF) == 17) {
425 uint32_t mode = spirv_code[i + 2];
434 "Extracted compute workgroup size: [{}, {}, {}]",
453 const std::string& filepath)
455 std::filesystem::path path(filepath);
456 std::string ext = path.extension().string();
458 std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
460 static const std::unordered_map<std::string, vk::ShaderStageFlagBits> extension_map = {
461 {
".comp", vk::ShaderStageFlagBits::eCompute },
462 {
".vert", vk::ShaderStageFlagBits::eVertex },
463 {
".frag", vk::ShaderStageFlagBits::eFragment },
464 {
".geom", vk::ShaderStageFlagBits::eGeometry },
465 {
".tesc", vk::ShaderStageFlagBits::eTessellationControl },
466 {
".tese", vk::ShaderStageFlagBits::eTessellationEvaluation },
467 {
".rgen", vk::ShaderStageFlagBits::eRaygenKHR },
468 {
".rint", vk::ShaderStageFlagBits::eIntersectionKHR },
469 {
".rahit", vk::ShaderStageFlagBits::eAnyHitKHR },
470 {
".rchit", vk::ShaderStageFlagBits::eClosestHitKHR },
471 {
".rmiss", vk::ShaderStageFlagBits::eMissKHR },
472 {
".rcall", vk::ShaderStageFlagBits::eCallableKHR },
473 {
".mesh", vk::ShaderStageFlagBits::eMeshEXT },
474 {
".task", vk::ShaderStageFlagBits::eTaskEXT }
477 auto it = extension_map.find(ext);
478 if (it != extension_map.end()) {
486 const std::string& glsl_source,
487 vk::ShaderStageFlagBits stage,
488 const std::vector<std::string>& include_directories,
489 const std::unordered_map<std::string, std::string>& defines)
491#ifdef MAYAFLUX_USE_SHADERC
492 shaderc::Compiler compiler;
493 shaderc::CompileOptions options;
495 options.SetOptimizationLevel(shaderc_optimization_level_performance);
497 for (
const auto& dir : include_directories) {
501 for (
const auto& [name, value] : defines) {
502 options.AddMacroDefinition(name, value);
505 shaderc_shader_kind shader_kind;
507 case vk::ShaderStageFlagBits::eVertex:
508 shader_kind = shaderc_glsl_vertex_shader;
510 case vk::ShaderStageFlagBits::eFragment:
511 shader_kind = shaderc_glsl_fragment_shader;
513 case vk::ShaderStageFlagBits::eCompute:
514 shader_kind = shaderc_glsl_compute_shader;
516 case vk::ShaderStageFlagBits::eGeometry:
517 shader_kind = shaderc_glsl_geometry_shader;
519 case vk::ShaderStageFlagBits::eTessellationControl:
520 shader_kind = shaderc_glsl_tess_control_shader;
522 case vk::ShaderStageFlagBits::eTessellationEvaluation:
523 shader_kind = shaderc_glsl_tess_evaluation_shader;
527 "Unsupported shader stage for GLSL compilation: {}", vk::to_string(stage));
531 shaderc::SpvCompilationResult result = compiler.CompileGlslToSpv(
537 if (result.GetCompilationStatus() != shaderc_compilation_status_success) {
539 "GLSL compilation failed:\n{}", result.GetErrorMessage());
543 std::vector<uint32_t> spirv(result.cbegin(), result.cend());
546 "Compiled GLSL ({} stage) -> {} bytes SPIR-V",
547 vk::to_string(stage), spirv.size() * 4);
553 "GLSL compilation requested but shaderc not available - use pre-compiled SPIR-V");
560 std::ifstream file(filepath, std::ios::binary | std::ios::ate);
561 if (!file.is_open()) {
563 "Failed to open SPIR-V file: '{}'", filepath);
567 size_t file_size =
static_cast<size_t>(file.tellg());
568 if (file_size == 0) {
570 "SPIR-V file is empty: '{}'", filepath);
574 if (file_size %
sizeof(uint32_t) != 0) {
576 "SPIR-V file size ({} bytes) is not multiple of 4: '{}'",
577 file_size, filepath);
581 std::vector<uint32_t> buffer(file_size /
sizeof(uint32_t));
583 file.read(
reinterpret_cast<char*
>(buffer.data()), file_size);
587 "Failed to read SPIR-V file: '{}'", filepath);
596 std::ifstream file(filepath);
597 if (!file.is_open()) {
599 "Failed to open file: '{}'", filepath);
604 (std::istreambuf_iterator<char>(file)),
605 std::istreambuf_iterator<char>());
607 if (content.empty()) {
609 "File is empty: '{}'", filepath);
618 case vk::ShaderStageFlagBits::eCompute:
620 case vk::ShaderStageFlagBits::eVertex:
622 case vk::ShaderStageFlagBits::eFragment:
624 case vk::ShaderStageFlagBits::eGeometry:
626 case vk::ShaderStageFlagBits::eTessellationControl:
628 case vk::ShaderStageFlagBits::eTessellationEvaluation:
632 "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.
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.
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.)
vk::ShaderStageFlags stage
Stage visibility.
uint32_t size
Size in bytes.
uint32_t offset
Offset in push constant block.
std::vector< DescriptorBinding > bindings
std::vector< PushConstantRange > push_constants
std::optional< std::array< uint32_t, 3 > > workgroup_size
local_size_x/y/z
Metadata extracted from shader module.