漫反射贴图
将材质结构体中的漫反射设置成贴图
struct Material {
sampler2D diffuse;
vec3 specular;
float shininess;
};
...
in vec2 TexCoords;
同时修改漫反射光照的公式,注意这里diffuse是一个vec3,而texture输出的是vec4,所以要在后面加上.rgb。
vec3 diffuse = light.diffuse * diff * texture(material.diffuse, TexCoords).rgb;
这是我们使用的贴图,下面是贴图使用的代码,与前一章1.6.2中使用的类似。
unsigned int loadtexture(const char* path)
{
unsigned int textureid;
glGenTextures(1, &textureid);
int width, height, nrcomponent;
unsigned char* data = stbi_load(path, &width, &height, &nrcomponent, 0);
if (data))
{
GLenum format;
if (nrcomponent == 1)
format = GL_RED;
else if (nrcomponent == 3)
format = GL_RGB;
else if (nrcomponent == 4)
format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, textureid);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
}
else
{
std::cout << "Texture failed to load at path: " << path << std::endl;
stbi_image_free(data);
}
return textureid;
}
int main()
{
...
float vertices[] = {
// positions // normals // texture coords
...};
...
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);
...
unsigned int diffusemap = loadtexture("container2.png");
lightingshader.use();
lightingshader.setInt("material.diffuse", 0);
while (!glfwWindowShouldClose(window))
{
...
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, diffusemap);
...
}
}
镜面反射贴图
我们同样可以使用一个专门用于镜面高光的纹理贴图。这也就意味着我们需要生成一个黑白的(如果你想得话也可以是彩色的)纹理,来定义物体每部分的镜面光强度。下面是一个镜面光贴图(Specular Map)的例子
贴图的使用几乎和漫反射相同
struct Material {
sampler2D diffuse;
sampler2D specular;
float shininess;
};
vec3 specular=spe*light.specular*texture(material.specular,texcoor).rgb;