How to get pixel information inside a fragment shader?

好久不见. 提交于 2019-12-03 05:38:54

问题


In my fragment shader I can load a texture, then do this:

uniform sampler2D tex;

void main(void) {
   vec4 color = texture2D(tex, gl_TexCoord[0].st);
   gl_FragColor = color;
}

That sets the current pixel to color value of texture. I can modify these, etc and it works well.

But a few questions. How do I tell "which" pixel I am? For example, say I want to set pixel 100,100 (x,y) to red. Everything else to black. How do I do a :

"if currentSelf.Position() == (100,100); then color=red; else color=black?"

?

I know how to set colors, but how do I get "my" location?

Secondly, how do I get values from a neighbor pixel?

I tried this:

vec4 nextColor = texture2D(tex, gl_TexCoord[1].st);

But not clear what it is returning? if I'm pixel 100,100; how do I get the values from 101,100 or 100,101?


回答1:


How do I tell "which" pixel I am?

You're not a pixel. You're a fragment. There's a reason that OpenGL calls them "Fragment shaders"; it's because they aren't pixels yet. Indeed, not only may they never become pixels (via discard or depth tests or whatever), thanks to multisampling, multiple fragments can combine to form a single pixel.

If you want to tell where your fragment shader is in window-space, use gl_FragCoord. Fragment positions are floating-point values, not integers, so you have to test with a range instead of a single "100, 100" value.

Secondly, how do I get values from a neighbor pixel?

If you're talking about the neighboring framebuffer pixel, you don't. Fragment shaders cannot arbitrarily read from the framebuffer, either in their own position or in a neighboring one.

If you're talking about accessing a neighboring texel from the one you accessed, then that's just a matter of biasing the texture coordinate you pass to texture2D. You have to get the size of the texture (since you're not using GLSL 1.30 or above, you have to manually pass this in), invert the size and either add or subtract these sizes from the S and T component of the texture coordinate.




回答2:


Easy peasy.

Just compute the size of a pixel based on resolution. Then look up +1 and -1.

vec2 onePixel = vec2(1.0, 1.0) / u_textureSize;
gl_FragColor = (
   texture2D(u_image, v_texCoord) +
   texture2D(u_image, v_texCoord + vec2(onePixel.x, 0.0)) +
   texture2D(u_image, v_texCoord + vec2(-onePixel.x, 0.0))) / 3.0;

There's a good example here



来源:https://stackoverflow.com/questions/9779415/how-to-get-pixel-information-inside-a-fragment-shader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!