更改片段着色器中显示的纹理

时间:2012-11-16 04:12:04

标签: opengl glsl texture-mapping multitexturing

我正在尝试将2个纹理传递给着色器,我对此处的工作感到有些困惑 这是opengl代码

    GLuint textures;
    GLuint textures1;</code>
    glGenTextures(1,&textures);
    glGenTextures(1,&textures1);
    glBindTexture(GL_TEXTURE_2D,textures);
    glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,256,256,0,GL_RGB,GL_UNSIGNED_BYTE,texImg);
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );

    glBindTexture(GL_TEXTURE_2D,textures1);
    glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,256,256,0,GL_RGB,GL_UNSIGNED_BYTE,texImg1);
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
    glBindTexture(GL_TEXTURE_2D,textures1);

    GLuint location1=glGetUniformLocation(programObjectFloor,"Tex1");
    GLuint location2=glGetUniformLocation(programObjectFloor,"Tex2");

    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D,textures1);
    glUniform1i(location2, 1);

    glActiveTexture(GL_TEXTURE0);
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D,textures);
    glUniform1i(location1, 0);

顶点着色器

attribute vec4 position; 
attribute vec4 texture;

uniform mat4 MVP;


varying vec4 ptexture; 

void main()
{
    ptexture = texture;     
    gl_Position = MVP * position; 
}

Fragment Shader是

varying vec4 ptexture; 

uniform sampler2D Tex1;
uniform sampler2D Tex2;
uniform bool swit;

void main() 
{
        gl_FragColor = texture2D(Tex1,ptexture.st);
} 

当我更改行

gl_FragColor = texture2D(Tex2,ptexture.st);

仍然只显示第一个纹理,但是当我注释掉下面的线条时,会显示第二个纹理,你能解释一下为什么会这样吗?

//        glActiveTexture(GL_TEXTURE0);
//        glEnable(GL_TEXTURE_2D);
//        glBindTexture(GL_TEXTURE_2D,textures);
//        glUniform1i(location1, 0);

1 个答案:

答案 0 :(得分:0)

在查询统一位置并为其分配值之前,您必须先调用glUseProgram。很可能你以后转换程序,把你设置的那些制服留在未定义的状态。

同样在使用着色器时,不需要glEnable(GL_TEXTURE_2D);,如果纹理使用与否,则由着色器的代码确定。

与您的问题无关,只需指出,您在查询统一位置之前就有glBindTexture的冗余电话。