Phong.frag 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // ----------------------------------------------------------------
  2. // From Game Programming in C++ by Sanjay Madhav
  3. // Copyright (C) 2017 Sanjay Madhav. All rights reserved.
  4. //
  5. // Released under the BSD License
  6. // See LICENSE in root directory for full details.
  7. // ----------------------------------------------------------------
  8. // Request GLSL 3.3
  9. #version 330
  10. // Inputs from vertex shader
  11. // Tex coord
  12. in vec2 fragTexCoord;
  13. // Normal (in world space)
  14. in vec3 fragNormal;
  15. // Position (in world space)
  16. in vec3 fragWorldPos;
  17. // This corresponds to the output color to the color buffer
  18. out vec4 outColor;
  19. // This is used for the texture sampling
  20. uniform sampler2D uTexture;
  21. // Create a struct for directional light
  22. struct DirectionalLight
  23. {
  24. // Direction of light
  25. vec3 mDirection;
  26. // Diffuse color
  27. vec3 mDiffuseColor;
  28. // Specular color
  29. vec3 mSpecColor;
  30. };
  31. // Uniforms for lighting
  32. // Camera position (in world space)
  33. uniform vec3 uCameraPos;
  34. // Specular power for this surface
  35. uniform float uSpecPower;
  36. // Ambient light level
  37. uniform vec3 uAmbientLight;
  38. // Directional Light
  39. uniform DirectionalLight uDirLight;
  40. void main()
  41. {
  42. // Surface normal
  43. vec3 N = normalize(fragNormal);
  44. // Vector from surface to light
  45. vec3 L = normalize(-uDirLight.mDirection);
  46. // Vector from surface to camera
  47. vec3 V = normalize(uCameraPos - fragWorldPos);
  48. // Reflection of -L about N
  49. vec3 R = normalize(reflect(-L, N));
  50. // Compute phong reflection
  51. vec3 Phong = uAmbientLight;
  52. float NdotL = dot(N, L);
  53. if (NdotL > 0)
  54. {
  55. vec3 Diffuse = uDirLight.mDiffuseColor * NdotL;
  56. vec3 Specular = uDirLight.mSpecColor * pow(max(0.0, dot(R, V)), uSpecPower);
  57. Phong += Diffuse + Specular;
  58. }
  59. // Final color is texture color times phong light (alpha = 1)
  60. outColor = texture(uTexture, fragTexCoord) * vec4(Phong, 1.0f);
  61. }