added basic lighting

This commit is contained in:
Lukian 2025-02-08 15:36:41 +01:00
parent 32fd486cc3
commit 93333821d8
3 changed files with 36 additions and 4 deletions

View file

@ -1,11 +1,32 @@
#version 330 core #version 330 core
out vec4 FragColor; out vec4 FragColor;
in vec3 Normal;
in vec2 TexCoords; in vec2 TexCoords;
in vec3 FragPos;
uniform sampler2D texture_diffuse1; uniform sampler2D texture_diffuse1;
uniform vec3 lightColor;
uniform vec3 lightPos;
uniform vec3 viewPos;
void main() void main()
{ {
FragColor = texture(texture_diffuse1, TexCoords); float ambientStrength = 0.1;
vec3 ambient = ambientStrength * lightColor;
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(lightPos - FragPos);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = diff * lightColor;
float specularStrength = 0.5;
vec3 viewDir = normalize(viewPos - FragPos);
vec3 reflectDir = reflect(-lightDir, norm);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32);
vec3 specular = specularStrength * spec * lightColor;
vec3 result = (ambient + diffuse + specular) * vec3(1.0, 0.5, 0.2);
vec4 light = vec4(result, 1.0);
FragColor = texture(texture_diffuse1, TexCoords) * light;
} }

View file

@ -3,7 +3,9 @@ layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal; layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoords; layout (location = 2) in vec2 aTexCoords;
out vec3 Normal;
out vec2 TexCoords; out vec2 TexCoords;
out vec3 FragPos;
uniform mat4 model; uniform mat4 model;
uniform mat4 view; uniform mat4 view;
@ -11,6 +13,8 @@ uniform mat4 projection;
void main() void main()
{ {
TexCoords = aTexCoords; TexCoords = aTexCoords;
gl_Position = projection * view * model * vec4(aPos, 1.0); Normal = mat3(transpose(inverse(model))) * aNormal;
FragPos = vec3(model * vec4(aPos, 1.0));
gl_Position = projection * view * model * vec4(aPos, 1.0);
} }

View file

@ -67,6 +67,9 @@ int main()
glm::mat4 model = glm::mat4(1.0f); glm::mat4 model = glm::mat4(1.0f);
model = glm::rotate(model, glm::radians(-55.0f), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::rotate(model, glm::radians(-55.0f), glm::vec3(1.0f, 0.0f, 0.0f));
glm::vec3 lightPos = glm::vec3(1.2f, 1.0f, 2.0f);
glm::vec3 lightColor = glm::vec3(1.0f, 1.0f, 1.0f);
while(!glfwWindowShouldClose(window)) while(!glfwWindowShouldClose(window))
{ {
float currentFrame = glfwGetTime(); float currentFrame = glfwGetTime();
@ -80,6 +83,10 @@ int main()
ourShader.use(); ourShader.use();
ourShader.setVec3("lightPos", lightPos);
ourShader.setVec3("lightColor", lightColor);
ourShader.setVec3("viewPos", camera.Position);
glm::mat4 view = camera.GetViewMatrix(); glm::mat4 view = camera.GetViewMatrix();
glm::mat4 projection = glm::perspective(glm::radians(45.0f), float(width) / float(height), 0.1f, 100.0f); glm::mat4 projection = glm::perspective(glm::radians(45.0f), float(width) / float(height), 0.1f, 100.0f);
ourShader.setMat4("view", view); ourShader.setMat4("view", view);