1 // Calculates adaptation to minimum/maximum luminance values,
2 // based on "currently adapted" and "new values to adapt to"
3 // textures (both 1x1).
4
5 Shader "Hidden/Contrast Stretch Adaptation" {
6 Properties {
7 _MainTex ("Base (RGB)", 2D) = "white" {}
8 _CurTex ("Base (RGB)", 2D) = "white" {}
9 }
10
11 Category {
12 SubShader {
13 Pass {
14 ZTest Always Cull Off ZWrite Off
15
16 CGPROGRAM
17 #pragma vertex vert_img
18 #pragma fragment frag
19 #include "UnityCG.cginc"
20
21 uniform sampler2D _MainTex; // currently adapted to
22 uniform sampler2D _CurTex; // new value to adapt to
23 uniform float4 _AdaptParams; // x=adaptLerp, y=limitMinimum, z=limitMaximum
24
25 float4 frag (v2f_img i) : SV_Target {
26 // value is: max, min
27 float2 valAdapted = tex2D(_MainTex, i.uv).xy;
28 float2 valCur = tex2D(_CurTex, i.uv).xy;
29
30 // Calculate new adapted values: interpolate
31 // from valAdapted to valCur by script-supplied amount.
32 //
33 // Because we store adaptation levels in a simple 8 bit/channel
34 // texture, we might not have enough precision - the interpolation
35 // amount might be too small to change anything, and we'll never
36 // arrive at the needed values.
37 //
38 // So we make sure the change we do is at least 1/255th of the
39 // color range - this way we'll always change the value.
40 const float kMinChange = 1.0/255.0;
41 float2 delta = (valCur-valAdapted) * _AdaptParams.x;
42 delta.x = sign(delta.x) * max( kMinChange, abs(delta.x) );
43 delta.y = sign(delta.y) * max( kMinChange, abs(delta.y) );
44
45 float4 valNew;
46 valNew.xy = valAdapted + delta;
47
48 // Impose user limits on maximum/minimum values
49 valNew.x = max( valNew.x, _AdaptParams.z );
50 valNew.y = min( valNew.y, _AdaptParams.y );
51
52 // Optimization so that our final apply pass is faster:
53 // z = max-min (plus a small amount to prevent division by zero)
54 valNew.z = valNew.x - valNew.y + 0.01;
55 // w = min/(max-min)
56 valNew.w = valNew.y / valNew.z;
57
58 return valNew;
59 }
60 ENDCG
61
62 }
63 }
64 }
65
66 Fallback off
67
68 }