您可以使用glslang
C 接口 ( https://github.com/KhronosGroup/glslang/pull/2038 ) 将着色器源代码编译为 SPIR-V,如下所示。
const char* shaderCodeVertex = ...;
const glslang_input_t input =
{
.language = GLSLANG_SOURCE_GLSL,
.stage = GLSLANG_STAGE_VERTEX,
.client = GLSLANG_CLIENT_VULKAN,
.client_version = GLSLANG_TARGET_VULKAN_1_1,
.target_language = GLSLANG_TARGET_SPV,
.target_language_version = GLSLANG_TARGET_SPV_1_3,
.code = shaderCodeVertex,
.default_version = 100,
.default_profile = GLSLANG_NO_PROFILE,
.force_default_version_and_profile = false,
.forward_compatible = false,
.messages = GLSLANG_MSG_DEFAULT_BIT,
};
glslang_initialize_process();
glslang_shader_t* shader = glslang_shader_create( &input );
if ( !glslang_shader_preprocess(shader, &input) )
{
// use glslang_shader_get_info_log() and glslang_shader_get_info_debug_log()
}
if ( !glslang_shader_parse(shader, &input) )
{
// use glslang_shader_get_info_log() and glslang_shader_get_info_debug_log()
}
glslang_program_t* program = glslang_program_create();
glslang_program_add_shader( program, shader );
if (!glslang_program_link(program, GLSLANG_MSG_SPV_RULES_BIT | GLSLANG_MSG_VULKAN_RULES_BIT))
{
// use glslang_program_get_info_log() and glslang_program_get_info_debug_log();
}
glslang_program_SPIRV_generate( program, input.stage );
if ( glslang_program_SPIRV_get_messages(program) )
{
printf("%s", glslang_program_SPIRV_get_messages(program));
}
glslang_shader_delete( shader );
编译后的 SPIR-V blob 可以通过以下方式与 Vulkan 一起使用。
const VkShaderModuleCreateInfo ci =
{
.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
.codeSize = glslang_program_SPIRV_get_size(program) * sizeof(unsigned int),
.pCode = glslang_program_SPIRV_get_ptr(program)
};
VkResult result = vkCreateShaderModule(device, &ci, nullptr, ...);
glslang_program_delete( program );