Advertisement
Guest User

Untitled

a guest
Apr 6th, 2020
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.12 KB | None | 0 0
  1. // Shared functions for all shaders in the engine. Contents of this
  2. // file will be *automatically* included in all shaders!
  3.  
  4. // Projects world space position (typical use case) by given matrix.
  5. vec3 S_Project(vec3 worldPosition, mat4 matrix)
  6. {
  7.     vec4 screenPos = matrix * vec4(worldPosition, 1);
  8.  
  9.     screenPos.xyz /= screenPos.w;
  10.  
  11.     return screenPos.xyz * 0.5 + 0.5;
  12. }
  13.  
  14. // Returns matrix-space position from given screen position.
  15. // Real space of returned value is defined by matrix and can
  16. // be any, but there are few common use cases:
  17. //  - To get position in view space pass inverse projection matrix.
  18. //  - To get position in world space pass inverse view-projection matrix.
  19. vec3 S_UnProject(vec3 screenPos, mat4 matrix)
  20. {
  21.     vec4 clipSpacePos = vec4(screenPos * 2.0 - 1.0, 1.0);
  22.  
  23.     vec4 position = matrix * clipSpacePos;
  24.  
  25.     return position.xyz / position.w;
  26. }
  27.  
  28. struct TBlinnPhongContext {
  29.     vec3 lightPosition;
  30.     float lightRadius;
  31.     vec3 fragmentNormal;
  32.     vec3 fragmentPosition;
  33.     vec3 cameraPosition;
  34.     float specularPower;
  35. };
  36.  
  37. struct TBlinnPhong {
  38.     // Total "brightness" of fragment.
  39.     float attenuation;
  40.  
  41.     // Specular component of lighting.
  42.     float specular;
  43.  
  44.     // Distance from light to fragment.
  45.     float distance;
  46.  
  47.     // Normalized vector from fragment position to light.
  48.     vec3 direction;
  49. };
  50.  
  51. TBlinnPhong S_BlinnPhong(TBlinnPhongContext ctx)
  52. {
  53.     vec3 lightVector = ctx.lightPosition - ctx.fragmentPosition;
  54.  
  55.     float distance = length(lightVector);
  56.  
  57.     float clampedDistance = min(distance, ctx.lightRadius);
  58.     vec3 normLightVector = lightVector / clampedDistance;
  59.     vec3 h = normalize(lightVector + (ctx.cameraPosition - ctx.fragmentPosition));
  60.     float specular = pow(clamp(dot(ctx.fragmentNormal, h), 0.0, 1.0), ctx.specularPower);
  61.  
  62.     float lambertian = max(dot(ctx.fragmentNormal, normLightVector), 0);
  63.  
  64.     float distance_attenuation = 1.0 + cos((clampedDistance / ctx.lightRadius) * 3.14159);
  65.  
  66.     float attenuation = lambertian * distance_attenuation;
  67.  
  68.     return TBlinnPhong(attenuation, specular, distance, normLightVector);
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement