GLSL中两个纹理的交替gl_FragColor值

sno*_*147 1 opengl textures glsl

我有两个纹理,云和山,每个都有512 x 512大小,我打算创建一个gl_FragColor输出,它将从以前的纹理获取像素值.在这种情况下,我想gl_FragColor从第一纹理中的第一像素,第二纹理中的第二像素中gl_FragColor的第二像素,第一纹理中的第三像素中gl_FragColor的第三像素等获得第一像素. .这是我的片段着色器代码:

 uniform sampler2D tex0;
 uniform sampler2D tex1;

 void main() {
     vec4 cloud = texture2D(tex0, gl_TexCoord[0].st);
     vec4 hill = texture2D(tex1, gl_TexCoord[0].st);
     for (int i=0;i<512;i++) {
       for (int j=0;j<512;j++) {
            if ( j%2 == 0)
                gl_FragColor =  cloud;
            else
                gl_FragColor =  hill;
          }
     }
  }
Run Code Online (Sandbox Code Playgroud)

这是纹理单元设置:

t1 = loadTexture("pY.raw", 512, 512);
t2 = loadTexture("pZ.raw", 512, 512);

glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, t2);
glEnable(GL_TEXTURE_2D);

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, t1);
glEnable(GL_TEXTURE_2D);
Run Code Online (Sandbox Code Playgroud)

这是统一的设置:glUseProgram(program);

GLuint t1Location = glGetUniformLocation(program, "tex0");
GLuint t2Location = glGetUniformLocation(program, "tex1");

glUniform1i(t1Location, 0);
glUniform1i(t2Location, 1);
Run Code Online (Sandbox Code Playgroud)

问题是,程序的输出只是山纹理,我不知道如何解决这个问题.有什么建议吗?

Pio*_*zmo 7

您不需要在着色器中进行任何迭代.对象中的每个像素都会调用一次像素着色器.而是使用gl_TexCoord [0]来获取当前纹理坐标.您的代码看起来应该是这样的:

uniform sampler2D tex0;
uniform sampler2D tex1;

void main()
{
    vec4 cloud = texture2D(tex0, gl_TexCoord[0].st);
    vec4 hill = texture2D(tex1, gl_TexCoord[0].st);

    if ( int(gl_TexCoord[0].x*512)%2 == 0)
        gl_FragColor =  cloud;
    else
        gl_FragColor =  hill;

    }
}
Run Code Online (Sandbox Code Playgroud)

这个应该工作,即使使用旧的opengl:

#ifdef GL_ES
precision highp float;
#endif

uniform sampler2D tex0;
uniform sampler2D tex1;

void main(void)
{

    if((gl_FragCoord/32.0- vec4(ivec4(gl_FragCoord/32.0))).x<0.5)
        gl_FragColor = texture2D(tex0, gl_FragCoord.xy/512.0);
    else
        gl_FragColor = texture2D(tex1, gl_FragCoord.xy/512.0);
}
Run Code Online (Sandbox Code Playgroud)

您可以使用WebGL进行试用:http://www.iquilezles.org/apps/shadertoy/