Lighting (1) Directional Light

1. Directional Light

insert image description here

Define a light direction vector instead of a position vector to simulate a directional light. The calculation of the shader remains basically the same, but this time we will use the light's direction vector directly instead of going through the position to calculate the lightDir vector.

struct Light {
    
    
    // vec3 position; // 使用定向光就不再需要了
    vec3 direction;

    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};
...
void main()
{
    
    
  vec3 lightDir = normalize(-light.direction);
  ...
}

step2. Define ten different box positions, and generate a different model matrix for each box, and each model matrix contains the corresponding local-world coordinate transformation:

for(unsigned int i = 0; i < 10; i++)
{
    
    
    glm::mat4 model;
    model = glm::translate(model, cubePositions[i]);
    float angle = 20.0f * i;
    model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f));
    lightingShader.setMat4("model", model);

    glDrawArrays(GL_TRIANGLES, 0, 36);
}

step3. Define the direction of the light source (note that we define the direction as the direction from the light source, you can easily see that the direction of the light is downward).

lightingShader.setVec3("light.direction", -0.2f, -1.0f, -0.3f);


if(lightVector.w == 0.0) // 注意浮点数据类型的误差
  // 执行定向光照计算
else if(lightVector.w == 1.0)
  // 根据光源的位置做光照计算 

Guess you like

Origin blog.csdn.net/thefist11cc/article/details/127020754