VERTEX shader


SUBMITTED BY: Guest

DATE: June 14, 2013, 12:19 p.m.

FORMAT: C++

SIZE: 2.9 kB

HITS: 5082

  1. ------------------ VERTEX shader ------------------
  2. #version 420
  3. in vec4 vVertex; // Incoming vertex attribute
  4. in vec3 vNormal; // Incoming normal attribute
  5. smooth out vec3 vVaryingNormal; // NEW: Outgoing interpolated normal
  6. smooth out vec3 vVaryingLightDir; // NEW: Outgoing interpolated direction to light source
  7. uniform mat4 pMatrix; // Projection matrix
  8. uniform mat4 vMatrix; // View matrix
  9. uniform mat4 mMatrix; // Model matrix
  10. uniform mat3 normalMatrix; // Normal matrix (3x3)
  11. void main(void)
  12. {
  13. // Specify light position
  14. vec3 vLightPosition = vec3(0.0, 0.0, 10.0);
  15. // Get vertex normal in eye coodinates and output to fragment shader for interpolation
  16. vVaryingNormal = normalMatrix * vNormal;
  17. // Create the ModelView matrix
  18. mat4 mvMatrix = vMatrix * mMatrix;
  19. // Get vertex position in eye coordinates and normalize it by dividing by w
  20. vec4 vPosition4 = mvMatrix * vVertex;
  21. vec3 vPosition3 = vPosition4.xyz / vPosition4.w;
  22. // Get vector to light source to output to fragment shader for interpolation
  23. vVaryingLightDir = normalize(vLightPosition - vPosition3);
  24. // Calculate the final vertex screen position
  25. gl_Position = pMatrix * mvMatrix * vVertex;
  26. }
  27. ----------------- FRAGMENT shader ---------------------------
  28. #version 420
  29. // Input from our vertex shader
  30. in vec3 vVaryingNormal;
  31. in vec3 vVaryingLightDir;
  32. // Output fragments
  33. out vec4 vFragColour;
  34. void main(void)
  35. {
  36. vec4 ambientColour = vec4(0.2, 0.2, 0.2, 1.0);
  37. vec4 diffuseColour = vec4(0.6, 0.6, 0.6, 1.0);
  38. vec4 specularColour = vec4(1.0, 1.0, 1.0, 1.0);
  39. // Start by adding in ambient colour
  40. vFragColour = ambientColour;
  41. // Calculate the diffuse intensity by getting the dot product of the normal and the light direction
  42. float diffuseIntensity = max(0.0, dot(normalize(vVaryingNormal), normalize(vVaryingLightDir)));
  43. // Add in diffuse colour calculated as multiplication of diffuse intensity and diffuse colour
  44. vFragColour += diffuseIntensity * diffuseColour;
  45. // Specular light
  46. vec3 vReflectionVector = normalize(reflect(normalize(-vVaryingNormal), normalize(vVaryingLightDir)));
  47. float specularIntensity = max(0.0, dot(normalize(vVaryingNormal), vReflectionVector));
  48. // If the diffuse light is more than zero then (and only then) calculate specular contribution (pow function is expensive!)
  49. if (diffuseIntensity > 0.0)
  50. {
  51. float fSpec = pow(specularIntensity, 32.0);
  52. vFragColour.rgb += vec3(fSpec * specularColour.rgb);
  53. }
  54. }

comments powered by Disqus