In OpenGL , sometimes when doing multi-pass rendering and post-processing I need to apply texels to the primitive’s assembly fragments which are part of full screen texture composition.That is usually the case when the current pass comes from FBO texture to which the screen quad had been rendered during previous pass.To achieve this I calculate objects UV coordinates in SCREEN SPACE .In GLSL I calculate it like this:
vec2 texelSize = 1.0 / vec2(textureSize(TEXTURE, 0));
vec2 screenTexCoords = gl_FragCoord.xy * texelSize;
Now I am experimenting with Unity3D which uses CG/HLSL.The docs for these languages are poor.How can I calculate screen uv coordinates in CG/HLSL?
To calculate screen texcoords, you typically pass the screen resolution or reciprocal thereof (
resorrcpres) to the shader, then use the texcoords from your fullscreen quad (assuming a range of[0,1]) modified by those.Edit: Note that in many cases, you want both
resandrcpresavailable.resis useful for calculating the current position (you wouldn’t want to usercpresfor that, since it would then require division), butrcprescan be calculated once on the CPU and is useful for moving by a single texel ((res * uv) + rcpres)is one more texel from origin).Something like:
The logic being that the coords coming from the fs quad are
0,0at texel0,0and1,1at texelmaxX,maxY, so knowing the dimensions, you can just multiply.You have to provide the value of
resto each effect, however, which depends on your shader system (Unity3D may do it already).