Recursive AI

Choose an HLSL texture and sampler at runtime

OneShader is a free, open-source HLSL compiler library for .NET from Recursive AI. MIT or Apache-2.0.

Use a runtime flag to switch between two fixed texture and sampler pairs.

Terminal
dotnet add package RecursiveAI.OneShader

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

HLSL
Texture2D<float4> tex = UseNight ? Night : Day;
SamplerState filter = UseNight
    ? Nearest : Linear;
return tex.SampleLevel(filter, uv, 0);

This is the body of the pixel shader in Choose.hlsl below. It declares the resources and the UseNight flag; uv is the pixel shader’s texture coordinate. The example writes choose.spv, choose.metal, and choose.wgsl.

The example is the full program below: unzip it and dotnet run.

Full program

Save this input as Choose.hlsl beside Program.cs, or use the copy in the zip.

HLSL
Texture2D<float4> Day : register(t0);
Texture2D<float4> Night : register(t1);
SamplerState Linear : register(s2);
SamplerState Nearest : register(s3);
cbuffer Settings : register(b4) { uint UseNight; };
 
[shader("pixel")]
float4 PSMain(float2 uv : TEXCOORD0) : SV_Target
{
    Texture2D<float4> tex = UseNight ? Night : Day;
    SamplerState filter = UseNight
        ? Nearest : Linear;
    return tex.SampleLevel(filter, uv, 0);
}
C#
using OneShader;
 
var result = ShaderCompiler.CompileFile("Choose.hlsl",
    new CompileOptions { Targets = [CompileTarget.SpirV, CompileTarget.Msl, CompileTarget.Wgsl] });
if (!result.Success)
    throw new InvalidOperationException(
        string.Join(Environment.NewLine, result.Diagnostics));
 
foreach (var (target, file) in new[] {
    (CompileTarget.SpirV, "choose.spv"),
    (CompileTarget.Msl, "choose.metal"),
    (CompileTarget.Wgsl, "choose.wgsl") })
{
    var shader = result.Find("PSMain", target)!;
    File.WriteAllBytes(file, shader.ToArray());
    Console.WriteLine($"Wrote {file}");
}
Text
Wrote choose.spv
Wrote choose.metal
Wrote choose.wgsl

OSH0331 here means the choice uses an array index that isn’t known until the shader runs. Choose between named textures and samplers instead.

Variations

Use an if instead of ?:. Replace the pixel shader body with this. Both resources are still selected from fixed candidates.

HLSL
Texture2D<float4> tex = Day;
SamplerState filter = Linear;
if (UseNight != 0)
{
    tex = Night;
    filter = Nearest;
}
return tex.SampleLevel(filter, uv, 0);

The short answer

In OneShader 1.7.3, initialize local Texture2D and SamplerState variables from named, fixed resources using ?: or an if, then sample with the local variables. The runtime input here is UseNight: zero samples Day with Linear, and nonzero samples Night with Nearest. The C# example compiles the shader; it does not upload textures or render an image.

How do you bind the textures a shader chooses at runtime?

Bind both candidates before drawing, even when the setting only selects one for a particular draw. In this Vulkan example, set 0 bindings 0 and 1 are the sampled images, 2 and 3 are the samplers, and 4 is the constant buffer that supplies UseNight. Linear and Nearest are just HLSL names. Create the sampler objects with the filtering you want in the application and put them in the corresponding bindings. The flag changes which pair the shader uses, not what is bound.

The candidates can be named resources or elements selected with constant indices. That differs from picking Textures[index] with a runtime index. OneShader lowers each use of a local choice to branches that refer to known bindings. That means a small fixed list needs no descriptor indexing just for making this choice. When you have a large resource table rather than two or three known options, use a resource array if the target and its binding model support the indexing you need.

Can you call Sample after choosing a texture in a branch?

The emitted sampling instructions are inside branches too. Sample uses implicit derivatives for mip selection, so a choice that varies across neighboring fragments can cause derivative-uniformity problems. A constant-buffer flag that is the same for the draw avoids that kind of per-fragment variation. The example uses SampleLevel explicitly at mip level 0, so it doesn’t need implicit derivatives. If you need automatic mip selection, keep the resource choice uniform where the sample executes.

All oneshader recipes