### Install SPIRV-Cross using vcpkg Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md This sequence of commands demonstrates how to install SPIRV-Cross using the vcpkg package manager. It includes cloning the vcpkg repository, bootstrapping, integrating with your system, and finally installing the SPIRV-Cross port. ```bash git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg integrate install ./vcpkg install spirv-cross ``` -------------------------------- ### Install Pkg-Config File for Static Library Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Configures and installs the pkg-config file for the SPIRV-Cross C static library if installation is not skipped. ```cmake if (SPIRV_CROSS_STATIC) if (NOT SPIRV_CROSS_SKIP_INSTALL) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/pkg-config/spirv-cross-c.pc.in ${CMAKE_CURRENT_BINARY_DIR}/spirv-cross-c.pc @ONLY) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/spirv-cross-c.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) endif() spirv_cross_add_library(spirv-cross-core spirv_cross_core STATIC ${spirv-cross-core-sources}) if (SPIRV_CROSS_ENABLE_GLSL) spirv_cross_add_library(spirv-cross-glsl spirv_cross_glsl STATIC ${spirv-cross-glsl-sources}) target_link_libraries(spirv-cross-glsl PRIVATE spirv-cross-core) endif() if (SPIRV_CROSS_ENABLE_CPP) spirv_cross_add_library(spirv-cross-cpp spirv_cross_cpp STATIC ${spirv-cross-cpp-sources}) if (SPIRV_CROSS_ENABLE_GLSL) target_link_libraries(spirv-cross-cpp PRIVATE spirv-cross-glsl) else() message(FATAL_ERROR "Must enable GLSL support to enable C++ support.") ``` -------------------------------- ### Installation and Warning Options Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Controls installation targets and compiler warning behavior. SPIRV_CROSS_WERROR fails the build on warnings. ```cmake option(SPIRV_CROSS_SKIP_INSTALL "Skips installation targets." OFF) option(SPIRV_CROSS_WERROR "Fail build on warnings." OFF) option(SPIRV_CROSS_MISC_WARNINGS "Misc warnings useful for Travis runs." OFF) ``` -------------------------------- ### Get Help for Test Shaders Script Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Run this command to view the help message for the test_shaders.py script, which provides information on available options and usage. ```shell ./test_shaders.py --help ``` -------------------------------- ### Link SPIRV-Cross C API with pkg-config Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Use this command to get the necessary flags for linking against the SPIRV-Cross C API when installed as a system library on Unix-like systems. ```bash $ pkg-config spirv-cross-c-shared --libs --cflags -I/usr/local/include/spirv_cross -L/usr/local/lib -lspirv-cross-c-shared ``` -------------------------------- ### Project Definition and Testing Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines the project name and languages, and enables testing. This is a standard CMake setup. ```cmake project(SPIRV-Cross LANGUAGES CXX C) enable_testing() ``` -------------------------------- ### Compile SPIR-V to GLSL using C API Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Use the C API wrapper for C compatibility and stable ABI. Memory allocations are managed by `spvc_context`. This example shows parsing SPIR-V, creating a compiler, reflecting on uniform buffers, modifying compiler options, and compiling to GLSL. ```c #include const SpvId *spirv = get_spirv_data(); size_t word_count = get_spirv_word_count(); spvc_context context = NULL; spvc_parsed_ir ir = NULL; spvc_compiler compiler_glsl = NULL; spvc_compiler_options options = NULL; spvc_resources resources = NULL; const spvc_reflected_resource *list = NULL; const char *result = NULL; size_t count; size_t i; // Create context. spvc_context_create(&context); // Set debug callback. spvc_context_set_error_callback(context, error_callback, userdata); // Parse the SPIR-V. spvc_context_parse_spirv(context, spirv, word_count, &ir); // Hand it off to a compiler instance and give it ownership of the IR. spvc_context_create_compiler(context, SPVC_BACKEND_GLSL, ir, SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, &compiler_glsl); // Do some basic reflection. spvc_compiler_create_shader_resources(compiler_glsl, &resources); spvc_resources_get_resource_list_for_type(resources, SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, &list, &count); for (i = 0; i < count; i++) { printf("ID: %u, BaseTypeID: %u, TypeID: %u, Name: %s\n", list[i].id, list[i].base_type_id, list[i].type_id, list[i].name); printf(" Set: %u, Binding: %u\n", spvc_compiler_get_decoration(compiler_glsl, list[i].id, SpvDecorationDescriptorSet), spvc_compiler_get_decoration(compiler_glsl, list[i].id, SpvDecorationBinding)); } // Modify options. spvc_compiler_create_compiler_options(compiler_glsl, &options); spvc_compiler_options_set_uint(options, SPVC_COMPILER_OPTION_GLSL_VERSION, 330); spvc_compiler_options_set_bool(options, SPVC_COMPILER_OPTION_GLSL_ES, SPVC_FALSE); spvc_compiler_install_compiler_options(compiler_glsl, options); spvc_compiler_compile(compiler_glsl, &result); printf("Cross-compiled source: %s\n", result); // Frees all memory we allocated so far. spvc_context_destroy(context); ``` -------------------------------- ### Compile SPIR-V to GLSL using C++ API Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Use the C++ API for shader reflection and conversion. Link statically as the C++ API is not ABI-stable. This example demonstrates parsing SPIR-V, reflecting on shader resources, modifying decorations, setting compiler options, and compiling to GLSL. ```cpp #include "spirv_glsl.hpp" #include #include extern std::vector load_spirv_file(); int main() { // Read SPIR-V from disk or similar. std::vector spirv_binary = load_spirv_file(); spirv_cross::CompilerGLSL glsl(std::move(spirv_binary)); // The SPIR-V is now parsed, and we can perform reflection on it. spirv_cross::ShaderResources resources = glsl.get_shader_resources(); // Get all sampled images in the shader. for (auto &resource : resources.sampled_images) { unsigned set = glsl.get_decoration(resource.id, spv::DecorationDescriptorSet); unsigned binding = glsl.get_decoration(resource.id, spv::DecorationBinding); printf("Image %s at set = %u, binding = %u\n", resource.name.c_str(), set, binding); // Modify the decoration to prepare it for GLSL. glsl.unset_decoration(resource.id, spv::DecorationDescriptorSet); // Some arbitrary remapping if we want. glsl.set_decoration(resource.id, spv::DecorationBinding, set * 16 + binding); } // Set some options. spirv_cross::CompilerGLSL::Options options; options.version = 310; options.es = true; glsl.set_common_options(options); // Compile to GLSL, ready to give to GL driver. std::string source = glsl.compile(); } ``` -------------------------------- ### Find and Link SPIRV-Cross C API with CMake Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md This CMake script demonstrates how to find the installed SPIRV-Cross C API and link an executable against it. Ensure SPIRV-Cross is installed for this to work. ```cmake cmake_minimum_required(VERSION 3.5) set(CMAKE_C_STANDARD 99) project(Test LANGUAGES C) find_package(spirv_cross_c_shared) if (spirv_cross_c_shared_FOUND) message(STATUS "Found SPIRV-Cross C API! :)") else() message(STATUS "Could not find SPIRV-Cross C API! :(") endif() add_executable(test test.c) target_link_libraries(test spirv-cross-c-shared) ``` -------------------------------- ### SPIRV-Cross Test Suite Setup Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt This section configures the test suite for SPIRV-Cross. It checks for Python 3 and essential external tools like glslangValidator, spirv-as, spirv-val, and spirv-opt. If any are missing, testing is disabled with a descriptive message. ```cmake if (SPIRV_CROSS_ENABLE_TESTS) # Set up tests, using only the simplest modes of the test_shaders # script. You have to invoke the script manually to: # - Update the reference files # - Get cycle counts from malisc # - Keep failing outputs if (${CMAKE_VERSION} VERSION_GREATER "3.12") find_package(Python3) if (${PYTHON3_FOUND}) set(PYTHONINTERP_FOUND ON) set(PYTHON_VERSION_MAJOR 3) set(PYTHON_EXECUTABLE ${Python3_EXECUTABLE}) else() set(PYTHONINTERP_FOUND OFF) endif() else() find_package(PythonInterp) endif() find_program(spirv-cross-glslang NAMES glslangValidator PATHS ${CMAKE_CURRENT_SOURCE_DIR}/external/glslang-build/output/bin NO_DEFAULT_PATH) find_program(spirv-cross-spirv-as NAMES spirv-as PATHS ${CMAKE_CURRENT_SOURCE_DIR}/external/spirv-tools-build/output/bin NO_DEFAULT_PATH) find_program(spirv-cross-spirv-val NAMES spirv-val PATHS ${CMAKE_CURRENT_SOURCE_DIR}/external/spirv-tools-build/output/bin NO_DEFAULT_PATH) find_program(spirv-cross-spirv-opt NAMES spirv-opt PATHS ${CMAKE_CURRENT_SOURCE_DIR}/external/spirv-tools-build/output/bin NO_DEFAULT_PATH) if ((${spirv-cross-glslang} MATCHES "NOTFOUND") OR (${spirv-cross-spirv-as} MATCHES "NOTFOUND") OR (${spirv-cross-spirv-val} MATCHES "NOTFOUND") OR (${spirv-cross-spirv-opt} MATCHES "NOTFOUND")) set(SPIRV_CROSS_ENABLE_TESTS OFF) message("SPIRV-Cross: Testing will be disabled for SPIRV-Cross. Could not find glslang or SPIRV-Tools build under external/. To enable testing, run ./checkout_glslang_spirv_tools.sh and ./build_glslang_spirv_tools.sh first.") else() set(SPIRV_CROSS_ENABLE_TESTS ON) message("SPIRV-Cross: Found glslang and SPIRV-Tools. Enabling test suite.") message("SPIRV-Cross: Found glslangValidator in: ${spirv-cross-glslang}.") message("SPIRV-Cross: Found spirv-as in: ${spirv-cross-spirv-as}.") message("SPIRV-Cross: Found spirv-val in: ${spirv-cross-spirv-val}.") message("SPIRV-Cross: Found spirv-opt in: ${spirv-cross-spirv-opt}.") endif() set(spirv-cross-externals --glslang "${spirv-cross-glslang}" --spirv-as "${spirv-cross-spirv-as}" --spirv-opt "${spirv-cross-spirv-opt}" --spirv-val "${spirv-cross-spirv-val}") if (${PYTHONINTERP_FOUND} AND SPIRV_CROSS_ENABLE_TESTS) if (${PYTHON_VERSION_MAJOR} GREATER 2) add_executable(spirv-cross-c-api-test tests-other/c_api_test.c) target_link_libraries(spirv-cross-c-api-test spirv-cross-c) set_target_properties(spirv-cross-c-api-test PROPERTIES LINK_FLAGS "${spirv-cross-link-flags}") add_executable(spirv-cross-small-vector-test tests-other/small_vector.cpp) target_link_libraries(spirv-cross-small-vector-test spirv-cross-core) set_target_properties(spirv-cross-small-vector-test PROPERTIES LINK_FLAGS "${spirv-cross-link-flags}") add_executable(spirv-cross-msl-constexpr-test tests-other/msl_constexpr_test.cpp) target_link_libraries(spirv-cross-msl-constexpr-test spirv-cross-c) set_target_properties(spirv-cross-msl-constexpr-test PROPERTIES LINK_FLAGS "${spirv-cross-link-flags}") add_executable(spirv-cross-msl-resource-binding-test tests-other/msl_resource_bindings.cpp) target_link_libraries(spirv-cross-msl-resource-binding-test spirv-cross-c) set_target_properties(spirv-cross-msl-resource-binding-test PROPERTIES LINK_FLAGS "${spirv-cross-link-flags}") ``` -------------------------------- ### SPIR-V Array Declaration Example Source: https://github.com/khronosgroup/spirv-cross/wiki/Reflection-API-user-guide Illustrates how a C-style array declaration like 'int a[4][6]' is represented in pseudo-SPIR-V, showing the backward order of dimensions. ```spirv %int = OpTypeInt %int6 = OpTypeArray %int 6 %int4 = OpTypeArray %int6 4 ``` -------------------------------- ### Add Library Macro for CMake Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines a CMake macro to add a library, including setting include directories, properties, compile options, and definitions. It also handles installation rules and export configurations. ```cmake macro(spirv_cross_add_library name config_name library_type) add_library(${name} ${library_type} ${ARGN}) extract_headers(hdrs "${ARGN}") target_include_directories(${name} PUBLIC $ $) set_target_properties(${name} PROPERTIES PUBLIC_HEADERS "${hdrs}") if (SPIRV_CROSS_FORCE_PIC) set_target_properties(${name} PROPERTIES POSITION_INDEPENDENT_CODE ON) endif() target_compile_options(${name} PRIVATE ${spirv-compiler-options}) target_compile_definitions(${name} PRIVATE ${spirv-compiler-defines}) if (SPIRV_CROSS_NAMESPACE_OVERRIDE) if (${library_type} MATCHES "STATIC") target_compile_definitions(${name} PUBLIC SPIRV_CROSS_NAMESPACE_OVERRIDE=${SPIRV_CROSS_NAMESPACE_OVERRIDE}) else() target_compile_definitions(${name} PRIVATE SPIRV_CROSS_NAMESPACE_OVERRIDE=${SPIRV_CROSS_NAMESPACE_OVERRIDE}) endif() endif() if (SPIRV_CROSS_SPV_HEADER_NAMESPACE_OVERRIDE) if (${library_type} MATCHES "STATIC") target_compile_definitions(${name} PUBLIC SPIRV_CROSS_SPV_HEADER_NAMESPACE_OVERRIDE=${SPIRV_CROSS_SPV_HEADER_NAMESPACE_OVERRIDE}) else() target_compile_definitions(${name} PRIVATE SPIRV_CROSS_SPV_HEADER_NAMESPACE_OVERRIDE=${SPIRV_CROSS_SPV_HEADER_NAMESPACE_OVERRIDE}) endif() endif() if (NOT SPIRV_CROSS_SKIP_INSTALL) install(TARGETS ${name} EXPORT ${config_name}Config RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/spirv_cross) install(FILES ${hdrs} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/spirv_cross) install(EXPORT ${config_name}Config DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/${config_name}/cmake) export(TARGETS ${name} FILE ${config_name}Config.cmake) endif() endmacro() ``` -------------------------------- ### Analyze Mali Offline Compiler Cycle Counts Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Add the --malisc flag to ./test_shaders.py to obtain a CSV of static shader cycle counts before and after processing with spirv-cross. This requires the Mali Offline Compiler to be installed in the system's PATH. ```shell ./test_shaders.py --malisc ``` -------------------------------- ### Getting Direct Object Names Source: https://github.com/khronosgroup/spirv-cross/wiki/Reflection-API-user-guide Retrieve the direct name of an object using compiler.get_name() or the block name using compiler.get_name(resource.base_type_id). Useful for older versions or specific naming needs. ```cpp const string &uav_name = compiler.get_name(res.storage_buffers[0].id); const string &block_name = compiler.get_name(res.storage_buffers[0].base_type_id); ``` -------------------------------- ### Format All Source Files Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Use this script to automatically format all source files in the library according to the .clang-format style sheet. Run this command from the directory containing the script. ```shell ./format_all.sh ``` -------------------------------- ### Query and Set Shader Entry Points Source: https://github.com/khronosgroup/spirv-cross/wiki/Reflection-API-user-guide Retrieve a list of all entry points and their stages, and then set the active entry point for subsequent reflection operations. This is crucial when a shader has multiple entry points. ```cpp std::vector entry_points = comp.get_entry_points_and_stages(); // query comp.set_entry_point("MySpecialMain", spv::ExecutionModelFragment); // set ``` -------------------------------- ### Query Uniform Buffer Size Source: https://github.com/khronosgroup/spirv-cross/wiki/Reflection-API-user-guide Iterate through uniform buffers to get their declared struct size. This is useful for automatically crafting VkPushConstantRange structs. ```cpp for (const Resource &resource : res.uniform_buffers) { const SPIRType &type = comp.get_type(resource.base_type_id); size_t size = comp.get_declared_struct_size(type); print("UBO size: %zu\n", size); } ``` -------------------------------- ### Build Combined Image Samplers for GLSL Backends Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Before compiling to GLSL, call `Compiler::build_combined_image_samplers()` to create a mapping for image and sampler combinations. This is automatically handled by the command line client. ```c++ // From main.cpp // Builds a mapping for all combinations of images and samplers. compiler->build_combined_image_samplers(); // Give the remapped combined samplers new names. // Here you can also set up decorations if you want (binding = #N). for (auto &remap : compiler->get_combined_image_samplers()) { compiler->set_name(remap.combined_id, join("SPIRV_Cross_Combined", compiler->get_name(remap.image_id), compiler->get_name(remap.sampler_id))); } ``` -------------------------------- ### Create SPIRV-Cross Compiler Object Source: https://github.com/khronosgroup/spirv-cross/wiki/Reflection-API-user-guide Initialize the SPIRV-Cross compiler with SPIR-V bytecode. Ensure the SPIR-V data is loaded correctly before instantiation. ```cpp #include "spirv_cross.hpp" vector spirv = load_spirv_from_file(); spirv_cross::Compiler comp(move(spirv)); // const uint32_t *, size_t interface is also available. ``` -------------------------------- ### Run SPIRV-Cross Tests Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Execute the shader test suite to ensure no regressions. This requires glslang and SPIRV-Tools to be checked out and built. ```bash ./checkout_glslang_spirv_tools.sh ./build_glslang_spirv_tools.sh ./test_shaders.sh ``` -------------------------------- ### Perform Regression Testing Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Run this command to perform regression testing on shaders. The reference output is located in the reference/ directory. Use the --help flag for more options. ```shell ./test_shaders.py shaders ``` -------------------------------- ### Basic SPIRV-Cross C API Usage Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md A minimal C program demonstrating the creation and destruction of a SPIRV-Cross context. This serves as a basic integration test. ```c #include int main(void) { spvc_context context; spvc_context_create(&context); spvc_context_destroy(context); } ``` -------------------------------- ### Detect Git Version for Build Information Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Finds the Git executable and uses `git describe` to determine the build version. If Git is not found, it defaults to 'unknown'. ```cmake message(STATUS "SPIRV-Cross: Finding Git version for SPIRV-Cross.") set(spirv-cross-build-version "unknown") find_package(Git) if (GIT_FOUND) execute_process( COMMAND ${GIT_EXECUTABLE} describe --always --tags --dirty=+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} OUTPUT_VARIABLE spirv-cross-build-version ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE ) message(STATUS "SPIRV-Cross: Git hash: ${spirv-cross-build-version}") else() message(STATUS "SPIRV-Cross: Git not found, using unknown build version.") endif() ``` -------------------------------- ### Querying Shader Resource Decorations Source: https://github.com/khronosgroup/spirv-cross/wiki/Reflection-API-user-guide Use Compiler::get_decoration to retrieve descriptor set and binding information for sampled images, and attachment index for subpass inputs. ```cpp ShaderResources res = ...; for (const Resource &resource : res.sampled_images) { unsigned set = comp.get_decoration(resource.id, spv::DecorationDescriptorSet); unsigned binding = comp.get_decoration(resource.id, spv::DecorationBinding); } for (const Resource &resource : res.subpass_inputs) { unsigned attachment_index = comp.get_decoration(resource.id, spv::DecorationInputAttachmentIndex); } ``` -------------------------------- ### Configure Git Version Header Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Generates a `gitversion.h` file in the build directory using a template and the detected Git version or timestamp. This file is used to embed build information. ```cmake string(TIMESTAMP spirv-cross-timestamp) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/gitversion.in.h ${CMAKE_CURRENT_BINARY_DIR}/gitversion.h @ONLY) ``` -------------------------------- ### Build SPIRV-Cross CLI Tool Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Use this CMake option to build the SPIRV-Cross command-line interface tool. This allows you to convert shaders from the command line. ```bash -DSPIRV_CROSS_CLI=ON ``` -------------------------------- ### Initialize Compiler Flags Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Initializes variables for compiler options, defines, and link flags. These are populated later based on selected features and platform. ```cmake set(spirv-compiler-options "") set(spirv-compiler-defines "") set(spirv-cross-link-flags "") ``` -------------------------------- ### Convert SPIR-V to Desktop GLSL with spirv-cross Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Converts a SPIR-V file to desktop GLSL (version 330) and outputs to a file. The --no-es flag ensures it's not targeting ES. ```bash ./spirv-cross --version 330 --no-es test.spv --output test.comp ``` -------------------------------- ### Build SPIRV-Cross as Static Library Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Use this CMake option to build SPIRV-Cross as a static library. This can be useful for embedding the library directly into your project. ```bash -DSPIRV_CROSS_STATIC=ON ``` -------------------------------- ### Compile GLSL to SPIR-V with glslangValidator Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md This command compiles a GLSL fragment shader into a SPIR-V binary file. It assumes Vulkan GLSL input and modern GLSL versions. ```bash glslangValidator -H -V -o test.spv test.frag ``` -------------------------------- ### Run SPIRV-Cross Tests with CMake Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Travis CI uses CMake to run the test suite. This is a more straightforward alternative to the shell script method. ```bash ctest ``` -------------------------------- ### Build SPIRV-Cross as Shared Library Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Use this CMake option to build SPIRV-Cross as a shared library. This allows the library to be loaded at runtime. ```bash -DSPIRV_CROSS_SHARED=ON ``` -------------------------------- ### Configure SPIRV-Cross CLI Build Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt This snippet configures the build for the SPIRV-Cross CLI executable. It enforces the requirement that GLSL, HLSL, MSL, C++, reflection, and utility modules must be enabled if the CLI is being built. It also mandates building static libraries for the CLI. ```cmake if (SPIRV_CROSS_CLI) if (NOT SPIRV_CROSS_ENABLE_GLSL) message(FATAL_ERROR "Must enable GLSL if building CLI.") endif() if (NOT SPIRV_CROSS_ENABLE_HLSL) message(FATAL_ERROR "Must enable HLSL if building CLI.") endif() if (NOT SPIRV_CROSS_ENABLE_MSL) message(FATAL_ERROR "Must enable MSL if building CLI.") endif() if (NOT SPIRV_CROSS_ENABLE_CPP) message(FATAL_ERROR "Must enable C++ if building CLI.") endif() if (NOT SPIRV_CROSS_ENABLE_REFLECT) message(FATAL_ERROR "Must enable reflection if building CLI.") endif() if (NOT SPIRV_CROSS_ENABLE_UTIL) message(FATAL_ERROR "Must enable utils if building CLI.") endif() if (NOT SPIRV_CROSS_STATIC) message(FATAL_ERROR "Must build static libraries if building CLI.") endif() add_executable(spirv-cross main.cpp) target_compile_options(spirv-cross PRIVATE ${spirv-compiler-options}) target_include_directories(spirv-cross PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) target_compile_definitions(spirv-cross PRIVATE ${spirv-compiler-defines} HAVE_SPIRV_CROSS_GIT_VERSION) set_target_properties(spirv-cross PROPERTIES LINK_FLAGS "${spirv-cross-link-flags}") if (NOT SPIRV_CROSS_SKIP_INSTALL) install(TARGETS spirv-cross DESTINATION ${CMAKE_INSTALL_BINDIR}) endif() target_link_libraries(spirv-cross PRIVATE spirv-cross-glsl spirv-cross-hlsl spirv-cross-cpp spirv-cross-reflect spirv-cross-msl spirv-cross-util spirv-cross-core) endif() ``` -------------------------------- ### Set CMake Policy Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Ensures compatibility with newer CMake versions by setting specific policies. Use this at the beginning of your CMakeLists.txt. ```cmake cmake_policy(SET CMP0057 NEW) ``` -------------------------------- ### SPIRV-Cross Version Definitions Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Sets the ABI major, minor, and patch versions for SPIRV-Cross, and constructs the full version string. ```cmake set(spirv-cross-abi-major 0) set(spirv-cross-abi-minor 68) set(spirv-cross-abi-patch 0) set(SPIRV_CROSS_VERSION ${spirv-cross-abi-major}.${spirv-cross-abi-minor}.${spirv-cross-abi-patch}) ``` -------------------------------- ### SPIRV-Cross GLSL Source Files Definition Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines the list of source files for the SPIRV-Cross GLSL backend. This includes the GLSL implementation and header files. ```cmake set(spirv-cross-glsl-sources ${CMAKE_CURRENT_SOURCE_DIR}/spirv_glsl.cpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_glsl.hpp) ``` -------------------------------- ### Convert SPIR-V to GLSL ES with optimizations disabled Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Converts a SPIR-V file to GLSL ES (version 310) and disables prettifying optimizations. The --force-temporary flag might be used for specific output requirements. ```bash ./spirv-cross --version 310 --es test.spv --output test.comp --force-temporary ``` -------------------------------- ### Add Metal Shader Test Suite (No Optimization) Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines a CTest test case for Metal shaders without optimization. It executes 'test_shaders.py' with '--metal' and '--parallel' flags, using the 'shaders-msl-no-opt' directory. ```cmake add_test(NAME spirv-cross-test-metal-no-opt COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test_shaders.py --metal --parallel ${spirv-cross-externals} ${CMAKE_CURRENT_SOURCE_DIR}/shaders-msl-no-opt WORKING_DIRECTORY $) ``` -------------------------------- ### Test HLSL Backend Roundtrip Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Add the --hlsl flag to test the roundtrip path from GLSL to SPIR-V to HLSL. This command specifically targets HLSL shaders. ```shell ./test_shaders.py --hlsl shaders-hlsl ``` -------------------------------- ### Test Metal Backend Roundtrip Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Add the --msl flag to test the roundtrip path from GLSL to SPIR-V to MSL. This command specifically targets MSL shaders. ```shell ./test_shaders.py --msl shaders-msl ``` -------------------------------- ### SPIRV-Cross Reflect Source Files Definition Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines the list of source files for the SPIRV-Cross reflection API. This includes the reflection implementation and header files. ```cmake set(spirv-cross-reflect-sources ${CMAKE_CURRENT_SOURCE_DIR}/spirv_reflect.cpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_reflect.hpp) ``` -------------------------------- ### SPIRV-Cross HLSL Source Files Definition Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines the list of source files for the SPIRV-Cross HLSL backend. This includes the HLSL implementation and header files. ```cmake set(spirv-cross-hlsl-sources ${CMAKE_CURRENT_SOURCE_DIR}/spirv_hlsl.cpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_hlsl.hpp) ``` -------------------------------- ### SPIRV-Cross MSL Source Files Definition Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines the list of source files for the SPIRV-Cross MSL backend. This includes the MSL implementation and header files. ```cmake set(spirv-cross-msl-sources ${CMAKE_CURRENT_SOURCE_DIR}/spirv_msl.cpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_msl.hpp) ``` -------------------------------- ### Add HLSL Resource Binding Test Executable Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Configures the CMake build system to create an executable for testing HLSL resource bindings. It links against the spirv-cross-c library and sets specific link flags. ```cmake add_executable(spirv-cross-hlsl-resource-binding-test tests-other/hlsl_resource_bindings.cpp) target_link_libraries(spirv-cross-hlsl-resource-binding-test spirv-cross-c) set_target_properties(spirv-cross-hlsl-resource-binding-test PROPERTIES LINK_FLAGS "${spirv-cross-link-flags}") ``` -------------------------------- ### Update Test Shader Reference Files Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Update the reference output files for shader tests when legitimate changes to SPIRV-Cross behavior occur. Ensure the correct glslangValidator and SPIRV-Tools versions are used. ```bash ./update_test_shaders.sh ``` -------------------------------- ### Add HLSL Shader Test Suite (No Optimization) Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines a CTest test case for HLSL shaders without optimization. It executes 'test_shaders.py' with '--hlsl' and '--parallel' flags, using the 'shaders-hlsl-no-opt' directory. ```cmake add_test(NAME spirv-cross-test-hlsl-no-opt COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test_shaders.py --hlsl --parallel ${spirv-cross-externals} ${CMAKE_CURRENT_SOURCE_DIR}/shaders-hlsl-no-opt WORKING_DIRECTORY $) ``` -------------------------------- ### Add General Shader Test Suite (No Optimization) Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines a CTest test case for shader tests without optimization. It executes the 'test_shaders.py' script using Python, specifying the '--parallel' flag and the 'shaders-no-opt' directory. ```cmake add_test(NAME spirv-cross-test-no-opt COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test_shaders.py --parallel ${spirv-cross-externals} ${CMAKE_CURRENT_SOURCE_DIR}/shaders-no-opt WORKING_DIRECTORY $) ``` -------------------------------- ### Gather Shader Resources Source: https://github.com/khronosgroup/spirv-cross/wiki/Reflection-API-user-guide Retrieve all shader resources, including images, buffers, and interface variables, from the compiled SPIR-V module. This provides a comprehensive overview of the shader's external dependencies. ```cpp ShaderResources res = comp.get_shader_resources(); ``` -------------------------------- ### SPIRV-Cross C API Source Files Definition Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines the list of source files for the SPIRV-Cross C API. This includes the C header and implementation files. ```cmake set(spirv-cross-c-sources spirv.h ${CMAKE_CURRENT_SOURCE_DIR}/spirv_cross_c.cpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_cross_c.h) ``` -------------------------------- ### SPIRV-Cross Utility Source Files Definition Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines the list of source files for the SPIRV-Cross utility functions. This includes the utility implementation and header files. ```cmake set(spirv-cross-util-sources ${CMAKE_CURRENT_SOURCE_DIR}/spirv_cross_util.cpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_cross_util.hpp) ``` -------------------------------- ### Add MSL YCbCr Conversion Test Executable Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Sets up a CMake target for an executable that tests MSL YCbCr conversion. This involves linking with the spirv-cross-c library and applying defined link flags. ```cmake add_executable(spirv-cross-msl-ycbcr-conversion-test tests-other/msl_ycbcr_conversion_test.cpp) target_link_libraries(spirv-cross-msl-ycbcr-conversion-test spirv-cross-c) set_target_properties(spirv-cross-msl-ycbcr-conversion-test PROPERTIES LINK_FLAGS "${spirv-cross-link-flags}") ``` -------------------------------- ### SPIRV-Cross Core Source Files Definition Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines the list of source files for the SPIRV-Cross core library. This includes common headers, parser, and core implementation files. ```cmake set(spirv-cross-core-sources ${CMAKE_CURRENT_SOURCE_DIR}/GLSL.std.450.h ${CMAKE_CURRENT_SOURCE_DIR}/spirv_common.hpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_cross_containers.hpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_cross_error_handling.hpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv.hpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_cross.hpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_cross.cpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_parser.hpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_parser.cpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_cross_parsed_ir.hpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_cross_parsed_ir.cpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_cfg.hpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_cfg.cpp) ``` -------------------------------- ### Build SPIRV-Cross with Exceptions Disabled (Make) Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Append this flag to the make command to treat C++ exceptions as assertions, effectively disabling them. This is useful for environments where exceptions are not desired or supported. ```bash make SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS=1 ``` -------------------------------- ### SPIRV-Cross C++ API Source Files Definition Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines the list of source files for the SPIRV-Cross C++ API. This includes the C++ implementation and header files. ```cmake set(spirv-cross-cpp-sources ${CMAKE_CURRENT_SOURCE_DIR}/spirv_cpp.cpp ${CMAKE_CURRENT_SOURCE_DIR}/spirv_cpp.hpp) ``` -------------------------------- ### Query Statically Accessed Push Constant Ranges Source: https://github.com/khronosgroup/spirv-cross/wiki/Reflection-API-user-guide Retrieve information about the ranges of push constant buffers that are statically accessed by the shader. Note that this tracking is limited to top-level members. ```cpp vector ranges = comp.get_active_buffer_ranges(res.push_constant_buffers[0].id); for (auto &range : ranges) { print(range.index); // Struct member index print(range.offset); // Offset into struct print(range.range); // Size of struct member } ``` -------------------------------- ### Add General Shader Test Suite Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines a CTest test case named 'spirv-cross-test' that runs the shader test script. It uses Python to execute 'test_shaders.py' with parallel processing enabled, external dependencies, and the main shader directory. ```cmake add_test(NAME spirv-cross-test COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test_shaders.py --parallel ${spirv-cross-externals} ${CMAKE_CURRENT_SOURCE_DIR}/shaders WORKING_DIRECTORY $) ``` -------------------------------- ### Add HLSL Shader Test Suite Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines a CTest test case for HLSL shaders. It runs the 'test_shaders.py' script with '--hlsl' and '--parallel' flags, targeting the 'shaders-hlsl' directory. ```cmake add_test(NAME spirv-cross-test-hlsl COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test_shaders.py --hlsl --parallel ${spirv-cross-externals} ${CMAKE_CURRENT_SOURCE_DIR}/shaders-hlsl WORKING_DIRECTORY $) ``` -------------------------------- ### Add Metal Shader Test Suite Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines a CTest test case for Metal shaders. It runs the 'test_shaders.py' script with '--metal' and '--parallel' flags, targeting the 'shaders-msl' directory. ```cmake add_test(NAME spirv-cross-test-metal COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test_shaders.py --metal --parallel ${spirv-cross-externals} ${CMAKE_CURRENT_SOURCE_DIR}/shaders-msl WORKING_DIRECTORY $) ``` -------------------------------- ### Set C++ Standard and Extensions in CMake Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Configures the C++ standard to C++11 and disables C++ extensions. This ensures a consistent and standard-compliant build environment. ```cmake cmake_minimum_required(VERSION 3.10) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_EXTENSIONS OFF) ``` -------------------------------- ### Specify Custom SPIRV-Cross Path for Tests Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md When using a custom-built SPIRV-Cross binary, set the SPIRV_CROSS_PATH environment variable before running tests. ```bash SPIRV_CROSS_PATH=path/to/custom/spirv-cross ./test_shaders.sh ``` -------------------------------- ### Query Statically Used Resources Source: https://github.com/khronosgroup/spirv-cross/wiki/Reflection-API-user-guide Obtain shader resources that are actively used by the SPIR-V module, ignoring any unused textures or buffers. This is useful for optimizing resource management. ```cpp auto active = comp.get_active_interface_variables(); ShaderResources = comp.get_shader_resources(active); comp.set_enabled_interface_variables(move(active)); ``` -------------------------------- ### Query Runtime Sized Array Buffer Size Source: https://github.com/khronosgroup/spirv-cross/wiki/Reflection-API-user-guide When dealing with runtime sized arrays in SSBOs/UAVs, use get_declared_struct_size_runtime_array() to determine the buffer size based on an intended array size, as get_declared_struct_size() may return 0. ```cpp size_t size = comp.get_declared_struct_size_runtime_array(type, array_size); ``` -------------------------------- ### Distinguish Buffer vs Texture2D Source: https://github.com/khronosgroup/spirv-cross/wiki/Reflection-API-user-guide Identify if an image resource is a Buffer or a Texture2D by checking the image dimensions. Assumes 'type' is a SPIRType object. ```cpp print(type.image.dim == DimBuffer) ``` -------------------------------- ### Configure C++ Compiler Options for C API Test Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Conditionally sets C++ compiler options for the C API test executable if the compiler is GCC or Clang. This ensures specific standards and warning levels are applied. ```cmake if (CMAKE_COMPILER_IS_GNUCXX OR (${CMAKE_CXX_COMPILER_ID} MATCHES "Clang")) target_compile_options(spirv-cross-c-api-test PRIVATE -std=c89 -Wall -Wextra) endif() ``` -------------------------------- ### Sanitizer Options Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Enables various sanitizers for debugging memory and thread issues. These options are typically set to OFF by default. ```cmake option(SPIRV_CROSS_SANITIZE_ADDRESS "Sanitize address" OFF) option(SPIRV_CROSS_SANITIZE_MEMORY "Sanitize memory" OFF) option(SPIRV_CROSS_SANITIZE_THREADS "Sanitize threads" OFF) option(SPIRV_CROSS_SANITIZE_UNDEFINED "Sanitize undefined" OFF) ``` -------------------------------- ### SPIRV-Cross Build Options Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Configures build features for SPIRV-Cross using CMake options. These control aspects like exception handling, shared/static libraries, CLI, and API support. ```cmake option(SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS "Instead of throwing exceptions assert" OFF) option(SPIRV_CROSS_SHARED "Build the C API as a single shared library." OFF) option(SPIRV_CROSS_STATIC "Build the C and C++ API as static libraries." ON) option(SPIRV_CROSS_CLI "Build the CLI binary. Requires SPIRV_CROSS_STATIC." ON) option(SPIRV_CROSS_ENABLE_TESTS "Enable SPIRV-Cross tests." ON) option(SPIRV_CROSS_ENABLE_GLSL "Enable GLSL support." ON) option(SPIRV_CROSS_ENABLE_HLSL "Enable HLSL target support." ON) option(SPIRV_CROSS_ENABLE_MSL "Enable MSL target support." ON) option(SPIRV_CROSS_ENABLE_CPP "Enable C++ target support." ON) option(SPIRV_CROSS_ENABLE_REFLECT "Enable JSON reflection target support." ON) option(SPIRV_CROSS_ENABLE_C_API "Enable C API wrapper support in static library." ON) option(SPIRV_CROSS_ENABLE_UTIL "Enable util module support." ON) ``` -------------------------------- ### Query Specialization Constants Source: https://github.com/khronosgroup/spirv-cross/wiki/Reflection-API-user-guide Reflect on specialization constants defined in the shader, retrieving their IDs, constant IDs, scalar values, and names. Requires SPIRConstant from spirv_common.hpp. ```cpp vector consts = comp.get_specialization_constants(); for (auto &c : consts) { print(c.id); // The ID of the spec constant, useful for further reflection. print(c.constant_id); // 20 const SPIRConstant &value = comp.get_constant(c.id); print(value.scalar_i32()); // 40 print(comp.get_name(c.id)); // Const } ``` -------------------------------- ### Query Array Dimensions Source: https://github.com/khronosgroup/spirv-cross/wiki/Reflection-API-user-guide Iterate through sampled image resources to query their array dimensions and literal size information. Assumes 'comp' is an instance of SPIRCross. ```cpp for (const Resource &resource : res.sampled_images) { const SPIRType &type = comp.get_type(resource.type_id); // Notice how we're using type_id here because we need the array information and not decoration information. print(type.array.size()); // 1, because it's one dimension. print(type.array[0]); // 10 print(type.array_size_literal[0]); // true } ``` -------------------------------- ### Build SPIRV-Cross with Exceptions Disabled (CMake) Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Use this CMake option to treat C++ exceptions as assertions, effectively disabling them. This is useful for environments where exceptions are not desired or supported. ```bash cmake -DSPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS=ON ``` -------------------------------- ### Remap Descriptor Sets for Legacy Backends Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Descriptor sets are remapped to a flat binding scheme (set 0) for backends that do not support them, using `Compiler::set_decoration(id, spv::DecorationDescriptorSet)`. ```c++ compiler->set_decoration(id, spv::DecorationDescriptorSet); ``` -------------------------------- ### Macro for Extracting Headers Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines a CMake macro `extract_headers` that takes an output variable for absolute paths and a list of files. It initializes the output variable. ```cmake macro(extract_headers out_abs file_list) set(${out_abs}) foreach(_a ${file_list}) ``` -------------------------------- ### Update Regression Tests Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Use the --update flag when legitimate changes are found to update regression files. Failure to do so will result in the script failing with an error code. ```shell ./test_shaders.py --update ``` -------------------------------- ### Add HLSL Resource Binding Test Case Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Defines a CTest test case for HLSL resource binding. It runs the 'spirv-cross-hlsl-resource-binding-test' executable with the specified SPIR-V file. ```cmake add_test(NAME spirv-cross-hlsl-resource-binding-test COMMAND $ ${CMAKE_CURRENT_SOURCE_DIR}/tests-other/hlsl_resource_binding.spv) ``` -------------------------------- ### Add Debug Info Test Executable Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Configures a CMake target for an executable to test debug information. It links against spirv-cross-core and applies the standard link flags. ```cmake add_executable(spirv-cross-debug-info-test tests-other/debug-info.cpp) target_link_libraries(spirv-cross-debug-info-test spirv-cross-core) set_target_properties(spirv-cross-debug-info-test PROPERTIES LINK_FLAGS "${spirv-cross-link-flags}") ``` -------------------------------- ### Namespace Override Options Source: https://github.com/khronosgroup/spirv-cross/blob/main/CMakeLists.txt Allows overriding default namespaces for the C++ API and spirv.hpp to prevent naming conflicts. These are typically empty by default. ```cmake option(SPIRV_CROSS_NAMESPACE_OVERRIDE "" "Override the namespace used in the C++ API.") option(SPIRV_CROSS_SPV_HEADER_NAMESPACE_OVERRIDE "" "Override the namespace used by spirv.hpp (to workaround conflicts).") ``` -------------------------------- ### Convert SPIR-V to GLSL ES with spirv-cross Source: https://github.com/khronosgroup/spirv-cross/blob/main/README.md Converts a SPIR-V file to GLSL ES (version 310). This is useful for targeting mobile or embedded platforms. ```bash ./spirv-cross --version 310 --es test.spv ```