### CMake Setup for Shader-Slang Examples and Base Libraries Source: https://github.com/shader-slang/slang/blob/master/examples/CMakeLists.txt Configures the build system to include various Shader-Slang examples and essential base libraries. It defines static libraries for example entry points and platform-specific components, and creates a meta-target `all-examples` for convenience. ```cmake if(SLANG_ENABLE_EXAMPLES AND SLANG_ENABLE_SLANG_RHI) # # Examples # slang_add_target( example-base STATIC LINK_WITH_PRIVATE core slang-rhi slang platform stb $<$:CUDA::cuda_driver> FOLDER examples ) slang_add_target(example-main STATIC FOLDER examples) slang_add_target(example-winmain STATIC FOLDER examples EXCLUDE_FROM_ALL) slang_add_target(stacktrace-windows STATIC FOLDER examples EXCLUDE_FROM_ALL) add_custom_target( all-examples COMMENT "meta target which depends on all examples" ) set_target_properties(all-examples PROPERTIES FOLDER examples) example(autodiff-texture WIN32_EXECUTABLE) example(cpu-com-example) example(cpu-hello-world) example(gpu-printing) example(hello-world LINK_WITH_PRIVATE Vulkan-Headers) example(model-viewer WIN32_EXECUTABLE) example(platform-test WIN32_EXECUTABLE) example(ray-tracing WIN32_EXECUTABLE) example(ray-tracing-pipeline WIN32_EXECUTABLE) example(reflection-api) example(reflection-parameter-blocks LINK_WITH_PRIVATE Vulkan-Headers) example(shader-object) example(shader-toy WIN32_EXECUTABLE) example(triangle WIN32_EXECUTABLE) if(SLANG_ENABLE_AFTERMATH) example(nv-aftermath-example WIN32_EXECUTABLE) endif() if(SLANG_ENABLE_SLANG_RHI) example(mlp-training LINK_WITH_PRIVATE slang-rhi) example(mlp-training-coopvec LINK_WITH_PRIVATE slang-rhi) endif() endif() ``` -------------------------------- ### Example CMake Usage for Slang Source: https://github.com/shader-slang/slang/blob/master/docs/building.md Demonstrates how to use CMake's find_package to locate a Slang installation and link against the `slang::slang` target library. Assumes Slang has been installed. ```cmake find_package(slang REQUIRED PATHS ${your_cmake_install_prefix_path} NO_DEFAULT_PATH) # slang_FOUND should be automatically set target_link_libraries(yourLib PUBLIC slang::slang ) ``` -------------------------------- ### Install Git Pre-commit Hook for Auto-Formatting Source: https://github.com/shader-slang/slang/blob/master/CONTRIBUTING.md Installs a pre-commit hook to automatically format C++, YAML, Markdown, shell scripts, and CMake files before each commit. This ensures code consistency without manual intervention. ```shell #!/bin/bash # This script installs the git pre-commit hook for Shader-Slang. # It ensures that code is automatically formatted before each commit. # Define the path to the pre-commit hook script PRE_COMMIT_HOOK="$(git rev-parse --show-toplevel)/.git/hooks/pre-commit" # Define the path to the custom pre-commit script provided by the project CUSTOM_HOOK="$(git rev-parse --show-toplevel)/extras/install-git-hooks.sh" # Copy the custom hook to the .git/hooks directory cp "$CUSTOM_HOOK" "$PRE_COMMIT_HOOK" # Make the hook executable chmod +x "$PRE_COMMIT_HOOK" echo "Git pre-commit hook installed successfully." ``` -------------------------------- ### Shader Slang Capability Requirement Examples Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/05-capabilities.md Demonstrates Shader Slang's `[require]` attribute to enforce capability compatibility between function declarations and their bodies. It shows examples of valid requirements, errors due to missing capabilities, and how stage switching works. ```csharp [require(sm_5_0)] public void requires_sm_5_0() { } [require(sm_4_0)] public void logic_sm_5_0_error() // Error, missing `sm_5_0` support { requires_sm_5_0(); } public void logic_sm_5_0__pass() // Pass, no requirements { requires_sm_5_0(); } [require(hlsl, vertex)] public void logic_vertex() { } [require(hlsl, fragment)] public void logic_fragment() { } [require(hlsl, vertex, fragment)] public void logic_stage_pass_1() // Pass, `vertex` and `fragment` supported { __stage_switch { case vertex: logic_vertex(); case fragment: logic_fragment(); } } [require(hlsl, vertex, fragment, mesh, hull, domain)] public void logic_many_stages() { } [require(hlsl, vertex, fragment)] public void logic_stage_pass_2() // Pass, function only requires that the body implements the stages `vertex` & `fragment`, the rest are irelevant { logic_many_stages(); } [require(hlsl, any_hit)] public void logic_stage_fail_1() // Error, function requires `any_hit`, body does not support `any_hit` { logic_many_stages(); } ``` -------------------------------- ### Type Extension Example in C# Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/03-convenience-features.md Demonstrates extending a type with methods, similar to Swift extensions or C# extension methods. Note that adding data fields is not permitted. ```csharp void test() { MyType t; float val = t.getNewField(); } ``` -------------------------------- ### Configure SLANG_ENABLE_EXAMPLES Option (CMake) Source: https://github.com/shader-slang/slang/blob/master/CMakeLists.txt Defines SLANG_ENABLE_EXAMPLES as a CMake option to enable the example targets. Building examples requires SLANG_ENABLE_SLANG_RHI. It defaults to ON. ```cmake option( SLANG_ENABLE_EXAMPLES "Enable example targets, requires SLANG_ENABLE_SLANG_RHI" ON ) ``` -------------------------------- ### Install Slang using CMake Source: https://github.com/shader-slang/slang/blob/master/docs/building.md Installs the built Slang compiler using CMake. This makes the SlangConfig.cmake file available, enabling find_package to locate Slang and define the `slang::slang` target for linking. ```bash cmake --build . --target install ``` -------------------------------- ### Configuring Package Installation in CMake Source: https://github.com/shader-slang/slang/blob/master/CMakeLists.txt This section details the packaging configuration for the Shader-Slang project using CPack. It sets options for component-based installation, single package creation, and stripping files. It also defines installation rules for the README, LICENSE, docs, and include directories, ensuring that the necessary files are included in the final package. ```cmake set(CPACK_ARCHIVE_COMPONENT_INSTALL ON) set(CPACK_COMPONENTS_ALL_IN_ONE_PACKAGE ON) set(CPACK_STRIP_FILES FALSE) install( FILES "${slang_SOURCE_DIR}/README.md" "${slang_SOURCE_DIR}/LICENSE" DESTINATION . COMPONENT metadata EXCLUDE_FROM_ALL ) install( DIRECTORY "${slang_SOURCE_DIR}/docs/" DESTINATION share/doc/slang PATTERN ".*" EXCLUDE ) install( DIRECTORY "${slang_SOURCE_DIR}/include" DESTINATION . PATTERN ".*" EXCLUDE ) include(CPack) ``` -------------------------------- ### CMake Function to Add Shader-Slang Example Target Source: https://github.com/shader-slang/slang/blob/master/examples/CMakeLists.txt Defines a CMake function `example` to streamline the creation of executable targets for Shader-Slang examples. It handles asset copying, library linking, and property setting, making it easier to define new examples. Dependencies like core, slang-rhi, and platform are automatically included. ```cmake function(example dir) cmake_parse_arguments(ARG "WIN32_EXECUTABLE" "" "" ${ARGN}) set(debug_dir ${CMAKE_CURRENT_BINARY_DIR}/${dir}) file( GLOB asset_files CONFIGURE_DEPENDS "${dir}/*.slang" "${dir}/*.jpg" "${dir}/*.obj" "${dir}/*.mtl" "${dir}/*.h" ) list(LENGTH asset_files asset_files_length) if(asset_files_length GREATER 0) set(copy_assets_target "${dir}-copy-assets") add_custom_target( ${copy_assets_target} COMMAND ${CMAKE_COMMAND} -E make_directory ${debug_dir} COMMAND ${CMAKE_COMMAND} -E copy_if_different ${asset_files} ${debug_dir} COMMENT "Copy example assets to ${debug_dir}" ) set_target_properties( ${copy_assets_target} PROPERTIES FOLDER "examples/copy_assets" ) endif() # Libraries providing a main function that prints stack traces on exceptions if(CMAKE_SYSTEM_NAME MATCHES "Windows") # On Windows we have two different versions: main for "console applications" and # WinMain for normal Windows applications. if(${ARG_WIN32_EXECUTABLE}) set(main_wrapper_libraries example-winmain) else() set(main_wrapper_libraries example-main) endif() # Add stack printing support set(main_wrapper_libraries ${main_wrapper_libraries} stacktrace-windows) set(main_wrapper_libraries ${main_wrapper_libraries} dbghelp.lib) else() set(main_wrapper_libraries example-main) endif() slang_add_target( ${dir} EXECUTABLE USE_FEWER_WARNINGS LINK_WITH_PRIVATE core example-base slang-rhi slang platform $<$:CUDA::cuda_driver> ${main_wrapper_libraries} INCLUDE_DIRECTORIES_PUBLIC ${slang_SOURCE_DIR} EXTRA_COMPILE_DEFINITIONS_PRIVATE SLANG_EXAMPLE_NAME=${dir} $<$:SLANG_ENABLE_XLIB> REQUIRED_BY all-examples OPTIONAL_REQUIRES ${copy_assets_target} copy-prebuilt-binaries FOLDER examples DEBUG_DIR ${debug_dir} ${ARGN} ) endfunction() ``` -------------------------------- ### Setup Emscripten SDK for WebAssembly Build Source: https://github.com/shader-slang/slang/blob/master/docs/building.md Downloads and activates the latest version of the Emscripten SDK, which is required for building the WebAssembly version of Slang. This process differs slightly between Windows and other platforms. ```bash # For non-Windows platforms ./emsdk install latest ./emsdk activate latest ``` ```cmd rem For Windows emsdk.bat install latest emsdk.bat activate latest ``` -------------------------------- ### Module Declaration and Includes in Slang Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/04-modules-and-access-control.md An example of a Slang module declaration file (`utils.slang`) that imports external modules and includes other Slang files. This structure helps manage dependencies and organize implementation details. ```slang module utils; import slangpy; __include "utils/accumlator.slang"; __include "utils/tonemap.slang"; __include "utils/fill.slang"; ``` -------------------------------- ### C# Interface with Implementation: Atomic Add (Valid) Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/05-capabilities.md A valid C# extension example demonstrating the `atomicAdd` function. The implementation in `int64_t` matches the requirements of `IAtomicAddable_Pass` without explicit capability annotations causing issues. ```csharp public interface IAtomicAddable_Pass { public static void atomicAdd(RWByteAddressBuffer buf, uint addr, This value); } public extension int64_t : IAtomicAddable_Pass { public static void atomicAdd(RWByteAddressBuffer buf, uint addr, int64_t value) { buf.InterlockedAddI64(addr, value); } } ``` -------------------------------- ### Install Slang Configuration Files with CMake Source: https://github.com/shader-slang/slang/blob/master/CMakeLists.txt This snippet installs the main Slang configuration files, including SlangConfig.cmake and SlangConfigVersion.cmake. These files are essential for other projects to find and use the Slang library. They are installed regardless of the system or library type. ```cmake install( FILES "${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" "${PROJECT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" DESTINATION ${SLANG_CMAKE_CONFIG_DIR} ) ``` -------------------------------- ### Cross-Compilation: Build Generators and Specify Path Source: https://github.com/shader-slang/slang/blob/master/docs/building.md Instructions for cross-compiling Shader-Slang. First, build the necessary generators using the 'generators' preset and install them. Then, reconfigure the main build, pointing to the installed generators using SLANG_GENERATORS_PATH. ```bash # build the generators cmake --workflow --preset generators --fresh mkdir build-platform-generators cmake --install build --config Release --prefix build-platform-generators --component generators # reconfigure, pointing to these generators ``` -------------------------------- ### Install Neural Module to Release Package Source: https://github.com/shader-slang/slang/blob/master/source/standard-modules/neural/CMakeLists.txt Configures the CMake install process to copy the neural module directory contents to the configured installation location, filtering for .slang and .slang-module files only. ```cmake install( DIRECTORY ${neural_output_dir}/ DESTINATION ${SLANG_STANDARD_MODULE_INSTALL_DIR} FILES_MATCHING PATTERN "*.slang" PATTERN "*.slang-module" ) ``` -------------------------------- ### Run Slang Unit Tests with slang-unit-test-tool Source: https://github.com/shader-slang/slang/blob/master/tools/slang-test/README.md Shows how to invoke regular unit tests from the slang-unit-test-tool using the slang-test command. The example demonstrates running the byteEncode test located in the tools/slang-unit-test directory. ```bash # Regular unit tests slang-test slang-unit-test-tool/ # e.g. run the `byteEncode` test. slang-test slang-unit-test-tool/byteEncode ``` -------------------------------- ### Build Host Platform Generators for Cross-Compilation Source: https://github.com/shader-slang/slang/blob/master/source/standard-modules/README.md Builds the Slang generator tools (including slang-bootstrap) for the host platform and installs them to a specified directory. This step is necessary before cross-compilation to ensure standard modules can be compiled on the build host. ```bash cmake --workflow --preset generators --fresh cmake --install build --config Release --component generators --prefix build-platform-generators ``` -------------------------------- ### Build Slang from Source on Linux (CMake) Source: https://github.com/shader-slang/slang/blob/master/CONTRIBUTING.md Configures and builds the Slang project from source on Linux using CMake and Ninja. Requires CMake version 3.25 or higher and Ninja build tool. ```bash $ sudo apt-get install cmake ninja-build $ cmake --preset default $ cmake --build --preset release ``` -------------------------------- ### ShaderSLang Generic Declaration Syntax Examples Source: https://github.com/shader-slang/slang/blob/master/docs/language-reference/07-declarations.md Provides various examples of ShaderSLang syntax for declaring generic functions, initializers, subscripts, generic types, and interfaces. ```ShaderSLang T genericFunction(T value); ``` ```ShaderSLang funct genericFunction(value: T) -> T; ``` ```ShaderSLang __init(T value); ``` ```ShaderSLang __subscript(T value) -> X { ... } ``` ```ShaderSLang struct GenericType { T field; } ``` ```ShaderSLang interface IGenericInterface : IBase { } ``` -------------------------------- ### Run Graphics Unit Tests with gfx-unit-test-tool Source: https://github.com/shader-slang/slang/blob/master/tools/slang-test/README.md Demonstrates how to execute graphics-specific unit tests using the gfx-unit-test-tool via the slang-test command. The example shows running the precompiledTargetModule2Vulkan test from the tools/gfx-unit-test directory. ```bash # Graphics unit tests slang-test gfx-unit-test-tool/ # e.g. run the `precompiledTargetModule2Vulkan` test. slang-test gfx-unit-test-tool/precompiledTargetModule2Vulkan ``` -------------------------------- ### Slang Module Inclusion Semantics and Circular Includes Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/04-modules-and-access-control.md This example showcases the advanced usage of '__include' in Slang, including handling circular includes and demonstrating how files within a module can access entities from other files in the same module regardless of inclusion order. ```slang // a.slang implementing m; void f_a() {} // b.slang implementing "m"; // alternate syntax. __include a; // pulls in `a` to module `m`. void f_b() { f_a(); } // c.slang implementing "m.slang"; // alternate syntax. void f_c() { // OK, `c.slang` is part of module `m` because it is `__include`'d by // `m.slang`. f_a(); f_b(); } // m.slang module m; __include m; // OK, a file including itself is allowed and has no effect. __include "b"; // Pulls in file b (alternate syntax), and transitively pulls in file a. __include "c.slang"; // Pulls in file c, specifying the full file name. void test() { f_a(); f_b(); f_c(); } ``` -------------------------------- ### Return Interface Type in HLSL Source: https://github.com/shader-slang/slang/blob/master/docs/language-guide.md Demonstrates how a function can return an interface type, specifically an 'ILight' in this HLSL example. This functionality allows for flexible object-oriented programming patterns within shaders. The 'Scene' parameter suggests context might be passed to determine which light source to return. ```hlsl ILight getALightSource(Scene scene) { ... } ``` -------------------------------- ### Struct Splitting Example: Simple Case Source: https://github.com/shader-slang/slang/blob/master/docs/layout.md Demonstrates how Slang splits a struct with uniform and non-uniform data into separate variables for simpler layout management. This basic example shows a struct with a float3 and a Texture2D. ```hlsl struct LightInfo { float3 pos; Texture2D shadowMap; }; LightInfo gLight; ``` ```hlsl float3 gLight_pos; Texture2D gLight_shadowMap; ``` -------------------------------- ### Install Slang Targets with CMake Source: https://github.com/shader-slang/slang/blob/master/CMakeLists.txt This snippet installs the Slang targets using CMake's install command. It conditionally exports targets only if the system is not Emscripten and the library type is not static. This ensures that dynamic library targets are properly exported for consumers. ```cmake if(NOT CMAKE_SYSTEM_NAME STREQUAL "Emscripten") if(NOT ${SLANG_LIB_TYPE} STREQUAL "STATIC") install( EXPORT SlangTargets FILE ${PROJECT_NAME}Targets.cmake NAMESPACE ${PROJECT_NAME}:: DESTINATION ${SLANG_CMAKE_CONFIG_DIR} ) endif() endif() ``` -------------------------------- ### Set LLVM Binary URL (SLANG_SLANG_LLVM_BINARY_URL) Source: https://github.com/shader-slang/slang/blob/master/docs/building.md Specifies a URL or local path for a prebuilt slang-llvm library (`.so` or `.dll`) when `SLANG_SLANG_LLVM_FLAVOR` is set to fetch a binary. If not set, it defaults to downloading from GitHub releases. ```build configuration `SLANG_SLANG_LLVM_BINARY_URL` ``` -------------------------------- ### Shader Slang Capability Alias Definitions Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/05-capabilities.md Illustrates the definition of capability aliases in Shader Slang's `.capdef` files, showing how multiple platform-specific capabilities can be grouped under a single alias for easier usage in `[require]` attributes. Examples include `sm_6_6` and `GL_EXT_shader_atomic_int64`. ```slang-capabilities alias sm_6_6 = _sm_6_6 | glsl_spirv_1_5 + sm_6_5 + GL_EXT_shader_atomic_int64 + atomicfloat2 | spirv_1_5 + sm_6_5 + GL_EXT_shader_atomic_int64 + atomicfloat2 + SPV_EXT_descriptor_indexing | cuda | cpp; alias GL_EXT_shader_atomic_int64 = _GL_EXT_shader_atomic_int64 | spvInt64Atomics; ``` -------------------------------- ### Variadic Generics for Function Signatures (printf Example) Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/06-interfaces-generics.md Demonstrates a practical use of variadic generics in Shader-Slang with a `printf` function example. `printf(String message, expand each T args)` uses `each T` for a variable number of arguments and `expand` to unpack them. ```csharp void printf(String message, expand each T args) { ... } ``` -------------------------------- ### Update Table of Contents for Slang User's Guide (PowerShell) Source: https://github.com/shader-slang/slang/blob/master/CONTRIBUTING.md Updates the table of contents for the Slang User's Guide by running a PowerShell script. This is necessary for documentation changes and ensures the TOC is up-to-date. ```powershell # Navigate to the docs directory cd docs # Execute the build_toc.ps1 script to regenerate the table of contents # This script typically scans markdown files and generates an HTML TOC ./build_toc.ps1 # Add the generated TOC file to git staging for commit git add user-guide/toc.html # To automate this process, you can use the '/regenerate-toc' command in a PR comment. ``` -------------------------------- ### Setting up Nix direnv Environment Source: https://github.com/shader-slang/slang/blob/master/docs/building.md This snippet shows how to integrate the project's Nix flake with direnv for automatic environment activation. By creating a .envrc file with 'use flake' and allowing it with 'direnv allow', the necessary development environment is sourced upon entering the repository directory. ```bash echo 'use flake' > .envrc direnv allow ``` -------------------------------- ### Slang __file_decl Scope Example Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/03-convenience-features.md Demonstrates how symbols defined within separate `__file_decl` blocks are not visible to each other, enforcing distinct global scopes. ```csharp __file_decl { void f1() { } } __file_decl { void f2() { f1(); // error: f1 is not visible from here. } } ``` -------------------------------- ### Slang Subscript Declaration Example Source: https://github.com/shader-slang/slang/blob/master/docs/language-reference/07-declarations.md Demonstrates how to declare a subscript for a user-defined type using the `__subscript` keyword. This allows the type to be accessed using array-like indexing. The declaration includes parameters, a result type, and a `get` accessor. ```hlsl struct MyVector { // ... __subscript(int index) -> float { get { return index == 0 ? x : y; } } } ``` -------------------------------- ### Configure LLVM Support Flavor (SLANG_SLANG_LLVM_FLAVOR) Source: https://github.com/shader-slang/slang/blob/master/docs/building.md Defines how LLVM support is obtained. Options include fetching a prebuilt binary (FETCH_BINARY, FETCH_BINARY_IF_POSSIBLE), using a system-supplied LLVM (USE_SYSTEM_LLVM), or disabling LLVM support entirely (DISABLE). ```build configuration `SLANG_SLANG_LLVM_FLAVOR` (Default: `FETCH_BINARY_IF_POSSIBLE`) Options: `FETCH_BINARY`, `FETCH_BINARY_IF_POSSIBLE`, `USE_SYSTEM_LLVM`, `DISABLE` ``` -------------------------------- ### Nonuniform Descriptor Dereferencing Example Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/03-convenience-features.md Demonstrates how to dereference a DescriptorHandle when its resource pointer value is not uniform across execution threads. The `nonuniform` keyword must be used immediately before dereferencing to avoid undefined behavior. ```slang void test(DescriptorHandle t) { nonuniform(t)->Sample(...); } ``` -------------------------------- ### Set Standard Module Install Directory (CMake) Source: https://github.com/shader-slang/slang/blob/master/source/standard-modules/CMakeLists.txt Defines the installation path for the standard module, incorporating the platform-specific library directory and the standard module directory name. This is a cache variable. ```cmake # Set install directory using the platform-specific library directory set(SLANG_STANDARD_MODULE_INSTALL_DIR "${slang_library_dir}/${SLANG_STANDARD_MODULE_DIR_NAME}" CACHE STRING "Installation directory for neural module") ``` -------------------------------- ### Define getRealtimeClock with Target-Specific Implementations (Slang/HLSL/GLSL/SPIR-V) Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/a1-04-interop.md This example demonstrates how to define a cross-platform intrinsic function `getRealtimeClock` using `__target_switch`. It provides specific implementations for HLSL (using NVAPI), GLSL, and SPIR-V (using inline assembly), with a fallback for other targets. Dependencies include `__requiresNVAPI` and `GL_EXT_shader_realtime_clock` for the HLSL case. ```hlsl [__requiresNVAPI] __glsl_extension(GL_EXT_shader_realtime_clock) uint2 getRealtimeClock() { __target_switch { case hlsl: __intrinsic_asm "uint2(NvGetSpecial(NV_SPECIALOP_GLOBAL_TIMER_LO), NvGetSpecial( NV_SPECIALOP_GLOBAL_TIMER_HI))" ; case glsl: __intrinsic_asm "clockRealtime2x32EXT()"; case spirv: return spirv_asm { OpCapability ShaderClockKHR; OpExtension "SPV_KHR_shader_clock"; result : $$uint2 = OpReadClockKHR Device }; default: return uint2(0, 0); } } ``` -------------------------------- ### Clone Shader-Slang Repository and Fetch Tags (Git) Source: https://github.com/shader-slang/slang/blob/master/CONTRIBUTING.md Clones the Shader-Slang repository locally, sets up the upstream remote, and fetches all tags from the upstream repository. This is crucial for build processes that rely on version tags. ```bash git clone --recursive --tags https://github.com/USER-NAME/slang.git cd slang git remote add upstream https://github.com/shader-slang/slang.git git fetch --tags upstream git push --tags origin ``` -------------------------------- ### Reflecting Entry Point Stage Information Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/09-reflection.md Illustrates how to retrieve the shader stage (e.g., vertex, fragment) for a given shader entry point using the Slang reflection API. ```c++ void printEntryPointLayout(slang::EntryPointReflection* entryPointLayout) { print("stage: "); printStage(entryPointLayout->getStage()); // ... } ``` -------------------------------- ### C# Capability Mismatch: Missing Supertype Capability (Error) Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/05-capabilities.md Example of a C# error where a subtype implementing an interface misses a required capability specified in the interface. `Foo1` is missing the `spirv` capability required by `IFoo1`. ```csharp // Error, Foo1 is missing `spirv` [require(hlsl)] [require(spirv)] interface IFoo1 { } [require(hlsl)] struct Foo1 : IFoo1 { } ``` -------------------------------- ### Alternative Syntax for Slang Includes and Module References Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/04-modules-and-access-control.md Demonstrates the flexibility in Slang's module and file referencing, showing equivalent syntax using identifier tokens and string literals for '__include' and module declarations. ```slang __include dir.file_name; // `file_name` is translated to "file-name". __include "dir/file-name.slang"; __include "dir/file-name"; ``` -------------------------------- ### Configure SLANG_ENABLE_AFTERMATH Option (CMake) Source: https://github.com/shader-slang/slang/blob/master/CMakeLists.txt Defines the SLANG_ENABLE_AFTERMATH CMake option to enable Aftermath in GFX and include the aftermath crash example in the project. It provides a descriptive string for the option. ```cmake auto_option( SLANG_ENABLE_AFTERMATH Aftermath "Enable Aftermath in GFX, and add aftermath crash example to project" ) ``` -------------------------------- ### Create New Standard Module CMakeLists.txt Source: https://github.com/shader-slang/slang/blob/master/source/standard-modules/README.md Template for adding a new standard module to the Slang project. Create a CMakeLists.txt in the module subdirectory under source/standard-modules/ using the output directory variable for consistency across modules. ```cmake # Pattern from source/standard-modules/neural/CMakeLists.txt # Use ${SLANG_STANDARD_MODULE_DIR_NAME} for output directory consistency ``` -------------------------------- ### Get Tuple Element Count with countof - Slang Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/03-convenience-features.md Shows how to obtain the number of elements in a tuple type or value using the countof function. The result is a compile-time constant that can be used in type and value contexts. ```csharp int n = countof(Tuple); // 2 int n1 = countof(makeTuple(1,2,3)); // 3 ``` -------------------------------- ### Configure and Build Slang with Ninja Source: https://github.com/shader-slang/slang/blob/master/docs/building.md Configures the build system using CMake presets for a Ninja-based build and then builds Slang with different configurations (releaseWithDebugInfo, debug, release). Requires CMake 3.25+. ```bash cmake --preset default cmake --build --preset releaseWithDebugInfo # or --preset debug, or --preset release ``` -------------------------------- ### Private Visibility Scope in Slang Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/04-modules-and-access-control.md Demonstrates the scope of `private` visibility in Slang. Private symbols are only visible to other symbols within the same type. This example shows a private member `member` within `MyType` and how its accessibility is restricted. ```csharp struct MyType { private int member; int f() { member = 5; } // OK. struct ChildType { int g(MyType t) { return t.member; // OK. } } } void outerFunc(MyType t) { t.member = 2; // Error, `member` is not visible here. } ``` -------------------------------- ### Override Subscript Operator with __subscript - Slang Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/03-convenience-features.md Shows how to override the subscript operator [] using __subscript syntax with get and set accessors. Supports multi-dimensional subscripting for custom index mapping and value access patterns. ```csharp struct MyType { int val[12]; __subscript(int x, int y) -> int { get { return val[x*3 + y]; } set { val[x*3+y] = newValue; } } } int test() { MyType rs; rs[0, 0] = 1; rs[1, 0] = rs[0, 0] + 1; return rs[1, 0]; // returns 2. } ``` -------------------------------- ### Compile Slang to GLSL - Command Line Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/01-get-started.md Command-line invocation of slangc compiler to cross-compile a Slang shader to GLSL format instead of binary SPIRV. Uses same profile and entry point settings as the SPIRV compilation example. ```batch .\slangc.exe hello-world.slang -profile glsl_450 -target glsl -o hello-world.glsl -entry computeMain ``` -------------------------------- ### Slang Interface Definition and Implementation Example Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/06-interfaces-generics.md Defines a Slang interface 'IFoo' with a method 'foo' and a struct 'MyObject' that implements this interface. This serves as a basic example for interface conformance in Slang. ```csharp interface IFoo { int foo(); }; struct MyObject : IFoo { int foo() { return 0; } } ``` -------------------------------- ### Setting Slang __global Variable from C++ Host Code Source: https://github.com/shader-slang/slang/blob/master/docs/cpu-target.md Provides a C++ example demonstrating how to set the value of a Slang `__global` variable (`myGlobal`) from host code. It retrieves the shared library interface and uses `findSymbolAddressByName` to get a pointer to the global variable, which is then modified. ```C++ slang::ICompileRequest = ...; // Get the 'shared library' (note that this doesn't necessarily have to be implemented as a shared library // it's just an interface to executable code). ComPtr sharedLibrary; SLANG_RETURN_ON_FAIL(request->getTargetHostCallable(0, sharedLibrary.writeRef())); // Set myGlobal to 20 { auto myGlobalPtr = (int*)sharedLibrary->findSymbolAddressByName("myGlobal"); *myGlobalPtr = 20; } ``` -------------------------------- ### Error Handling: Catching Errors with do-catch in Slang Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/03-convenience-features.md Provides an example of catching errors in Slang using the `do-catch` statement. The code attempts to call a potentially throwing function `f` and handles the `MyError` type if it occurs. ```slang void g() { do { let result = try f(); printf("Success: %d\n", result); } catch(err: MyError) { printf("Not good!\n"); } } ``` -------------------------------- ### CMake: Configure slangd Language Server Source: https://github.com/shader-slang/slang/blob/master/tools/CMakeLists.txt Conditionally builds the 'slangd' executable (language server) if SLANG_ENABLE_SLANGD is defined. It links against several core Shader-Slang libraries and sets installation properties. ```cmake if(SLANG_ENABLE_SLANGD) slang_add_target( slangd EXECUTABLE LINK_WITH_PRIVATE core compiler-core slang slang-fiddle-output slang-capability-defs Threads::Threads INSTALL EXPORT_SET_NAME SlangTargets ) endif() ``` -------------------------------- ### Slang Inferred Function Capability Requirements Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/05-capabilities.md Illustrates how Slang infers capability requirements for internal/private functions. The `myFunc` example, containing a `discard` statement, infers capabilities related to `spirv`, `glsl`, `hlsl`, and the `fragment` shader stage. ```csharp void myFunc() { if (getClock().x % 1000 == 0) discard; } ``` -------------------------------- ### Build Slang from Source on Windows (CMake) Source: https://github.com/shader-slang/slang/blob/master/CONTRIBUTING.md Generates build files for Slang using CMake on Windows, targeting Visual Studio 2022 or 2019. It also shows how to build the release preset or configure without LLVM for ARM64. ```bash C:\git\slang> cmake.exe --preset vs2022 # For Visual Studio 2022 C:\git\slang> cmake.exe --preset vs2019 # For Visual Studio 2019 C:\git\slang> cmake.exe --build --preset release cmake.exe --preset vs2022 -DSLANG_SLANG_LLVM_FLAVOR=DISABLE ``` -------------------------------- ### Configure and Build Slang with Visual Studio Source: https://github.com/shader-slang/slang/blob/master/docs/building.md Configures the build system for Visual Studio (2022 or 2019) using CMake presets. It then provides commands to build Slang from the command line with different configurations. An option to open the solution in Visual Studio is also included. ```bash cmake --preset vs2022 # or 'vs2019' or `vs2022-dev` start devenv ./build/slang.sln # to optionally open the project in Visual Studio cmake --build --preset releaseWithDebugInfo # to build from the CLI, could also use --preset release or --preset debug ``` -------------------------------- ### SPIR-V Matrix Type Translation Example Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/a2-01-spirv-target-specific.md Demonstrates how Slang's float3x4 matrix type is translated into SPIR-V's OpTypeMatrix. Slang emits a matrix consisting of three vectors, each with four elements, aligning with its row-major interpretation. ```SPIR-V %float = OpTypeFloat 32 %v4float = OpTypeVector %float 4 ; <= float4 type %mat3v4float = OpTypeMatrix %v4float 3 ; <= three of float4 ``` -------------------------------- ### LLDB Debugging with command line Source: https://github.com/shader-slang/slang/blob/master/docs/debugging.md This example shows how to use LLDB from the command line to debug the Slang compiler. It requires building Slang with the 'debug' preset and assumes the presence of a .lldbinit file for data formatters. The output includes setting a breakpoint and running the debugger. ```shell $ cmake --build --preset debug $ lldb --local-lldbinit build/Debug/bin/slangc -- tests/byte-code/hello.slang -dump-ir (lldb) breakpoint set --name dumpIR (lldb) run ``` -------------------------------- ### Labeled Break Statement in Slang Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/03-convenience-features.md Illustrates the use of labeled break statements in Slang, allowing jumps to ancestor control flow points, not just immediate parents. The example shows breaking out of nested loops using an 'outer' label. ```slang outer: for (int i = 0; i < 5; i++) { inner: for (int j = 0; j < 10; j++) { if (someCondition) break outer; } } ``` -------------------------------- ### Build Project with CMake Presets Source: https://github.com/shader-slang/slang/blob/master/CLAUDE.md Configures and builds the Slang project using CMake presets. 'default' uses Ninja Multi-Config, while 'vs2022' is preferred for Windows. Building release or debug binaries can take significant time. ```bash cmake --preset default cmake.exe --preset vs2022 cmake --build --preset debug cmake --build --preset release cmake --build --preset debug --target slangc cmake --build --preset debug --target slang-test ``` -------------------------------- ### SPIR-V Assembly with Enum Values Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/a1-04-interop.md This example demonstrates using SPIR-V enum values directly as operands within an `spirv_asm` block. Here, `Device AcquireRelease|ImageMemory` is used as a flag for the `OpMemoryBarrier` instruction, showcasing direct integration of SPIR-V constants. ```cpp void memoryBarrierImage() { spirv_asm { OpMemoryBarrier Device AcquireRelease|ImageMemory }; } ``` -------------------------------- ### Interface with Associated Type in Slang Source: https://github.com/shader-slang/slang/blob/master/docs/language-guide.md This example demonstrates the use of associated types within an interface in Slang, specifically for defining an 'IMaterial' interface. It introduces an 'associatedtype B' which must conform to the 'IBRDF' interface, allowing implementing types to specify their own BRDF implementation. ```hlsl // A reflectance function interface IBRDF { float3 eval(float3 wi, float3 wo); } struct DisneyBRDF : IBRDF { ... }; struct KajiyaKay : IBRDF { ... }; // a surface pattern interface IMaterial { associatedtype B : IBRDF; B evalPattern(float3 position, float2 uv); } struct MyCoolMaterial : IMaterial { typedef DisneyBRDF B; B evalPattern(float3 position, float2 uv) { ... } } ``` -------------------------------- ### Enable DX11/DX12 on Vulkan via VKD3D-Proton (SLANG_ENABLE_DX_ON_VK) Source: https://github.com/shader-slang/slang/blob/master/docs/building.md This option allows running DX11 and DX12 tests on non-Windows platforms using vkd3d-proton. It requires system-provided D3D headers and is controlled by the SLANG_ENABLE_DX_ON_VK flag. ```build configuration `SLANG_ENABLE_DX_ON_VK` (Default: `FALSE`) ``` -------------------------------- ### Slang Structure Type Constructors Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/02-conventional-features.md Demonstrates how to define constructors for Slang structure types using the `__init` keyword. It includes examples of a default constructor and an overloaded constructor. ```hlsl struct MyData { int a; __init() { a = 5; } __init(int t) { a = t; } } void test() { MyData d; MyData h = MyData(4); } ``` -------------------------------- ### Print Entry Point Layout Information (C++) Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/09-reflection.md This C++ function demonstrates how to iterate through entry point reflection data and switch based on the shader stage to print relevant layout information. It is designed to be used with the Slang reflection API. ```c++ void printEntryPointLayout(slang::EntryPointReflection* entryPointLayout) { // ... switch (entryPointLayout->getStage()) { default: break; // ... } // ... } ``` -------------------------------- ### Generic Function for Computing Diffuse Lighting in Slang Source: https://github.com/shader-slang/slang/blob/master/docs/language-guide.md This example shows a generic function 'computeDiffuse' that accepts any type 'L' implementing the 'ILight' interface. It calculates diffuse lighting by sampling the provided light source. This promotes code reuse and type safety. ```hlsl // diffuse.slang import light; float4 computeDiffuse( float4 albedo, float3 P, float3 N, L light ) { LightSample sample = light.sample(P); float nDotL = max(0, dot(N, sample.direction)); return albedo * nDotL; } ``` -------------------------------- ### Generate Shader-Slang Core Module Documentation with slangc Source: https://github.com/shader-slang/slang/blob/master/docs/stdlib-docgen.md This command sequence demonstrates how to clone the stdlib-reference repository, clean existing generated files, and then use `slangc` to generate updated markdown documentation for the core module. It also shows an optional step to move the generated table of contents file. ```bash # clone stdlib-reference repo git clone https://github.com/shader-slang/stdlib-reference cd stdlib-reference # delete existing pages rm -rf ./interfaces rm -rf ./types rm -rf ./global-decls rm -rf ./attributes # generate updated pages slangc -compile-core-module -doc # optional: move generated toc.html to `_includes` mv toc.html ./_includes/stdlib-reference-toc.html ``` -------------------------------- ### Hoisted Primal Control Flow Example in Slang Source Style Source: https://github.com/shader-slang/slang/blob/master/docs/design/autodiff/ir-overview.md Illustrates the function after the primal hoisting step, where primal control flow is cloned to the start of the top-level differential region. It shows the placement of recompute blocks and potential issues with accessing values within branches. ```C void f_rev_hoisted(DifferentialPair dpx, float d_out) { // // Primal blocks (will be extracted into a separate function in Step 6: Extraction) // float x = dpx.getPrimal(); float p = 0; if (x < 0.5) { float t1 = x * x; p = t1 * t1 + x; } if (x > 10.f) { float t2 = x * x * x; p = t2 * t2 + x; } // // Reversed differential blocks start here (will be extracted into a separate function in Step 6: Extraction) // // Recompute blocks are inserted at the beginning of each differential region. float x_recompute = dpx.getPrimal(); if (x_recompute < 0.5) { // Only the t1 instruction is cloned in since it is used by the differential blocks. float t1_recompute = x_recompute * x_recompute; } if (x_recompute > 10.f) { // Only the t2 instruction is cloned in since it is used by the differential blocks. float t2_recompute = x_recompute * x_recompute * x_recompute; } float dp_rev = d_out; float dx_rev = 0.f; // accumulator var for 'x.d' if (x_recompute > 10.f) { float dt2_rev = t2_recompute * dp_rev; // invalid access of 't2_recompute' (it's inside a branch) dx_rev += dp_rev; dx_rev += x_recompute * x_recompute * dt2_rev; dx_rev += x_recompute * dt2_rev * x_recompute; dx_rev += dt2_rev * x_recompute * x_recompute; } if (x < 0.5) // ... (rest of the code is truncated in the example) } ``` -------------------------------- ### Force Inline Decoration in Slang Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/03-convenience-features.md Shows how to use the `[ForceInline]` attribute in Slang to instruct the compiler to inline function calls, which is often done by downstream compilers anyway. The example defines a simple function `f` that is marked for forced inlining. ```slang [ForceInline] int f(int x) { return x + 1; } ``` -------------------------------- ### Slang Uniformity Analysis: Forcing Dynamic Uniform with asDynamicUniform Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/a1-05-uniformity.md This example shows how to use the `asDynamicUniform()` function in Slang to explicitly force the compiler to treat a value as dynamic uniform, even if it cannot deduce it automatically. This is useful when you are certain a value can be treated uniformly. ```csharp void expectUniform(dynamic_uniform int x) {} void main(int tid: SV_DispatchThreadID) { expectUniform(asDynamicUniform(tid)); // OK. } ``` -------------------------------- ### Documenting Overloaded Functions in Shader-Slang Source: https://github.com/shader-slang/slang/blob/master/docs/stdlib-docgen.md This C# example illustrates how to document overloaded functions in Shader-Slang. It shows that only the first overload needs to be documented, and its comment block should include parameters from all overloads. Directives like @param, @return, and @see are used to structure the documentation. ```csharp /// Samples the texture at the given location. /// ///@param s The `SamplerState` to use for the sampling operation. This parameter is omitted when `this` is a combined texture sampler type (`isCombined == 0`). ///@param location The location to sample the texture at. ///@param offset Texel offset to apply. ///@param clamp The max level of detail to use. ///@param[out] status The result status of the operation. /// This parameter is currently only used when targeting HLSL. /// For other targets, the result status is always 0. ///@return The sampled texture value. ///@see `SampleBias`, `SampleLevel`, `SampleGrad`, `SampleCmp`, `SampleCmpLevelZero`. ///@remarks /// The `Sample` function is defined for all read-only texture types, including /// `Texture1D`, `Texture2D`, `Texture3D`, `TextureCube`, /// `Texture1DArray`, `Texture2DArray` and `TextureCubeArray`. /// /// The function is not available for read-write texture types. /// /// For HLSL/D3D targets, the texture element type must be a scalar or vector of float or half types. /// [__readNone] [ForceInline] [require(cpp_cuda_glsl_hlsl_metal_spirv_wgsl, texture_sm_4_0_fragment)] T Sample(vector location) { ... } [__readNone] [ForceInline] [require(cpp_glsl_hlsl_metal_spirv_wgsl, texture_sm_4_0_fragment)] T Sample(vector location, constexpr vector offset) { ... } ``` -------------------------------- ### Compare Tuples with IComparable - Slang Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/03-convenience-features.md Demonstrates comparison operators on tuples when all element types conform to IComparable interface. Tuple instances can be compared using standard comparison operators. ```csharp let cmp = t0 < t1; // false ``` -------------------------------- ### Error Handling: Throwing Errors in Slang Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/03-convenience-features.md Demonstrates Slang's error handling mechanism, which is explicit and performant. Functions can declare thrown error types using `throws`. The example defines an enum `MyError` and a function `f` that can throw `MyError.CatastrophicFailure`. ```slang enum MyError { Failure, CatastrophicFailure } int f() throws MyError { if (computerIsBroken()) throw MyError.CatastrophicFailure; return 42; } ``` -------------------------------- ### Clone Slang Repository Source: https://github.com/shader-slang/slang/blob/master/docs/building.md Clones the Slang repository and its submodules recursively. This is the initial step to obtain the source code for building. ```bash git clone https://github.com/shader-slang/slang --recursive ``` -------------------------------- ### Run Slang Tests Source: https://github.com/shader-slang/slang/blob/master/docs/building.md Executes the Slang test suite. The executable path may vary depending on the build configuration (e.g., Debug). ```bash build/Debug/bin/slang-test ``` -------------------------------- ### Overriding Descriptor Handle Conversion in SPIR-V with User Code Source: https://github.com/shader-slang/slang/blob/master/docs/user-guide/03-convenience-features.md Demonstrates how to override the default behavior for converting bindless handles to resource handles in SPIR-V. This example uses custom descriptor set bindings for resources and samplers and a user-defined getDescriptorFromHandle function. ```slang // All texture and buffer handles are defined in descriptor set 100. [vk::binding(0, 100)] __DynamicResource<__DynamicResourceKind.General> resourceHandles[]; // All sampler handles are defined in descriptor set 101. [vk::binding(0, 101)] __DynamicResource<__DynamicResourceKind.Sampler> samplerHandles[]; export T getDescriptorFromHandle(DescriptorHandle handle) where T : IOpaqueDescriptor { __target_switch { case spirv: if (T.kind == DescriptorKind.Sampler) return samplerHandles[((uint2)handle).x].asOpaqueDescriptor(); else return resourceHandles[((uint2)handle).x].asOpaqueDescriptor(); default: ```