GBufferPointLight.frag 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. // This corresponds to the output color to the color buffer
  14. layout(location = 0) out vec4 outColor;
  15. // Different textures from G-buffer
  16. uniform sampler2D uGDiffuse;
  17. uniform sampler2D uGNormal;
  18. uniform sampler2D uGWorldPos;
  19. // Create a struct for the point light
  20. struct PointLight
  21. {
  22. // Position of light
  23. vec3 mWorldPos;
  24. // Diffuse color
  25. vec3 mDiffuseColor;
  26. // Radius of the light
  27. float mInnerRadius;
  28. float mOuterRadius;
  29. };
  30. uniform PointLight uPointLight;
  31. // Stores width/height of screen
  32. uniform vec2 uScreenDimensions;
  33. void main()
  34. {
  35. // From this fragment, calculate the coordinate to sample into the G-buffer
  36. vec2 gbufferCoord = gl_FragCoord.xy / uScreenDimensions;
  37. // Sample from G-buffer
  38. vec3 gbufferDiffuse = texture(uGDiffuse, gbufferCoord).xyz;
  39. vec3 gbufferNorm = texture(uGNormal, gbufferCoord).xyz;
  40. vec3 gbufferWorldPos = texture(uGWorldPos, gbufferCoord).xyz;
  41. // Surface normal
  42. vec3 N = normalize(gbufferNorm);
  43. // Vector from surface to light
  44. vec3 L = normalize(uPointLight.mWorldPos - gbufferWorldPos);
  45. // Compute Phong diffuse component for the light
  46. vec3 Phong = vec3(0.0, 0.0, 0.0);
  47. float NdotL = dot(N, L);
  48. if (NdotL > 0)
  49. {
  50. // Get the distance between the light and the world pos
  51. float dist = distance(uPointLight.mWorldPos, gbufferWorldPos);
  52. // Use smoothstep to compute value in range [0,1]
  53. // between inner/outer radius
  54. float intensity = smoothstep(uPointLight.mInnerRadius,
  55. uPointLight.mOuterRadius, dist);
  56. // The diffuse color of the light depends on intensity
  57. vec3 DiffuseColor = mix(uPointLight.mDiffuseColor,
  58. vec3(0.0, 0.0, 0.0), intensity);
  59. Phong = DiffuseColor * NdotL;
  60. }
  61. // Final color is texture color times phong light (alpha = 1)
  62. outColor = vec4(gbufferDiffuse * Phong, 1.0);
  63. }