Search code examples
glslmetalshadingmetalkit

Metal Shading Language - FragCoord equivalent?


I tried to translate this shadertoy scene into Metal Kernel. In shadertoy code:

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec3 dir = rayDirection(45.0, iResolution.xy, fragCoord);
    ...
}

in OpenGL case, we need to send iResolution from the glfw window. And fragCoord will be gl_FragCoord from Fragment Shader.

I have this in metal file:

kernel void compute(texture2d<float, access::write> output [[texture(0)]],
                    uint2 gid [[thread_position_in_grid]]) {
    int width = output.get_width();
    int height = output.get_height();
    ....
}

So I can get my iResolution from the width and height. But I am not sure how to get gl_FragCoord.

Do Metal_stdlib have something equivalent to gl_FragCoord? Or if I have to calculate, How can I get obtain the same value?


Solution

  • If you're looking for the "fragment" position in window coordinates (as gl_FragCoord is), you can use float2(gid), which ranges from (0, 0) to (width, height). This is only the case if your grid dimensions (the product of your threadgroup size and threadgroup count) exactly match the dimensions of the destination texture.