- Home /
Can I sample a texture in a fragment shader using pixel coordinates instead of UV's?
I'm working on some complex image effects using fragment shaders, and it would be great if I could just access the pixels in _MainTex
with int coordinates instead of messing around with texels. I can get the pixel coordinate of each shader invocation using the VPOS semantic, but i have no idea how to read from a texture using these pixel coordinates.
Answer by Bunny83 · Apr 24, 2018 at 05:09 PM
Well, inside of a shader a texture is an abstract thing. Textures always go through a sampler and depending on your filtering setting you either get the nearest pixel or a bilinear interpolated result.
Unity actually feeds the texel size and the texture dimensions as a float4 which is named just like your sampler followed by _TexelSize
. So for the _MainTex sampler you just declare this in your cg code:
uniform float4 _MainTex_TexelSize;
It will contain the following values:
x --> 1f / texWidth
y --> 1f / texHeight
z --> texWidth
w --> texHeight
To samples a specific pixel you should make sure you set the texture filter mode to point and then just do this:
float2 pCoord;
float2 uv = (pCoord+0.5) * _MainTex_TexelSize.xy;
This assumes pCoord is your desired pixel integer coordinate. The "+0.5" makes sure we sample the center of each pixel. The resulting "uv" can be used in a tex2d call. Keep in mind that _TexelSize only works with 2d textures. 3d textures don't get this set.
Answer by Glurth · Apr 24, 2018 at 05:00 PM
from the unity shader sample page, note this line in the fragment shader:
fixed4 col = tex2D(_MainTex, i.uv);
This is the line that extracts the color from the texture. All you need to do is change the i.uv
to instead be two coordinates in your VPOS result.
The tex2D
function works in texel space, which is the exact opposite of what I want.
See Bunnies answer for how to scale your vertex appropriately. Indeed, this only answers the titular question.
Your answer
Follow this Question
Related Questions
Vertex Color Shader 0 Answers
Swapping textures / shader of two gameobjects 1 Answer
Possible for a shader to have two decal slots? 2 Answers
select float2 uv_Maintex to UV map channel in shader. 0 Answers