在opengl矩形上使用着色器使其消失

时间:2019-05-25 12:40:30

标签: c++ opengl shader

我目前正在尝试使用OpenGL将纹理渲染到我一直在研究的游戏引擎中,但是遇到了不确定的问题。在矩形上利用我的着色器渲染纹理时,它根本不显示。

我可以注释掉一行代码,然后将显示一个黑色矩形,因此我知道该矩形至少可以正确呈现。问题是当我要求OpenGL使用我的着色器程序时。

在这里ourshader.Use行被注释掉

// Clear the colorbuffer
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);

//ourShader.Use(); <----this is using the shader
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glUniform1i(glGetUniformLocation(ourShader.Program, "ourTexture"), 0);

// Draw container
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);

我得到

没有我就得到

这对我来说很奇怪,因为在另一个测试项目中,我可以使用完全相同的代码来渲染纹理。

frag着色器

#version 330 core
in vec3 ourColor;
in vec2 TexCoord;

out vec4 color;

// Texture samplers
uniform sampler2D ourTexture1;

void main()
{
    // Linearly interpolate between both textures (second texture is only slightly combined)
    color = texture(ourTexture1, TexCoord);
}

垂直着色器

#version 330 core
layout (location = 0) in vec3 position;
layout (location = 1) in vec3 color;
layout (location = 2) in vec2 texCoord;

out vec3 ourColor;
out vec2 TexCoord;

void main()
{
    gl_Position = vec4(position, 1.0f);
    ourColor = color;
    // We swap the y-axis by substracing our coordinates from 1. This is done because most images have the top y-axis inversed with OpenGL's top y-axis.
    // TexCoord = texCoord;
    TexCoord = vec2(texCoord.x, 1.0 - texCoord.y);
}

我从字面上复制并粘贴了代码,似乎无法获得相同的结果。问题之一可能是我正在将其渲染为一个以.dll构建的项目,然后在同一解决方案的另一个项目中进行引用,但是我知道OpenGL正在工作,因为我仍然可以渲染矩形? >

我还通过绘制一个简单的无纹理三角形对此进行了测试,并且效果很好。

我什至可以在其上使用着色器,并弄乱颜色,什么不起作用,那么为什么此纹理着色器不起作用?特别令人困惑,因为我已经在另一个项目中测试了此着色器,并且效果很好?因此,我非常困惑,不得不在这里寻求帮助。

1 个答案:

答案 0 :(得分:2)

    glUniform1i(glGetUniformLocation(ourShader.Program, "ourTexture"), 0);

您将采样器的位置指定为“ ourTexture”,但着色器内部的采样器的名称将为“ ourTexture1”。

您还可以通过以下方式明确指定着色器内的纹理位置

layout (location = 0) uniform sampler2D ourTexture;

那你只需要打电话

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);

将纹理绑定到纹理单元0。