Skip to content

Optional variables.

Sylvain Doremus edited this page Oct 23, 2023 · 5 revisions

ShaderWriter allows you to declare variables that will be optional, depending on a condition you decide.
This comes through the enabled parameter for each declXxx function in sdw::Writer, and in all composite types (sdw::Struct, sdw::Ubo, ...).
By default, this parameter is set to true, but you can set it to a condition on your own, to be able to disable the variable on demand.
This will result in the variable not being written to the resulting shader, and all operations using it will also be ignored.

Example:

// Somewhere
bool isHdrEnabled = false;

// Use it in shader writing
sdw::FragmentWriter writer;

// Shader inputs
auto mapHdr = writer.declCombinedImg< FImg2DRgba32 >( "mapHdr"
    , 0u    //binding
    , 0u ); // set
auto uv = writer.declInput< Vec2 >( "uv"
    , 0u ); // location
UniformBuffer hdrConfig{ "HdrConfig"
    , 1u              // binding
    , 0u              // set
    , isHdrEnabled }; // enabled
auto uboExposure = hdrConfig.declMember< Float >( "uboExposure"
    , isHdrEnabled ); // enabled
auto uboGamma = hdrConfig.declMember< Float >( "uboGamma"
    , isHdrEnabled ); // enabled
hdrConfig.end();

// Shader outputs
auto fragOutput = writer.declOutput< Vec4 >( "fragOutput"
    , 0 ); // location

// Helper functions
auto applyGamma = writer.implementFunction< Vec3 >( "applyGamma"
    , [&]( Float const & gamma, Vec3 const & hdr )
    {
        writer.returnStmt( pow( max( hdr, vec3( 0.0_f ) ), vec3( 1.0_f / gamma ) ) );
    }
    , InFloat{ writer, "gamma" }
    , InVec3{ writer, "hdr" } );

// Main
writer.implementMainT< VoidT, VoidT >( [&]( FragmentIn in
    , FragmentOut out )
    {
        // The following line, depending on disabled variables,
        // Won't be written to the shader, resulting in nothing written in fragOuput:
        fragOutput = vec4( applyGamma( uboGamma, mapHdr.sample( uv ).rgb() * uboExposure ), 1.0_f );
        // Hence you'll need to use a temporary variable for that purpose:
        auto hdrColor = writer.declLocale( "hdrColor"
            , mapHdr.sample( uv ).rgb() );
        // The two following lines, depending on disabled variables,
        // won't be written in the shader
        hdrColor *= vec3( uboExposure );
        hdrColor = vec4( applyGamma( uboGamma, hdrColor ), 1.0_f );
        // Here you are sure that a value is written to fragOutput.
        fragOutput = hdrColor;
    } );
Clone this wiki locally