Rename .glsl to .vert/.frag.
[movit] / effect_chain.cpp
1 #define GL_GLEXT_PROTOTYPES 1
2
3 #include <stdio.h>
4 #include <string.h>
5 #include <assert.h>
6
7 #include <GL/gl.h>
8 #include <GL/glext.h>
9
10 #include "util.h"
11 #include "effect_chain.h"
12 #include "gamma_expansion_effect.h"
13 #include "gamma_compression_effect.h"
14 #include "lift_gamma_gain_effect.h"
15 #include "colorspace_conversion_effect.h"
16 #include "saturation_effect.h"
17 #include "vignette_effect.h"
18 #include "texture_enum.h"
19
20 EffectChain::EffectChain(unsigned width, unsigned height)
21         : width(width), height(height), use_srgb_texture_format(false), finalized(false) {}
22
23 void EffectChain::add_input(const ImageFormat &format)
24 {
25         input_format = format;
26         current_color_space = format.color_space;
27         current_gamma_curve = format.gamma_curve;
28 }
29
30 void EffectChain::add_output(const ImageFormat &format)
31 {
32         output_format = format;
33 }
34         
35 Effect *instantiate_effect(EffectId effect)
36 {
37         switch (effect) {
38         case EFFECT_GAMMA_EXPANSION:
39                 return new GammaExpansionEffect();
40         case EFFECT_GAMMA_COMPRESSION:
41                 return new GammaCompressionEffect();
42         case EFFECT_COLOR_SPACE_CONVERSION:
43                 return new ColorSpaceConversionEffect();
44         case EFFECT_LIFT_GAMMA_GAIN:
45                 return new LiftGammaGainEffect();
46         case EFFECT_SATURATION:
47                 return new SaturationEffect();
48         case EFFECT_VIGNETTE:
49                 return new VignetteEffect();
50         }
51         assert(false);
52 }
53
54 void EffectChain::normalize_to_linear_gamma()
55 {
56         if (current_gamma_curve == GAMMA_sRGB) {
57                 // TODO: check if the extension exists
58                 use_srgb_texture_format = true;
59         } else {
60                 GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
61                 gamma_conversion->set_int("source_curve", current_gamma_curve);
62                 effects.push_back(gamma_conversion);
63         }
64         current_gamma_curve = GAMMA_LINEAR;
65 }
66
67 void EffectChain::normalize_to_srgb()
68 {
69         assert(current_gamma_curve == GAMMA_LINEAR);
70         ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
71         colorspace_conversion->set_int("source_space", current_color_space);
72         colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
73         effects.push_back(colorspace_conversion);
74         current_color_space = COLORSPACE_sRGB;
75 }
76
77 Effect *EffectChain::add_effect(EffectId effect_id)
78 {
79         Effect *effect = instantiate_effect(effect_id);
80
81         if (effect->needs_linear_light() && current_gamma_curve != GAMMA_LINEAR) {
82                 normalize_to_linear_gamma();
83         }
84
85         if (effect->needs_srgb_primaries() && current_color_space != COLORSPACE_sRGB) {
86                 normalize_to_srgb();
87         }
88
89         // not handled yet
90         assert(!effect->needs_many_samples());
91         assert(!effect->needs_mipmaps());
92
93         effects.push_back(effect);
94         return effect;
95 }
96
97 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
98 std::string replace_prefix(const std::string &text, const std::string &prefix)
99 {
100         std::string output;
101         size_t start = 0;
102
103         while (start < text.size()) {
104                 size_t pos = text.find("PREFIX(", start);
105                 if (pos == std::string::npos) {
106                         output.append(text.substr(start, std::string::npos));
107                         break;
108                 }
109
110                 output.append(text.substr(start, pos - start));
111                 output.append(prefix);
112                 output.append("_");
113
114                 pos += strlen("PREFIX(");
115         
116                 // Output stuff until we find the matching ), which we then eat.
117                 int depth = 1;
118                 size_t end_arg_pos = pos;
119                 while (end_arg_pos < text.size()) {
120                         if (text[end_arg_pos] == '(') {
121                                 ++depth;
122                         } else if (text[end_arg_pos] == ')') {
123                                 --depth;
124                                 if (depth == 0) {
125                                         break;
126                                 }
127                         }
128                         ++end_arg_pos;
129                 }
130                 output.append(text.substr(pos, end_arg_pos - pos));
131                 ++end_arg_pos;
132                 assert(depth == 0);
133                 start = end_arg_pos;
134         }
135         return output;
136 }
137
138 void EffectChain::finalize()
139 {
140         if (current_color_space != output_format.color_space) {
141                 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
142                 colorspace_conversion->set_int("source_space", current_color_space);
143                 colorspace_conversion->set_int("destination_space", output_format.color_space);
144                 effects.push_back(colorspace_conversion);
145                 current_color_space = output_format.color_space;
146         }
147
148         if (current_gamma_curve != output_format.gamma_curve) {
149                 if (current_gamma_curve != GAMMA_LINEAR) {
150                         normalize_to_linear_gamma();
151                 }
152                 assert(current_gamma_curve == GAMMA_LINEAR);
153                 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
154                 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
155                 effects.push_back(gamma_conversion);
156                 current_gamma_curve = output_format.gamma_curve;
157         }
158         
159         std::string vert_shader = read_file("header.vert");
160         for (unsigned i = 0; i < effects.size(); ++i) {
161                 char effect_id[256];
162                 sprintf(effect_id, "eff%d", i);
163         
164                 vert_shader += "\n";
165                 vert_shader += std::string("#define FUNCNAME ") + effect_id + "\n";
166                 vert_shader += replace_prefix(effects[i]->output_convenience_uniforms(), effect_id);
167                 vert_shader += replace_prefix(effects[i]->output_vertex_shader(), effect_id);
168                 vert_shader += "#undef PREFIX\n";
169                 vert_shader += "#undef FUNCNAME\n";
170                 vert_shader += "#undef LAST_INPUT\n";
171                 vert_shader += std::string("#define LAST_INPUT ") + effect_id + "\n";
172                 vert_shader += "\n";
173         }
174         vert_shader.append(read_file("footer.vert"));
175         printf("%s\n", vert_shader.c_str());
176
177         std::string frag_shader = read_file("header.frag");
178         for (unsigned i = 0; i < effects.size(); ++i) {
179                 char effect_id[256];
180                 sprintf(effect_id, "eff%d", i);
181         
182                 frag_shader += "\n";
183                 frag_shader += std::string("#define FUNCNAME ") + effect_id + "\n";
184                 frag_shader += replace_prefix(effects[i]->output_convenience_uniforms(), effect_id);
185                 frag_shader += replace_prefix(effects[i]->output_fragment_shader(), effect_id);
186                 frag_shader += "#undef PREFIX\n";
187                 frag_shader += "#undef FUNCNAME\n";
188                 frag_shader += "#undef LAST_INPUT\n";
189                 frag_shader += std::string("#define LAST_INPUT ") + effect_id + "\n";
190                 frag_shader += "\n";
191         }
192         frag_shader.append(read_file("footer.frag"));
193         printf("%s\n", frag_shader.c_str());
194         
195         glsl_program_num = glCreateProgram();
196         GLuint vs_obj = compile_shader(vert_shader, GL_VERTEX_SHADER);
197         GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
198         glAttachShader(glsl_program_num, vs_obj);
199         check_error();
200         glAttachShader(glsl_program_num, fs_obj);
201         check_error();
202         glLinkProgram(glsl_program_num);
203         check_error();
204
205         // Translate the format to OpenGL's enums.
206         GLenum internal_format;
207         if (use_srgb_texture_format) {
208                 internal_format = GL_SRGB8;
209         } else {
210                 internal_format = GL_RGBA8;
211         }
212         if (input_format.pixel_format == FORMAT_RGB) {
213                 format = GL_RGB;
214                 bytes_per_pixel = 3;
215         } else if (input_format.pixel_format == FORMAT_RGBA) {
216                 format = GL_RGBA;
217                 bytes_per_pixel = 4;
218         } else if (input_format.pixel_format == FORMAT_BGR) {
219                 format = GL_BGR;
220                 bytes_per_pixel = 3;
221         } else if (input_format.pixel_format == FORMAT_BGRA) {
222                 format = GL_BGRA;
223                 bytes_per_pixel = 4;
224         } else {
225                 assert(false);
226         }
227
228         // Create PBO to hold the texture, and then the texture itself.
229         glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 2);
230         check_error();
231         glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, width * height * bytes_per_pixel, NULL, GL_STREAM_DRAW);
232         check_error();
233
234         void *mapped_pbo = glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY);
235         memset(mapped_pbo, 0, width * height * bytes_per_pixel);
236         glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB);
237         
238         glBindTexture(GL_TEXTURE_2D, SOURCE_IMAGE);
239         check_error();
240         glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0, format, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
241         check_error();
242         glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
243         check_error();
244
245         finalized = true;
246 }
247
248 void EffectChain::render_to_screen(unsigned char *src)
249 {
250         assert(finalized);
251
252         // Copy the pixel data into the PBO.
253         glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 2);
254         check_error();
255         void *mapped_pbo = glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY);
256         memcpy(mapped_pbo, src, width * height * bytes_per_pixel);
257         glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB);
258         check_error();
259
260         // Re-upload the texture from the PBO.
261         glActiveTexture(GL_TEXTURE0);
262         check_error();
263         glBindTexture(GL_TEXTURE_2D, SOURCE_IMAGE);
264         check_error();
265         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
266         check_error();
267         glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
268         check_error();
269
270         glUseProgram(glsl_program_num);
271         check_error();
272
273         check_error();
274         glUniform1i(glGetUniformLocation(glsl_program_num, "input_tex"), 0);
275
276         for (unsigned i = 0; i < effects.size(); ++i) {
277                 char effect_id[256];
278                 sprintf(effect_id, "eff%d", i);
279                 effects[i]->set_uniforms(glsl_program_num, effect_id);
280         }
281
282         glDisable(GL_BLEND);
283         check_error();
284         glDisable(GL_DEPTH_TEST);
285         check_error();
286         glDepthMask(GL_FALSE);
287         check_error();
288
289         glMatrixMode(GL_PROJECTION);
290         glLoadIdentity();
291         glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
292
293         glMatrixMode(GL_MODELVIEW);
294         glLoadIdentity();
295
296         glBegin(GL_QUADS);
297
298         glTexCoord2f(0.0f, 1.0f);
299         glVertex2f(0.0f, 0.0f);
300
301         glTexCoord2f(1.0f, 1.0f);
302         glVertex2f(1.0f, 0.0f);
303
304         glTexCoord2f(1.0f, 0.0f);
305         glVertex2f(1.0f, 1.0f);
306
307         glTexCoord2f(0.0f, 0.0f);
308         glVertex2f(0.0f, 1.0f);
309
310         glEnd();
311         check_error();
312 }