aae2941f791ca86faf9ce16cea4912cd9c05fd1b
[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 <algorithm>
8 #include <set>
9 #include <stack>
10 #include <vector>
11
12 #include "util.h"
13 #include "effect_chain.h"
14 #include "gamma_expansion_effect.h"
15 #include "gamma_compression_effect.h"
16 #include "colorspace_conversion_effect.h"
17 #include "input.h"
18 #include "opengl.h"
19
20 EffectChain::EffectChain(unsigned width, unsigned height)
21         : width(width),
22           height(height),
23           finalized(false) {}
24
25 Input *EffectChain::add_input(Input *input)
26 {
27         char eff_id[256];
28         sprintf(eff_id, "src_image%u", (unsigned)inputs.size());
29
30         inputs.push_back(input);
31
32         Node *node = new Node;
33         node->effect = input;
34         node->effect_id = eff_id;
35         node->output_color_space = input->get_color_space();
36         node->output_gamma_curve = input->get_gamma_curve();
37
38         nodes.push_back(node);
39         node_map[input] = node;
40
41         return input;
42 }
43
44 void EffectChain::add_output(const ImageFormat &format)
45 {
46         output_format = format;
47 }
48
49 void EffectChain::add_effect_raw(Effect *effect, const std::vector<Effect *> &inputs)
50 {
51         char effect_id[256];
52         sprintf(effect_id, "eff%u", (unsigned)nodes.size());
53
54         Node *node = new Node;
55         node->effect = effect;
56         node->effect_id = effect_id;
57
58         assert(inputs.size() == effect->num_inputs());
59         assert(inputs.size() >= 1);
60         for (unsigned i = 0; i < inputs.size(); ++i) {
61                 assert(node_map.count(inputs[i]) != 0);
62                 node_map[inputs[i]]->outgoing_links.push_back(node);
63                 node->incoming_links.push_back(node_map[inputs[i]]);
64                 if (i == 0) {
65                         node->output_gamma_curve = node_map[inputs[i]]->output_gamma_curve;
66                         node->output_color_space = node_map[inputs[i]]->output_color_space;
67                 } else {
68                         assert(node->output_gamma_curve == node_map[inputs[i]]->output_gamma_curve);
69                         assert(node->output_color_space == node_map[inputs[i]]->output_color_space);
70                 }
71         }
72
73         nodes.push_back(node);
74         node_map[effect] = node;
75 }
76
77 void EffectChain::find_all_nonlinear_inputs(Node *node,
78                                             std::vector<Node *> *nonlinear_inputs,
79                                             std::vector<Node *> *intermediates)
80 {
81         if (node->output_gamma_curve == GAMMA_LINEAR) {
82                 return;
83         }
84         if (node->effect->num_inputs() == 0) {
85                 nonlinear_inputs->push_back(node);
86         } else {
87                 intermediates->push_back(node);
88                 assert(node->effect->num_inputs() == node->incoming_links.size());
89                 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
90                         find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs, intermediates);
91                 }
92         }
93 }
94
95 Node *EffectChain::normalize_to_linear_gamma(Node *input)
96 {
97         // Find out if all the inputs can be set to deliver sRGB inputs.
98         // If so, we can just ask them to do that instead of inserting a
99         // (possibly expensive) conversion operation.
100         //
101         // NOTE: We assume that effects generally don't mess with the gamma
102         // curve (except GammaCompressionEffect, which should never be
103         // inserted into a chain when this is called), so that we can just
104         // update the output gamma as we go.
105         //
106         // TODO: Setting this flag for one source might confuse a different
107         // part of the pipeline using the same source.
108         std::vector<Node *> nonlinear_inputs;
109         std::vector<Node *> intermediates;
110         find_all_nonlinear_inputs(input, &nonlinear_inputs, &intermediates);
111
112         bool all_ok = true;
113         for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
114                 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
115                 all_ok &= input->can_output_linear_gamma();
116         }
117
118         if (all_ok) {
119                 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
120                         bool ok = nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1);
121                         assert(ok);
122                         nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
123                 }
124                 for (unsigned i = 0; i < intermediates.size(); ++i) {
125                         intermediates[i]->output_gamma_curve = GAMMA_LINEAR;
126                 }
127                 return input;
128         }
129
130         // OK, that didn't work. Insert a conversion effect.
131         GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
132         gamma_conversion->set_int("source_curve", input->output_gamma_curve);
133         std::vector<Effect *> inputs;
134         inputs.push_back(input->effect);
135         gamma_conversion->add_self_to_effect_chain(this, inputs);
136
137         assert(node_map.count(gamma_conversion) != 0);
138         Node *node = node_map[gamma_conversion];
139         node->output_gamma_curve = GAMMA_LINEAR;
140         return node;
141 }
142
143 Node *EffectChain::normalize_to_srgb(Node *input)
144 {
145         assert(input->output_gamma_curve == GAMMA_LINEAR);
146         ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
147         colorspace_conversion->set_int("source_space", input->output_color_space);
148         colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
149         std::vector<Effect *> inputs;
150         inputs.push_back(input->effect);
151         colorspace_conversion->add_self_to_effect_chain(this, inputs);
152
153         assert(node_map.count(colorspace_conversion) != 0);
154         Node *node = node_map[colorspace_conversion];
155         node->output_color_space = COLORSPACE_sRGB;
156         return node;
157 }
158
159 Effect *EffectChain::add_effect(Effect *effect, const std::vector<Effect *> &inputs)
160 {
161         assert(inputs.size() == effect->num_inputs());
162
163         std::vector<Effect *> normalized_inputs = inputs;
164         for (unsigned i = 0; i < normalized_inputs.size(); ++i) {
165                 assert(node_map.count(normalized_inputs[i]) != 0);
166                 Node *input = node_map[normalized_inputs[i]];
167                 if (effect->needs_linear_light() && input->output_gamma_curve != GAMMA_LINEAR) {
168                         input = normalize_to_linear_gamma(input);
169                 }
170                 if (effect->needs_srgb_primaries() && input->output_color_space != COLORSPACE_sRGB) {
171                         input = normalize_to_srgb(input);
172                 }
173                 normalized_inputs[i] = input->effect;
174         }
175
176         effect->add_self_to_effect_chain(this, normalized_inputs);
177         return effect;
178 }
179
180 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
181 std::string replace_prefix(const std::string &text, const std::string &prefix)
182 {
183         std::string output;
184         size_t start = 0;
185
186         while (start < text.size()) {
187                 size_t pos = text.find("PREFIX(", start);
188                 if (pos == std::string::npos) {
189                         output.append(text.substr(start, std::string::npos));
190                         break;
191                 }
192
193                 output.append(text.substr(start, pos - start));
194                 output.append(prefix);
195                 output.append("_");
196
197                 pos += strlen("PREFIX(");
198         
199                 // Output stuff until we find the matching ), which we then eat.
200                 int depth = 1;
201                 size_t end_arg_pos = pos;
202                 while (end_arg_pos < text.size()) {
203                         if (text[end_arg_pos] == '(') {
204                                 ++depth;
205                         } else if (text[end_arg_pos] == ')') {
206                                 --depth;
207                                 if (depth == 0) {
208                                         break;
209                                 }
210                         }
211                         ++end_arg_pos;
212                 }
213                 output.append(text.substr(pos, end_arg_pos - pos));
214                 ++end_arg_pos;
215                 assert(depth == 0);
216                 start = end_arg_pos;
217         }
218         return output;
219 }
220
221 Phase *EffectChain::compile_glsl_program(
222         const std::vector<Node *> &inputs,
223         const std::vector<Node *> &effects)
224 {
225         assert(!effects.empty());
226
227         // Deduplicate the inputs.
228         std::vector<Node *> true_inputs = inputs;
229         std::sort(true_inputs.begin(), true_inputs.end());
230         true_inputs.erase(std::unique(true_inputs.begin(), true_inputs.end()), true_inputs.end());
231
232         bool input_needs_mipmaps = false;
233         std::string frag_shader = read_file("header.frag");
234
235         // Create functions for all the texture inputs that we need.
236         for (unsigned i = 0; i < true_inputs.size(); ++i) {
237                 Node *input = true_inputs[i];
238         
239                 frag_shader += std::string("uniform sampler2D tex_") + input->effect_id + ";\n";
240                 frag_shader += std::string("vec4 ") + input->effect_id + "(vec2 tc) {\n";
241                 frag_shader += "\treturn texture2D(tex_" + input->effect_id + ", tc);\n";
242                 frag_shader += "}\n";
243                 frag_shader += "\n";
244         }
245
246         for (unsigned i = 0; i < effects.size(); ++i) {
247                 Node *node = effects[i];
248
249                 if (node->incoming_links.size() == 1) {
250                         frag_shader += std::string("#define INPUT ") + node->incoming_links[0]->effect_id + "\n";
251                 } else {
252                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
253                                 char buf[256];
254                                 sprintf(buf, "#define INPUT%d %s\n", j + 1, node->incoming_links[j]->effect_id.c_str());
255                                 frag_shader += buf;
256                         }
257                 }
258         
259                 frag_shader += "\n";
260                 frag_shader += std::string("#define FUNCNAME ") + node->effect_id + "\n";
261                 frag_shader += replace_prefix(node->effect->output_convenience_uniforms(), node->effect_id);
262                 frag_shader += replace_prefix(node->effect->output_fragment_shader(), node->effect_id);
263                 frag_shader += "#undef PREFIX\n";
264                 frag_shader += "#undef FUNCNAME\n";
265                 if (node->incoming_links.size() == 1) {
266                         frag_shader += "#undef INPUT\n";
267                 } else {
268                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
269                                 char buf[256];
270                                 sprintf(buf, "#undef INPUT%d\n", j + 1);
271                                 frag_shader += buf;
272                         }
273                 }
274                 frag_shader += "\n";
275
276                 input_needs_mipmaps |= node->effect->needs_mipmaps();
277         }
278         for (unsigned i = 0; i < effects.size(); ++i) {
279                 Node *node = effects[i];
280                 if (node->effect->num_inputs() == 0) {
281                         node->effect->set_int("needs_mipmaps", input_needs_mipmaps);
282                 }
283         }
284         frag_shader += std::string("#define INPUT ") + effects.back()->effect_id + "\n";
285         frag_shader.append(read_file("footer.frag"));
286         printf("%s\n", frag_shader.c_str());
287         
288         GLuint glsl_program_num = glCreateProgram();
289         GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
290         GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
291         glAttachShader(glsl_program_num, vs_obj);
292         check_error();
293         glAttachShader(glsl_program_num, fs_obj);
294         check_error();
295         glLinkProgram(glsl_program_num);
296         check_error();
297
298         Phase *phase = new Phase;
299         phase->glsl_program_num = glsl_program_num;
300         phase->input_needs_mipmaps = input_needs_mipmaps;
301         phase->inputs = true_inputs;
302         phase->effects = effects;
303
304         return phase;
305 }
306
307 // Construct GLSL programs, starting at the given effect and following
308 // the chain from there. We end a program every time we come to an effect
309 // marked as "needs texture bounce", one that is used by multiple other
310 // effects, every time an effect wants to change the output size,
311 // and of course at the end.
312 //
313 // We follow a quite simple depth-first search from the output, although
314 // without any explicit recursion.
315 void EffectChain::construct_glsl_programs(Node *output)
316 {
317         // Which effects have already been completed in this phase?
318         // We need to keep track of it, as an effect with multiple outputs
319         // could otherwise be calculate multiple times.
320         std::set<Node *> completed_effects;
321
322         // Effects in the current phase, as well as inputs (outputs from other phases
323         // that we depend on). Note that since we start iterating from the end,
324         // the effect list will be in the reverse order.
325         std::vector<Node *> this_phase_inputs;
326         std::vector<Node *> this_phase_effects;
327
328         // Effects that we have yet to calculate, but that we know should
329         // be in the current phase.
330         std::stack<Node *> effects_todo_this_phase;
331
332         // Effects that we have yet to calculate, but that come from other phases.
333         // We delay these until we have this phase done in its entirety,
334         // at which point we pick any of them and start a new phase from that.
335         std::stack<Node *> effects_todo_other_phases;
336
337         effects_todo_this_phase.push(output);
338
339         for ( ;; ) {  // Termination condition within loop.
340                 if (!effects_todo_this_phase.empty()) {
341                         // OK, we have more to do this phase.
342                         Node *node = effects_todo_this_phase.top();
343                         effects_todo_this_phase.pop();
344
345                         // This should currently only happen for effects that are phase outputs,
346                         // and we throw those out separately below.
347                         assert(completed_effects.count(node) == 0);
348
349                         this_phase_effects.push_back(node);
350                         completed_effects.insert(node);
351
352                         // Find all the dependencies of this effect, and add them to the stack.
353                         std::vector<Node *> deps = node->incoming_links;
354                         assert(node->effect->num_inputs() == deps.size());
355                         for (unsigned i = 0; i < deps.size(); ++i) {
356                                 bool start_new_phase = false;
357
358                                 // FIXME: If we sample directly from a texture, we won't need this.
359                                 if (node->effect->needs_texture_bounce()) {
360                                         start_new_phase = true;
361                                 }
362
363                                 if (deps[i]->outgoing_links.size() > 1 && deps[i]->effect->num_inputs() > 0) {
364                                         // More than one effect uses this as the input,
365                                         // and it is not a texture itself.
366                                         // The easiest thing to do (and probably also the safest
367                                         // performance-wise in most cases) is to bounce it to a texture
368                                         // and then let the next passes read from that.
369                                         start_new_phase = true;
370                                 }
371
372                                 if (deps[i]->effect->changes_output_size()) {
373                                         start_new_phase = true;
374                                 }
375
376                                 if (start_new_phase) {
377                                         effects_todo_other_phases.push(deps[i]);
378                                         this_phase_inputs.push_back(deps[i]);
379                                 } else {
380                                         effects_todo_this_phase.push(deps[i]);
381                                 }
382                         }
383                         continue;
384                 }
385
386                 // No more effects to do this phase. Take all the ones we have,
387                 // and create a GLSL program for it.
388                 if (!this_phase_effects.empty()) {
389                         reverse(this_phase_effects.begin(), this_phase_effects.end());
390                         phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
391                         this_phase_effects.back()->phase = phases.back();
392                         this_phase_inputs.clear();
393                         this_phase_effects.clear();
394                 }
395                 assert(this_phase_inputs.empty());
396                 assert(this_phase_effects.empty());
397
398                 // If we have no effects left, exit.
399                 if (effects_todo_other_phases.empty()) {
400                         break;
401                 }
402
403                 Node *node = effects_todo_other_phases.top();
404                 effects_todo_other_phases.pop();
405
406                 if (completed_effects.count(node) == 0) {
407                         // Start a new phase, calculating from this effect.
408                         effects_todo_this_phase.push(node);
409                 }
410         }
411
412         // Finally, since the phases are found from the output but must be executed
413         // from the input(s), reverse them, too.
414         std::reverse(phases.begin(), phases.end());
415 }
416
417 void EffectChain::output_dot(const char *filename)
418 {
419         FILE *fp = fopen(filename, "w");
420         if (fp == NULL) {
421                 perror(filename);
422                 exit(1);
423         }
424
425         fprintf(fp, "digraph G {\n");
426         for (unsigned i = 0; i < nodes.size(); ++i) {
427                 fprintf(fp, "  n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
428                 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
429                         std::vector<std::string> labels;
430
431                         if (nodes[i]->outgoing_links[j]->effect->needs_texture_bounce()) {
432                                 labels.push_back("needs_bounce");
433                         }
434                         if (nodes[i]->effect->changes_output_size()) {
435                                 labels.push_back("resize");
436                         }
437
438                         switch (nodes[i]->output_color_space) {
439                         case COLORSPACE_REC_601_525:
440                                 labels.push_back("spc[rec601-525]");
441                                 break;
442                         case COLORSPACE_REC_601_625:
443                                 labels.push_back("spc[rec601-625]");
444                                 break;
445                         default:
446                                 break;
447                         }
448
449                         switch (nodes[i]->output_gamma_curve) {
450                         case GAMMA_sRGB:
451                                 labels.push_back("gamma[sRGB]");
452                                 break;
453                         case GAMMA_REC_601:  // and GAMMA_REC_709
454                                 labels.push_back("gamma[rec601/709]");
455                                 break;
456                         default:
457                                 break;
458                         }
459
460                         if (labels.empty()) {
461                                 fprintf(fp, "  n%ld -> n%ld;\n", (long)nodes[i], (long)nodes[i]->outgoing_links[j]);
462                         } else {
463                                 std::string label = labels[0];
464                                 for (unsigned k = 1; k < labels.size(); ++k) {
465                                         label += ", " + labels[k];
466                                 }
467                                 fprintf(fp, "  n%ld -> n%ld [label=\"%s\"];\n", (long)nodes[i], (long)nodes[i]->outgoing_links[j], label.c_str());
468                         }
469                 }
470         }
471         fprintf(fp, "}\n");
472
473         fclose(fp);
474 }
475
476 void EffectChain::find_output_size(Phase *phase)
477 {
478         Node *output_node = phase->effects.back();
479
480         // If the last effect explicitly sets an output size,
481         // use that.
482         if (output_node->effect->changes_output_size()) {
483                 output_node->effect->get_output_size(&phase->output_width, &phase->output_height);
484                 return;
485         }
486
487         // If not, look at the input phases, if any. We select the largest one
488         // (really assuming they all have the same aspect currently), by pixel count.
489         if (!phase->inputs.empty()) {
490                 unsigned best_width = 0, best_height = 0;
491                 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
492                         Node *input = phase->inputs[i];
493                         assert(input->phase->output_width != 0);
494                         assert(input->phase->output_height != 0);
495                         if (input->phase->output_width * input->phase->output_height > best_width * best_height) {
496                                 best_width = input->phase->output_width;
497                                 best_height = input->phase->output_height;
498                         }
499                 }
500                 assert(best_width != 0);
501                 assert(best_height != 0);
502                 phase->output_width = best_width;
503                 phase->output_height = best_height;
504                 return;
505         }
506
507         // OK, no inputs. Just use the global width/height.
508         // TODO: We probably want to use the texture's size eventually.
509         phase->output_width = width;
510         phase->output_height = height;
511 }
512
513 void EffectChain::finalize()
514 {
515         output_dot("final.dot");
516
517         // Find the output effect. This is, simply, one that has no outgoing links.
518         // If there are multiple ones, the graph is malformed (we do not support
519         // multiple outputs right now).
520         std::vector<Node *> output_nodes;
521         for (unsigned i = 0; i < nodes.size(); ++i) {
522                 Node *node = nodes[i];
523                 if (node->outgoing_links.empty()) {
524                         output_nodes.push_back(node);
525                 }
526         }
527         assert(output_nodes.size() == 1);
528         Node *output_node = output_nodes[0];
529
530         // Add normalizers to get the output format right.
531         if (output_node->output_color_space != output_format.color_space) {
532                 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
533                 colorspace_conversion->set_int("source_space", output_node->output_color_space);
534                 colorspace_conversion->set_int("destination_space", output_format.color_space);
535                 std::vector<Effect *> inputs;
536                 inputs.push_back(output_node->effect);
537                 colorspace_conversion->add_self_to_effect_chain(this, inputs);
538
539                 assert(node_map.count(colorspace_conversion) != 0);
540                 output_node = node_map[colorspace_conversion];
541                 output_node->output_color_space = output_format.color_space;
542         }
543         if (output_node->output_gamma_curve != output_format.gamma_curve) {
544                 if (output_node->output_gamma_curve != GAMMA_LINEAR) {
545                         output_node = normalize_to_linear_gamma(output_node);
546                 }
547                 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
548                 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
549                 std::vector<Effect *> inputs;
550                 inputs.push_back(output_node->effect);
551                 gamma_conversion->add_self_to_effect_chain(this, inputs);
552
553                 assert(node_map.count(gamma_conversion) != 0);
554                 output_node = node_map[gamma_conversion];
555                 output_node->output_gamma_curve = output_format.gamma_curve;
556         }
557
558         // Construct all needed GLSL programs, starting at the output.
559         construct_glsl_programs(output_node);
560
561         // If we have more than one phase, we need intermediate render-to-texture.
562         // Construct an FBO, and then as many textures as we need.
563         // We choose the simplest option of having one texture per output,
564         // since otherwise this turns into an (albeit simple)
565         // register allocation problem.
566         if (phases.size() > 1) {
567                 glGenFramebuffers(1, &fbo);
568
569                 for (unsigned i = 0; i < phases.size() - 1; ++i) {
570                         find_output_size(phases[i]);
571
572                         Node *output_node = phases[i]->effects.back();
573                         glGenTextures(1, &output_node->output_texture);
574                         check_error();
575                         glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
576                         check_error();
577                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
578                         check_error();
579                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
580                         check_error();
581                         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[i]->output_width, phases[i]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
582                         check_error();
583
584                         output_node->output_texture_width = phases[i]->output_width;
585                         output_node->output_texture_height = phases[i]->output_height;
586                 }
587         }
588                 
589         for (unsigned i = 0; i < inputs.size(); ++i) {
590                 inputs[i]->finalize();
591         }
592
593         assert(phases[0]->inputs.empty());
594         
595         finalized = true;
596 }
597
598 void EffectChain::render_to_screen()
599 {
600         assert(finalized);
601
602         // Basic state.
603         glDisable(GL_BLEND);
604         check_error();
605         glDisable(GL_DEPTH_TEST);
606         check_error();
607         glDepthMask(GL_FALSE);
608         check_error();
609
610         glMatrixMode(GL_PROJECTION);
611         glLoadIdentity();
612         glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
613
614         glMatrixMode(GL_MODELVIEW);
615         glLoadIdentity();
616
617         if (phases.size() > 1) {
618                 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
619                 check_error();
620         }
621
622         std::set<Node *> generated_mipmaps;
623
624         for (unsigned phase = 0; phase < phases.size(); ++phase) {
625                 // See if the requested output size has changed. If so, we need to recreate
626                 // the texture (and before we start setting up inputs).
627                 if (phase != phases.size() - 1) {
628                         find_output_size(phases[phase]);
629
630                         Node *output_node = phases[phase]->effects.back();
631
632                         if (output_node->output_texture_width != phases[phase]->output_width ||
633                             output_node->output_texture_height != phases[phase]->output_height) {
634                                 glActiveTexture(GL_TEXTURE0);
635                                 check_error();
636                                 glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
637                                 check_error();
638                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[phase]->output_width, phases[phase]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
639                                 check_error();
640                                 glBindTexture(GL_TEXTURE_2D, 0);
641                                 check_error();
642
643                                 output_node->output_texture_width = phases[phase]->output_width;
644                                 output_node->output_texture_height = phases[phase]->output_height;
645                         }
646                 }
647
648                 glUseProgram(phases[phase]->glsl_program_num);
649                 check_error();
650
651                 // Set up RTT inputs for this phase.
652                 for (unsigned sampler = 0; sampler < phases[phase]->inputs.size(); ++sampler) {
653                         glActiveTexture(GL_TEXTURE0 + sampler);
654                         Node *input = phases[phase]->inputs[sampler];
655                         glBindTexture(GL_TEXTURE_2D, input->output_texture);
656                         check_error();
657                         if (phases[phase]->input_needs_mipmaps) {
658                                 if (generated_mipmaps.count(input) == 0) {
659                                         glGenerateMipmap(GL_TEXTURE_2D);
660                                         check_error();
661                                         generated_mipmaps.insert(input);
662                                 }
663                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
664                                 check_error();
665                         } else {
666                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
667                                 check_error();
668                         }
669
670                         std::string texture_name = std::string("tex_") + input->effect_id;
671                         glUniform1i(glGetUniformLocation(phases[phase]->glsl_program_num, texture_name.c_str()), sampler);
672                         check_error();
673                 }
674
675                 // And now the output.
676                 if (phase == phases.size() - 1) {
677                         // Last phase goes directly to the screen.
678                         glBindFramebuffer(GL_FRAMEBUFFER, 0);
679                         check_error();
680                         glViewport(0, 0, width, height);
681                 } else {
682                         Node *output_node = phases[phase]->effects.back();
683                         glFramebufferTexture2D(
684                                 GL_FRAMEBUFFER,
685                                 GL_COLOR_ATTACHMENT0,
686                                 GL_TEXTURE_2D,
687                                 output_node->output_texture,
688                                 0);
689                         check_error();
690                         glViewport(0, 0, phases[phase]->output_width, phases[phase]->output_height);
691                 }
692
693                 // Give the required parameters to all the effects.
694                 unsigned sampler_num = phases[phase]->inputs.size();
695                 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
696                         Node *node = phases[phase]->effects[i];
697                         node->effect->set_gl_state(phases[phase]->glsl_program_num, node->effect_id, &sampler_num);
698                         check_error();
699                 }
700
701                 // Now draw!
702                 glBegin(GL_QUADS);
703
704                 glTexCoord2f(0.0f, 0.0f);
705                 glVertex2f(0.0f, 0.0f);
706
707                 glTexCoord2f(1.0f, 0.0f);
708                 glVertex2f(1.0f, 0.0f);
709
710                 glTexCoord2f(1.0f, 1.0f);
711                 glVertex2f(1.0f, 1.0f);
712
713                 glTexCoord2f(0.0f, 1.0f);
714                 glVertex2f(0.0f, 1.0f);
715
716                 glEnd();
717                 check_error();
718
719                 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
720                         Node *node = phases[phase]->effects[i];
721                         node->effect->clear_gl_state();
722                 }
723         }
724 }