### Initialize Generation Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/generator-class.md Called at the start of generation to perform any initialization. Override to add custom setup. ```cpp virtual ErrMsg begin(const GenInput& gen); ``` -------------------------------- ### Resource Binding Slot Constants Example Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/compilation-flow.md Example of generated resource binding slot constants. ```c #define SG_SLOT_MY_PROGRAM_PARAMS 0 #define SG_SLOT_MY_PROGRAM_TEX_DIFFUSE 1 ``` -------------------------------- ### Reflection Function Example Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/compilation-flow.md Example of generated runtime reflection functions. ```c const char* my_program_attr_name(int attr_slot) { ... } int my_program_texture_slot(const char* tex_name) { ... } ``` -------------------------------- ### Implementing and using a custom Generator Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/generator-class.md Example of extending the base Generator class and executing the generation pipeline. ```cpp #include "generators/generator.h" class MyLanguageGenerator : public Generator { // Implement pure virtual methods... }; MyLanguageGenerator gen; GenInput input = /* ... populated from parsed shaders ... */; ErrMsg err = gen.generate(input); if (err.valid()) { fprintf(stderr, "Generation failed: %s\n", err.msg.c_str()); return 1; } std::string output = gen.content; // Retrieve generated source code ``` -------------------------------- ### Get Help for sokol-shdc Source: https://github.com/floooh/sokol-tools/blob/master/README.md Run the sokol-shdc tool with the --help flag to display its command-line options and usage instructions. ```bash ./fibs run sokol-shdc --help ``` -------------------------------- ### Descriptor Builder Function Example Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/compilation-flow.md Example of a generated descriptor builder function. ```c sg_shader_desc my_program_shader_desc(void) { return (sg_shader_desc) { ... }; } ``` -------------------------------- ### Slang Usage Examples Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/types.md Demonstrates common usage patterns for Slang enum bitmasks and string conversion. ```cpp uint32_t targets = Slang::bit(Slang::GLSL430) | Slang::bit(Slang::HLSL5); // targets = 0x00000808 (bits 3 and 11 set) const char* name = Slang::to_str(Slang::GLSL430); // "glsl430" bool is_mobile = Slang::is_glsl(lang) && !Slang::is_glsl(Slang::GLSL410); ``` -------------------------------- ### Uniform Structure Definition Example Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/compilation-flow.md Example of a generated uniform structure definition. ```c typedef struct { float time; float aspect; } params_t; ``` -------------------------------- ### Check Deno Version Source: https://github.com/floooh/sokol-tools/blob/master/README.md Verify that the Deno version is compatible with sokol-tools. Ensure Deno is installed and accessible in your PATH. ```bash deno --version ``` -------------------------------- ### Vertex Attribute Constants Example Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/compilation-flow.md Example of generated vertex attribute slot constants. ```c #define MY_PROGRAM_VS_POSITION 0 #define MY_PROGRAM_VS_TEXCOORD 1 ``` -------------------------------- ### Complete ErrMsg Usage Example Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/errmsg-class.md Demonstrates creating error messages, printing them in different formats, and checking validity. ```cpp #include "types/errmsg.h" #include int main() { // Create various error messages ErrMsg err1 = ErrMsg::error("shader.glsl", 42, "Undefined variable 'mvp'"); ErrMsg warn1 = ErrMsg::warning("shader.glsl", 10, "Unused uniform 'unused_param'"); ErrMsg err2 = ErrMsg::error("Failed to compile"); // Print in GCC format std::cout << "GCC Format:\n"; err1.print(ErrMsg::GCC); // shader.glsl:43:0: error: Undefined variable 'mvp' warn1.print(ErrMsg::GCC); // shader.glsl:11:0: warning: Unused uniform 'unused_param' err2.print(ErrMsg::GCC); // :0: error: Failed to compile // Print in MSVC format std::cout << "\nMSVC Format:\n"; err1.print(ErrMsg::MSVC); // shader.glsl(43): error: Undefined variable 'mvp' warn1.print(ErrMsg::MSVC); // shader.glsl(11): warning: Unused uniform 'unused_param' // Convert to strings and manipulate std::string msg = err1.as_string(ErrMsg::GCC); std::cout << "Message: " << msg << "\n"; // Check validity ErrMsg success; // type = NONE by default if (!success.valid()) { std::cout << "Success - no error\n"; } return 0; } ``` -------------------------------- ### Check Ninja Version Source: https://github.com/floooh/sokol-tools/blob/master/README.md Optionally, check if Ninja is installed, which may be used as a build system generator. ```bash ninja --version ``` -------------------------------- ### Check CMake Version Source: https://github.com/floooh/sokol-tools/blob/master/README.md Verify that CMake is installed and meets the minimum version requirement for sokol-tools. ```bash cmake --version ``` -------------------------------- ### Embedded Shader Arrays Example Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/compilation-flow.md Example of generated embedded shader bytecode or source code arrays. ```c static const uint8_t my_program_vs_spirv_vk[1024] = { ... }; static const char* my_program_vs_source_glsl430 = "..."; ``` -------------------------------- ### Module Keyword Override Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Example of the @module keyword used for code generation. ```text @module ``` -------------------------------- ### Define a fragment shader with @fs Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Starts a named fragment shader block that is compiled as a fragment shader. ```glsl @fs my_fragment_shader in vec4 color; out vec4 frag_color; void main() { frag_color = color; } @end ``` -------------------------------- ### Usage of format_to_str Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/errmsg-class.md Example of using the static format_to_str method to retrieve the error format name. ```cpp Args args = Args::parse(argc, argv); const char* fmt_name = ErrMsg::format_to_str(args.error_format); // "gcc" or "msvc" ``` -------------------------------- ### Define a vertex shader with @vs Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Starts a named vertex shader block that is compiled as a vertex shader. ```glsl @vs my_vertex_shader layout(binding=0) uniform vs_params { mat4 mvp; }; in vec4 position; in vec4 color0; out vec4 color; void main() { gl_Position = mvp * position; color = color0; } @end ``` -------------------------------- ### Define Uniform Blocks in GLSL Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Example of defining uniform blocks with explicit binding slots in vertex and fragment shaders. ```glsl @ctype mat4 hmm_mat4 @ctype vec4 hmm_vec4 @vs layout(binding=0) uniform vs_params { mat4 mvp; }; ... @end @fs layout(binding=1) uniform fs_params { vec4 color; }; ... @end ``` -------------------------------- ### init() Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/shdc-class.md Initializes the Shdc compiler system and sets up internal resources. ```APIDOC ## void init() ### Description Initializes the Shdc compiler system, setting up any required internal resources and state. ### Parameters None ### Return Type void ``` -------------------------------- ### Initialize Shdc Instance Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/compilation-flow.md Sets up internal state, memory pools, and compiler dependencies. ```cpp Shdc shdc; shdc.init(); // Set up internal state, initialize dependencies ``` -------------------------------- ### Invoke sokol-shdc from the command line Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Run the compiler to generate a C header file from the annotated GLSL source. ```bash > ./sokol-shdc --input shd.glsl --output shd.h --slang glsl430:hlsl5:metal_macos ``` -------------------------------- ### Accessing Shader Reflection Data in C++ Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/reflection-classes.md Demonstrates building a reflection object and iterating through programs, textures, and uniform block fields. ```cpp #include "reflection.h" #include "input.h" // After parsing and reflection building Reflection refl = Reflection::build(args, input, spirvcross); if (refl.error.valid()) { fprintf(stderr, "Reflection error: %s\n", refl.error.msg.c_str()); return 1; } // Access a program and its resources for (const auto& prog : refl.progs) { printf("Program: %s\n", prog.name.c_str()); // Look up a specific texture const auto* tex = prog.bindings.find_texture_by_name("albedo_tex"); if (tex) { printf(" Texture 'albedo_tex' at slot %d, type=%s\n", tex->sokol_slot, ImageType::to_str(tex->type)); } // Iterate all uniform blocks for (const auto& ub : prog.bindings.uniform_blocks) { printf(" Uniform block '%s' at slot %d\n", ub.name.c_str(), ub.sokol_slot); for (const auto& field : ub.struct_info.struct_items) { printf(" Field '%s': %s (offset=%d)\n", field.name.c_str(), Type::type_to_str(field.type).c_str(), field.offset); } } } ``` -------------------------------- ### Perform Resource Lookup via Reflection Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/sampler-and-resources.md Demonstrates how to retrieve resource bindings by name or slot after building the reflection object. ```cpp #include "reflection.h" Reflection refl = Reflection::build(args, input, spirvcross); for (const auto& prog : refl.progs) { const auto& bindings = prog.bindings; // Find specific resources by name const Texture* tex = bindings.find_texture_by_name("diffuse"); const Sampler* smp = bindings.find_sampler_by_name("linear_sampler"); const UniformBlock* ub = bindings.find_uniform_block_by_name("params"); const StorageBuffer* sbuf = bindings.find_storage_buffer_by_name("particle_data"); // Find resources by sokol slot const Texture* slot0_tex = bindings.find_texture_by_sokol_slot(0); const UniformBlock* slot1_ub = bindings.find_uniform_block_by_sokol_slot(1); // Iterate all resources of a type for (const auto& texture : bindings.textures) { printf("Texture '%s' at slot %d\n", texture.name.c_str(), texture.sokol_slot); } for (const auto& sampler : bindings.samplers) { printf("Sampler '%s' (type=%s)\n", sampler.name.c_str(), SamplerType::to_str(sampler.type)); } for (const auto& ub : bindings.uniform_blocks) { printf("Uniform block '%s' at slot %d\n", ub.name.c_str(), ub.sokol_slot); // Access structure members for (const auto& field : ub.struct_info.struct_items) { printf(" Field '%s': %s\n", field.name.c_str(), Type::type_to_str(field.type).c_str()); } } } ``` -------------------------------- ### Create Shader and Pipeline Objects Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Initialize a shader and pipeline using the generated descriptor and attribute constants. ```c // create a shader object from generated sg_shader_desc: sg_shader shd = sg_make_shader(texcube_shader_desc(sg_query_backend())); // create a pipeline object with this shader, and // code-generated vertex attribute location constants // (ATTR_vs_position and ATTR_vs_color0) pip = sg_make_pipeline(&(sg_pipeline_desc){ .shader = shd, .layout = { .attrs = { [ATTR_texcube_position].format = SG_VERTEXFORMAT_FLOAT3, [ATTR_texcube_texcoord0].format = SG_VERTEXFORMAT_FLOAT2, } } }); ``` -------------------------------- ### Generate basic C header Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/configuration.md Creates a C header file supporting OpenGL and HLSL. ```bash sokol-shdc -i shaders.glsl -o shaders.h -l glsl430:hlsl5 -f sokol ``` -------------------------------- ### Create graphics program Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/snippet-and-program.md Factory method to initialize a graphics program with vertex and fragment shaders. ```cpp static Program from_vs_fs(const std::string& name, const std::string& vs_name, const std::string& fs_name, int line_index); ``` ```cpp Program gfx = Program::from_vs_fs("lighting", "vs_lighting", "fs_lighting", 50); ``` -------------------------------- ### Generate Dependency File Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/README.md Creates a dependency file for build system integration. ```bash sokol-shdc -i shaders.glsl -o shaders.h \ -l glsl430 \ --dependency-file shaders.h.d ``` -------------------------------- ### Define a compute shader with @cs Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Starts a named compute shader block that is compiled as a compute shader. ```glsl @cs my_compute_shader layout(binding=0) uniform cs_params { float dt; int num_particles; }; struct particle { vec4 pos; vec4 vel; }; layout(binding=0) buffer cs_ssbo { particle prt[]; }; layout(local_size_x=64, local_size_y=1, local_size_z=1) in; void main() { uint idx = gl_GlobalInvocationID.x; if (idx >= num_particles) { return; } vec4 pos = prt[idx].pos; vec4 vel = prt[idx].vel; vel.y -= dt; pos += vel * dt; prt[idx].pos = pos; prt[idx].vel = vel; } @end ``` -------------------------------- ### Usage of warning() Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/input-class.md Shows how to generate and print a warning message. ```cpp Input input = Input::load_and_parse("shader.glsl", ""); if (deprecated_syntax_detected) { ErrMsg warn = input.warning(10, "Deprecated @ctype syntax"); warn.print(ErrMsg::GCC); } ``` -------------------------------- ### run() Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/shdc-class.md Executes the shader compilation and code generation pipeline. ```APIDOC ## int run(const Args& argc) ### Description Executes the shader compilation and code generation pipeline according to the provided arguments. ### Parameters - **argc** (const Args&) - Required - Parsed command-line arguments specifying input file, output format, target languages, and other options ### Return Type int (Returns 0 on success, non-zero on failure) ``` -------------------------------- ### Clone and Build sokol-tools Source: https://github.com/floooh/sokol-tools/blob/master/README.md Clone the sokol-tools repository recursively to include submodules, then build the project using the provided build script. ```bash git clone --recursive https://github.com/floooh/sokol-tools.git cd sokol-tools ./fibs build ``` -------------------------------- ### Create compute shader program Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/snippet-and-program.md Factory method to initialize a compute shader program. ```cpp static Program from_cs(const std::string& name, const std::string& cs_name, int line_index); ``` ```cpp Program compute = Program::from_cs("postprocess", "cs_blur", 100); ``` -------------------------------- ### Initialize Shdc system Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/shdc-class.md Initializes internal resources for the compiler. ```cpp void init(); ``` ```cpp Shdc shdc; shdc.init(); // ... use shdc.run() ... shdc.deinit(); ``` -------------------------------- ### Generate Multi-Platform Header with Reflection Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/README.md Compiles shaders for multiple platforms with reflection data and binary output enabled. ```bash sokol-shdc -i shaders.glsl -o shaders.h \ -l glsl430:glsl300es:hlsl5:metal_macos:wgsl \ -f sokol -r -b ``` -------------------------------- ### Optional Command-Line Options Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/README.md Additional flags to customize the compilation process, such as output format, reflection, and debugging. ```text -f, --format FORMAT Output format (default: sokol) -r, --reflection Generate reflection functions -b, --bytecode Generate bytecode (HLSL/Metal) -m, --module NAME Override @module name -e, --errfmt FORMAT Error format (gcc or msvc) --defines D1:D2:D3 Preprocessor defines --ifdef Wrap in #ifdef guards --tmpdir DIR Temporary directory --dependency-file FILE Generate dependency file --save-intermediate-spirv Save SPIR-V files --no-log-cmdline Omit cmdline from output -d, --dump Debug dump to stderr -h, --help Show help ``` -------------------------------- ### Generate Basic C Header Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/README.md Produces a C header file from a GLSL source for multiple shading languages. ```bash sokol-shdc -i shaders.glsl -o shaders.h -l glsl430:hlsl5:metal_macos -f sokol ``` -------------------------------- ### Parse Shader Input in C++ Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/snippet-and-program.md Demonstrates loading and parsing a shader file, iterating through snippets and programs, and accessing specific shader data. ```cpp #include "input.h" #include "types/snippet.h" #include "types/program.h" int main() { Input input = Input::load_and_parse("shaders.glsl", ""); if (input.out_error.valid()) { input.out_error.print(ErrMsg::GCC); return 1; } // Iterate all snippets printf("Snippets:\n"); for (const auto& snippet : input.snippets) { printf(" [%d] %s (%s)\n", snippet.index, snippet.name.c_str(), Snippet::type_to_str(snippet.type)); } // Iterate all programs printf("\nPrograms:\n"); for (const auto& [prog_name, program] : input.programs) { printf(" %s:\n", program.name.c_str()); if (program.has_vs_fs()) { printf(" Graphics: %s (vs) + %s (fs)\n", program.vs_name.c_str(), program.fs_name.c_str()); } else if (program.has_cs()) { printf(" Compute: %s (cs)\n", program.cs_name.c_str()); } } // Access specific snippet auto vs_it = input.vs_map.find("my_vertex_shader"); if (vs_it != input.vs_map.end()) { const Snippet& vs = input.snippets[vs_it->second]; printf("\nVertex shader '%s' has %zu source lines\n", vs.name.c_str(), vs.lines.size()); } return 0; } ``` -------------------------------- ### Generate File Prologue Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/generator-class.md Generates file prologue including license headers, include guards, and standard includes. ```cpp virtual void gen_prolog(const GenInput& gen); ``` -------------------------------- ### Build sokol-tools with Docker Source: https://github.com/floooh/sokol-tools/blob/master/README.md Build sokol-tools within a Docker container for a consistent build environment, especially if native builds fail. ```bash ./build_docker.sh ``` -------------------------------- ### Configure sokol-tools for IDE Debugging Source: https://github.com/floooh/sokol-tools/blob/master/README.md Set up the build configuration for various IDEs to enable debugging. Choose the configuration that matches your development environment. ```bash ./fibs config macos-xcode-debug ``` ```bash ./fibs config macos-vscode-debug ``` ```bash ./fibs config win-vstudio-debug ``` ```bash ./fibs config win-vscode-debug ``` ```bash ./fibs config linux-vscode-debug ``` -------------------------------- ### Orchestrate manual compilation steps Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/compilation-flow.md Demonstrates manual control over the compilation pipeline, including loading input, compiling to target languages, extracting reflection data, and generating output code. ```cpp #include "input.h" #include "reflection.h" #include "generators/generator.h" #include "spirvcross.h" using namespace shdc; using namespace shdc::refl; using namespace shdc::gen; int main() { // Parse arguments Args args; args.input = "shaders.glsl"; args.output = "shaders.h"; args.slang = Slang::bit(Slang::GLSL430) | Slang::bit(Slang::HLSL5); args.output_format = Format::SOKOL; args.valid = true; // Load and parse input Input input = Input::load_and_parse(args.input, ""); if (input.out_error.valid()) { input.out_error.print(ErrMsg::GCC); return 1; } // Compile to target languages Spirvcross spirvcross; spirvcross.compile(input, args.slang, args.defines); // Extract reflection Reflection refl = Reflection::build(args, input, spirvcross); if (refl.error.valid()) { refl.error.print(ErrMsg::GCC); return 1; } // Generate code SokolCGenerator gen; GenInput gen_input = { args, input, refl, spirvcross }; ErrMsg gen_err = gen.generate(gen_input); if (gen_err.valid()) { gen_err.print(ErrMsg::GCC); return 1; } // Write output FILE* f = fopen(args.output.c_str(), "w"); fprintf(f, "%s", gen.content.c_str()); fclose(f); printf("Success: %s\n", args.output.c_str()); return 0; } ``` -------------------------------- ### Usage of load_and_parse Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/input-class.md Demonstrates loading a file and checking for parsing errors. ```cpp #include "input.h" Input input = Input::load_and_parse("shaders/example.glsl", ""); if (input.out_error.valid()) { input.out_error.print(ErrMsg::GCC); return 1; } // Successfully parsed; input.snippets, input.programs, etc. now contain extracted data ``` -------------------------------- ### Lookup Resources by Name Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/reflection-classes.md Use find_*_by_name methods to retrieve resources. These methods return nullptr if the resource is not found. ```cpp const UniformBlock* ub = bindings.find_uniform_block_by_name("params"); if (ub) { printf("Found uniform block 'params' at slot %d\n", ub->sokol_slot); } ``` -------------------------------- ### Args::parse() Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/args-class.md Parses command-line arguments and returns an Args structure with all settings initialized. ```APIDOC ## Args::parse(int argc, const char** argv) ### Description Parses command-line arguments and returns an Args structure with all settings initialized. Returns an Args structure with `valid = true` if parsing succeeded, or `valid = false` with an appropriate `exit_code` if parsing or validation failed. ### Parameters - **argc** (int) - Required - Argument count from main(int argc, const char** argv) - **argv** (const char**) - Required - Argument vector from main() ### Supported Options - `-h, --help`: Print help text - `-i, --input FILE`: Input GLSL source file (required) - `-o, --output FILE`: Output code-generated header file (required) - `-l, --slang LANGS`: Target shader languages as colon-separated list - `-m, --module NAME`: Override @module name from input file - `-b, --bytecode`: Enable bytecode generation for HLSL and Metal - `-r, --reflection`: Enable runtime reflection function generation - `-f, --format FORMAT`: Output format - `-e, --errfmt FORMAT`: Error message format (gcc or msvc) - `-d, --dump`: Print debug information to stderr - `-g, --genver VERSION`: Code generation version stamp - `-t, --tmpdir DIR`: Directory for temporary files - `--defines DEFS`: Additional preprocessor defines - `--ifdef`: Wrap backend code in #ifdef/#endif - `--save-intermediate-spirv`: Save intermediate SPIR-V bytecode files - `--no-log-cmdline`: Omit command line from output comments - `--dependency-file FILE`: Generate a dependency file for build systems ``` -------------------------------- ### Compile shader source with sokol-tools Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/overview.md The standard compilation pipeline involves parsing arguments, initializing the compiler, processing input, generating target code, and writing the output file. ```cpp // 1. Parse arguments Args args = Args::parse(argc, argv); // 2. Initialize compiler Shdc shdc; shdc.init(); // 3. Load and parse input file Input input = Input::load_and_parse(args.input, args.module); // 4. Compile to SPIR-V and all target languages Spirvcross spirvcross; spirvcross.compile(input, args.slang); // 5. Extract reflection metadata Reflection refl = Reflection::build(args, input, spirvcross); // 6. Generate target code Generator* gen = create_generator(args.output_format); GenInput gen_input = { args, input, refl, spirvcross }; ErrMsg err = gen->generate(gen_input); // 7. Write output write_output_file(args.output, gen->content); // 8. Cleanup shdc.deinit(); ``` -------------------------------- ### Input::load_and_parse() Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/input-class.md Loads and parses a GLSL source file, extracting all snippets, programs, and metadata. ```APIDOC ## Input::load_and_parse(const std::string& path, const std::string& module_override) ### Description Loads and parses a GLSL source file, extracting all snippets, programs, and metadata. ### Parameters - **path** (const std::string&) - Required - File system path to the GLSL source file - **module_override** (const std::string&) - Required - Module name override; if non-empty, supersedes @module declaration in file ### Return Type Input ``` -------------------------------- ### Compile with preprocessor defines Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/configuration.md Passes custom preprocessor definitions to the shader compiler. ```bash sokol-shdc -i shaders.glsl -o shaders.h \ -l glsl430 \ --defines USE_NORMAL_MAP:SHADOW_QUALITY=2 ``` -------------------------------- ### Command-Line Interface Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/overview.md The sokol-tools compiler is invoked via command-line arguments to process GLSL source files into target shader languages. ```APIDOC ## Command-Line Usage ### Description Configures the shader compilation process using command-line arguments. ### Parameters #### Required - **-i, --input** (FILE) - Input GLSL source file - **-o, --output** (FILE) - Output code file - **-l, --slang** (LANGS) - Target languages (e.g., glsl430:hlsl5:metal_macos) #### Optional - **-f, --format** (FORMAT) - Output format (sokol, sokol_zig, sokol_rust, etc.) - **-r, --reflection** (flag) - Generate runtime reflection functions - **-b, --bytecode** (flag) - Generate bytecode instead of source - **-m, --module** (NAME) - Override @module name - **--defines** (D1:D2:D3) - Preprocessor defines - **--ifdef** (flag) - Wrap in #ifdef guards - **--dependency-file** (FILE) - Generate build dependency file ``` -------------------------------- ### Build Reflection Metadata Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/compilation-flow.md Extracts metadata for all shader resources. ```cpp Reflection refl = Reflection::build(args, input, spirvcross); if (refl.error.valid()) { return 11; // Reflection error } ``` -------------------------------- ### Required Command-Line Options Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/README.md The mandatory arguments required to run the shader compiler. ```text -i, --input FILE Input GLSL source -o, --output FILE Output code file -l, --slang LANGS Target languages (colon-separated) ``` -------------------------------- ### Apply storage image bindings Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Apply storage image bindings using generated constants or explicit indices. ```c // using the code-generated constant: sg_apply_bindings(&(sg_bindings){ .vertex_buffers[0] = vbuf, .views = { [VIEW_cs_outp_tex] = simg_view, }, }); // or directly using the explicit binding: sg_apply_bindings(&(sg_bindings){ .vertex_buffers[0] = vbuf, .views = { [0] = simg_view, }, }); ``` -------------------------------- ### Apply Bindings and Uniforms Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Bind resources and update uniform blocks using generated constants and structs. ```c sg_apply_bindings(&(sg_bindings){ .vertex_buffers[0] = vbuf, .views[VIEW_tex] = tex_view, .samplers[SMP_smp] = smp, }); const vs_params_t vs_params = { .mvp = ..., }; sg_apply_uniforms(UB_vs_params, &SG_RANGE(vs_params)); ``` -------------------------------- ### Load and parse GLSL source Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/input-class.md Defines the static method signature for loading and parsing a GLSL file. ```cpp static Input load_and_parse(const std::string& path, const std::string& module_override); ``` -------------------------------- ### Apply storage buffer bindings Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Apply storage buffer bindings using either generated constants or explicit binding indices. ```c // using the code-generated constant: sg_apply_bindings(&(sg_bindings){ .vertex_buffers[0] = vbuf, .views = { [VIEW_in_ssbo] = sbuf_view_in, [VIEW_out_ssbo] = sbuf_view_out, }, }); // or directly using the explicit binding: sg_apply_bindings(&(sg_bindings){ .vertex_buffers[0] = vbuf, .views = { [0] = sbuf_view_in, [1] = sbuf_view_out, }, }); ``` -------------------------------- ### Declare Image Sample Type Tags in GLSL Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/sampler-and-resources.md Syntax for defining image sample type tags within input shader files. ```glsl // Define image sample type tags with @image_sample_type @image_sample_type normal_tex float @image_sample_type height_tex float @image_sample_type mask_tex uint @image_sample_type depth_tex depth ``` -------------------------------- ### Specify multiple output shader languages Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Use the --slang flag with colon-separated values to target multiple shader backends. ```bash --slang glsl430:metal_macos ``` -------------------------------- ### Project File Structure Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/README.md The directory layout for the documentation files within the project. ```text output/ ├── README.md (this file) ├── overview.md (high-level overview) ├── types.md (type system reference) ├── configuration.md (options and directives) └── api-reference/ ├── shdc-class.md (Shdc orchestrator) ├── args-class.md (argument parsing) ├── input-class.md (input parsing) ├── errmsg-class.md (error handling) ├── snippet-and-program.md (code organization) ├── generator-class.md (code generation) ├── reflection-classes.md (metadata extraction) ├── sampler-and-resources.md (resource types) └── compilation-flow.md (pipeline orchestration) ``` -------------------------------- ### Define an annotated GLSL shader Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Create a file with @vs, @fs, and @program annotations to define vertex and fragment shaders. ```glsl @vs vs in vec4 pos; void main() { gl_Position = pos; } @end @fs fs out vec4 frag_color; void main() { frag_color = vec4(1.0, 0.0, 0.0, 1.0); } @end @program shd vs fs ``` -------------------------------- ### Define Namespace Prefix with @module Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Using @module to prefix generated C identifiers. ```glsl @module bla @ctype mat4 hmm_mat4 @ctype vec4 hmm_vec4 @vs my_vs layout(binding=0) uniform shape_uniforms { mat4 mvp; mat4 model; vec4 shape_color; vec4 light_dir; vec4 eye_pos; }; @end ``` -------------------------------- ### Parse command-line arguments Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/args-class.md Initializes an Args structure from main function arguments. Returns an object with a valid flag indicating success or failure. ```cpp static Args parse(int argc, const char** argv); ``` ```cpp #include "args.h" int main(int argc, const char** argv) { Args args = Args::parse(argc, argv); if (!args.valid) { return args.exit_code; // Validation failed } // Proceed with compilation using args settings return 0; } ``` -------------------------------- ### Iterate Shader Stage Inputs Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/sampler-and-resources.md Demonstrates how to iterate through shader stage inputs and print attribute details for active slots. ```cpp #include "reflection.h" #include "types/reflection/stage_attr.h" const auto& vs_stage = prog.vs(); for (const auto& input : vs_stage.inputs) { if (input.slot >= 0) { // Check if slot is used printf("Attribute slot %d: %s (type=%s)\n", input.slot, input.name.c_str(), Type::type_to_str(input.type).c_str()); } } ``` -------------------------------- ### Link shader stages with @program Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Links vertex/fragment or compute shader stages into a program and generates the corresponding C shader descriptor function. ```glsl // vertex- and fragment-shader @program my_program my_vertex_shader my_fragment_shader // ...or just a compute shader @program my_program my_compute_shader ``` ```C static const sg_shader_desc* my_program_shader_desc(sg_backend backend); ``` -------------------------------- ### Execute shader compilation Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/shdc-class.md Runs the pipeline using parsed command-line arguments. ```cpp int run(const Args& argc); ``` ```cpp Shdc shdc; shdc.init(); const Args args = Args::parse(argc, argv); if (args.valid) { int exit_code = shdc.run(args); } shdc.deinit(); return exit_code; ``` -------------------------------- ### Configure shader dialects in CMakeLists.txt Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Set the ${slang} variable based on the target platform to ensure the correct shader dialects are generated. ```cmake if (FIPS_EMSCRIPTEN) add_definitions(-DSOKOL_GLES3) set(slang "glsl300es") elseif (FIPS_ANDROID) add_definitions(-DSOKOL_GLES3) set(slang "glsl300es") elseif (SOKOL_USE_D3D11) add_definitions(-DSOKOL_D3D11) set(slang "hlsl5") elseif (SOKOL_USE_METAL) add_definitions(-DSOKOL_METAL) if (FIPS_IOS) set(slang "metal_ios:metal_sim") else() set(slang "metal_macos") endif() elseif (SOKOL_USE_VULKAN) add_definitions(-DSOKOL_VULKAN) set(slang "spirv_vk") else() if (FIPS_IOS) add_definitions(-DSOKOL_GLES3) set(slang "glsl300es") else() add_definitions(-DSOKOL_GLCORE) if (FIPS_MACOS) set(slang "glsl410") else() set(slang "glsl410") endif() endif() endif() ``` -------------------------------- ### Set Output Format Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/configuration.md Define the generated output format using the --format argument, defaulting to 'sokol' if not specified. ```text --format sokol_impl ``` -------------------------------- ### Declare shader programs Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/configuration.md Combines shader snippets into a complete program. ```glsl @program my_program my_vertex_shader my_fragment_shader @program compute_prog my_compute_shader ``` -------------------------------- ### Build reflection information Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/reflection-classes.md Creates a complete reflection object from compiled shader inputs and SPIR-V data. ```cpp static Reflection build(const Args& args, const Input& inp, const std::array& spirvcross); ``` -------------------------------- ### Provide Image Sample Type Hint Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Using @image_sample_type to specify texture sample types for reflection. ```glsl @image_sample_type joint_tex unfilterable_float layout(binding=0) uniform texture2D joint_tex; ``` -------------------------------- ### Apply Uniforms using Generated Constants Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Using the generated bind slot constants to apply uniform data in sokol-gfx. ```c vs_params_t vs_params = { .mvp = ... }; fs_params_t fs_params = { .color = ... }; sg_apply_uniforms(UB_vs_params, &SG_RANGE(vs_params)); sg_apply_uniforms(UB_fs_params, &SG_RANGE(fs_params)); ``` -------------------------------- ### Declare module name Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/configuration.md Sets the namespace for generated code in non-C languages. ```glsl @module myshaders ``` -------------------------------- ### Execute Compilation Pipeline Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/compilation-flow.md Parses command-line arguments and triggers the main execution loop. ```cpp const Args args = Args::parse(argc, argv); if (!args.valid) { return args.exit_code; // Validation failed; print errors already done } int exit_code = shdc.run(args); ``` -------------------------------- ### Open Project in IDE Source: https://github.com/floooh/sokol-tools/blob/master/README.md Open the configured project in your IDE (Xcode, Visual Studio, or VSCode) using the fibs tool. ```bash ./fibs open ``` -------------------------------- ### Use Pragma for Sokol Tags Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Use #pragma sokol to prefix tags for compatibility with other GLSL parsing tools. ```glsl #pragma sokol @program texcube vs fs ``` -------------------------------- ### Inspect Storage Resources Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Functions for querying the bind slots of storage buffers and storage images. ```c int [mod]_[prog]_storagebuffer_slot(const char* sbuf_name); int [mod]_[prog]_storageimage_slot(const char* sbuf_name); ``` -------------------------------- ### Generate Prerequisites Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/generator-class.md Generates prerequisites like custom type definitions and language-specific boilerplate needed before main declarations. ```cpp virtual void gen_prerequisites(const GenInput& gen); ``` -------------------------------- ### Sokol-gfx Backend Selection Defines Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Preprocessor defines used for wrapping backend-specific code when using the --ifdef flag. ```c SOKOL_GLCORE SOKOL_GLES3 SOKOL_D3D11 SOKOL_METAL SOKOL_WGPU SOKOL_VULKAN ``` -------------------------------- ### Inspect Texture and Sampler Bind Slots Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Query the bind slots for textures and samplers to correctly populate the bindings structure. ```c sg_view specular_texture_view = ...; sg_sampler specular_sampler = ...; sg_bindings binds = { ... }; // check if the shader expects a specular texture, // if yes set it in the bindings struct at the expected slot index: const int spec_tex_slot = mod_prog_texture_slot("spec_tex"); const int spec_smp_slot = mod_prog_sampler_slot("spec_smp"); if ((spec_tex_slot >= 0) && (spec_smp_slot >= 0)) { bindings.views[spec_tex_slot] = specular_texture_view; bindings.samplers[spex_smp_slot] = specular_sampler; } // apply bindings sg_apply_bindings(&binds); ``` -------------------------------- ### Lookup Resources by Sokol Slot Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/reflection-classes.md Use find_*_by_sokol_slot methods to retrieve resources. These methods return nullptr if the resource is not found. ```cpp const Texture* tex = bindings.find_texture_by_sokol_slot(0); if (tex) { printf("Texture at slot 0: %s\n", tex->name.c_str()); } ``` -------------------------------- ### Configure Target Shader Languages Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/configuration.md Specify multiple target shader languages using a colon-separated string for the --slang argument. ```text --slang glsl430:glsl300es:hlsl5:metal_macos:wgsl ``` -------------------------------- ### Generate Reflection Functions Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/generator-class.md Generates optional runtime reflection functions. Base implementation does nothing; override to enable reflection output for your language. ```cpp virtual void gen_attr_slot_refl_func(const GenInput& gen, const refl::ProgramReflection& prog); virtual void gen_texture_slot_refl_func(const GenInput& gen, const refl::ProgramReflection& prog); virtual void gen_sampler_slot_refl_func(const GenInput& gen, const refl::ProgramReflection& prog); virtual void gen_uniform_block_slot_refl_func(const GenInput& gen, const refl::ProgramReflection& prog); virtual void gen_uniform_block_size_refl_func(const GenInput& gen, const refl::ProgramReflection& prog); virtual void gen_uniform_offset_refl_func(const GenInput& gen, const refl::ProgramReflection& prog); virtual void gen_uniform_desc_refl_func(const GenInput& gen, const refl::ProgramReflection& prog); virtual void gen_storage_buffer_slot_refl_func(const GenInput& gen, const refl::ProgramReflection& prog); virtual void gen_storage_image_slot_refl_func(const GenInput& gen, const refl::ProgramReflection& prog); ``` -------------------------------- ### Check for complete graphics program Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/snippet-and-program.md Query method to verify if both vertex and fragment shaders are present. ```cpp bool has_vs_fs() const; ``` ```cpp if (program.has_vs_fs()) { // This is a graphics pipeline program } ``` -------------------------------- ### Compile in debug mode with dependency generation Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/configuration.md Enables debug mode and generates a dependency file for build systems. ```bash sokol-shdc -i shaders.glsl -o shaders.h \ -l glsl430 \ -d \ --dependency-file shaders.h.d ``` -------------------------------- ### Generate Header Content Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/generator-class.md Generates main header content: program info structures, binding slot definitions, and other top-level declarations. ```cpp virtual void gen_header(const GenInput& gen); ``` -------------------------------- ### Apply Uniforms using Explicit Bind Slots Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Applying uniform data using hardcoded bind slot indices instead of generated constants. ```c sg_apply_uniforms(0, &SG_RANGE(vs_params)); sg_apply_uniforms(1, &SG_RANGE(fs_params)); ``` -------------------------------- ### Generate Storage Buffer Declarations Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/generator-class.md Generates declarations for storage buffer structures. Abstract method; must be implemented by subclasses. ```cpp virtual void gen_storage_buffer_decl(const GenInput& gen, const refl::Type& sbuf_struct) = 0; ``` -------------------------------- ### Apply Bindings using Generated Constants Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Using generated constants to populate the sg_bindings struct for rendering. ```c sg_apply_bindings(&(sg_bindings){ .vertex_buffers[0] = vbuf, .views[VIEW_tex] = tex_view, .samplers[SMP_smp] = smp, }); ``` -------------------------------- ### Fetch and update fips dependencies Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Run these commands to download and update the project dependencies after modifying fips.yml. ```bash > ./fips fetch > ./fips update ``` -------------------------------- ### Generate Target Code Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/compilation-flow.md Creates the output source code based on the specified format. ```cpp Generator* gen = create_generator(args.output_format); // C, Zig, Rust, etc. GenInput gen_input = { args, input, refl, spirvcross }; ErrMsg gen_err = gen->generate(gen_input); if (gen_err.valid()) { return 11; // Generation error } ``` -------------------------------- ### Error Recovery Pattern Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/compilation-flow.md Demonstrates the standard error handling flow using a cleanup label to ensure proper deinitialization after a failure. ```cpp int exit_code = 0; Args args = Args::parse(argc, argv); if (!args.valid) { return args.exit_code; // Validation failed } Shdc shdc; shdc.init(); Input input = Input::load_and_parse(args.input, args.module); if (input.out_error.valid()) { input.out_error.print(args.error_format); exit_code = 11; goto cleanup; } // ... rest of pipeline ... cleanup: shdc.deinit(); return exit_code; ``` -------------------------------- ### Include external files with @include Source: https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md Includes an external file relative to the top-level source file. ```glsl @ctype mat4 hmm_mat4 @vs vs @include bla/vs.glsl @end @include fs.glsl @program cube vs fs ``` -------------------------------- ### Sampler Equality Comparison Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/sampler-and-resources.md Method signature for comparing two Sampler objects for structural equality. ```cpp bool equals(const Sampler& other) const; ``` -------------------------------- ### Resource Lookup API Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/sampler-and-resources.md Methods for retrieving shader resource bindings from a Reflection object by name or by Sokol slot index. ```APIDOC ## Resource Lookup Methods ### Description These methods are available on the `bindings` object within a `Reflection` instance to query shader resources. ### Methods - `find_texture_by_name(name: std::string)`: Returns a pointer to a `Texture` resource matching the given name. - `find_sampler_by_name(name: std::string)`: Returns a pointer to a `Sampler` resource matching the given name. - `find_uniform_block_by_name(name: std::string)`: Returns a pointer to a `UniformBlock` resource matching the given name. - `find_storage_buffer_by_name(name: std::string)`: Returns a pointer to a `StorageBuffer` resource matching the given name. - `find_texture_by_sokol_slot(slot: int)`: Returns a pointer to a `Texture` resource at the specified Sokol slot. - `find_uniform_block_by_sokol_slot(slot: int)`: Returns a pointer to a `UniformBlock` resource at the specified Sokol slot. ### Usage Example ```cpp Reflection refl = Reflection::build(args, input, spirvcross); for (const auto& prog : refl.progs) { const auto& bindings = prog.bindings; const Texture* tex = bindings.find_texture_by_name("diffuse"); const UniformBlock* ub = bindings.find_uniform_block_by_sokol_slot(1); } ``` ``` -------------------------------- ### Generate Rust Module Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/README.md Generates a Rust module file using the sokol_rust format. ```bash sokol-shdc -i shaders.glsl -o shaders.rs \ -l glsl430:wgsl \ -f sokol_rust \ -m graphics ``` -------------------------------- ### Parse Input Shader Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/compilation-flow.md Loads and parses the input shader file and module. ```cpp Input input = Input::load_and_parse(args.input, args.module); if (input.out_error.valid()) { return 11; // Parse error } ``` -------------------------------- ### Iterate over shader reflection bindings in C++ Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/api-reference/sampler-and-resources.md Uses the reflection API to build a reflection object and iterate through program bindings including textures, samplers, uniform blocks, and storage buffers. ```cpp #include "reflection.h" Reflection refl = Reflection::build(args, input, spirvcross); for (const auto& prog : refl.progs) { printf("Program: %s\n", prog.name.c_str()); printf(" Textures:\n"); for (const auto& tex : prog.bindings.textures) { printf(" [slot %d] %s (%s)\n", tex.sokol_slot, tex.name.c_str(), ImageType::to_str(tex.type)); } printf(" Samplers:\n"); for (const auto& smp : prog.bindings.samplers) { printf(" [slot %d] %s (%s)\n", smp.sokol_slot, smp.name.c_str(), SamplerType::to_str(smp.type)); } printf(" Uniform Blocks:\n"); for (const auto& ub : prog.bindings.uniform_blocks) { printf(" [slot %d] %s (%s, size=%d bytes)\n", ub.sokol_slot, ub.name.c_str(), ub.name.c_str(), ub.struct_info.size); } printf(" Storage Buffers:\n"); for (const auto& sbuf : prog.bindings.storage_buffers) { printf(" [slot %d] %s (%s)\n", sbuf.sokol_slot, sbuf.name.c_str(), sbuf.readonly ? "read-only" : "read-write"); } } ``` -------------------------------- ### Declare shader snippets Source: https://github.com/floooh/sokol-tools/blob/master/_autodocs/configuration.md Defines vertex, fragment, or compute shader stages. ```glsl @vs my_vertex_shader #version 450 layout(location = 0) in vec3 position; layout(location = 0) out vec3 color; void main() { gl_Position = vec4(position, 1.0); color = vec3(1.0); } @end @fs my_fragment_shader #version 450 layout(location = 0) in vec3 color; layout(location = 0) out vec4 output_color; void main() { output_color = vec4(color, 1.0); } @end ```