首先创建模型渲染管线
Shader ourShader("1.model_loading.vs", "1.model_loading.fs");
vertexShader
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoords;
out vec2 TexCoords;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main()
{
TexCoords = aTexCoords;
gl_Position = projection * view * model * vec4(aPos, 1.0);
}
fragmentShader
#version 330 core
out vec4 FragColor;
in vec2 TexCoords;
uniform sampler2D texture_diffuse1;
void main()
{
FragColor = texture(texture_diffuse1, TexCoords);
}
可以看到,该着色器只引入了aPos顶点位置,aNormal法线,aTexCoords纹理坐标.
引入的全局变量有texture_diffuse1漫反射光照,以及变化矩阵。
因此需要对这些全局变量赋值。
全局变量赋值
ourShader.use();
ourShader.setMat4("projection", projection);
ourShader.setMat4("view", view);
model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(0.0f, 0.0f, 0.0f)); // translate it down so it's at the center of the scene
model = glm::scale(model, glm::vec3(1.0f, 1.0f, 1.0f)); // it's a bit too big for our scene, so scale it down
ourShader.setMat4("model", model);
绘制
ourModel.Draw(ourShader);
进入函数内部
void Draw(Shader& shader)
{
for (unsigned int i = 0; i < meshes.size(); i++)
meshes[i].Draw(shader);
}
对每一个存储在meshes中的Mesh数据进行draw操作
void Draw(Shader& shader)
{
// bind appropriate textures
unsigned int diffuseNr = 1;
unsigned int specularNr = 1;
unsigned int normalNr = 1;
unsigned int heightNr = 1;
for (unsigned int i = 0; i < textures.size(); i++)
{
glActiveTexture(GL_TEXTURE0 + i); // active proper texture unit before binding
// retrieve texture number (the N in diffuse_textureN)
string number;
string name = textures[i].type;
if (name == "texture_diffuse")
number = std::to_string(diffuseNr++);
else if (name == "texture_specular")
number = std::to_string(specularNr++); // transfer unsigned int to stream
else if (name == "texture_normal")
number = std::to_string(normalNr++); // transfer unsigned int to stream
else if (name == "texture_height")
number = std::to_string(heightNr++); // transfer unsigned int to stream
// now set the sampler to the correct texture unit
glUniform1i(glGetUniformLocation(shader.ID, (name + number).c_str()), i);
// and finally bind the texture
glBindTexture(GL_TEXTURE_2D, textures[i].id);
}
// draw mesh
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
// always good practice to set everything back to defaults once configured.
glActiveTexture(GL_TEXTURE0);
}
glActiveTexture(GL_TEXTURE0 + i);
激活第i号纹理绑定器
glUniform1i(glGetUniformLocation(shader.ID, (name + number).c_str()), i);
将全局变量中名为 name + number的纹理采样器,绑定到该Shader的第i号绑定器上。
glBindTexture(GL_TEXTURE_2D, textures[i].id);
将第i号纹理的id(存储在texture容器中)绑定到当前激活的绑定器上
即,将第i号纹理通过绑定器(GL_TEXTURE0 + i)与Shader中的名为name + number的采样器绑定。
然后glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
最终效果
添加光照效果后(使用lightShader着色器)
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容