common.sh 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright 2011-2019 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "../common/common.sh"
  6. vec2 blinn(vec3 _lightDir, vec3 _normal, vec3 _viewDir)
  7. {
  8. float ndotl = dot(_normal, _lightDir);
  9. vec3 reflected = _lightDir - 2.0*ndotl*_normal; // reflect(_lightDir, _normal);
  10. float rdotv = dot(reflected, _viewDir);
  11. return vec2(ndotl, rdotv);
  12. }
  13. float fresnel(float _ndotl, float _bias, float _pow)
  14. {
  15. float facing = (1.0 - _ndotl);
  16. return max(_bias + (1.0 - _bias) * pow(facing, _pow), 0.0);
  17. }
  18. vec4 lit(float _ndotl, float _rdotv, float _m)
  19. {
  20. float diff = max(0.0, _ndotl);
  21. float spec = step(0.0, _ndotl) * max(0.0, _rdotv * _m);
  22. return vec4(1.0, diff, spec, 1.0);
  23. }
  24. vec4 powRgba(vec4 _rgba, float _pow)
  25. {
  26. vec4 result;
  27. result.xyz = pow(_rgba.xyz, vec3_splat(_pow) );
  28. result.w = _rgba.w;
  29. return result;
  30. }
  31. vec3 calcLight(vec3 _wpos, vec3 _normal, vec3 _view, vec3 _lightPos, float _lightRadius, vec3 _lightRgb, float _lightInner)
  32. {
  33. vec3 lp = _lightPos - _wpos;
  34. float attn = 1.0 - smoothstep(_lightInner, 1.0, length(lp) / _lightRadius);
  35. vec3 lightDir = normalize(lp);
  36. vec2 bln = blinn(lightDir, _normal, _view);
  37. vec4 lc = lit(bln.x, bln.y, 1.0);
  38. vec3 rgb = _lightRgb * saturate(lc.y) * attn;
  39. return rgb;
  40. }
  41. float toClipSpaceDepth(float _depthTextureZ)
  42. {
  43. #if BGFX_SHADER_LANGUAGE_GLSL
  44. return _depthTextureZ * 2.0 - 1.0;
  45. #else
  46. return _depthTextureZ;
  47. #endif // BGFX_SHADER_LANGUAGE_GLSL
  48. }
  49. vec3 clipToWorld(mat4 _invViewProj, vec3 _clipPos)
  50. {
  51. vec4 wpos = mul(_invViewProj, vec4(_clipPos, 1.0) );
  52. return wpos.xyz / wpos.w;
  53. }