]> git.sesse.net Git - movit/blob - effect_chain.cpp
Add edge information about odd things, such as bounces, resizes and non-standard...
[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_709:
440                                 labels.push_back("spc[rec709]");
441                                 break;
442                         case COLORSPACE_REC_601_525:
443                                 labels.push_back("spc[rec601-525]");
444                                 break;
445                         case COLORSPACE_REC_601_625:
446                                 labels.push_back("spc[rec601-625]");
447                                 break;
448                         default:
449                                 break;
450                         }
451
452                         switch (nodes[i]->output_gamma_curve) {
453                         case GAMMA_sRGB:
454                                 labels.push_back("gamma[sRGB]");
455                                 break;
456                         case GAMMA_REC_601:  // and GAMMA_REC_709
457                                 labels.push_back("gamma[rec601/709]");
458                                 break;
459                         default:
460                                 break;
461                         }
462
463                         if (labels.empty()) {
464                                 fprintf(fp, "  n%ld -> n%ld;\n", (long)nodes[i], (long)nodes[i]->outgoing_links[j]);
465                         } else {
466                                 std::string label = labels[0];
467                                 for (unsigned k = 1; k < labels.size(); ++k) {
468                                         label += ", " + labels[k];
469                                 }
470                                 fprintf(fp, "  n%ld -> n%ld [label=\"%s\"];\n", (long)nodes[i], (long)nodes[i]->outgoing_links[j], label.c_str());
471                         }
472                 }
473         }
474         fprintf(fp, "}\n");
475
476         fclose(fp);
477 }
478
479 void EffectChain::find_output_size(Phase *phase)
480 {
481         Node *output_node = phase->effects.back();
482
483         // If the last effect explicitly sets an output size,
484         // use that.
485         if (output_node->effect->changes_output_size()) {
486                 output_node->effect->get_output_size(&phase->output_width, &phase->output_height);
487                 return;
488         }
489
490         // If not, look at the input phases, if any. We select the largest one
491         // (really assuming they all have the same aspect currently), by pixel count.
492         if (!phase->inputs.empty()) {
493                 unsigned best_width = 0, best_height = 0;
494                 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
495                         Node *input = phase->inputs[i];
496                         assert(input->phase->output_width != 0);
497                         assert(input->phase->output_height != 0);
498                         if (input->phase->output_width * input->phase->output_height > best_width * best_height) {
499                                 best_width = input->phase->output_width;
500                                 best_height = input->phase->output_height;
501                         }
502                 }
503                 assert(best_width != 0);
504                 assert(best_height != 0);
505                 phase->output_width = best_width;
506                 phase->output_height = best_height;
507                 return;
508         }
509
510         // OK, no inputs. Just use the global width/height.
511         // TODO: We probably want to use the texture's size eventually.
512         phase->output_width = width;
513         phase->output_height = height;
514 }
515
516 void EffectChain::finalize()
517 {
518         output_dot("final.dot");
519
520         // Find the output effect. This is, simply, one that has no outgoing links.
521         // If there are multiple ones, the graph is malformed (we do not support
522         // multiple outputs right now).
523         std::vector<Node *> output_nodes;
524         for (unsigned i = 0; i < nodes.size(); ++i) {
525                 Node *node = nodes[i];
526                 if (node->outgoing_links.empty()) {
527                         output_nodes.push_back(node);
528                 }
529         }
530         assert(output_nodes.size() == 1);
531         Node *output_node = output_nodes[0];
532
533         // Add normalizers to get the output format right.
534         if (output_node->output_color_space != output_format.color_space) {
535                 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
536                 colorspace_conversion->set_int("source_space", output_node->output_color_space);
537                 colorspace_conversion->set_int("destination_space", output_format.color_space);
538                 std::vector<Effect *> inputs;
539                 inputs.push_back(output_node->effect);
540                 colorspace_conversion->add_self_to_effect_chain(this, inputs);
541
542                 assert(node_map.count(colorspace_conversion) != 0);
543                 output_node = node_map[colorspace_conversion];
544                 output_node->output_color_space = output_format.color_space;
545         }
546         if (output_node->output_gamma_curve != output_format.gamma_curve) {
547                 if (output_node->output_gamma_curve != GAMMA_LINEAR) {
548                         output_node = normalize_to_linear_gamma(output_node);
549                 }
550                 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
551                 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
552                 std::vector<Effect *> inputs;
553                 inputs.push_back(output_node->effect);
554                 gamma_conversion->add_self_to_effect_chain(this, inputs);
555
556                 assert(node_map.count(gamma_conversion) != 0);
557                 output_node = node_map[gamma_conversion];
558                 output_node->output_gamma_curve = output_format.gamma_curve;
559         }
560
561         // Construct all needed GLSL programs, starting at the output.
562         construct_glsl_programs(output_node);
563
564         // If we have more than one phase, we need intermediate render-to-texture.
565         // Construct an FBO, and then as many textures as we need.
566         // We choose the simplest option of having one texture per output,
567         // since otherwise this turns into an (albeit simple)
568         // register allocation problem.
569         if (phases.size() > 1) {
570                 glGenFramebuffers(1, &fbo);
571
572                 for (unsigned i = 0; i < phases.size() - 1; ++i) {
573                         find_output_size(phases[i]);
574
575                         Node *output_node = phases[i]->effects.back();
576                         glGenTextures(1, &output_node->output_texture);
577                         check_error();
578                         glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
579                         check_error();
580                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
581                         check_error();
582                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
583                         check_error();
584                         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[i]->output_width, phases[i]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
585                         check_error();
586
587                         output_node->output_texture_width = phases[i]->output_width;
588                         output_node->output_texture_height = phases[i]->output_height;
589                 }
590         }
591                 
592         for (unsigned i = 0; i < inputs.size(); ++i) {
593                 inputs[i]->finalize();
594         }
595
596         assert(phases[0]->inputs.empty());
597         
598         finalized = true;
599 }
600
601 void EffectChain::render_to_screen()
602 {
603         assert(finalized);
604
605         // Basic state.
606         glDisable(GL_BLEND);
607         check_error();
608         glDisable(GL_DEPTH_TEST);
609         check_error();
610         glDepthMask(GL_FALSE);
611         check_error();
612
613         glMatrixMode(GL_PROJECTION);
614         glLoadIdentity();
615         glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
616
617         glMatrixMode(GL_MODELVIEW);
618         glLoadIdentity();
619
620         if (phases.size() > 1) {
621                 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
622                 check_error();
623         }
624
625         std::set<Node *> generated_mipmaps;
626
627         for (unsigned phase = 0; phase < phases.size(); ++phase) {
628                 // See if the requested output size has changed. If so, we need to recreate
629                 // the texture (and before we start setting up inputs).
630                 if (phase != phases.size() - 1) {
631                         find_output_size(phases[phase]);
632
633                         Node *output_node = phases[phase]->effects.back();
634
635                         if (output_node->output_texture_width != phases[phase]->output_width ||
636                             output_node->output_texture_height != phases[phase]->output_height) {
637                                 glActiveTexture(GL_TEXTURE0);
638                                 check_error();
639                                 glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
640                                 check_error();
641                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[phase]->output_width, phases[phase]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
642                                 check_error();
643                                 glBindTexture(GL_TEXTURE_2D, 0);
644                                 check_error();
645
646                                 output_node->output_texture_width = phases[phase]->output_width;
647                                 output_node->output_texture_height = phases[phase]->output_height;
648                         }
649                 }
650
651                 glUseProgram(phases[phase]->glsl_program_num);
652                 check_error();
653
654                 // Set up RTT inputs for this phase.
655                 for (unsigned sampler = 0; sampler < phases[phase]->inputs.size(); ++sampler) {
656                         glActiveTexture(GL_TEXTURE0 + sampler);
657                         Node *input = phases[phase]->inputs[sampler];
658                         glBindTexture(GL_TEXTURE_2D, input->output_texture);
659                         check_error();
660                         if (phases[phase]->input_needs_mipmaps) {
661                                 if (generated_mipmaps.count(input) == 0) {
662                                         glGenerateMipmap(GL_TEXTURE_2D);
663                                         check_error();
664                                         generated_mipmaps.insert(input);
665                                 }
666                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
667                                 check_error();
668                         } else {
669                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
670                                 check_error();
671                         }
672
673                         std::string texture_name = std::string("tex_") + input->effect_id;
674                         glUniform1i(glGetUniformLocation(phases[phase]->glsl_program_num, texture_name.c_str()), sampler);
675                         check_error();
676                 }
677
678                 // And now the output.
679                 if (phase == phases.size() - 1) {
680                         // Last phase goes directly to the screen.
681                         glBindFramebuffer(GL_FRAMEBUFFER, 0);
682                         check_error();
683                         glViewport(0, 0, width, height);
684                 } else {
685                         Node *output_node = phases[phase]->effects.back();
686                         glFramebufferTexture2D(
687                                 GL_FRAMEBUFFER,
688                                 GL_COLOR_ATTACHMENT0,
689                                 GL_TEXTURE_2D,
690                                 output_node->output_texture,
691                                 0);
692                         check_error();
693                         glViewport(0, 0, phases[phase]->output_width, phases[phase]->output_height);
694                 }
695
696                 // Give the required parameters to all the effects.
697                 unsigned sampler_num = phases[phase]->inputs.size();
698                 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
699                         Node *node = phases[phase]->effects[i];
700                         node->effect->set_gl_state(phases[phase]->glsl_program_num, node->effect_id, &sampler_num);
701                         check_error();
702                 }
703
704                 // Now draw!
705                 glBegin(GL_QUADS);
706
707                 glTexCoord2f(0.0f, 0.0f);
708                 glVertex2f(0.0f, 0.0f);
709
710                 glTexCoord2f(1.0f, 0.0f);
711                 glVertex2f(1.0f, 0.0f);
712
713                 glTexCoord2f(1.0f, 1.0f);
714                 glVertex2f(1.0f, 1.0f);
715
716                 glTexCoord2f(0.0f, 1.0f);
717                 glVertex2f(0.0f, 1.0f);
718
719                 glEnd();
720                 check_error();
721
722                 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
723                         Node *node = phases[phase]->effects[i];
724                         node->effect->clear_gl_state();
725                 }
726         }
727 }