voxel_lighting.fs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #version 100
  2. precision mediump float;
  3. // Input from vertex shader
  4. varying vec3 fragPosition;
  5. varying vec4 fragColor;
  6. varying vec3 fragNormal;
  7. // Uniforms
  8. uniform vec4 colDiffuse;
  9. uniform vec4 ambient;
  10. uniform vec3 viewPos;
  11. #define MAX_LIGHTS 4
  12. #define LIGHT_DIRECTIONAL 0
  13. #define LIGHT_POINT 1
  14. struct Light {
  15. int enabled;
  16. int type;
  17. vec3 position;
  18. vec3 target;
  19. vec4 color;
  20. };
  21. uniform Light lights[MAX_LIGHTS];
  22. void main()
  23. {
  24. vec3 lightDot = vec3(0.0);
  25. vec3 normal = normalize(fragNormal);
  26. vec3 viewD = normalize(viewPos - fragPosition);
  27. vec3 specular = vec3(0.0);
  28. for (int i = 0; i < MAX_LIGHTS; i++)
  29. {
  30. if (lights[i].enabled == 1)
  31. {
  32. vec3 light = vec3(0.0);
  33. if (lights[i].type == LIGHT_DIRECTIONAL)
  34. light = -normalize(lights[i].target - lights[i].position);
  35. if (lights[i].type == LIGHT_POINT)
  36. light = normalize(lights[i].position - fragPosition);
  37. float NdotL = max(dot(normal, light), 0.0);
  38. lightDot += lights[i].color.rgb*NdotL;
  39. if (NdotL > 0.0)
  40. {
  41. float specCo = pow(max(0.0, dot(viewD, reflect(-light, normal))), 16.0);
  42. specular += specCo;
  43. }
  44. }
  45. }
  46. vec4 finalColor = (fragColor*((colDiffuse + vec4(specular, 1.0))*vec4(lightDot, 1.0)));
  47. finalColor += fragColor*(ambient/10.0)*colDiffuse;
  48. finalColor = pow(finalColor, vec4(1.0/2.2)); // gamma correction
  49. gl_FragColor = finalColor;
  50. }