问题描述
我正在按照 learnopengl.com 的教程制作游戏引擎。
我使用 stb_image.h 加载纹理,并使用我自己的头文件来编译和链接着色器。
我到达了入门/纹理中的部分,其中 container.jpg 纹理应该填充窗口上的矩形。但是每当我编译和运行代码时,纹理都不会出现在窗口中的任何地方。这是我的纹理加载代码:
// Load and create a texture
unsigned int texture1;
glGenTextures(1,&texture1);
glBindTexture(GL_TEXTURE_2D,texture1);
// Set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
// Set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
// Load image,create texture,and generate minmaps
int width,height,nrChannels;
unsigned char* data = stbi_load("C:\\Users\\Lucas\\OneDrive\\Desktop\\C++ Projects\\Working Game Engine\\container.jpg",&width,&height,&nrChannels,0);
if (data) {
glTexImage2D(GL_TEXTURE_2D,GL_RGB,width,GL_UNSIGNED_BYTE,data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else {
std::cout << "Failed to load texture(s)\n";
}
这些是四边形的坐标:
float vertices[] = {
// Positions // Colors // Texture Coords
0.5f,0.5f,0.0f,1.0f,-0.5f,1.0f
};
unsigned int indices[] = {
0,1,3,2,3
};
渲染代码:
// Process inputs
processInput(window);
// Render
glClearColor(0.2f,0.3f,1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Bind Texture
glBindTexture(GL_TEXTURE_2D,texture1);
// Render Container
ourShader.use();
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT,0);
// Swap buffers and poll IO events (Key pressed/released,mouse moved etc.)
glfwSwapBuffers(window);
glfwPollEvents();
顶点着色器代码:
#version 460 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
layout (location = 2) in vec2 aTexCoord;
out vec3 ourColor;
out vec2 TexCoord;
void main()
{
gl_Position = vec4(aPos,1.0);
ourColor = aColor;
TexCoord = vec2(aTexCoord.x,aTexCoord.y);
}
片段着色器代码:
#version 460 core
out vec4 FragColor;
in vec3 ourColor;
in vec2 TexCoord;
uniform sampler2D texture1;
void main()
{
FragColor = texture(texture1,TexCoord);
}
请注意,图像加载器或着色器编译器不会返回任何错误代码。 The rectangle appears like this.
解决方法
你需要像这样更新texture1统一:
glUniform1i(glGetUniformLocation(program_id,"texture1"),0);
,
所以结果我没有 glEnableVertexAttribArray();纹理坐标。好尴尬。