1 #define GL_GLEXT_PROTOTYPES 1
16 #include "alpha_division_effect.h"
17 #include "alpha_multiplication_effect.h"
18 #include "colorspace_conversion_effect.h"
19 #include "dither_effect.h"
21 #include "effect_chain.h"
22 #include "gamma_compression_effect.h"
23 #include "gamma_expansion_effect.h"
28 EffectChain::EffectChain(float aspect_nom, float aspect_denom)
29 : aspect_nom(aspect_nom),
30 aspect_denom(aspect_denom),
35 EffectChain::~EffectChain()
37 for (unsigned i = 0; i < nodes.size(); ++i) {
38 if (nodes[i]->output_texture != 0) {
39 glDeleteTextures(1, &nodes[i]->output_texture);
41 delete nodes[i]->effect;
44 for (unsigned i = 0; i < phases.size(); ++i) {
45 glDeleteProgram(phases[i]->glsl_program_num);
46 glDeleteShader(phases[i]->vertex_shader);
47 glDeleteShader(phases[i]->fragment_shader);
52 Input *EffectChain::add_input(Input *input)
55 inputs.push_back(input);
60 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
63 output_format = format;
64 output_alpha_format = alpha_format;
67 Node *EffectChain::add_node(Effect *effect)
70 sprintf(effect_id, "eff%u", (unsigned)nodes.size());
72 Node *node = new Node;
73 node->effect = effect;
74 node->disabled = false;
75 node->effect_id = effect_id;
76 node->output_color_space = COLORSPACE_INVALID;
77 node->output_gamma_curve = GAMMA_INVALID;
78 node->output_alpha_type = ALPHA_INVALID;
79 node->output_texture = 0;
81 nodes.push_back(node);
82 node_map[effect] = node;
86 void EffectChain::connect_nodes(Node *sender, Node *receiver)
88 sender->outgoing_links.push_back(receiver);
89 receiver->incoming_links.push_back(sender);
92 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
94 new_receiver->incoming_links = old_receiver->incoming_links;
95 old_receiver->incoming_links.clear();
97 for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
98 Node *sender = new_receiver->incoming_links[i];
99 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
100 if (sender->outgoing_links[j] == old_receiver) {
101 sender->outgoing_links[j] = new_receiver;
107 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
109 new_sender->outgoing_links = old_sender->outgoing_links;
110 old_sender->outgoing_links.clear();
112 for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
113 Node *receiver = new_sender->outgoing_links[i];
114 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
115 if (receiver->incoming_links[j] == old_sender) {
116 receiver->incoming_links[j] = new_sender;
122 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
124 for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
125 if (sender->outgoing_links[i] == receiver) {
126 sender->outgoing_links[i] = middle;
127 middle->incoming_links.push_back(sender);
130 for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
131 if (receiver->incoming_links[i] == sender) {
132 receiver->incoming_links[i] = middle;
133 middle->outgoing_links.push_back(receiver);
137 assert(middle->incoming_links.size() == middle->effect->num_inputs());
140 void EffectChain::find_all_nonlinear_inputs(Node *node, std::vector<Node *> *nonlinear_inputs)
142 if (node->output_gamma_curve == GAMMA_LINEAR &&
143 node->effect->effect_type_id() != "GammaCompressionEffect") {
146 if (node->effect->num_inputs() == 0) {
147 nonlinear_inputs->push_back(node);
149 assert(node->effect->num_inputs() == node->incoming_links.size());
150 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
151 find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
156 Effect *EffectChain::add_effect(Effect *effect, const std::vector<Effect *> &inputs)
159 assert(inputs.size() == effect->num_inputs());
160 Node *node = add_node(effect);
161 for (unsigned i = 0; i < inputs.size(); ++i) {
162 assert(node_map.count(inputs[i]) != 0);
163 connect_nodes(node_map[inputs[i]], node);
168 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
169 std::string replace_prefix(const std::string &text, const std::string &prefix)
174 while (start < text.size()) {
175 size_t pos = text.find("PREFIX(", start);
176 if (pos == std::string::npos) {
177 output.append(text.substr(start, std::string::npos));
181 output.append(text.substr(start, pos - start));
182 output.append(prefix);
185 pos += strlen("PREFIX(");
187 // Output stuff until we find the matching ), which we then eat.
189 size_t end_arg_pos = pos;
190 while (end_arg_pos < text.size()) {
191 if (text[end_arg_pos] == '(') {
193 } else if (text[end_arg_pos] == ')') {
201 output.append(text.substr(pos, end_arg_pos - pos));
209 Phase *EffectChain::compile_glsl_program(
210 const std::vector<Node *> &inputs,
211 const std::vector<Node *> &effects)
213 assert(!effects.empty());
215 // Deduplicate the inputs.
216 std::vector<Node *> true_inputs = inputs;
217 std::sort(true_inputs.begin(), true_inputs.end());
218 true_inputs.erase(std::unique(true_inputs.begin(), true_inputs.end()), true_inputs.end());
220 bool input_needs_mipmaps = false;
221 std::string frag_shader = read_file("header.frag");
223 // Create functions for all the texture inputs that we need.
224 for (unsigned i = 0; i < true_inputs.size(); ++i) {
225 Node *input = true_inputs[i];
227 frag_shader += std::string("uniform sampler2D tex_") + input->effect_id + ";\n";
228 frag_shader += std::string("vec4 ") + input->effect_id + "(vec2 tc) {\n";
229 frag_shader += "\treturn texture2D(tex_" + input->effect_id + ", tc);\n";
230 frag_shader += "}\n";
234 std::vector<Node *> sorted_effects = topological_sort(effects);
236 for (unsigned i = 0; i < sorted_effects.size(); ++i) {
237 Node *node = sorted_effects[i];
239 if (node->incoming_links.size() == 1) {
240 frag_shader += std::string("#define INPUT ") + node->incoming_links[0]->effect_id + "\n";
242 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
244 sprintf(buf, "#define INPUT%d %s\n", j + 1, node->incoming_links[j]->effect_id.c_str());
250 frag_shader += std::string("#define FUNCNAME ") + node->effect_id + "\n";
251 frag_shader += replace_prefix(node->effect->output_convenience_uniforms(), node->effect_id);
252 frag_shader += replace_prefix(node->effect->output_fragment_shader(), node->effect_id);
253 frag_shader += "#undef PREFIX\n";
254 frag_shader += "#undef FUNCNAME\n";
255 if (node->incoming_links.size() == 1) {
256 frag_shader += "#undef INPUT\n";
258 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
260 sprintf(buf, "#undef INPUT%d\n", j + 1);
266 input_needs_mipmaps |= node->effect->needs_mipmaps();
268 for (unsigned i = 0; i < sorted_effects.size(); ++i) {
269 Node *node = sorted_effects[i];
270 if (node->effect->num_inputs() == 0) {
271 CHECK(node->effect->set_int("needs_mipmaps", input_needs_mipmaps));
274 frag_shader += std::string("#define INPUT ") + sorted_effects.back()->effect_id + "\n";
275 frag_shader.append(read_file("footer.frag"));
277 if (movit_debug_level == MOVIT_DEBUG_ON) {
278 // Output shader to a temporary file, for easier debugging.
279 static int compiled_shader_num = 0;
281 sprintf(filename, "chain-%03d.frag", compiled_shader_num++);
282 FILE *fp = fopen(filename, "w");
287 fprintf(fp, "%s\n", frag_shader.c_str());
291 GLuint glsl_program_num = glCreateProgram();
292 GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
293 GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
294 glAttachShader(glsl_program_num, vs_obj);
296 glAttachShader(glsl_program_num, fs_obj);
298 glLinkProgram(glsl_program_num);
301 Phase *phase = new Phase;
302 phase->glsl_program_num = glsl_program_num;
303 phase->vertex_shader = vs_obj;
304 phase->fragment_shader = fs_obj;
305 phase->input_needs_mipmaps = input_needs_mipmaps;
306 phase->inputs = true_inputs;
307 phase->effects = sorted_effects;
312 // Construct GLSL programs, starting at the given effect and following
313 // the chain from there. We end a program every time we come to an effect
314 // marked as "needs texture bounce", one that is used by multiple other
315 // effects, every time an effect wants to change the output size,
316 // and of course at the end.
318 // We follow a quite simple depth-first search from the output, although
319 // without any explicit recursion.
320 void EffectChain::construct_glsl_programs(Node *output)
322 // Which effects have already been completed?
323 // We need to keep track of it, as an effect with multiple outputs
324 // could otherwise be calculated multiple times.
325 std::set<Node *> completed_effects;
327 // Effects in the current phase, as well as inputs (outputs from other phases
328 // that we depend on). Note that since we start iterating from the end,
329 // the effect list will be in the reverse order.
330 std::vector<Node *> this_phase_inputs;
331 std::vector<Node *> this_phase_effects;
333 // Effects that we have yet to calculate, but that we know should
334 // be in the current phase.
335 std::stack<Node *> effects_todo_this_phase;
337 // Effects that we have yet to calculate, but that come from other phases.
338 // We delay these until we have this phase done in its entirety,
339 // at which point we pick any of them and start a new phase from that.
340 std::stack<Node *> effects_todo_other_phases;
342 effects_todo_this_phase.push(output);
344 for ( ;; ) { // Termination condition within loop.
345 if (!effects_todo_this_phase.empty()) {
346 // OK, we have more to do this phase.
347 Node *node = effects_todo_this_phase.top();
348 effects_todo_this_phase.pop();
350 // This should currently only happen for effects that are inputs
351 // (either true inputs or phase outputs). We special-case inputs,
352 // and then deduplicate phase outputs in compile_glsl_program().
353 if (node->effect->num_inputs() == 0) {
354 if (find(this_phase_effects.begin(), this_phase_effects.end(), node) != this_phase_effects.end()) {
358 assert(completed_effects.count(node) == 0);
361 this_phase_effects.push_back(node);
362 completed_effects.insert(node);
364 // Find all the dependencies of this effect, and add them to the stack.
365 std::vector<Node *> deps = node->incoming_links;
366 assert(node->effect->num_inputs() == deps.size());
367 for (unsigned i = 0; i < deps.size(); ++i) {
368 bool start_new_phase = false;
370 // FIXME: If we sample directly from a texture, we won't need this.
371 if (node->effect->needs_texture_bounce()) {
372 start_new_phase = true;
375 if (deps[i]->outgoing_links.size() > 1) {
376 if (deps[i]->effect->num_inputs() > 0) {
377 // More than one effect uses this as the input,
378 // and it is not a texture itself.
379 // The easiest thing to do (and probably also the safest
380 // performance-wise in most cases) is to bounce it to a texture
381 // and then let the next passes read from that.
382 start_new_phase = true;
384 // For textures, we try to be slightly more clever;
385 // if none of our outputs need a bounce, we don't bounce
386 // but instead simply use the effect many times.
388 // Strictly speaking, we could bounce it for some outputs
389 // and use it directly for others, but the processing becomes
390 // somewhat simpler if the effect is only used in one such way.
391 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
392 Node *rdep = deps[i]->outgoing_links[j];
393 start_new_phase |= rdep->effect->needs_texture_bounce();
398 if (deps[i]->effect->changes_output_size()) {
399 start_new_phase = true;
402 if (start_new_phase) {
403 effects_todo_other_phases.push(deps[i]);
404 this_phase_inputs.push_back(deps[i]);
406 effects_todo_this_phase.push(deps[i]);
412 // No more effects to do this phase. Take all the ones we have,
413 // and create a GLSL program for it.
414 if (!this_phase_effects.empty()) {
415 reverse(this_phase_effects.begin(), this_phase_effects.end());
416 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
417 this_phase_effects.back()->phase = phases.back();
418 this_phase_inputs.clear();
419 this_phase_effects.clear();
421 assert(this_phase_inputs.empty());
422 assert(this_phase_effects.empty());
424 // If we have no effects left, exit.
425 if (effects_todo_other_phases.empty()) {
429 Node *node = effects_todo_other_phases.top();
430 effects_todo_other_phases.pop();
432 if (completed_effects.count(node) == 0) {
433 // Start a new phase, calculating from this effect.
434 effects_todo_this_phase.push(node);
438 // Finally, since the phases are found from the output but must be executed
439 // from the input(s), reverse them, too.
440 std::reverse(phases.begin(), phases.end());
443 void EffectChain::output_dot(const char *filename)
445 if (movit_debug_level != MOVIT_DEBUG_ON) {
449 FILE *fp = fopen(filename, "w");
455 fprintf(fp, "digraph G {\n");
456 fprintf(fp, " output [shape=box label=\"(output)\"];\n");
457 for (unsigned i = 0; i < nodes.size(); ++i) {
458 // Find out which phase this event belongs to.
459 std::vector<int> in_phases;
460 for (unsigned j = 0; j < phases.size(); ++j) {
461 const Phase* p = phases[j];
462 if (std::find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
463 in_phases.push_back(j);
467 if (in_phases.empty()) {
468 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
469 } else if (in_phases.size() == 1) {
470 fprintf(fp, " n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
471 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
472 (in_phases[0] % 8) + 1);
474 // If we had new enough Graphviz, style="wedged" would probably be ideal here.
476 fprintf(fp, " n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
477 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
478 (in_phases[0] % 8) + 1);
481 char from_node_id[256];
482 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
484 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
485 char to_node_id[256];
486 snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
488 std::vector<std::string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
489 output_dot_edge(fp, from_node_id, to_node_id, labels);
492 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
494 std::vector<std::string> labels = get_labels_for_edge(nodes[i], NULL);
495 output_dot_edge(fp, from_node_id, "output", labels);
503 std::vector<std::string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
505 std::vector<std::string> labels;
507 if (to != NULL && to->effect->needs_texture_bounce()) {
508 labels.push_back("needs_bounce");
510 if (from->effect->changes_output_size()) {
511 labels.push_back("resize");
514 switch (from->output_color_space) {
515 case COLORSPACE_INVALID:
516 labels.push_back("spc[invalid]");
518 case COLORSPACE_REC_601_525:
519 labels.push_back("spc[rec601-525]");
521 case COLORSPACE_REC_601_625:
522 labels.push_back("spc[rec601-625]");
528 switch (from->output_gamma_curve) {
530 labels.push_back("gamma[invalid]");
533 labels.push_back("gamma[sRGB]");
535 case GAMMA_REC_601: // and GAMMA_REC_709
536 labels.push_back("gamma[rec601/709]");
542 switch (from->output_alpha_type) {
544 labels.push_back("alpha[invalid]");
547 labels.push_back("alpha[blank]");
549 case ALPHA_POSTMULTIPLIED:
550 labels.push_back("alpha[postmult]");
559 void EffectChain::output_dot_edge(FILE *fp,
560 const std::string &from_node_id,
561 const std::string &to_node_id,
562 const std::vector<std::string> &labels)
564 if (labels.empty()) {
565 fprintf(fp, " %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
567 std::string label = labels[0];
568 for (unsigned k = 1; k < labels.size(); ++k) {
569 label += ", " + labels[k];
571 fprintf(fp, " %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
575 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
577 unsigned scaled_width, scaled_height;
579 if (float(width) * aspect_denom >= float(height) * aspect_nom) {
580 // Same aspect, or W/H > aspect (image is wider than the frame).
581 // In either case, keep width, and adjust height.
582 scaled_width = width;
583 scaled_height = lrintf(width * aspect_denom / aspect_nom);
585 // W/H < aspect (image is taller than the frame), so keep height,
587 scaled_width = lrintf(height * aspect_nom / aspect_denom);
588 scaled_height = height;
591 // We should be consistently larger or smaller then the existing choice,
592 // since we have the same aspect.
593 assert(!(scaled_width < *output_width && scaled_height > *output_height));
594 assert(!(scaled_height < *output_height && scaled_width > *output_width));
596 if (scaled_width >= *output_width && scaled_height >= *output_height) {
597 *output_width = scaled_width;
598 *output_height = scaled_height;
602 // Propagate input texture sizes throughout, and inform effects downstream.
603 // (Like a lot of other code, we depend on effects being in topological order.)
604 void EffectChain::inform_input_sizes(Phase *phase)
606 // All effects that have a defined size (inputs and RTT inputs)
607 // get that. Reset all others.
608 for (unsigned i = 0; i < phase->effects.size(); ++i) {
609 Node *node = phase->effects[i];
610 if (node->effect->num_inputs() == 0) {
611 Input *input = static_cast<Input *>(node->effect);
612 node->output_width = input->get_width();
613 node->output_height = input->get_height();
614 assert(node->output_width != 0);
615 assert(node->output_height != 0);
617 node->output_width = node->output_height = 0;
620 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
621 Node *input = phase->inputs[i];
622 input->output_width = input->phase->virtual_output_width;
623 input->output_height = input->phase->virtual_output_height;
624 assert(input->output_width != 0);
625 assert(input->output_height != 0);
628 // Now propagate from the inputs towards the end, and inform as we go.
629 // The rules are simple:
631 // 1. Don't touch effects that already have given sizes (ie., inputs).
632 // 2. If all of your inputs have the same size, that will be your output size.
633 // 3. Otherwise, your output size is 0x0.
634 for (unsigned i = 0; i < phase->effects.size(); ++i) {
635 Node *node = phase->effects[i];
636 if (node->effect->num_inputs() == 0) {
639 unsigned this_output_width = 0;
640 unsigned this_output_height = 0;
641 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
642 Node *input = node->incoming_links[j];
643 node->effect->inform_input_size(j, input->output_width, input->output_height);
645 this_output_width = input->output_width;
646 this_output_height = input->output_height;
647 } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
649 this_output_width = 0;
650 this_output_height = 0;
653 node->output_width = this_output_width;
654 node->output_height = this_output_height;
658 // Note: You should call inform_input_sizes() before this, as the last effect's
659 // desired output size might change based on the inputs.
660 void EffectChain::find_output_size(Phase *phase)
662 Node *output_node = phase->effects.back();
664 // If the last effect explicitly sets an output size, use that.
665 if (output_node->effect->changes_output_size()) {
666 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
667 &phase->virtual_output_width, &phase->virtual_output_height);
671 // If all effects have the same size, use that.
672 unsigned output_width = 0, output_height = 0;
673 bool all_inputs_same_size = true;
675 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
676 Node *input = phase->inputs[i];
677 assert(input->phase->output_width != 0);
678 assert(input->phase->output_height != 0);
679 if (output_width == 0 && output_height == 0) {
680 output_width = input->phase->virtual_output_width;
681 output_height = input->phase->virtual_output_height;
682 } else if (output_width != input->phase->virtual_output_width ||
683 output_height != input->phase->virtual_output_height) {
684 all_inputs_same_size = false;
687 for (unsigned i = 0; i < phase->effects.size(); ++i) {
688 Effect *effect = phase->effects[i]->effect;
689 if (effect->num_inputs() != 0) {
693 Input *input = static_cast<Input *>(effect);
694 if (output_width == 0 && output_height == 0) {
695 output_width = input->get_width();
696 output_height = input->get_height();
697 } else if (output_width != input->get_width() ||
698 output_height != input->get_height()) {
699 all_inputs_same_size = false;
703 if (all_inputs_same_size) {
704 assert(output_width != 0);
705 assert(output_height != 0);
706 phase->virtual_output_width = phase->output_width = output_width;
707 phase->virtual_output_height = phase->output_height = output_height;
711 // If not, fit all the inputs into the current aspect, and select the largest one.
714 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
715 Node *input = phase->inputs[i];
716 assert(input->phase->output_width != 0);
717 assert(input->phase->output_height != 0);
718 size_rectangle_to_fit(input->phase->output_width, input->phase->output_height, &output_width, &output_height);
720 for (unsigned i = 0; i < phase->effects.size(); ++i) {
721 Effect *effect = phase->effects[i]->effect;
722 if (effect->num_inputs() != 0) {
726 Input *input = static_cast<Input *>(effect);
727 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
729 assert(output_width != 0);
730 assert(output_height != 0);
731 phase->virtual_output_width = phase->output_width = output_width;
732 phase->virtual_output_height = phase->output_height = output_height;
735 void EffectChain::sort_all_nodes_topologically()
737 nodes = topological_sort(nodes);
740 std::vector<Node *> EffectChain::topological_sort(const std::vector<Node *> &nodes)
742 std::set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
743 std::vector<Node *> sorted_list;
744 for (unsigned i = 0; i < nodes.size(); ++i) {
745 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
747 reverse(sorted_list.begin(), sorted_list.end());
751 void EffectChain::topological_sort_visit_node(Node *node, std::set<Node *> *nodes_left_to_visit, std::vector<Node *> *sorted_list)
753 if (nodes_left_to_visit->count(node) == 0) {
756 nodes_left_to_visit->erase(node);
757 for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
758 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
760 sorted_list->push_back(node);
763 void EffectChain::find_color_spaces_for_inputs()
765 for (unsigned i = 0; i < nodes.size(); ++i) {
766 Node *node = nodes[i];
767 if (node->disabled) {
770 if (node->incoming_links.size() == 0) {
771 Input *input = static_cast<Input *>(node->effect);
772 node->output_color_space = input->get_color_space();
773 node->output_gamma_curve = input->get_gamma_curve();
775 Effect::AlphaHandling alpha_handling = input->alpha_handling();
776 switch (alpha_handling) {
777 case Effect::OUTPUT_BLANK_ALPHA:
778 node->output_alpha_type = ALPHA_BLANK;
780 case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
781 node->output_alpha_type = ALPHA_PREMULTIPLIED;
783 case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
784 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
786 case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
787 case Effect::DONT_CARE_ALPHA_TYPE:
792 if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
793 assert(node->output_gamma_curve == GAMMA_LINEAR);
799 // Propagate gamma and color space information as far as we can in the graph.
800 // The rules are simple: Anything where all the inputs agree, get that as
801 // output as well. Anything else keeps having *_INVALID.
802 void EffectChain::propagate_gamma_and_color_space()
804 // We depend on going through the nodes in order.
805 sort_all_nodes_topologically();
807 for (unsigned i = 0; i < nodes.size(); ++i) {
808 Node *node = nodes[i];
809 if (node->disabled) {
812 assert(node->incoming_links.size() == node->effect->num_inputs());
813 if (node->incoming_links.size() == 0) {
814 assert(node->output_color_space != COLORSPACE_INVALID);
815 assert(node->output_gamma_curve != GAMMA_INVALID);
819 Colorspace color_space = node->incoming_links[0]->output_color_space;
820 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
821 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
822 if (node->incoming_links[j]->output_color_space != color_space) {
823 color_space = COLORSPACE_INVALID;
825 if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
826 gamma_curve = GAMMA_INVALID;
830 // The conversion effects already have their outputs set correctly,
831 // so leave them alone.
832 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
833 node->output_color_space = color_space;
835 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
836 node->effect->effect_type_id() != "GammaExpansionEffect") {
837 node->output_gamma_curve = gamma_curve;
842 // Propagate alpha information as far as we can in the graph.
843 // Similar to propagate_gamma_and_color_space().
844 void EffectChain::propagate_alpha()
846 // We depend on going through the nodes in order.
847 sort_all_nodes_topologically();
849 for (unsigned i = 0; i < nodes.size(); ++i) {
850 Node *node = nodes[i];
851 if (node->disabled) {
854 assert(node->incoming_links.size() == node->effect->num_inputs());
855 if (node->incoming_links.size() == 0) {
856 assert(node->output_alpha_type != ALPHA_INVALID);
860 // The alpha multiplication/division effects are special cases.
861 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
862 assert(node->incoming_links.size() == 1);
863 assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
864 node->output_alpha_type = ALPHA_PREMULTIPLIED;
867 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
868 assert(node->incoming_links.size() == 1);
869 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
870 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
874 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
875 // because they are the only one that _need_ postmultiplied alpha.
876 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
877 node->effect->effect_type_id() == "GammaExpansionEffect") {
878 assert(node->incoming_links.size() == 1);
879 if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
880 node->output_alpha_type = ALPHA_BLANK;
881 } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
882 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
884 node->output_alpha_type = ALPHA_INVALID;
889 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
890 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
891 // taken care of above. Rationale: Even if you could imagine
892 // e.g. an effect that took in an image and set alpha=1.0
893 // unconditionally, it wouldn't make any sense to have it as
894 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
895 // got its input pre- or postmultiplied, so it wouldn't know
896 // whether to divide away the old alpha or not.
897 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
898 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
899 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
900 alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
902 // If the node has multiple inputs, check that they are all valid and
904 bool any_invalid = false;
905 bool any_premultiplied = false;
906 bool any_postmultiplied = false;
908 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
909 switch (node->incoming_links[j]->output_alpha_type) {
914 // Blank is good as both pre- and postmultiplied alpha,
915 // so just ignore it.
917 case ALPHA_PREMULTIPLIED:
918 any_premultiplied = true;
920 case ALPHA_POSTMULTIPLIED:
921 any_postmultiplied = true;
929 node->output_alpha_type = ALPHA_INVALID;
933 // Inputs must be of the same type.
934 if (any_premultiplied && any_postmultiplied) {
935 node->output_alpha_type = ALPHA_INVALID;
939 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
940 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
941 // If the effect has asked for premultiplied alpha, check that it has got it.
942 if (any_postmultiplied) {
943 node->output_alpha_type = ALPHA_INVALID;
944 } else if (!any_premultiplied &&
945 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
946 // Blank input alpha, and the effect preserves blank alpha.
947 node->output_alpha_type = ALPHA_BLANK;
949 node->output_alpha_type = ALPHA_PREMULTIPLIED;
952 // OK, all inputs are the same, and this effect is not going
954 assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
955 if (any_premultiplied) {
956 node->output_alpha_type = ALPHA_PREMULTIPLIED;
957 } else if (any_postmultiplied) {
958 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
960 node->output_alpha_type = ALPHA_BLANK;
966 bool EffectChain::node_needs_colorspace_fix(Node *node)
968 if (node->disabled) {
971 if (node->effect->num_inputs() == 0) {
975 // propagate_gamma_and_color_space() has already set our output
976 // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
977 if (node->output_color_space == COLORSPACE_INVALID) {
980 return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
983 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
984 // the graph. Our strategy is not always optimal, but quite simple:
985 // Find an effect that's as early as possible where the inputs are of
986 // unacceptable colorspaces (that is, either different, or, if the effect only
987 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
988 // propagate the information anew, and repeat until there are no more such
990 void EffectChain::fix_internal_color_spaces()
992 unsigned colorspace_propagation_pass = 0;
996 for (unsigned i = 0; i < nodes.size(); ++i) {
997 Node *node = nodes[i];
998 if (!node_needs_colorspace_fix(node)) {
1002 // Go through each input that is not sRGB, and insert
1003 // a colorspace conversion after it.
1004 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1005 Node *input = node->incoming_links[j];
1006 assert(input->output_color_space != COLORSPACE_INVALID);
1007 if (input->output_color_space == COLORSPACE_sRGB) {
1010 Node *conversion = add_node(new ColorspaceConversionEffect());
1011 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1012 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1013 conversion->output_color_space = COLORSPACE_sRGB;
1014 replace_sender(input, conversion);
1015 connect_nodes(input, conversion);
1018 // Re-sort topologically, and propagate the new information.
1019 propagate_gamma_and_color_space();
1026 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1027 output_dot(filename);
1028 assert(colorspace_propagation_pass < 100);
1029 } while (found_any);
1031 for (unsigned i = 0; i < nodes.size(); ++i) {
1032 Node *node = nodes[i];
1033 if (node->disabled) {
1036 assert(node->output_color_space != COLORSPACE_INVALID);
1040 bool EffectChain::node_needs_alpha_fix(Node *node)
1042 if (node->disabled) {
1046 // propagate_alpha() has already set our output to ALPHA_INVALID if the
1047 // inputs differ or we are otherwise in mismatch, so we can rely on that.
1048 return (node->output_alpha_type == ALPHA_INVALID);
1051 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1052 // the graph. Similar to fix_internal_color_spaces().
1053 void EffectChain::fix_internal_alpha(unsigned step)
1055 unsigned alpha_propagation_pass = 0;
1059 for (unsigned i = 0; i < nodes.size(); ++i) {
1060 Node *node = nodes[i];
1061 if (!node_needs_alpha_fix(node)) {
1065 // If we need to fix up GammaExpansionEffect, then clearly something
1066 // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1068 assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1070 AlphaType desired_type = ALPHA_PREMULTIPLIED;
1072 // GammaCompressionEffect is special; it needs postmultiplied alpha.
1073 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1074 assert(node->incoming_links.size() == 1);
1075 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1076 desired_type = ALPHA_POSTMULTIPLIED;
1079 // Go through each input that is not premultiplied alpha, and insert
1080 // a conversion before it.
1081 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1082 Node *input = node->incoming_links[j];
1083 assert(input->output_alpha_type != ALPHA_INVALID);
1084 if (input->output_alpha_type == desired_type ||
1085 input->output_alpha_type == ALPHA_BLANK) {
1089 if (desired_type == ALPHA_PREMULTIPLIED) {
1090 conversion = add_node(new AlphaMultiplicationEffect());
1092 conversion = add_node(new AlphaDivisionEffect());
1094 conversion->output_alpha_type = desired_type;
1095 replace_sender(input, conversion);
1096 connect_nodes(input, conversion);
1099 // Re-sort topologically, and propagate the new information.
1100 propagate_gamma_and_color_space();
1108 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1109 output_dot(filename);
1110 assert(alpha_propagation_pass < 100);
1111 } while (found_any);
1113 for (unsigned i = 0; i < nodes.size(); ++i) {
1114 Node *node = nodes[i];
1115 if (node->disabled) {
1118 assert(node->output_alpha_type != ALPHA_INVALID);
1122 // Make so that the output is in the desired color space.
1123 void EffectChain::fix_output_color_space()
1125 Node *output = find_output_node();
1126 if (output->output_color_space != output_format.color_space) {
1127 Node *conversion = add_node(new ColorspaceConversionEffect());
1128 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1129 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1130 conversion->output_color_space = output_format.color_space;
1131 connect_nodes(output, conversion);
1133 propagate_gamma_and_color_space();
1137 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1138 void EffectChain::fix_output_alpha()
1140 Node *output = find_output_node();
1141 assert(output->output_alpha_type != ALPHA_INVALID);
1142 if (output->output_alpha_type == ALPHA_BLANK) {
1143 // No alpha output, so we don't care.
1146 if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1147 output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1148 Node *conversion = add_node(new AlphaDivisionEffect());
1149 connect_nodes(output, conversion);
1151 propagate_gamma_and_color_space();
1153 if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1154 output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1155 Node *conversion = add_node(new AlphaMultiplicationEffect());
1156 connect_nodes(output, conversion);
1158 propagate_gamma_and_color_space();
1162 bool EffectChain::node_needs_gamma_fix(Node *node)
1164 if (node->disabled) {
1168 // Small hack since the output is not an explicit node:
1169 // If we are the last node and our output is in the wrong
1170 // space compared to EffectChain's output, we need to fix it.
1171 // This will only take us to linear, but fix_output_gamma()
1172 // will come and take us to the desired output gamma
1175 // This needs to be before everything else, since it could
1176 // even apply to inputs (if they are the only effect).
1177 if (node->outgoing_links.empty() &&
1178 node->output_gamma_curve != output_format.gamma_curve &&
1179 node->output_gamma_curve != GAMMA_LINEAR) {
1183 if (node->effect->num_inputs() == 0) {
1187 // propagate_gamma_and_color_space() has already set our output
1188 // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1189 // except for GammaCompressionEffect.
1190 if (node->output_gamma_curve == GAMMA_INVALID) {
1193 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1194 assert(node->incoming_links.size() == 1);
1195 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1198 return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1201 // Very similar to fix_internal_color_spaces(), but for gamma.
1202 // There is one difference, though; before we start adding conversion nodes,
1203 // we see if we can get anything out of asking the sources to deliver
1204 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1205 // does that part, while fix_internal_gamma_by_inserting_nodes()
1206 // inserts nodes as needed afterwards.
1207 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1209 unsigned gamma_propagation_pass = 0;
1213 for (unsigned i = 0; i < nodes.size(); ++i) {
1214 Node *node = nodes[i];
1215 if (!node_needs_gamma_fix(node)) {
1219 // See if all inputs can give us linear gamma. If not, leave it.
1220 std::vector<Node *> nonlinear_inputs;
1221 find_all_nonlinear_inputs(node, &nonlinear_inputs);
1222 assert(!nonlinear_inputs.empty());
1225 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1226 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1227 all_ok &= input->can_output_linear_gamma();
1234 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1235 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1236 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1239 // Re-sort topologically, and propagate the new information.
1240 propagate_gamma_and_color_space();
1247 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1248 output_dot(filename);
1249 assert(gamma_propagation_pass < 100);
1250 } while (found_any);
1253 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1255 unsigned gamma_propagation_pass = 0;
1259 for (unsigned i = 0; i < nodes.size(); ++i) {
1260 Node *node = nodes[i];
1261 if (!node_needs_gamma_fix(node)) {
1265 // Special case: We could be an input and still be asked to
1266 // fix our gamma; if so, we should be the only node
1267 // (as node_needs_gamma_fix() would only return true in
1268 // for an input in that case). That means we should insert
1269 // a conversion node _after_ ourselves.
1270 if (node->incoming_links.empty()) {
1271 assert(node->outgoing_links.empty());
1272 Node *conversion = add_node(new GammaExpansionEffect());
1273 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1274 conversion->output_gamma_curve = GAMMA_LINEAR;
1275 connect_nodes(node, conversion);
1278 // If not, go through each input that is not linear gamma,
1279 // and insert a gamma conversion after it.
1280 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1281 Node *input = node->incoming_links[j];
1282 assert(input->output_gamma_curve != GAMMA_INVALID);
1283 if (input->output_gamma_curve == GAMMA_LINEAR) {
1286 Node *conversion = add_node(new GammaExpansionEffect());
1287 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1288 conversion->output_gamma_curve = GAMMA_LINEAR;
1289 replace_sender(input, conversion);
1290 connect_nodes(input, conversion);
1293 // Re-sort topologically, and propagate the new information.
1295 propagate_gamma_and_color_space();
1302 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1303 output_dot(filename);
1304 assert(gamma_propagation_pass < 100);
1305 } while (found_any);
1307 for (unsigned i = 0; i < nodes.size(); ++i) {
1308 Node *node = nodes[i];
1309 if (node->disabled) {
1312 assert(node->output_gamma_curve != GAMMA_INVALID);
1316 // Make so that the output is in the desired gamma.
1317 // Note that this assumes linear input gamma, so it might create the need
1318 // for another pass of fix_internal_gamma().
1319 void EffectChain::fix_output_gamma()
1321 Node *output = find_output_node();
1322 if (output->output_gamma_curve != output_format.gamma_curve) {
1323 Node *conversion = add_node(new GammaCompressionEffect());
1324 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1325 conversion->output_gamma_curve = output_format.gamma_curve;
1326 connect_nodes(output, conversion);
1330 // If the user has requested dither, add a DitherEffect right at the end
1331 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1332 // since dither is about the only effect that can _not_ be done in linear space.
1333 void EffectChain::add_dither_if_needed()
1335 if (num_dither_bits == 0) {
1338 Node *output = find_output_node();
1339 Node *dither = add_node(new DitherEffect());
1340 CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1341 connect_nodes(output, dither);
1343 dither_effect = dither->effect;
1346 // Find the output node. This is, simply, one that has no outgoing links.
1347 // If there are multiple ones, the graph is malformed (we do not support
1348 // multiple outputs right now).
1349 Node *EffectChain::find_output_node()
1351 std::vector<Node *> output_nodes;
1352 for (unsigned i = 0; i < nodes.size(); ++i) {
1353 Node *node = nodes[i];
1354 if (node->disabled) {
1357 if (node->outgoing_links.empty()) {
1358 output_nodes.push_back(node);
1361 assert(output_nodes.size() == 1);
1362 return output_nodes[0];
1365 void EffectChain::finalize()
1367 // Save the current locale, and set it to C, so that we can output decimal
1368 // numbers with printf and be sure to get them in the format mandated by GLSL.
1369 char *saved_locale = setlocale(LC_NUMERIC, "C");
1371 // Output the graph as it is before we do any conversions on it.
1372 output_dot("step0-start.dot");
1374 // Give each effect in turn a chance to rewrite its own part of the graph.
1375 // Note that if more effects are added as part of this, they will be
1376 // picked up as part of the same for loop, since they are added at the end.
1377 for (unsigned i = 0; i < nodes.size(); ++i) {
1378 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1380 output_dot("step1-rewritten.dot");
1382 find_color_spaces_for_inputs();
1383 output_dot("step2-input-colorspace.dot");
1386 output_dot("step3-propagated-alpha.dot");
1388 propagate_gamma_and_color_space();
1389 output_dot("step4-propagated-all.dot");
1391 fix_internal_color_spaces();
1392 fix_internal_alpha(6);
1393 fix_output_color_space();
1394 output_dot("step7-output-colorspacefix.dot");
1396 output_dot("step8-output-alphafix.dot");
1398 // Note that we need to fix gamma after colorspace conversion,
1399 // because colorspace conversions might create needs for gamma conversions.
1400 // Also, we need to run an extra pass of fix_internal_gamma() after
1401 // fixing the output gamma, as we only have conversions to/from linear,
1402 // and fix_internal_alpha() since GammaCompressionEffect needs
1403 // postmultiplied input.
1404 fix_internal_gamma_by_asking_inputs(9);
1405 fix_internal_gamma_by_inserting_nodes(10);
1407 output_dot("step11-output-gammafix.dot");
1409 output_dot("step12-output-alpha-propagated.dot");
1410 fix_internal_alpha(13);
1411 output_dot("step14-output-alpha-fixed.dot");
1412 fix_internal_gamma_by_asking_inputs(15);
1413 fix_internal_gamma_by_inserting_nodes(16);
1415 output_dot("step17-before-dither.dot");
1417 add_dither_if_needed();
1419 output_dot("step18-final.dot");
1421 // Construct all needed GLSL programs, starting at the output.
1422 construct_glsl_programs(find_output_node());
1424 output_dot("step19-split-to-phases.dot");
1426 // If we have more than one phase, we need intermediate render-to-texture.
1427 // Construct an FBO, and then as many textures as we need.
1428 // We choose the simplest option of having one texture per output,
1429 // since otherwise this turns into an (albeit simple)
1430 // register allocation problem.
1431 if (phases.size() > 1) {
1432 for (unsigned i = 0; i < phases.size() - 1; ++i) {
1433 inform_input_sizes(phases[i]);
1434 find_output_size(phases[i]);
1436 Node *output_node = phases[i]->effects.back();
1437 glGenTextures(1, &output_node->output_texture);
1439 glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
1441 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1443 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1445 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[i]->output_width, phases[i]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
1448 output_node->output_texture_width = phases[i]->output_width;
1449 output_node->output_texture_height = phases[i]->output_height;
1451 inform_input_sizes(phases.back());
1454 for (unsigned i = 0; i < inputs.size(); ++i) {
1455 inputs[i]->finalize();
1458 assert(phases[0]->inputs.empty());
1461 setlocale(LC_NUMERIC, saved_locale);
1464 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1468 // Save original viewport.
1469 GLuint x = 0, y = 0;
1472 if (width == 0 && height == 0) {
1474 glGetIntegerv(GL_VIEWPORT, viewport);
1477 width = viewport[2];
1478 height = viewport[3];
1482 glDisable(GL_BLEND);
1484 glDisable(GL_DEPTH_TEST);
1486 glDepthMask(GL_FALSE);
1489 glMatrixMode(GL_PROJECTION);
1491 glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
1493 glMatrixMode(GL_MODELVIEW);
1496 if (phases.size() > 1) {
1497 glGenFramebuffers(1, &fbo);
1499 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1503 std::set<Node *> generated_mipmaps;
1505 for (unsigned phase = 0; phase < phases.size(); ++phase) {
1506 // See if the requested output size has changed. If so, we need to recreate
1507 // the texture (and before we start setting up inputs).
1508 inform_input_sizes(phases[phase]);
1509 if (phase != phases.size() - 1) {
1510 find_output_size(phases[phase]);
1512 Node *output_node = phases[phase]->effects.back();
1514 if (output_node->output_texture_width != phases[phase]->output_width ||
1515 output_node->output_texture_height != phases[phase]->output_height) {
1516 glActiveTexture(GL_TEXTURE0);
1518 glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
1520 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[phase]->output_width, phases[phase]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
1522 glBindTexture(GL_TEXTURE_2D, 0);
1525 output_node->output_texture_width = phases[phase]->output_width;
1526 output_node->output_texture_height = phases[phase]->output_height;
1530 glUseProgram(phases[phase]->glsl_program_num);
1533 // Set up RTT inputs for this phase.
1534 for (unsigned sampler = 0; sampler < phases[phase]->inputs.size(); ++sampler) {
1535 glActiveTexture(GL_TEXTURE0 + sampler);
1536 Node *input = phases[phase]->inputs[sampler];
1537 glBindTexture(GL_TEXTURE_2D, input->output_texture);
1539 if (phases[phase]->input_needs_mipmaps) {
1540 if (generated_mipmaps.count(input) == 0) {
1541 glGenerateMipmap(GL_TEXTURE_2D);
1543 generated_mipmaps.insert(input);
1545 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1548 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1552 std::string texture_name = std::string("tex_") + input->effect_id;
1553 glUniform1i(glGetUniformLocation(phases[phase]->glsl_program_num, texture_name.c_str()), sampler);
1557 // And now the output.
1558 if (phase == phases.size() - 1) {
1559 // Last phase goes to the output the user specified.
1560 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1562 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1563 assert(status == GL_FRAMEBUFFER_COMPLETE);
1564 glViewport(x, y, width, height);
1565 if (dither_effect != NULL) {
1566 CHECK(dither_effect->set_int("output_width", width));
1567 CHECK(dither_effect->set_int("output_height", height));
1570 Node *output_node = phases[phase]->effects.back();
1571 glFramebufferTexture2D(
1573 GL_COLOR_ATTACHMENT0,
1575 output_node->output_texture,
1578 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1579 assert(status == GL_FRAMEBUFFER_COMPLETE);
1580 glViewport(0, 0, phases[phase]->output_width, phases[phase]->output_height);
1583 // Give the required parameters to all the effects.
1584 unsigned sampler_num = phases[phase]->inputs.size();
1585 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
1586 Node *node = phases[phase]->effects[i];
1587 node->effect->set_gl_state(phases[phase]->glsl_program_num, node->effect_id, &sampler_num);
1594 glTexCoord2f(0.0f, 0.0f);
1595 glVertex2f(0.0f, 0.0f);
1597 glTexCoord2f(1.0f, 0.0f);
1598 glVertex2f(1.0f, 0.0f);
1600 glTexCoord2f(1.0f, 1.0f);
1601 glVertex2f(1.0f, 1.0f);
1603 glTexCoord2f(0.0f, 1.0f);
1604 glVertex2f(0.0f, 1.0f);
1609 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
1610 Node *node = phases[phase]->effects[i];
1611 node->effect->clear_gl_state();
1615 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1619 glDeleteFramebuffers(1, &fbo);