6

对不起,我会重写这个问题,希望能清楚。

在我的 .cpp 代码中,我创建了一个四边形列表,其中一些有一个标志,在像素着色器中,我检查是否设置了这个标志,如果没有设置标志,例如,四边形会变成红色,如果设置了标志,我想决定每个像素的颜色,所以如果我需要将标记的四边形的一半涂成红色,另一半涂成蓝色,我可以简单地执行以下操作:

if coordinate in quad < something color = red
else colour = blue; 

通过这种方式,我可以将四边形的一半涂成蓝色,另一半涂成红色,或者我可以决定将红色放在哪里或蓝色放在哪里。

想象一下我有一个四边形 50x50 像素

[碎片]

if(quad.flag == 1)
  {    
    if(Pixel_coordinate.x<25 ) gl_fragColor = vec4(1.0, 0.0, 0.0, 1.0);
    else gl_fragColor = vec4(0.0, 1.0, 0.0, 1.0);
  }
else
  gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);

在这种情况下,我希望设置了标志的四边形将在每个面上获得两种颜色。我希望我现在已经更具体了。

谢谢。

只是添加一些我不能使用任何纹理的东西。

好的,我现在这样做:

每个四边形有 4 个纹理协调 (0,0), (0,1), (1,1), (1,0);

我使用以下方法启用纹理坐标:

glTexCoordPointer(2, GL_SHORT, sizeof(Vertex), BUFFER_OFFSET(sizeof(float) * 7));

[垂直]

varying vec2 texCoord;

main()
{
    texCoord = gl_MultiTexCoord0.xy;
} 

[碎片]

varying vec2 texCoord;

main()
{
    float x1 = texCoord.s;
    float x2 = texCoord.t;

    gl_FragColor = vec4(x1, x2, 0.0, 1.0);
}

我总是得到黄色,所以 x1 =1 和 x2 = 1 几乎总是和一些四边形是黄色/绿色。

我希望片段着色器中的纹理坐标发生变化,所以我应该得到一个渐变,我错了吗?

4

2 回答 2

4

If you want to know the coordinate within the quad, you need to calculate it yourself. In order to that, you'll need to create a new interpolant (call it something like vec2 quadCoord), and set it appropriately for each vertex, which means you'll likely also need to add it as an attribute and pass it through your vertex shader. eg:

// in the vertex shader
attribute vec2 quadCoordIn;
varying vec2 quadCoord;

main() {
    quadCoord = quadCoordIn;
              :

You'll need to feed in this attribute in your drawing code when drawing your quads. For each quad, the vertexes will have likely have quadCoordIn values of (0,0), (0,1), (1,1) and (1,0) -- you could use some other coordinate system if you prefer, but this is the easiest.

Then, in your fragment program, you can access quadCoord.xy to determine where in the quad you are.

于 2012-08-24T17:58:58.343 回答
3

除了Chris Dodd的回答之外,您还可以?.5通过特殊的片段着色器变量访问当前处理的片段的屏幕空间坐标(以像素为单位,尽管实际上是像素中心,因此)gl_FragCoord

gl_FragColor = (gl_FragCoord.x<25.0) ? vec4(1.0, 0.0, 0.0, 1.0) : vec4(0.0, 1.0, 0.0, 1.0);

但这为您提供了片段在屏幕空间中的位置,因此相对于视口的左下角。如果您确实需要知道单个四边形内部的位置(如果您想实际对每个四边形进行一半着色,这更有意义,因为“半切”会随着四边形的位置而变化),那么Chris Dodd的答案是正确的做法。

于 2012-08-24T18:11:52.957 回答