mesh.frag 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. precision highp float;
  7. struct Light {
  8. vec3 position;
  9. vec3 color;
  10. vec3 ambient;
  11. float falloff;
  12. float radius;
  13. };
  14. uniform Light light;
  15. uniform mat4 view;
  16. varying vec3 vNormal, vViewPosition, vColor;
  17. float phongSpecular(vec3 lightDirection, vec3 viewDirection, vec3 surfaceNormal, float shininess) {
  18. //Calculate Phong power
  19. vec3 R = -reflect(lightDirection, surfaceNormal);
  20. return pow(max(0.0, dot(viewDirection, R)), shininess);
  21. }
  22. #define PI 3.14159265
  23. float orenNayarDiffuse(vec3 lightDirection, vec3 viewDirection, vec3 surfaceNormal, float roughness, float albedo) {
  24. float LdotV = dot(lightDirection, viewDirection);
  25. float NdotL = dot(lightDirection, surfaceNormal);
  26. float NdotV = dot(surfaceNormal, viewDirection);
  27. float s = LdotV - NdotL * NdotV;
  28. float t = mix(1.0, max(NdotL, NdotV), step(0.0, s));
  29. float sigma2 = roughness * roughness;
  30. float A = 1.0 + sigma2 * (albedo / (sigma2 + 0.13) + 0.5 / (sigma2 + 0.33));
  31. float B = 0.45 * sigma2 / (sigma2 + 0.09);
  32. return albedo * max(0.0, NdotL) * (A + B * s / t) / PI;
  33. }
  34. #pragma glslify: attenuation = require(./attenuation.glsl)
  35. const float specularScale = 0.65;
  36. const float shininess = 10.0;
  37. const float roughness = 5.0;
  38. const float albedo = 0.95;
  39. void main() {
  40. // determine surface to light direction
  41. vec4 lightPosition = view * vec4(light.position, 1.0);
  42. vec3 lightVector = lightPosition.xyz - vViewPosition;
  43. // calculate attenuation
  44. float lightDistance = length(lightVector);
  45. float falloff = 1.0; // attenuation(light.radius, light.falloff, lightDistance);
  46. vec3 L = normalize(lightVector); // light direction
  47. vec3 V = normalize(vViewPosition); // eye direction
  48. vec3 N = normalize(vNormal); // surface normal
  49. // compute our diffuse & specular terms
  50. float specular = phongSpecular(L, V, N, shininess) * specularScale * falloff;
  51. vec3 diffuse = light.color * orenNayarDiffuse(L, V, N, roughness, albedo) * falloff;
  52. vec3 ambient = light.ambient;
  53. // add the lighting
  54. vec3 color = vColor * (diffuse + ambient) + specular;
  55. gl_FragColor.rgb = N;
  56. gl_FragColor.a = 1.0;
  57. }