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"
26 #include "resource_pool.h"
33 EffectChain::EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool)
34 : aspect_nom(aspect_nom),
35 aspect_denom(aspect_denom),
39 resource_pool(resource_pool),
40 do_phase_timing(false) {
41 if (resource_pool == NULL) {
42 this->resource_pool = new ResourcePool();
43 owns_resource_pool = true;
45 owns_resource_pool = false;
49 EffectChain::~EffectChain()
51 for (unsigned i = 0; i < nodes.size(); ++i) {
52 delete nodes[i]->effect;
55 for (unsigned i = 0; i < phases.size(); ++i) {
56 resource_pool->release_glsl_program(phases[i]->glsl_program_num);
59 if (owns_resource_pool) {
64 Input *EffectChain::add_input(Input *input)
67 inputs.push_back(input);
72 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
75 output_format = format;
76 output_alpha_format = alpha_format;
79 Node *EffectChain::add_node(Effect *effect)
81 for (unsigned i = 0; i < nodes.size(); ++i) {
82 assert(nodes[i]->effect != effect);
85 Node *node = new Node;
86 node->effect = effect;
87 node->disabled = false;
88 node->output_color_space = COLORSPACE_INVALID;
89 node->output_gamma_curve = GAMMA_INVALID;
90 node->output_alpha_type = ALPHA_INVALID;
91 node->needs_mipmaps = false;
93 nodes.push_back(node);
94 node_map[effect] = node;
95 effect->inform_added(this);
99 void EffectChain::connect_nodes(Node *sender, Node *receiver)
101 sender->outgoing_links.push_back(receiver);
102 receiver->incoming_links.push_back(sender);
105 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
107 new_receiver->incoming_links = old_receiver->incoming_links;
108 old_receiver->incoming_links.clear();
110 for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
111 Node *sender = new_receiver->incoming_links[i];
112 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
113 if (sender->outgoing_links[j] == old_receiver) {
114 sender->outgoing_links[j] = new_receiver;
120 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
122 new_sender->outgoing_links = old_sender->outgoing_links;
123 old_sender->outgoing_links.clear();
125 for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
126 Node *receiver = new_sender->outgoing_links[i];
127 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
128 if (receiver->incoming_links[j] == old_sender) {
129 receiver->incoming_links[j] = new_sender;
135 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
137 for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
138 if (sender->outgoing_links[i] == receiver) {
139 sender->outgoing_links[i] = middle;
140 middle->incoming_links.push_back(sender);
143 for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
144 if (receiver->incoming_links[i] == sender) {
145 receiver->incoming_links[i] = middle;
146 middle->outgoing_links.push_back(receiver);
150 assert(middle->incoming_links.size() == middle->effect->num_inputs());
153 GLenum EffectChain::get_input_sampler(Node *node, unsigned input_num) const
155 assert(node->effect->needs_texture_bounce());
156 assert(input_num < node->incoming_links.size());
157 assert(node->incoming_links[input_num]->bound_sampler_num >= 0);
158 assert(node->incoming_links[input_num]->bound_sampler_num < 8);
159 return GL_TEXTURE0 + node->incoming_links[input_num]->bound_sampler_num;
162 void EffectChain::find_all_nonlinear_inputs(Node *node, vector<Node *> *nonlinear_inputs)
164 if (node->output_gamma_curve == GAMMA_LINEAR &&
165 node->effect->effect_type_id() != "GammaCompressionEffect") {
168 if (node->effect->num_inputs() == 0) {
169 nonlinear_inputs->push_back(node);
171 assert(node->effect->num_inputs() == node->incoming_links.size());
172 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
173 find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
178 Effect *EffectChain::add_effect(Effect *effect, const vector<Effect *> &inputs)
181 assert(inputs.size() == effect->num_inputs());
182 Node *node = add_node(effect);
183 for (unsigned i = 0; i < inputs.size(); ++i) {
184 assert(node_map.count(inputs[i]) != 0);
185 connect_nodes(node_map[inputs[i]], node);
190 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
191 string replace_prefix(const string &text, const string &prefix)
196 while (start < text.size()) {
197 size_t pos = text.find("PREFIX(", start);
198 if (pos == string::npos) {
199 output.append(text.substr(start, string::npos));
203 output.append(text.substr(start, pos - start));
204 output.append(prefix);
207 pos += strlen("PREFIX(");
209 // Output stuff until we find the matching ), which we then eat.
211 size_t end_arg_pos = pos;
212 while (end_arg_pos < text.size()) {
213 if (text[end_arg_pos] == '(') {
215 } else if (text[end_arg_pos] == ')') {
223 output.append(text.substr(pos, end_arg_pos - pos));
231 void EffectChain::compile_glsl_program(Phase *phase)
233 string frag_shader = read_version_dependent_file("header", "frag");
235 // Create functions for all the texture inputs that we need.
236 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
237 Node *input = phase->inputs[i]->output_node;
239 sprintf(effect_id, "in%u", i);
240 phase->effect_ids.insert(make_pair(input, effect_id));
242 frag_shader += string("uniform sampler2D tex_") + effect_id + ";\n";
243 frag_shader += string("vec4 ") + effect_id + "(vec2 tc) {\n";
244 frag_shader += "\treturn tex2D(tex_" + string(effect_id) + ", tc);\n";
245 frag_shader += "}\n";
249 for (unsigned i = 0; i < phase->effects.size(); ++i) {
250 Node *node = phase->effects[i];
252 sprintf(effect_id, "eff%u", i);
253 phase->effect_ids.insert(make_pair(node, effect_id));
255 if (node->incoming_links.size() == 1) {
256 frag_shader += string("#define INPUT ") + phase->effect_ids[node->incoming_links[0]] + "\n";
258 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
260 sprintf(buf, "#define INPUT%d %s\n", j + 1, phase->effect_ids[node->incoming_links[j]].c_str());
266 frag_shader += string("#define FUNCNAME ") + effect_id + "\n";
267 frag_shader += replace_prefix(node->effect->output_convenience_uniforms(), effect_id);
268 frag_shader += replace_prefix(node->effect->output_fragment_shader(), effect_id);
269 frag_shader += "#undef PREFIX\n";
270 frag_shader += "#undef FUNCNAME\n";
271 if (node->incoming_links.size() == 1) {
272 frag_shader += "#undef INPUT\n";
274 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
276 sprintf(buf, "#undef INPUT%d\n", j + 1);
282 frag_shader += string("#define INPUT ") + phase->effect_ids[phase->effects.back()] + "\n";
283 frag_shader.append(read_version_dependent_file("footer", "frag"));
285 string vert_shader = read_version_dependent_file("vs", "vert");
286 phase->glsl_program_num = resource_pool->compile_glsl_program(vert_shader, frag_shader);
289 // Construct GLSL programs, starting at the given effect and following
290 // the chain from there. We end a program every time we come to an effect
291 // marked as "needs texture bounce", one that is used by multiple other
292 // effects, every time an effect wants to change the output size,
293 // and of course at the end.
295 // We follow a quite simple depth-first search from the output, although
296 // without recursing explicitly within each phase.
297 Phase *EffectChain::construct_phase(Node *output, map<Node *, Phase *> *completed_effects)
299 if (completed_effects->count(output)) {
300 return (*completed_effects)[output];
303 Phase *phase = new Phase;
304 phase->output_node = output;
306 // Effects that we have yet to calculate, but that we know should
307 // be in the current phase.
308 stack<Node *> effects_todo_this_phase;
309 effects_todo_this_phase.push(output);
311 while (!effects_todo_this_phase.empty()) {
312 Node *node = effects_todo_this_phase.top();
313 effects_todo_this_phase.pop();
315 if (node->effect->needs_mipmaps()) {
316 node->needs_mipmaps = true;
319 // This should currently only happen for effects that are inputs
320 // (either true inputs or phase outputs). We special-case inputs,
321 // and then deduplicate phase outputs below.
322 if (node->effect->num_inputs() == 0) {
323 if (find(phase->effects.begin(), phase->effects.end(), node) != phase->effects.end()) {
327 assert(completed_effects->count(node) == 0);
330 phase->effects.push_back(node);
332 // Find all the dependencies of this effect, and add them to the stack.
333 vector<Node *> deps = node->incoming_links;
334 assert(node->effect->num_inputs() == deps.size());
335 for (unsigned i = 0; i < deps.size(); ++i) {
336 bool start_new_phase = false;
338 if (node->effect->needs_texture_bounce() &&
339 !deps[i]->effect->is_single_texture()) {
340 start_new_phase = true;
343 // Propagate information about needing mipmaps down the chain,
344 // breaking the phase if we notice an incompatibility.
346 // Note that we cannot do this propagation as a normal pass,
347 // because it needs information about where the phases end
348 // (we should not propagate the flag across phases).
349 if (node->needs_mipmaps) {
350 if (deps[i]->effect->num_inputs() == 0) {
351 Input *input = static_cast<Input *>(deps[i]->effect);
352 start_new_phase |= !input->can_supply_mipmaps();
354 deps[i]->needs_mipmaps = true;
358 if (deps[i]->outgoing_links.size() > 1) {
359 if (!deps[i]->effect->is_single_texture()) {
360 // More than one effect uses this as the input,
361 // and it is not a texture itself.
362 // The easiest thing to do (and probably also the safest
363 // performance-wise in most cases) is to bounce it to a texture
364 // and then let the next passes read from that.
365 start_new_phase = true;
367 assert(deps[i]->effect->num_inputs() == 0);
369 // For textures, we try to be slightly more clever;
370 // if none of our outputs need a bounce, we don't bounce
371 // but instead simply use the effect many times.
373 // Strictly speaking, we could bounce it for some outputs
374 // and use it directly for others, but the processing becomes
375 // somewhat simpler if the effect is only used in one such way.
376 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
377 Node *rdep = deps[i]->outgoing_links[j];
378 start_new_phase |= rdep->effect->needs_texture_bounce();
383 if (deps[i]->effect->changes_output_size()) {
384 start_new_phase = true;
387 if (start_new_phase) {
388 phase->inputs.push_back(construct_phase(deps[i], completed_effects));
390 effects_todo_this_phase.push(deps[i]);
395 // No more effects to do this phase. Take all the ones we have,
396 // and create a GLSL program for it.
397 assert(!phase->effects.empty());
399 // Deduplicate the inputs.
400 sort(phase->inputs.begin(), phase->inputs.end());
401 phase->inputs.erase(unique(phase->inputs.begin(), phase->inputs.end()), phase->inputs.end());
403 // We added the effects from the output and back, but we need to output
404 // them in topological sort order in the shader.
405 phase->effects = topological_sort(phase->effects);
407 // Figure out if we need mipmaps or not, and if so, tell the inputs that.
408 phase->input_needs_mipmaps = false;
409 for (unsigned i = 0; i < phase->effects.size(); ++i) {
410 Node *node = phase->effects[i];
411 phase->input_needs_mipmaps |= node->effect->needs_mipmaps();
413 for (unsigned i = 0; i < phase->effects.size(); ++i) {
414 Node *node = phase->effects[i];
415 if (node->effect->num_inputs() == 0) {
416 Input *input = static_cast<Input *>(node->effect);
417 assert(!phase->input_needs_mipmaps || input->can_supply_mipmaps());
418 CHECK(input->set_int("needs_mipmaps", phase->input_needs_mipmaps));
422 // Actually make the shader for this phase.
423 compile_glsl_program(phase);
425 // Initialize timer objects.
426 if (movit_timer_queries_supported) {
427 glGenQueries(1, &phase->timer_query_object);
428 phase->time_elapsed_ns = 0;
429 phase->num_measured_iterations = 0;
432 assert(completed_effects->count(output) == 0);
433 completed_effects->insert(make_pair(output, phase));
434 phases.push_back(phase);
438 void EffectChain::output_dot(const char *filename)
440 if (movit_debug_level != MOVIT_DEBUG_ON) {
444 FILE *fp = fopen(filename, "w");
450 fprintf(fp, "digraph G {\n");
451 fprintf(fp, " output [shape=box label=\"(output)\"];\n");
452 for (unsigned i = 0; i < nodes.size(); ++i) {
453 // Find out which phase this event belongs to.
454 vector<int> in_phases;
455 for (unsigned j = 0; j < phases.size(); ++j) {
456 const Phase* p = phases[j];
457 if (find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
458 in_phases.push_back(j);
462 if (in_phases.empty()) {
463 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
464 } else if (in_phases.size() == 1) {
465 fprintf(fp, " n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
466 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
467 (in_phases[0] % 8) + 1);
469 // If we had new enough Graphviz, style="wedged" would probably be ideal here.
471 fprintf(fp, " n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
472 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
473 (in_phases[0] % 8) + 1);
476 char from_node_id[256];
477 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
479 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
480 char to_node_id[256];
481 snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
483 vector<string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
484 output_dot_edge(fp, from_node_id, to_node_id, labels);
487 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
489 vector<string> labels = get_labels_for_edge(nodes[i], NULL);
490 output_dot_edge(fp, from_node_id, "output", labels);
498 vector<string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
500 vector<string> labels;
502 if (to != NULL && to->effect->needs_texture_bounce()) {
503 labels.push_back("needs_bounce");
505 if (from->effect->changes_output_size()) {
506 labels.push_back("resize");
509 switch (from->output_color_space) {
510 case COLORSPACE_INVALID:
511 labels.push_back("spc[invalid]");
513 case COLORSPACE_REC_601_525:
514 labels.push_back("spc[rec601-525]");
516 case COLORSPACE_REC_601_625:
517 labels.push_back("spc[rec601-625]");
523 switch (from->output_gamma_curve) {
525 labels.push_back("gamma[invalid]");
528 labels.push_back("gamma[sRGB]");
530 case GAMMA_REC_601: // and GAMMA_REC_709
531 labels.push_back("gamma[rec601/709]");
537 switch (from->output_alpha_type) {
539 labels.push_back("alpha[invalid]");
542 labels.push_back("alpha[blank]");
544 case ALPHA_POSTMULTIPLIED:
545 labels.push_back("alpha[postmult]");
554 void EffectChain::output_dot_edge(FILE *fp,
555 const string &from_node_id,
556 const string &to_node_id,
557 const vector<string> &labels)
559 if (labels.empty()) {
560 fprintf(fp, " %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
562 string label = labels[0];
563 for (unsigned k = 1; k < labels.size(); ++k) {
564 label += ", " + labels[k];
566 fprintf(fp, " %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
570 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
572 unsigned scaled_width, scaled_height;
574 if (float(width) * aspect_denom >= float(height) * aspect_nom) {
575 // Same aspect, or W/H > aspect (image is wider than the frame).
576 // In either case, keep width, and adjust height.
577 scaled_width = width;
578 scaled_height = lrintf(width * aspect_denom / aspect_nom);
580 // W/H < aspect (image is taller than the frame), so keep height,
582 scaled_width = lrintf(height * aspect_nom / aspect_denom);
583 scaled_height = height;
586 // We should be consistently larger or smaller then the existing choice,
587 // since we have the same aspect.
588 assert(!(scaled_width < *output_width && scaled_height > *output_height));
589 assert(!(scaled_height < *output_height && scaled_width > *output_width));
591 if (scaled_width >= *output_width && scaled_height >= *output_height) {
592 *output_width = scaled_width;
593 *output_height = scaled_height;
597 // Propagate input texture sizes throughout, and inform effects downstream.
598 // (Like a lot of other code, we depend on effects being in topological order.)
599 void EffectChain::inform_input_sizes(Phase *phase)
601 // All effects that have a defined size (inputs and RTT inputs)
602 // get that. Reset all others.
603 for (unsigned i = 0; i < phase->effects.size(); ++i) {
604 Node *node = phase->effects[i];
605 if (node->effect->num_inputs() == 0) {
606 Input *input = static_cast<Input *>(node->effect);
607 node->output_width = input->get_width();
608 node->output_height = input->get_height();
609 assert(node->output_width != 0);
610 assert(node->output_height != 0);
612 node->output_width = node->output_height = 0;
615 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
616 Phase *input = phase->inputs[i];
617 input->output_node->output_width = input->virtual_output_width;
618 input->output_node->output_height = input->virtual_output_height;
619 assert(input->output_node->output_width != 0);
620 assert(input->output_node->output_height != 0);
623 // Now propagate from the inputs towards the end, and inform as we go.
624 // The rules are simple:
626 // 1. Don't touch effects that already have given sizes (ie., inputs
627 // or effects that change the output size).
628 // 2. If all of your inputs have the same size, that will be your output size.
629 // 3. Otherwise, your output size is 0x0.
630 for (unsigned i = 0; i < phase->effects.size(); ++i) {
631 Node *node = phase->effects[i];
632 if (node->effect->num_inputs() == 0) {
635 unsigned this_output_width = 0;
636 unsigned this_output_height = 0;
637 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
638 Node *input = node->incoming_links[j];
639 node->effect->inform_input_size(j, input->output_width, input->output_height);
641 this_output_width = input->output_width;
642 this_output_height = input->output_height;
643 } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
645 this_output_width = 0;
646 this_output_height = 0;
649 if (node->effect->changes_output_size()) {
650 // We cannot call get_output_size() before we've done inform_input_size()
652 unsigned real_width_ignored, real_height_ignored;
653 node->effect->get_output_size(&real_width_ignored, &real_height_ignored,
654 &node->output_width, &node->output_height);
656 node->output_width = this_output_width;
657 node->output_height = this_output_height;
662 // Note: You should call inform_input_sizes() before this, as the last effect's
663 // desired output size might change based on the inputs.
664 void EffectChain::find_output_size(Phase *phase)
666 Node *output_node = phase->effects.back();
668 // If the last effect explicitly sets an output size, use that.
669 if (output_node->effect->changes_output_size()) {
670 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
671 &phase->virtual_output_width, &phase->virtual_output_height);
675 // If all effects have the same size, use that.
676 unsigned output_width = 0, output_height = 0;
677 bool all_inputs_same_size = true;
679 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
680 Phase *input = phase->inputs[i];
681 assert(input->output_width != 0);
682 assert(input->output_height != 0);
683 if (output_width == 0 && output_height == 0) {
684 output_width = input->virtual_output_width;
685 output_height = input->virtual_output_height;
686 } else if (output_width != input->virtual_output_width ||
687 output_height != input->virtual_output_height) {
688 all_inputs_same_size = false;
691 for (unsigned i = 0; i < phase->effects.size(); ++i) {
692 Effect *effect = phase->effects[i]->effect;
693 if (effect->num_inputs() != 0) {
697 Input *input = static_cast<Input *>(effect);
698 if (output_width == 0 && output_height == 0) {
699 output_width = input->get_width();
700 output_height = input->get_height();
701 } else if (output_width != input->get_width() ||
702 output_height != input->get_height()) {
703 all_inputs_same_size = false;
707 if (all_inputs_same_size) {
708 assert(output_width != 0);
709 assert(output_height != 0);
710 phase->virtual_output_width = phase->output_width = output_width;
711 phase->virtual_output_height = phase->output_height = output_height;
715 // If not, fit all the inputs into the current aspect, and select the largest one.
718 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
719 Phase *input = phase->inputs[i];
720 assert(input->output_width != 0);
721 assert(input->output_height != 0);
722 size_rectangle_to_fit(input->output_width, input->output_height, &output_width, &output_height);
724 for (unsigned i = 0; i < phase->effects.size(); ++i) {
725 Effect *effect = phase->effects[i]->effect;
726 if (effect->num_inputs() != 0) {
730 Input *input = static_cast<Input *>(effect);
731 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
733 assert(output_width != 0);
734 assert(output_height != 0);
735 phase->virtual_output_width = phase->output_width = output_width;
736 phase->virtual_output_height = phase->output_height = output_height;
739 void EffectChain::sort_all_nodes_topologically()
741 nodes = topological_sort(nodes);
744 vector<Node *> EffectChain::topological_sort(const vector<Node *> &nodes)
746 set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
747 vector<Node *> sorted_list;
748 for (unsigned i = 0; i < nodes.size(); ++i) {
749 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
751 reverse(sorted_list.begin(), sorted_list.end());
755 void EffectChain::topological_sort_visit_node(Node *node, set<Node *> *nodes_left_to_visit, vector<Node *> *sorted_list)
757 if (nodes_left_to_visit->count(node) == 0) {
760 nodes_left_to_visit->erase(node);
761 for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
762 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
764 sorted_list->push_back(node);
767 void EffectChain::find_color_spaces_for_inputs()
769 for (unsigned i = 0; i < nodes.size(); ++i) {
770 Node *node = nodes[i];
771 if (node->disabled) {
774 if (node->incoming_links.size() == 0) {
775 Input *input = static_cast<Input *>(node->effect);
776 node->output_color_space = input->get_color_space();
777 node->output_gamma_curve = input->get_gamma_curve();
779 Effect::AlphaHandling alpha_handling = input->alpha_handling();
780 switch (alpha_handling) {
781 case Effect::OUTPUT_BLANK_ALPHA:
782 node->output_alpha_type = ALPHA_BLANK;
784 case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
785 node->output_alpha_type = ALPHA_PREMULTIPLIED;
787 case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
788 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
790 case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
791 case Effect::DONT_CARE_ALPHA_TYPE:
796 if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
797 assert(node->output_gamma_curve == GAMMA_LINEAR);
803 // Propagate gamma and color space information as far as we can in the graph.
804 // The rules are simple: Anything where all the inputs agree, get that as
805 // output as well. Anything else keeps having *_INVALID.
806 void EffectChain::propagate_gamma_and_color_space()
808 // We depend on going through the nodes in order.
809 sort_all_nodes_topologically();
811 for (unsigned i = 0; i < nodes.size(); ++i) {
812 Node *node = nodes[i];
813 if (node->disabled) {
816 assert(node->incoming_links.size() == node->effect->num_inputs());
817 if (node->incoming_links.size() == 0) {
818 assert(node->output_color_space != COLORSPACE_INVALID);
819 assert(node->output_gamma_curve != GAMMA_INVALID);
823 Colorspace color_space = node->incoming_links[0]->output_color_space;
824 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
825 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
826 if (node->incoming_links[j]->output_color_space != color_space) {
827 color_space = COLORSPACE_INVALID;
829 if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
830 gamma_curve = GAMMA_INVALID;
834 // The conversion effects already have their outputs set correctly,
835 // so leave them alone.
836 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
837 node->output_color_space = color_space;
839 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
840 node->effect->effect_type_id() != "GammaExpansionEffect") {
841 node->output_gamma_curve = gamma_curve;
846 // Propagate alpha information as far as we can in the graph.
847 // Similar to propagate_gamma_and_color_space().
848 void EffectChain::propagate_alpha()
850 // We depend on going through the nodes in order.
851 sort_all_nodes_topologically();
853 for (unsigned i = 0; i < nodes.size(); ++i) {
854 Node *node = nodes[i];
855 if (node->disabled) {
858 assert(node->incoming_links.size() == node->effect->num_inputs());
859 if (node->incoming_links.size() == 0) {
860 assert(node->output_alpha_type != ALPHA_INVALID);
864 // The alpha multiplication/division effects are special cases.
865 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
866 assert(node->incoming_links.size() == 1);
867 assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
868 node->output_alpha_type = ALPHA_PREMULTIPLIED;
871 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
872 assert(node->incoming_links.size() == 1);
873 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
874 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
878 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
879 // because they are the only one that _need_ postmultiplied alpha.
880 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
881 node->effect->effect_type_id() == "GammaExpansionEffect") {
882 assert(node->incoming_links.size() == 1);
883 if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
884 node->output_alpha_type = ALPHA_BLANK;
885 } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
886 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
888 node->output_alpha_type = ALPHA_INVALID;
893 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
894 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
895 // taken care of above. Rationale: Even if you could imagine
896 // e.g. an effect that took in an image and set alpha=1.0
897 // unconditionally, it wouldn't make any sense to have it as
898 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
899 // got its input pre- or postmultiplied, so it wouldn't know
900 // whether to divide away the old alpha or not.
901 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
902 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
903 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
904 alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
906 // If the node has multiple inputs, check that they are all valid and
908 bool any_invalid = false;
909 bool any_premultiplied = false;
910 bool any_postmultiplied = false;
912 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
913 switch (node->incoming_links[j]->output_alpha_type) {
918 // Blank is good as both pre- and postmultiplied alpha,
919 // so just ignore it.
921 case ALPHA_PREMULTIPLIED:
922 any_premultiplied = true;
924 case ALPHA_POSTMULTIPLIED:
925 any_postmultiplied = true;
933 node->output_alpha_type = ALPHA_INVALID;
937 // Inputs must be of the same type.
938 if (any_premultiplied && any_postmultiplied) {
939 node->output_alpha_type = ALPHA_INVALID;
943 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
944 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
945 // If the effect has asked for premultiplied alpha, check that it has got it.
946 if (any_postmultiplied) {
947 node->output_alpha_type = ALPHA_INVALID;
948 } else if (!any_premultiplied &&
949 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
950 // Blank input alpha, and the effect preserves blank alpha.
951 node->output_alpha_type = ALPHA_BLANK;
953 node->output_alpha_type = ALPHA_PREMULTIPLIED;
956 // OK, all inputs are the same, and this effect is not going
958 assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
959 if (any_premultiplied) {
960 node->output_alpha_type = ALPHA_PREMULTIPLIED;
961 } else if (any_postmultiplied) {
962 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
964 node->output_alpha_type = ALPHA_BLANK;
970 bool EffectChain::node_needs_colorspace_fix(Node *node)
972 if (node->disabled) {
975 if (node->effect->num_inputs() == 0) {
979 // propagate_gamma_and_color_space() has already set our output
980 // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
981 if (node->output_color_space == COLORSPACE_INVALID) {
984 return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
987 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
988 // the graph. Our strategy is not always optimal, but quite simple:
989 // Find an effect that's as early as possible where the inputs are of
990 // unacceptable colorspaces (that is, either different, or, if the effect only
991 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
992 // propagate the information anew, and repeat until there are no more such
994 void EffectChain::fix_internal_color_spaces()
996 unsigned colorspace_propagation_pass = 0;
1000 for (unsigned i = 0; i < nodes.size(); ++i) {
1001 Node *node = nodes[i];
1002 if (!node_needs_colorspace_fix(node)) {
1006 // Go through each input that is not sRGB, and insert
1007 // a colorspace conversion after it.
1008 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1009 Node *input = node->incoming_links[j];
1010 assert(input->output_color_space != COLORSPACE_INVALID);
1011 if (input->output_color_space == COLORSPACE_sRGB) {
1014 Node *conversion = add_node(new ColorspaceConversionEffect());
1015 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1016 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1017 conversion->output_color_space = COLORSPACE_sRGB;
1018 replace_sender(input, conversion);
1019 connect_nodes(input, conversion);
1022 // Re-sort topologically, and propagate the new information.
1023 propagate_gamma_and_color_space();
1030 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1031 output_dot(filename);
1032 assert(colorspace_propagation_pass < 100);
1033 } while (found_any);
1035 for (unsigned i = 0; i < nodes.size(); ++i) {
1036 Node *node = nodes[i];
1037 if (node->disabled) {
1040 assert(node->output_color_space != COLORSPACE_INVALID);
1044 bool EffectChain::node_needs_alpha_fix(Node *node)
1046 if (node->disabled) {
1050 // propagate_alpha() has already set our output to ALPHA_INVALID if the
1051 // inputs differ or we are otherwise in mismatch, so we can rely on that.
1052 return (node->output_alpha_type == ALPHA_INVALID);
1055 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1056 // the graph. Similar to fix_internal_color_spaces().
1057 void EffectChain::fix_internal_alpha(unsigned step)
1059 unsigned alpha_propagation_pass = 0;
1063 for (unsigned i = 0; i < nodes.size(); ++i) {
1064 Node *node = nodes[i];
1065 if (!node_needs_alpha_fix(node)) {
1069 // If we need to fix up GammaExpansionEffect, then clearly something
1070 // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1072 assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1074 AlphaType desired_type = ALPHA_PREMULTIPLIED;
1076 // GammaCompressionEffect is special; it needs postmultiplied alpha.
1077 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1078 assert(node->incoming_links.size() == 1);
1079 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1080 desired_type = ALPHA_POSTMULTIPLIED;
1083 // Go through each input that is not premultiplied alpha, and insert
1084 // a conversion before it.
1085 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1086 Node *input = node->incoming_links[j];
1087 assert(input->output_alpha_type != ALPHA_INVALID);
1088 if (input->output_alpha_type == desired_type ||
1089 input->output_alpha_type == ALPHA_BLANK) {
1093 if (desired_type == ALPHA_PREMULTIPLIED) {
1094 conversion = add_node(new AlphaMultiplicationEffect());
1096 conversion = add_node(new AlphaDivisionEffect());
1098 conversion->output_alpha_type = desired_type;
1099 replace_sender(input, conversion);
1100 connect_nodes(input, conversion);
1103 // Re-sort topologically, and propagate the new information.
1104 propagate_gamma_and_color_space();
1112 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1113 output_dot(filename);
1114 assert(alpha_propagation_pass < 100);
1115 } while (found_any);
1117 for (unsigned i = 0; i < nodes.size(); ++i) {
1118 Node *node = nodes[i];
1119 if (node->disabled) {
1122 assert(node->output_alpha_type != ALPHA_INVALID);
1126 // Make so that the output is in the desired color space.
1127 void EffectChain::fix_output_color_space()
1129 Node *output = find_output_node();
1130 if (output->output_color_space != output_format.color_space) {
1131 Node *conversion = add_node(new ColorspaceConversionEffect());
1132 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1133 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1134 conversion->output_color_space = output_format.color_space;
1135 connect_nodes(output, conversion);
1137 propagate_gamma_and_color_space();
1141 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1142 void EffectChain::fix_output_alpha()
1144 Node *output = find_output_node();
1145 assert(output->output_alpha_type != ALPHA_INVALID);
1146 if (output->output_alpha_type == ALPHA_BLANK) {
1147 // No alpha output, so we don't care.
1150 if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1151 output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1152 Node *conversion = add_node(new AlphaDivisionEffect());
1153 connect_nodes(output, conversion);
1155 propagate_gamma_and_color_space();
1157 if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1158 output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1159 Node *conversion = add_node(new AlphaMultiplicationEffect());
1160 connect_nodes(output, conversion);
1162 propagate_gamma_and_color_space();
1166 bool EffectChain::node_needs_gamma_fix(Node *node)
1168 if (node->disabled) {
1172 // Small hack since the output is not an explicit node:
1173 // If we are the last node and our output is in the wrong
1174 // space compared to EffectChain's output, we need to fix it.
1175 // This will only take us to linear, but fix_output_gamma()
1176 // will come and take us to the desired output gamma
1179 // This needs to be before everything else, since it could
1180 // even apply to inputs (if they are the only effect).
1181 if (node->outgoing_links.empty() &&
1182 node->output_gamma_curve != output_format.gamma_curve &&
1183 node->output_gamma_curve != GAMMA_LINEAR) {
1187 if (node->effect->num_inputs() == 0) {
1191 // propagate_gamma_and_color_space() has already set our output
1192 // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1193 // except for GammaCompressionEffect.
1194 if (node->output_gamma_curve == GAMMA_INVALID) {
1197 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1198 assert(node->incoming_links.size() == 1);
1199 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1202 return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1205 // Very similar to fix_internal_color_spaces(), but for gamma.
1206 // There is one difference, though; before we start adding conversion nodes,
1207 // we see if we can get anything out of asking the sources to deliver
1208 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1209 // does that part, while fix_internal_gamma_by_inserting_nodes()
1210 // inserts nodes as needed afterwards.
1211 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1213 unsigned gamma_propagation_pass = 0;
1217 for (unsigned i = 0; i < nodes.size(); ++i) {
1218 Node *node = nodes[i];
1219 if (!node_needs_gamma_fix(node)) {
1223 // See if all inputs can give us linear gamma. If not, leave it.
1224 vector<Node *> nonlinear_inputs;
1225 find_all_nonlinear_inputs(node, &nonlinear_inputs);
1226 assert(!nonlinear_inputs.empty());
1229 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1230 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1231 all_ok &= input->can_output_linear_gamma();
1238 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1239 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1240 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1243 // Re-sort topologically, and propagate the new information.
1244 propagate_gamma_and_color_space();
1251 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1252 output_dot(filename);
1253 assert(gamma_propagation_pass < 100);
1254 } while (found_any);
1257 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1259 unsigned gamma_propagation_pass = 0;
1263 for (unsigned i = 0; i < nodes.size(); ++i) {
1264 Node *node = nodes[i];
1265 if (!node_needs_gamma_fix(node)) {
1269 // Special case: We could be an input and still be asked to
1270 // fix our gamma; if so, we should be the only node
1271 // (as node_needs_gamma_fix() would only return true in
1272 // for an input in that case). That means we should insert
1273 // a conversion node _after_ ourselves.
1274 if (node->incoming_links.empty()) {
1275 assert(node->outgoing_links.empty());
1276 Node *conversion = add_node(new GammaExpansionEffect());
1277 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1278 conversion->output_gamma_curve = GAMMA_LINEAR;
1279 connect_nodes(node, conversion);
1282 // If not, go through each input that is not linear gamma,
1283 // and insert a gamma conversion after it.
1284 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1285 Node *input = node->incoming_links[j];
1286 assert(input->output_gamma_curve != GAMMA_INVALID);
1287 if (input->output_gamma_curve == GAMMA_LINEAR) {
1290 Node *conversion = add_node(new GammaExpansionEffect());
1291 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1292 conversion->output_gamma_curve = GAMMA_LINEAR;
1293 replace_sender(input, conversion);
1294 connect_nodes(input, conversion);
1297 // Re-sort topologically, and propagate the new information.
1299 propagate_gamma_and_color_space();
1306 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1307 output_dot(filename);
1308 assert(gamma_propagation_pass < 100);
1309 } while (found_any);
1311 for (unsigned i = 0; i < nodes.size(); ++i) {
1312 Node *node = nodes[i];
1313 if (node->disabled) {
1316 assert(node->output_gamma_curve != GAMMA_INVALID);
1320 // Make so that the output is in the desired gamma.
1321 // Note that this assumes linear input gamma, so it might create the need
1322 // for another pass of fix_internal_gamma().
1323 void EffectChain::fix_output_gamma()
1325 Node *output = find_output_node();
1326 if (output->output_gamma_curve != output_format.gamma_curve) {
1327 Node *conversion = add_node(new GammaCompressionEffect());
1328 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1329 conversion->output_gamma_curve = output_format.gamma_curve;
1330 connect_nodes(output, conversion);
1334 // If the user has requested dither, add a DitherEffect right at the end
1335 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1336 // since dither is about the only effect that can _not_ be done in linear space.
1337 void EffectChain::add_dither_if_needed()
1339 if (num_dither_bits == 0) {
1342 Node *output = find_output_node();
1343 Node *dither = add_node(new DitherEffect());
1344 CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1345 connect_nodes(output, dither);
1347 dither_effect = dither->effect;
1350 // Find the output node. This is, simply, one that has no outgoing links.
1351 // If there are multiple ones, the graph is malformed (we do not support
1352 // multiple outputs right now).
1353 Node *EffectChain::find_output_node()
1355 vector<Node *> output_nodes;
1356 for (unsigned i = 0; i < nodes.size(); ++i) {
1357 Node *node = nodes[i];
1358 if (node->disabled) {
1361 if (node->outgoing_links.empty()) {
1362 output_nodes.push_back(node);
1365 assert(output_nodes.size() == 1);
1366 return output_nodes[0];
1369 void EffectChain::finalize()
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 // We need to keep track of which effects have already been computed,
1423 // as an effect with multiple users could otherwise be calculated
1425 map<Node *, Phase *> completed_effects;
1426 construct_phase(find_output_node(), &completed_effects);
1428 output_dot("step19-split-to-phases.dot");
1430 assert(phases[0]->inputs.empty());
1435 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1439 // Save original viewport.
1440 GLuint x = 0, y = 0;
1442 if (width == 0 && height == 0) {
1444 glGetIntegerv(GL_VIEWPORT, viewport);
1447 width = viewport[2];
1448 height = viewport[3];
1452 glDisable(GL_BLEND);
1454 glDisable(GL_DEPTH_TEST);
1456 glDepthMask(GL_FALSE);
1459 set<Phase *> generated_mipmaps;
1461 // We choose the simplest option of having one texture per output,
1462 // since otherwise this turns into an (albeit simple) register allocation problem.
1463 map<Phase *, GLuint> output_textures;
1465 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1466 Phase *phase = phases[phase_num];
1468 if (do_phase_timing) {
1469 glBeginQuery(GL_TIME_ELAPSED, phase->timer_query_object);
1471 if (phase_num == phases.size() - 1) {
1472 // Last phase goes to the output the user specified.
1473 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1475 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1476 assert(status == GL_FRAMEBUFFER_COMPLETE);
1477 glViewport(x, y, width, height);
1478 if (dither_effect != NULL) {
1479 CHECK(dither_effect->set_int("output_width", width));
1480 CHECK(dither_effect->set_int("output_height", height));
1483 execute_phase(phase, phase_num == phases.size() - 1, &output_textures, &generated_mipmaps);
1484 if (do_phase_timing) {
1485 glEndQuery(GL_TIME_ELAPSED);
1489 for (map<Phase *, GLuint>::const_iterator texture_it = output_textures.begin();
1490 texture_it != output_textures.end();
1492 resource_pool->release_2d_texture(texture_it->second);
1495 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1500 if (do_phase_timing) {
1501 // Get back the timer queries.
1502 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1503 Phase *phase = phases[phase_num];
1504 GLint available = 0;
1505 while (!available) {
1506 glGetQueryObjectiv(phase->timer_query_object, GL_QUERY_RESULT_AVAILABLE, &available);
1508 GLuint64 time_elapsed;
1509 glGetQueryObjectui64v(phase->timer_query_object, GL_QUERY_RESULT, &time_elapsed);
1510 phase->time_elapsed_ns += time_elapsed;
1511 ++phase->num_measured_iterations;
1516 void EffectChain::enable_phase_timing(bool enable)
1519 assert(movit_timer_queries_supported);
1521 this->do_phase_timing = enable;
1524 void EffectChain::reset_phase_timing()
1526 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1527 Phase *phase = phases[phase_num];
1528 phase->time_elapsed_ns = 0;
1529 phase->num_measured_iterations = 0;
1533 void EffectChain::print_phase_timing()
1535 double total_time_ms = 0.0;
1536 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1537 Phase *phase = phases[phase_num];
1538 double avg_time_ms = phase->time_elapsed_ns * 1e-6 / phase->num_measured_iterations;
1539 printf("Phase %d: %5.1f ms [", phase_num, avg_time_ms);
1540 for (unsigned effect_num = 0; effect_num < phase->effects.size(); ++effect_num) {
1541 if (effect_num != 0) {
1544 printf("%s", phase->effects[effect_num]->effect->effect_type_id().c_str());
1547 total_time_ms += avg_time_ms;
1549 printf("Total: %5.1f ms\n", total_time_ms);
1552 void EffectChain::execute_phase(Phase *phase, bool last_phase, map<Phase *, GLuint> *output_textures, set<Phase *> *generated_mipmaps)
1556 // Find a texture for this phase.
1557 inform_input_sizes(phase);
1559 find_output_size(phase);
1561 GLuint tex_num = resource_pool->create_2d_texture(GL_RGBA16F, phase->output_width, phase->output_height);
1562 output_textures->insert(make_pair(phase, tex_num));
1565 const GLuint glsl_program_num = phase->glsl_program_num;
1567 glUseProgram(glsl_program_num);
1570 // Set up RTT inputs for this phase.
1571 for (unsigned sampler = 0; sampler < phase->inputs.size(); ++sampler) {
1572 glActiveTexture(GL_TEXTURE0 + sampler);
1573 Phase *input = phase->inputs[sampler];
1574 input->output_node->bound_sampler_num = sampler;
1575 glBindTexture(GL_TEXTURE_2D, (*output_textures)[input]);
1577 if (phase->input_needs_mipmaps && generated_mipmaps->count(input) == 0) {
1578 glGenerateMipmap(GL_TEXTURE_2D);
1580 generated_mipmaps->insert(input);
1582 setup_rtt_sampler(glsl_program_num, sampler, phase->effect_ids[input->output_node], phase->input_needs_mipmaps);
1585 // And now the output. (Already set up for us if it is the last phase.)
1587 fbo = resource_pool->create_fbo((*output_textures)[phase]);
1588 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1589 glViewport(0, 0, phase->output_width, phase->output_height);
1592 // Give the required parameters to all the effects.
1593 unsigned sampler_num = phase->inputs.size();
1594 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1595 Node *node = phase->effects[i];
1596 unsigned old_sampler_num = sampler_num;
1597 node->effect->set_gl_state(glsl_program_num, phase->effect_ids[node], &sampler_num);
1600 if (node->effect->is_single_texture()) {
1601 assert(sampler_num - old_sampler_num == 1);
1602 node->bound_sampler_num = old_sampler_num;
1604 node->bound_sampler_num = -1;
1609 float vertices[] = {
1617 glGenVertexArrays(1, &vao);
1619 glBindVertexArray(vao);
1622 GLuint position_vbo = fill_vertex_attribute(glsl_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
1623 GLuint texcoord_vbo = fill_vertex_attribute(glsl_program_num, "texcoord", 2, GL_FLOAT, sizeof(vertices), vertices); // Same as vertices.
1625 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1628 cleanup_vertex_attribute(glsl_program_num, "position", position_vbo);
1629 cleanup_vertex_attribute(glsl_program_num, "texcoord", texcoord_vbo);
1634 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1635 Node *node = phase->effects[i];
1636 node->effect->clear_gl_state();
1640 resource_pool->release_fbo(fbo);
1643 glDeleteVertexArrays(1, &vao);
1647 void EffectChain::setup_rtt_sampler(GLuint glsl_program_num, int sampler_num, const string &effect_id, bool use_mipmaps)
1649 glActiveTexture(GL_TEXTURE0 + sampler_num);
1652 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1655 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1658 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1660 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1663 string texture_name = string("tex_") + effect_id;
1664 glUniform1i(glGetUniformLocation(glsl_program_num, texture_name.c_str()), sampler_num);
1668 } // namespace movit