]> git.tdb.fi Git - libs/gl.git/blob - source/colorcurve.cpp
Add a color curve post-processor
[libs/gl.git] / source / colorcurve.cpp
1 #include "colorcurve.h"
2 #include "mesh.h"
3 #include "shader.h"
4 #include "texture2d.h"
5
6 using namespace std;
7
8 namespace {
9
10 static const char fragment_src[] =
11         "uniform sampler2D texture;\n"
12         "uniform float peak;\n"
13         "uniform float brightness;\n"
14         "varying vec2 texcoord;\n"
15         "void main()\n"
16         "{\n"
17         "       vec4 sample = texture2D(texture, texcoord);\n"
18         "       float maxc = max(sample.r, max(sample.g, sample.b));\n"
19         "       if(maxc>1.0-peak)\n"
20         "       {\n"
21         "               vec3 saturated = sample.rgb/maxc;\n"
22         "               if(maxc>1.0+peak)\n"
23         "               {\n"
24         "                       gl_FragColor.rgb = mix(vec3(1.0), saturated, 1.0/pow(brightness, maxc-1-peak));\n"
25         "               }\n"
26         "               else\n"
27         "               {\n"
28         "                       float x = (1.0+peak-maxc)/(2.0*peak);\n"
29         "                       gl_FragColor.rgb = saturated.rgb*(1.0-peak+(1-x*x)*peak);\n"
30         "               }\n"
31         "               gl_FragColor.a = sample.a;\n"
32         "       }\n"
33         "       else\n"
34         "               gl_FragColor = sample;\n"
35         "}";
36
37 }
38
39 namespace Msp {
40 namespace GL {
41
42 ColorCurve::ColorCurve():
43         quad(get_fullscreen_quad())
44 {
45         shprog.attach_shader(get_fullscreen_vertex_shader());
46         Shader *fs = new Shader(FRAGMENT_SHADER, fragment_src);
47         shprog.attach_shader_owned(fs);
48         shprog.link();
49
50         set_peak(0.2);
51         set_brightness(1.5);
52 }
53
54 void ColorCurve::set_peak(float p)
55 {
56         if(p<0 || p>1)
57                 throw invalid_argument("ColorCurve::set_peak");
58         shdata.uniform("peak", p);
59 }
60
61 void ColorCurve::set_brightness(float b)
62 {
63         if(b<1)
64                 throw invalid_argument("ColorCurve::set_brightness");
65         shdata.uniform("brightness", b);
66 }
67
68 void ColorCurve::render(const Texture2D &color_buf, const Texture2D &)
69 {
70         Bind _bind_shader(shprog);
71         shdata.apply();
72         Bind _bind_tex(color_buf);
73         quad.draw();
74 }
75
76 } // namespace GL
77 } // namespace Msp