Skip to content

Instantly share code, notes, and snippets.

@florianvazelle
Last active February 10, 2021 12:27
Show Gist options
  • Save florianvazelle/fc1ac0e2b63b66870c7fbc293672e577 to your computer and use it in GitHub Desktop.
Save florianvazelle/fc1ac0e2b63b66870c7fbc293672e577 to your computer and use it in GitHub Desktop.
Simple Illumination Shader in GLSL
#version 450
layout(location = 0) in vec3 inNormal;
layout(location = 1) in vec3 inLightVec;
layout(location = 2) in vec3 inViewVec;
layout(binding = 1) uniform Material {
vec3 Ambient;
vec3 Diffuse;
vec3 Specular;
float Shininess;
} uMaterial;
layout(location = 0) out vec4 outColor;
void main() {
const vec3 lightColor = vec3(0.2, 0.8, 0.5);
vec3 N = normalize(inNormal);
vec3 L = normalize(inLightVec);
vec3 V = normalize(inViewVec);
vec3 R = reflect(-L, N);
vec3 ambient = uMaterial.Ambient;
vec3 diffuse = max(dot(N, L), 0.0) * uMaterial.Diffuse;
vec3 specular = pow(max(dot(R, V), 0.0), uMaterial.Shininess) * uMaterial.Specular;
float distance = length(inLightVec);
distance = distance * distance;
float attenuation = 1.0 / distance;
vec3 color = (ambient + diffuse + specular) * lightColor * attenuation;
// correction gamma
color = pow(color, vec3(1.0 / 2.2));
outFragColor = vec4(color, 1.0);
}
#version 450
layout(location = 0) in vec3 positions;
layout(location = 1) in vec3 normals;
layout(binding = 0) uniform UniformBufferObject {
mat4 model;
mat4 view;
mat4 proj;
vec3 lightPos;
} ubo;
layout(location = 0) out vec3 outNormal;
layout(location = 1) out vec3 outLightVec;
layout(location = 2) out vec3 outViewVec;
out gl_PerVertex { vec4 gl_Position; };
void main(void) {
const vec3 cameraPos = vec3(2);
vec3 ModPos = vec3(ubo.model * vec4(positions, 1.0));
outNormal = vec3(transpose(inverse(ubo.model)) * vec4(normals, 0.0));
gl_Position = ubo.proj * ubo.view * vec4(ModPos, 1);
vec3 lPos = mat3(ubo.model) * ubo.lightPos;
outLightVec = lPos - ModPos;
outViewVec = cameraPos - ModPos;
}
#ifndef MATERIAL_HPP
#define MATERIAL_HPP
#include <glm/glm.hpp>
struct Material {
alignas(16) glm::vec3 ambient;
alignas(16) glm::vec3 diffuse;
alignas(16) glm::vec3 specular;
alignas(4) float shininess; // need to specify alignas(4)
};
#endif // MATERIAL_HPP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment