如何获取片段着色器中的像素信息? [英] How to get pixel information inside a fragment shader?

查看:350
本文介绍了如何获取片段着色器中的像素信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在片段着色器中,我可以加载纹理,然后执行以下操作:

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.

但是有几个问题.我如何知道我是哪个"像素?例如,假设我要将像素100,100(x,y)设置为红色.其他一切都变黑了.我该怎么做:

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 :

如果currentSelf.Position()==(100,100);那么颜色=红色;否则颜色=黑色?"

"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?

我尝试过:

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

但不清楚返回的内容是什么?如果我是100,100像素;如何从101,100或100,101中获取值?

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?

推荐答案

如何知道我是哪个"像素?

How do I tell "which" pixel I am?

您不是像素.您是片段. OpenGL将它们称为片段着色器"是有原因的.这是因为它们还不是 像素.的确,由于多重采样,它们不仅不会成为像素(通过discard或深度测试或其他方法),而且多个片段可以组合形成一个单个像素.

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.

如果要告诉您的片段着色器在窗口空间中的位置,请使用 gl_FragCoord .片段位置是浮点值,而不是整数,因此您必须使用范围而不是单个"100,100"值进行测试.

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.

如果您要谈论的是从所访问的纹理中访问相邻的 texel ,那只是偏置传递给texture2D的纹理坐标的问题.您必须获取纹理的大小(由于您未使用GLSL 1.30或更高版本,因此必须手动将其传递进来),反转该大小,然后从纹理坐标的S和T分量中添加或减去这些大小

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.

这篇关于如何获取片段着色器中的像素信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆