1 #define GL_GLEXT_PROTOTYPES 1
14 #include "effect_chain.h"
15 #include "gamma_expansion_effect.h"
16 #include "gamma_compression_effect.h"
17 #include "colorspace_conversion_effect.h"
21 EffectChain::EffectChain(float aspect_nom, float aspect_denom)
22 : aspect_nom(aspect_nom),
23 aspect_denom(aspect_denom),
26 Input *EffectChain::add_input(Input *input)
28 inputs.push_back(input);
30 Node *node = add_node(input);
31 node->output_color_space = input->get_color_space();
32 node->output_gamma_curve = input->get_gamma_curve();
36 void EffectChain::add_output(const ImageFormat &format)
38 output_format = format;
41 Node *EffectChain::add_node(Effect *effect)
44 sprintf(effect_id, "eff%u", (unsigned)nodes.size());
46 Node *node = new Node;
47 node->effect = effect;
48 node->disabled = false;
49 node->effect_id = effect_id;
50 node->output_color_space = COLORSPACE_INVALID;
51 node->output_gamma_curve = GAMMA_INVALID;
53 nodes.push_back(node);
54 node_map[effect] = node;
58 void EffectChain::connect_nodes(Node *sender, Node *receiver)
60 sender->outgoing_links.push_back(receiver);
61 receiver->incoming_links.push_back(sender);
64 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
66 new_receiver->incoming_links = old_receiver->incoming_links;
67 old_receiver->incoming_links.clear();
69 for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
70 Node *sender = new_receiver->incoming_links[i];
71 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
72 if (sender->outgoing_links[j] == old_receiver) {
73 sender->outgoing_links[j] = new_receiver;
79 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
81 new_sender->outgoing_links = old_sender->outgoing_links;
82 old_sender->outgoing_links.clear();
84 for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
85 Node *receiver = new_sender->outgoing_links[i];
86 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
87 if (receiver->incoming_links[j] == old_sender) {
88 receiver->incoming_links[j] = new_sender;
94 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
96 for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
97 if (sender->outgoing_links[i] == receiver) {
98 sender->outgoing_links[i] = middle;
99 middle->incoming_links.push_back(sender);
102 for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
103 if (receiver->incoming_links[i] == sender) {
104 receiver->incoming_links[i] = middle;
105 middle->outgoing_links.push_back(receiver);
109 assert(middle->incoming_links.size() == middle->effect->num_inputs());
112 void EffectChain::find_all_nonlinear_inputs(Node *node, std::vector<Node *> *nonlinear_inputs)
114 if (node->output_gamma_curve == GAMMA_LINEAR &&
115 node->effect->effect_type_id() != "GammaCompressionEffect") {
118 if (node->effect->num_inputs() == 0) {
119 nonlinear_inputs->push_back(node);
121 assert(node->effect->num_inputs() == node->incoming_links.size());
122 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
123 find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
128 Effect *EffectChain::add_effect(Effect *effect, const std::vector<Effect *> &inputs)
130 assert(inputs.size() == effect->num_inputs());
131 Node *node = add_node(effect);
132 for (unsigned i = 0; i < inputs.size(); ++i) {
133 assert(node_map.count(inputs[i]) != 0);
134 connect_nodes(node_map[inputs[i]], node);
139 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
140 std::string replace_prefix(const std::string &text, const std::string &prefix)
145 while (start < text.size()) {
146 size_t pos = text.find("PREFIX(", start);
147 if (pos == std::string::npos) {
148 output.append(text.substr(start, std::string::npos));
152 output.append(text.substr(start, pos - start));
153 output.append(prefix);
156 pos += strlen("PREFIX(");
158 // Output stuff until we find the matching ), which we then eat.
160 size_t end_arg_pos = pos;
161 while (end_arg_pos < text.size()) {
162 if (text[end_arg_pos] == '(') {
164 } else if (text[end_arg_pos] == ')') {
172 output.append(text.substr(pos, end_arg_pos - pos));
180 Phase *EffectChain::compile_glsl_program(
181 const std::vector<Node *> &inputs,
182 const std::vector<Node *> &effects)
184 assert(!effects.empty());
186 // Deduplicate the inputs.
187 std::vector<Node *> true_inputs = inputs;
188 std::sort(true_inputs.begin(), true_inputs.end());
189 true_inputs.erase(std::unique(true_inputs.begin(), true_inputs.end()), true_inputs.end());
191 bool input_needs_mipmaps = false;
192 std::string frag_shader = read_file("header.frag");
194 // Create functions for all the texture inputs that we need.
195 for (unsigned i = 0; i < true_inputs.size(); ++i) {
196 Node *input = true_inputs[i];
198 frag_shader += std::string("uniform sampler2D tex_") + input->effect_id + ";\n";
199 frag_shader += std::string("vec4 ") + input->effect_id + "(vec2 tc) {\n";
200 frag_shader += "\treturn texture2D(tex_" + input->effect_id + ", tc);\n";
201 frag_shader += "}\n";
205 for (unsigned i = 0; i < effects.size(); ++i) {
206 Node *node = effects[i];
208 if (node->incoming_links.size() == 1) {
209 frag_shader += std::string("#define INPUT ") + node->incoming_links[0]->effect_id + "\n";
211 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
213 sprintf(buf, "#define INPUT%d %s\n", j + 1, node->incoming_links[j]->effect_id.c_str());
219 frag_shader += std::string("#define FUNCNAME ") + node->effect_id + "\n";
220 frag_shader += replace_prefix(node->effect->output_convenience_uniforms(), node->effect_id);
221 frag_shader += replace_prefix(node->effect->output_fragment_shader(), node->effect_id);
222 frag_shader += "#undef PREFIX\n";
223 frag_shader += "#undef FUNCNAME\n";
224 if (node->incoming_links.size() == 1) {
225 frag_shader += "#undef INPUT\n";
227 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
229 sprintf(buf, "#undef INPUT%d\n", j + 1);
235 input_needs_mipmaps |= node->effect->needs_mipmaps();
237 for (unsigned i = 0; i < effects.size(); ++i) {
238 Node *node = effects[i];
239 if (node->effect->num_inputs() == 0) {
240 node->effect->set_int("needs_mipmaps", input_needs_mipmaps);
243 frag_shader += std::string("#define INPUT ") + effects.back()->effect_id + "\n";
244 frag_shader.append(read_file("footer.frag"));
246 // Output shader to a temporary file, for easier debugging.
247 static int compiled_shader_num = 0;
249 sprintf(filename, "chain-%03d.frag", compiled_shader_num++);
250 FILE *fp = fopen(filename, "w");
255 fprintf(fp, "%s\n", frag_shader.c_str());
258 GLuint glsl_program_num = glCreateProgram();
259 GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
260 GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
261 glAttachShader(glsl_program_num, vs_obj);
263 glAttachShader(glsl_program_num, fs_obj);
265 glLinkProgram(glsl_program_num);
268 Phase *phase = new Phase;
269 phase->glsl_program_num = glsl_program_num;
270 phase->input_needs_mipmaps = input_needs_mipmaps;
271 phase->inputs = true_inputs;
272 phase->effects = effects;
277 // Construct GLSL programs, starting at the given effect and following
278 // the chain from there. We end a program every time we come to an effect
279 // marked as "needs texture bounce", one that is used by multiple other
280 // effects, every time an effect wants to change the output size,
281 // and of course at the end.
283 // We follow a quite simple depth-first search from the output, although
284 // without any explicit recursion.
285 void EffectChain::construct_glsl_programs(Node *output)
287 // Which effects have already been completed in this phase?
288 // We need to keep track of it, as an effect with multiple outputs
289 // could otherwise be calculate multiple times.
290 std::set<Node *> completed_effects;
292 // Effects in the current phase, as well as inputs (outputs from other phases
293 // that we depend on). Note that since we start iterating from the end,
294 // the effect list will be in the reverse order.
295 std::vector<Node *> this_phase_inputs;
296 std::vector<Node *> this_phase_effects;
298 // Effects that we have yet to calculate, but that we know should
299 // be in the current phase.
300 std::stack<Node *> effects_todo_this_phase;
302 // Effects that we have yet to calculate, but that come from other phases.
303 // We delay these until we have this phase done in its entirety,
304 // at which point we pick any of them and start a new phase from that.
305 std::stack<Node *> effects_todo_other_phases;
307 effects_todo_this_phase.push(output);
309 for ( ;; ) { // Termination condition within loop.
310 if (!effects_todo_this_phase.empty()) {
311 // OK, we have more to do this phase.
312 Node *node = effects_todo_this_phase.top();
313 effects_todo_this_phase.pop();
315 // This should currently only happen for effects that are phase outputs,
316 // and we throw those out separately below.
317 assert(completed_effects.count(node) == 0);
319 this_phase_effects.push_back(node);
320 completed_effects.insert(node);
322 // Find all the dependencies of this effect, and add them to the stack.
323 std::vector<Node *> deps = node->incoming_links;
324 assert(node->effect->num_inputs() == deps.size());
325 for (unsigned i = 0; i < deps.size(); ++i) {
326 bool start_new_phase = false;
328 // FIXME: If we sample directly from a texture, we won't need this.
329 if (node->effect->needs_texture_bounce()) {
330 start_new_phase = true;
333 if (deps[i]->outgoing_links.size() > 1) {
334 if (deps[i]->effect->num_inputs() > 0) {
335 // More than one effect uses this as the input,
336 // and it is not a texture itself.
337 // The easiest thing to do (and probably also the safest
338 // performance-wise in most cases) is to bounce it to a texture
339 // and then let the next passes read from that.
340 start_new_phase = true;
342 // For textures, we try to be slightly more clever;
343 // if none of our outputs need a bounce, we don't bounce
344 // but instead simply use the effect many times.
346 // Strictly speaking, we could bounce it for some outputs
347 // and use it directly for others, but the processing becomes
348 // somewhat simpler if the effect is only used in one such way.
349 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
350 Node *rdep = deps[i]->outgoing_links[j];
351 start_new_phase |= rdep->effect->needs_texture_bounce();
356 if (deps[i]->effect->changes_output_size()) {
357 start_new_phase = true;
360 if (start_new_phase) {
361 effects_todo_other_phases.push(deps[i]);
362 this_phase_inputs.push_back(deps[i]);
364 effects_todo_this_phase.push(deps[i]);
370 // No more effects to do this phase. Take all the ones we have,
371 // and create a GLSL program for it.
372 if (!this_phase_effects.empty()) {
373 reverse(this_phase_effects.begin(), this_phase_effects.end());
374 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
375 this_phase_effects.back()->phase = phases.back();
376 this_phase_inputs.clear();
377 this_phase_effects.clear();
379 assert(this_phase_inputs.empty());
380 assert(this_phase_effects.empty());
382 // If we have no effects left, exit.
383 if (effects_todo_other_phases.empty()) {
387 Node *node = effects_todo_other_phases.top();
388 effects_todo_other_phases.pop();
390 if (completed_effects.count(node) == 0) {
391 // Start a new phase, calculating from this effect.
392 effects_todo_this_phase.push(node);
396 // Finally, since the phases are found from the output but must be executed
397 // from the input(s), reverse them, too.
398 std::reverse(phases.begin(), phases.end());
401 void EffectChain::output_dot(const char *filename)
403 FILE *fp = fopen(filename, "w");
409 fprintf(fp, "digraph G {\n");
410 for (unsigned i = 0; i < nodes.size(); ++i) {
411 // Find out which phase this event belongs to.
413 for (unsigned j = 0; j < phases.size(); ++j) {
414 const Phase* p = phases[j];
415 if (std::find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
416 assert(in_phase == -1);
421 if (in_phase == -1) {
422 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
424 fprintf(fp, " n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
425 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
428 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
429 std::vector<std::string> labels;
431 if (nodes[i]->outgoing_links[j]->effect->needs_texture_bounce()) {
432 labels.push_back("needs_bounce");
434 if (nodes[i]->effect->changes_output_size()) {
435 labels.push_back("resize");
438 switch (nodes[i]->output_color_space) {
439 case COLORSPACE_INVALID:
440 labels.push_back("spc[invalid]");
442 case COLORSPACE_REC_601_525:
443 labels.push_back("spc[rec601-525]");
445 case COLORSPACE_REC_601_625:
446 labels.push_back("spc[rec601-625]");
452 switch (nodes[i]->output_gamma_curve) {
454 labels.push_back("gamma[invalid]");
457 labels.push_back("gamma[sRGB]");
459 case GAMMA_REC_601: // and GAMMA_REC_709
460 labels.push_back("gamma[rec601/709]");
466 if (labels.empty()) {
467 fprintf(fp, " n%ld -> n%ld;\n", (long)nodes[i], (long)nodes[i]->outgoing_links[j]);
469 std::string label = labels[0];
470 for (unsigned k = 1; k < labels.size(); ++k) {
471 label += ", " + labels[k];
473 fprintf(fp, " n%ld -> n%ld [label=\"%s\"];\n", (long)nodes[i], (long)nodes[i]->outgoing_links[j], label.c_str());
482 unsigned EffectChain::fit_rectangle_to_aspect(unsigned width, unsigned height)
484 if (float(width) * aspect_denom >= float(height) * aspect_nom) {
485 // Same aspect, or W/H > aspect (image is wider than the frame).
486 // In either case, keep width.
489 // W/H < aspect (image is taller than the frame), so keep height,
490 // and adjust width correspondingly.
491 return lrintf(height * aspect_nom / aspect_denom);
495 // Propagate input texture sizes throughout, and inform effects downstream.
496 // (Like a lot of other code, we depend on effects being in topological order.)
497 void EffectChain::inform_input_sizes(Phase *phase)
499 // All effects that have a defined size (inputs and RTT inputs)
500 // get that. Reset all others.
501 for (unsigned i = 0; i < phase->effects.size(); ++i) {
502 Node *node = phase->effects[i];
503 if (node->effect->num_inputs() == 0) {
504 Input *input = static_cast<Input *>(node->effect);
505 node->output_width = input->get_width();
506 node->output_height = input->get_height();
507 assert(node->output_width != 0);
508 assert(node->output_height != 0);
510 node->output_width = node->output_height = 0;
513 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
514 Node *input = phase->inputs[i];
515 input->output_width = input->phase->output_width;
516 input->output_height = input->phase->output_height;
517 assert(input->output_width != 0);
518 assert(input->output_height != 0);
521 // Now propagate from the inputs towards the end, and inform as we go.
522 // The rules are simple:
524 // 1. Don't touch effects that already have given sizes (ie., inputs).
525 // 2. If all of your inputs have the same size, that will be your output size.
526 // 3. Otherwise, your output size is 0x0.
527 for (unsigned i = 0; i < phase->effects.size(); ++i) {
528 Node *node = phase->effects[i];
529 if (node->effect->num_inputs() == 0) {
532 unsigned this_output_width = 0;
533 unsigned this_output_height = 0;
534 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
535 Node *input = node->incoming_links[j];
536 node->effect->inform_input_size(j, input->output_width, input->output_height);
538 this_output_width = input->output_width;
539 this_output_height = input->output_height;
540 } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
542 this_output_width = 0;
543 this_output_height = 0;
546 node->output_width = this_output_width;
547 node->output_height = this_output_height;
551 // Note: You should call inform_input_sizes() before this, as the last effect's
552 // desired output size might change based on the inputs.
553 void EffectChain::find_output_size(Phase *phase)
555 Node *output_node = phase->effects.back();
557 // If the last effect explicitly sets an output size, use that.
558 if (output_node->effect->changes_output_size()) {
559 output_node->effect->get_output_size(&phase->output_width, &phase->output_height);
563 // If not, look at the input phases and textures.
564 // We select the largest one (by fit into the current aspect).
565 unsigned best_width = 0;
566 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
567 Node *input = phase->inputs[i];
568 assert(input->phase->output_width != 0);
569 assert(input->phase->output_height != 0);
570 unsigned width = fit_rectangle_to_aspect(input->phase->output_width, input->phase->output_height);
571 if (width > best_width) {
575 for (unsigned i = 0; i < phase->effects.size(); ++i) {
576 Effect *effect = phase->effects[i]->effect;
577 if (effect->num_inputs() != 0) {
581 Input *input = static_cast<Input *>(effect);
582 unsigned width = fit_rectangle_to_aspect(input->get_width(), input->get_height());
583 if (width > best_width) {
587 assert(best_width != 0);
588 phase->output_width = best_width;
589 phase->output_height = best_width * aspect_denom / aspect_nom;
592 void EffectChain::sort_nodes_topologically()
594 std::set<Node *> visited_nodes;
595 std::vector<Node *> sorted_list;
596 for (unsigned i = 0; i < nodes.size(); ++i) {
597 if (nodes[i]->incoming_links.size() == 0) {
598 topological_sort_visit_node(nodes[i], &visited_nodes, &sorted_list);
601 reverse(sorted_list.begin(), sorted_list.end());
605 void EffectChain::topological_sort_visit_node(Node *node, std::set<Node *> *visited_nodes, std::vector<Node *> *sorted_list)
607 if (visited_nodes->count(node) != 0) {
610 visited_nodes->insert(node);
611 for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
612 topological_sort_visit_node(node->outgoing_links[i], visited_nodes, sorted_list);
614 sorted_list->push_back(node);
617 // Propagate gamma and color space information as far as we can in the graph.
618 // The rules are simple: Anything where all the inputs agree, get that as
619 // output as well. Anything else keeps having *_INVALID.
620 void EffectChain::propagate_gamma_and_color_space()
622 // We depend on going through the nodes in order.
623 sort_nodes_topologically();
625 for (unsigned i = 0; i < nodes.size(); ++i) {
626 Node *node = nodes[i];
627 if (node->disabled) {
630 assert(node->incoming_links.size() == node->effect->num_inputs());
631 if (node->incoming_links.size() == 0) {
632 assert(node->output_color_space != COLORSPACE_INVALID);
633 assert(node->output_gamma_curve != GAMMA_INVALID);
637 ColorSpace color_space = node->incoming_links[0]->output_color_space;
638 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
639 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
640 if (node->incoming_links[j]->output_color_space != color_space) {
641 color_space = COLORSPACE_INVALID;
643 if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
644 gamma_curve = GAMMA_INVALID;
648 // The conversion effects already have their outputs set correctly,
649 // so leave them alone.
650 if (node->effect->effect_type_id() != "ColorSpaceConversionEffect") {
651 node->output_color_space = color_space;
653 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
654 node->effect->effect_type_id() != "GammaExpansionEffect") {
655 node->output_gamma_curve = gamma_curve;
660 bool EffectChain::node_needs_colorspace_fix(Node *node)
662 if (node->disabled) {
665 if (node->effect->num_inputs() == 0) {
669 // propagate_gamma_and_color_space() has already set our output
670 // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
671 if (node->output_color_space == COLORSPACE_INVALID) {
674 return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
677 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
678 // the graph. Our strategy is not always optimal, but quite simple:
679 // Find an effect that's as early as possible where the inputs are of
680 // unacceptable colorspaces (that is, either different, or, if the effect only
681 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
682 // propagate the information anew, and repeat until there are no more such
684 void EffectChain::fix_internal_color_spaces()
686 unsigned colorspace_propagation_pass = 0;
690 for (unsigned i = 0; i < nodes.size(); ++i) {
691 Node *node = nodes[i];
692 if (!node_needs_colorspace_fix(node)) {
696 // Go through each input that is not sRGB, and insert
697 // a colorspace conversion before it.
698 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
699 Node *input = node->incoming_links[j];
700 assert(input->output_color_space != COLORSPACE_INVALID);
701 if (input->output_color_space == COLORSPACE_sRGB) {
704 Node *conversion = add_node(new ColorSpaceConversionEffect());
705 conversion->effect->set_int("source_space", input->output_color_space);
706 conversion->effect->set_int("destination_space", COLORSPACE_sRGB);
707 conversion->output_color_space = COLORSPACE_sRGB;
708 insert_node_between(input, conversion, node);
711 // Re-sort topologically, and propagate the new information.
712 propagate_gamma_and_color_space();
719 sprintf(filename, "step3-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
720 output_dot(filename);
721 assert(colorspace_propagation_pass < 100);
724 for (unsigned i = 0; i < nodes.size(); ++i) {
725 Node *node = nodes[i];
726 if (node->disabled) {
729 assert(node->output_color_space != COLORSPACE_INVALID);
733 // Make so that the output is in the desired color space.
734 void EffectChain::fix_output_color_space()
736 Node *output = find_output_node();
737 if (output->output_color_space != output_format.color_space) {
738 Node *conversion = add_node(new ColorSpaceConversionEffect());
739 conversion->effect->set_int("source_space", output->output_color_space);
740 conversion->effect->set_int("destination_space", output_format.color_space);
741 conversion->output_color_space = output_format.color_space;
742 connect_nodes(output, conversion);
746 bool EffectChain::node_needs_gamma_fix(Node *node)
748 if (node->disabled) {
752 // Small hack since the output is not an explicit node:
753 // If we are the last node and our output is in the wrong
754 // space compared to EffectChain's output, we need to fix it.
755 // This will only take us to linear, but fix_output_gamma()
756 // will come and take us to the desired output gamma
759 // This needs to be before everything else, since it could
760 // even apply to inputs (if they are the only effect).
761 if (node->outgoing_links.empty() &&
762 node->output_gamma_curve != output_format.gamma_curve &&
763 node->output_gamma_curve != GAMMA_LINEAR) {
767 if (node->effect->num_inputs() == 0) {
771 // propagate_gamma_and_color_space() has already set our output
772 // to GAMMA_INVALID if the inputs differ, so we can rely on that,
773 // except for GammaCompressionEffect.
774 if (node->output_gamma_curve == GAMMA_INVALID) {
777 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
778 assert(node->incoming_links.size() == 1);
779 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
782 return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
785 // Very similar to fix_internal_color_spaces(), but for gamma.
786 // There is one difference, though; before we start adding conversion nodes,
787 // we see if we can get anything out of asking the sources to deliver
788 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
789 // does that part, while fix_internal_gamma_by_inserting_nodes()
790 // inserts nodes as needed afterwards.
791 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
793 unsigned gamma_propagation_pass = 0;
797 for (unsigned i = 0; i < nodes.size(); ++i) {
798 Node *node = nodes[i];
799 if (!node_needs_gamma_fix(node)) {
803 // See if all inputs can give us linear gamma. If not, leave it.
804 std::vector<Node *> nonlinear_inputs;
805 find_all_nonlinear_inputs(node, &nonlinear_inputs);
806 assert(!nonlinear_inputs.empty());
809 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
810 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
811 all_ok &= input->can_output_linear_gamma();
818 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
819 nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1);
820 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
823 // Re-sort topologically, and propagate the new information.
824 propagate_gamma_and_color_space();
831 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
832 output_dot(filename);
833 assert(gamma_propagation_pass < 100);
837 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
839 unsigned gamma_propagation_pass = 0;
843 for (unsigned i = 0; i < nodes.size(); ++i) {
844 Node *node = nodes[i];
845 if (!node_needs_gamma_fix(node)) {
849 // Special case: We could be an input and still be asked to
850 // fix our gamma; if so, we should be the only node
851 // (as node_needs_gamma_fix() would only return true in
852 // for an input in that case). That means we should insert
853 // a conversion node _after_ ourselves.
854 if (node->incoming_links.empty()) {
855 assert(node->outgoing_links.empty());
856 Node *conversion = add_node(new GammaExpansionEffect());
857 conversion->effect->set_int("source_curve", node->output_gamma_curve);
858 conversion->output_gamma_curve = GAMMA_LINEAR;
859 connect_nodes(node, conversion);
862 // If not, go through each input that is not linear gamma,
863 // and insert a gamma conversion before it.
864 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
865 Node *input = node->incoming_links[j];
866 assert(input->output_gamma_curve != GAMMA_INVALID);
867 if (input->output_gamma_curve == GAMMA_LINEAR) {
870 Node *conversion = add_node(new GammaExpansionEffect());
871 conversion->effect->set_int("source_curve", input->output_gamma_curve);
872 conversion->output_gamma_curve = GAMMA_LINEAR;
873 insert_node_between(input, conversion, node);
876 // Re-sort topologically, and propagate the new information.
877 propagate_gamma_and_color_space();
884 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
885 output_dot(filename);
886 assert(gamma_propagation_pass < 100);
889 for (unsigned i = 0; i < nodes.size(); ++i) {
890 Node *node = nodes[i];
891 if (node->disabled) {
894 assert(node->output_gamma_curve != GAMMA_INVALID);
898 // Make so that the output is in the desired gamma.
899 // Note that this assumes linear input gamma, so it might create the need
900 // for another pass of fix_internal_gamma().
901 void EffectChain::fix_output_gamma()
903 Node *output = find_output_node();
904 if (output->output_gamma_curve != output_format.gamma_curve) {
905 Node *conversion = add_node(new GammaCompressionEffect());
906 conversion->effect->set_int("destination_curve", output_format.gamma_curve);
907 conversion->output_gamma_curve = output_format.gamma_curve;
908 connect_nodes(output, conversion);
912 // Find the output node. This is, simply, one that has no outgoing links.
913 // If there are multiple ones, the graph is malformed (we do not support
914 // multiple outputs right now).
915 Node *EffectChain::find_output_node()
917 std::vector<Node *> output_nodes;
918 for (unsigned i = 0; i < nodes.size(); ++i) {
919 Node *node = nodes[i];
920 if (node->disabled) {
923 if (node->outgoing_links.empty()) {
924 output_nodes.push_back(node);
927 assert(output_nodes.size() == 1);
928 return output_nodes[0];
931 void EffectChain::finalize()
933 // Output the graph as it is before we do any conversions on it.
934 output_dot("step0-start.dot");
936 // Give each effect in turn a chance to rewrite its own part of the graph.
937 // Note that if more effects are added as part of this, they will be
938 // picked up as part of the same for loop, since they are added at the end.
939 for (unsigned i = 0; i < nodes.size(); ++i) {
940 nodes[i]->effect->rewrite_graph(this, nodes[i]);
942 output_dot("step1-rewritten.dot");
944 propagate_gamma_and_color_space();
945 output_dot("step2-propagated.dot");
947 fix_internal_color_spaces();
948 fix_output_color_space();
949 output_dot("step4-output-colorspacefix.dot");
951 // Note that we need to fix gamma after colorspace conversion,
952 // because colorspace conversions might create needs for gamma conversions.
953 // Also, we need to run an extra pass of fix_internal_gamma() after
954 // fixing the output gamma, as we only have conversions to/from linear.
955 fix_internal_gamma_by_asking_inputs(5);
956 fix_internal_gamma_by_inserting_nodes(6);
958 output_dot("step7-output-gammafix.dot");
959 fix_internal_gamma_by_asking_inputs(8);
960 fix_internal_gamma_by_inserting_nodes(9);
962 output_dot("step10-final.dot");
964 // Construct all needed GLSL programs, starting at the output.
965 construct_glsl_programs(find_output_node());
967 output_dot("step11-split-to-phases.dot");
969 // If we have more than one phase, we need intermediate render-to-texture.
970 // Construct an FBO, and then as many textures as we need.
971 // We choose the simplest option of having one texture per output,
972 // since otherwise this turns into an (albeit simple)
973 // register allocation problem.
974 if (phases.size() > 1) {
975 glGenFramebuffers(1, &fbo);
977 for (unsigned i = 0; i < phases.size() - 1; ++i) {
978 inform_input_sizes(phases[i]);
979 find_output_size(phases[i]);
981 Node *output_node = phases[i]->effects.back();
982 glGenTextures(1, &output_node->output_texture);
984 glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
986 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
988 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
990 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[i]->output_width, phases[i]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
993 output_node->output_texture_width = phases[i]->output_width;
994 output_node->output_texture_height = phases[i]->output_height;
996 inform_input_sizes(phases.back());
999 for (unsigned i = 0; i < inputs.size(); ++i) {
1000 inputs[i]->finalize();
1003 assert(phases[0]->inputs.empty());
1008 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1012 // Save original viewport.
1013 GLuint x = 0, y = 0;
1015 if (width == 0 && height == 0) {
1017 glGetIntegerv(GL_VIEWPORT, viewport);
1020 width = viewport[2];
1021 height = viewport[3];
1025 glDisable(GL_BLEND);
1027 glDisable(GL_DEPTH_TEST);
1029 glDepthMask(GL_FALSE);
1032 glMatrixMode(GL_PROJECTION);
1034 glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
1036 glMatrixMode(GL_MODELVIEW);
1039 if (phases.size() > 1) {
1040 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1044 std::set<Node *> generated_mipmaps;
1046 for (unsigned phase = 0; phase < phases.size(); ++phase) {
1047 // See if the requested output size has changed. If so, we need to recreate
1048 // the texture (and before we start setting up inputs).
1049 inform_input_sizes(phases[phase]);
1050 if (phase != phases.size() - 1) {
1051 find_output_size(phases[phase]);
1053 Node *output_node = phases[phase]->effects.back();
1055 if (output_node->output_texture_width != phases[phase]->output_width ||
1056 output_node->output_texture_height != phases[phase]->output_height) {
1057 glActiveTexture(GL_TEXTURE0);
1059 glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
1061 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[phase]->output_width, phases[phase]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
1063 glBindTexture(GL_TEXTURE_2D, 0);
1066 output_node->output_texture_width = phases[phase]->output_width;
1067 output_node->output_texture_height = phases[phase]->output_height;
1071 glUseProgram(phases[phase]->glsl_program_num);
1074 // Set up RTT inputs for this phase.
1075 for (unsigned sampler = 0; sampler < phases[phase]->inputs.size(); ++sampler) {
1076 glActiveTexture(GL_TEXTURE0 + sampler);
1077 Node *input = phases[phase]->inputs[sampler];
1078 glBindTexture(GL_TEXTURE_2D, input->output_texture);
1080 if (phases[phase]->input_needs_mipmaps) {
1081 if (generated_mipmaps.count(input) == 0) {
1082 glGenerateMipmap(GL_TEXTURE_2D);
1084 generated_mipmaps.insert(input);
1086 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1089 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1093 std::string texture_name = std::string("tex_") + input->effect_id;
1094 glUniform1i(glGetUniformLocation(phases[phase]->glsl_program_num, texture_name.c_str()), sampler);
1098 // And now the output.
1099 if (phase == phases.size() - 1) {
1100 // Last phase goes to the output the user specified.
1101 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1103 glViewport(x, y, width, height);
1105 Node *output_node = phases[phase]->effects.back();
1106 glFramebufferTexture2D(
1108 GL_COLOR_ATTACHMENT0,
1110 output_node->output_texture,
1113 glViewport(0, 0, phases[phase]->output_width, phases[phase]->output_height);
1116 // Give the required parameters to all the effects.
1117 unsigned sampler_num = phases[phase]->inputs.size();
1118 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
1119 Node *node = phases[phase]->effects[i];
1120 node->effect->set_gl_state(phases[phase]->glsl_program_num, node->effect_id, &sampler_num);
1127 glTexCoord2f(0.0f, 0.0f);
1128 glVertex2f(0.0f, 0.0f);
1130 glTexCoord2f(1.0f, 0.0f);
1131 glVertex2f(1.0f, 0.0f);
1133 glTexCoord2f(1.0f, 1.0f);
1134 glVertex2f(1.0f, 1.0f);
1136 glTexCoord2f(0.0f, 1.0f);
1137 glVertex2f(0.0f, 1.0f);
1142 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
1143 Node *node = phases[phase]->effects[i];
1144 node->effect->clear_gl_state();