OpenGL学习10——材质

2021-06-24  本文已影响0人  蓬篙人
// Material结构存储表面的材质属性
struct Material{
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
    float shininess;
};

uniform Material material;
1. `ambient`材质矢量:定义表面在环境光下的反射的颜色,一般就是表面的颜色。
2. `diffuse`材质矢量:定义表面在扩散光下的反射的颜色。一般设置为表面想要的颜色。
3. `specular`材质矢量:设置镜面光斑在表面上的颜色。
4. `shininess`:影响镜面光斑的扩散/直径。

1. 设置材质

void main()
{
    // ambient
    vec3 ambient = lightColor * material.ambient;
    // diffuse
    vec3 norm = normalize(Normal);
    vec3 lightDir = normalize(lightPos - FragPos);
    float diff = max(dot(norm, lightDir), 0.0);
    vec3 diffuse = lightColor * (diff * material.diffuse);
    // specular
    vec3 viewDir = normalize(viewPos - FragPos);
    vec3 reflectDir = reflect(-lightDir, norm);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
    vec3 specular = lightColor * (spec * material.specular);

    vec3 result = ambient + diffuse + specular;
    FragColor = vec4(result, 1.0);
}
objectShader.setVec3("material.ambient", 1.0f, 0.5f, 0.31f);
objectShader.setVec3("material.diffuse", 1.0f, 0.5f, 0.31f);
objectShader.setVec3("material.specular", 0.5f, 0.5f, 0.5f);
objectShader.setFloat("material.shininess", 32.0f);

2. 光属性

vec3 ambient = vec3(1.0) * material.ambient;
vec3 diffuse = vec3(1.0) * (diff * material.diffuse);
vec3 specular = vec3(1.0) * (spec * material.specular);
struct Light{
    vec3 position;
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};

uniform Light light;
// ambient
vec3 ambient = light.ambient * material.ambient;
// diffuse
vec3 diffuse = light.diffuse * (diff * material.diffuse);
// specular
vec3 specular = light.specular * (spec * material.specular);
objectShader.setVec3("light.ambient", 0.2f, 0.2f, 0.2f);
objectShader.setVec3("light.diffuse", 0.5f, 0.5f, 0.5f);  // 偏暗
objectShader.setVec3("light.specular", 1.0f, 1.0f, 1.0f);

3. 不同的光颜色

// 光的颜色
glm::vec3 lightColor;
lightColor.x = sin(glfwGetTime() * 2.0f);
lightColor.y = sin(glfwGetTime() * 0.7f);
lightColor.z = sin(glfwGetTime() * 1.3f);
// 扩散光分量
glm::vec3 diffuseColor = lightColor * glm::vec3(0.5f);
// 环境光分量
glm::vec3 ambientColor = diffuseColor * glm::vec3(0.2f);
// 设置到片元着色器中
objectShader.setVec3("light.ambient", ambientColor);
objectShader.setVec3("light.diffuse", diffuseColor);
光颜色渲染2 光颜色渲染3
上一篇下一篇

猜你喜欢

热点阅读