Histogram.shader 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. Shader "Hidden/PostProcessing/Debug/Histogram"
  2. {
  3. HLSLINCLUDE
  4. #pragma exclude_renderers gles gles3 d3d11_9x
  5. #pragma target 4.5
  6. #include "../StdLib.hlsl"
  7. #if SHADER_API_GLES3
  8. #define HISTOGRAM_BINS 128
  9. #else
  10. #define HISTOGRAM_BINS 256
  11. #endif
  12. struct VaryingsHistogram
  13. {
  14. float4 vertex : SV_POSITION;
  15. float2 texcoord : TEXCOORD0;
  16. float maxValue : TEXCOORD1;
  17. };
  18. StructuredBuffer<uint> _HistogramBuffer;
  19. float2 _Params; // x: width, y: height
  20. float FindMaxHistogramValue()
  21. {
  22. uint maxValue = 0u;
  23. UNITY_UNROLL
  24. for (uint i = 0; i < HISTOGRAM_BINS; i++)
  25. {
  26. uint h = _HistogramBuffer[i];
  27. maxValue = max(maxValue, h);
  28. }
  29. return float(maxValue);
  30. }
  31. VaryingsHistogram Vert(AttributesDefault v)
  32. {
  33. VaryingsHistogram o;
  34. o.vertex = float4(v.vertex.xy, 0.0, 1.0);
  35. o.texcoord = TransformTriangleVertexToUV(v.vertex.xy);
  36. #if UNITY_UV_STARTS_AT_TOP
  37. o.texcoord = o.texcoord * float2(1.0, -1.0) + float2(0.0, 1.0);
  38. #endif
  39. #if SHADER_API_GLES3 // No texture loopup in VS on GLES3/Android
  40. o.maxValue = 0;
  41. #else
  42. o.maxValue = _Params.y / FindMaxHistogramValue();
  43. #endif
  44. return o;
  45. }
  46. float4 Frag(VaryingsHistogram i) : SV_Target
  47. {
  48. #if SHADER_API_GLES3
  49. float maxValue = _Params.y / FindMaxHistogramValue();
  50. #else
  51. float maxValue = i.maxValue;
  52. #endif
  53. const float kBinsMinusOne = HISTOGRAM_BINS - 1.0;
  54. float remapI = i.texcoord.x * kBinsMinusOne;
  55. uint index = floor(remapI);
  56. float delta = frac(remapI);
  57. float v1 = float(_HistogramBuffer[index]) * maxValue;
  58. float v2 = float(_HistogramBuffer[min(index + 1, kBinsMinusOne)]) * maxValue;
  59. float h = v1 * (1.0 - delta) + v2 * delta;
  60. uint y = (uint)round(i.texcoord.y * _Params.y);
  61. float3 color = (0.0).xxx;
  62. float fill = step(y, h);
  63. color = lerp(color, (1.0).xxx, fill);
  64. return float4(color, 1.0);
  65. }
  66. ENDHLSL
  67. SubShader
  68. {
  69. Cull Off ZWrite Off ZTest Always
  70. Pass
  71. {
  72. HLSLPROGRAM
  73. #pragma vertex Vert
  74. #pragma fragment Frag
  75. ENDHLSL
  76. }
  77. }
  78. }