Screenspace UV Coordinates in Fragment Shader


how do I get the screen space UV coordinates in a fragment shader ?

In OpenGL I can simply do: gl_FragCoord.xy/screensize


You can get the fragment’s coordinate using the [[position]] attribute as a parameter to the fragment shader header.

Page 76 of the Metal Shading Language gives you all the attributes available

You might have to play around with retina scale - I’m not sure about that.

1 Like

But [[position]] comes from the vertex shader and contains the float3 position of the transformed vertex ? Not the screen uv position [0…1] ?

Remember that there is a lot going on in the fixed pipeline between the vertex shader and the fragment shader.

The vertex shader sends the position down the pipeline, and then primitive assembly sorts the vertices into triangles, then these triangles are scanned and any fragments inside these triangles are sent to the the fragment shader. If any of that is unfamiliar to you, I suggest that you study Chapter 3 The Rendering Pipeline. That one is an important chapter to understand, and probably needs a number of readings and going back to it later on for further understanding.

So [[position]] coming out of the vertex shader contains the float4 position of the vertex, but going into the fragment shader, the xy of the [[position]] contains the screen coordinates of the current fragment.

Btw, if you’re using a struct with [[stage_in]], the [[position]] attribute is inside that struct, as in this debug screenshot

Screen Shot 2020-06-16 at 3.29.31 pm

Hopefully you can see the coordinates (311.5, 199.5) of the fragment being debugged.

1 Like

The next question might be how to get the pixel coordinates relative 0…1.

That would be pixel coordinate / render target size, so you’d have to send the size of the render target texture to the fragment shader.

Here’s an SO post that explains that: how to get render target dimensions dynamically in a Metal fragment shader? - Stack Overflow

1 Like

Thanks a lot for your help Caroline, that helps a lot :smile:

Really enjoy the book and your support!

1 Like