Sergio0694 / ComputeSharp

A .NET library to run C# code in parallel on the GPU through DX12, D2D1, and dynamically generated HLSL compute and pixel shaders, with the goal of making GPU computing easy to use for all .NET developers! 🚀
MIT License
2.74k stars 122 forks source link

Please add [ShaderIgnore] to support managed function in shader code #783

Closed JohnMasen closed 6 months ago

JohnMasen commented 6 months ago

Description (optional)

Please add [ShaderIgnore] to support managed function in shader code.

  1. I want to allow my code load shader code by user options
  2. C# does not support constructor method in interface
  3. You can define a static method in interface after C# 11.
  4. My shader struct with static method implementation causes compile error(ComputeShader tried to compile my static method to HLSL)

Rationale

To support loading shader with a genetic method like LoadShader<T> where T:IComputeShader,IShaderCreator<T>

Proposed API

A new property [ShaderIgnoreProperty] Allows user to mark their code should not be treated as shader code, and skip shader compile. Sample useage:

public interface ICreateWithBuffer<T> where T : unmanaged
{
    static abstract T Create(ReadWriteBuffer<T> data); 
}

[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
public readonly partial struct myShader(ReadWriteBuffer<int> data) : IComputeShader, ICreateWithBuffer<int>
{
    [ShaderIgnore]
    public static int Create(ReadWriteBuffer<int> data)
    {
        return new myShader(data);
    }

    public void Execute()
    {
        var d = data[ThreadIds.X];
    }
}

Drawbacks

NA

Alternatives

NA

Other thoughts

NA

Sergio0694 commented 6 months ago

You can already do this, it's the same scenario that was fixed by #252. Just implement that Create method explicitly and the source generator will ignore it and not produce errors for it 🙂