15 #include "alpha_division_effect.h"
16 #include "alpha_multiplication_effect.h"
17 #include "colorspace_conversion_effect.h"
18 #include "dither_effect.h"
20 #include "effect_chain.h"
21 #include "effect_util.h"
22 #include "gamma_compression_effect.h"
23 #include "gamma_expansion_effect.h"
26 #include "resource_pool.h"
28 #include "ycbcr_conversion_effect.h"
30 using namespace Eigen;
37 // An effect whose only purpose is to sit in a phase on its own and take the
38 // texture output from a compute shader and display it to the normal backbuffer
39 // (or any FBO). That phase can be skipped when rendering using render_to_textures().
40 class ComputeShaderOutputDisplayEffect : public Effect {
42 ComputeShaderOutputDisplayEffect() {}
43 string effect_type_id() const override { return "ComputeShaderOutputDisplayEffect"; }
44 string output_fragment_shader() override { return read_file("identity.frag"); }
45 bool needs_texture_bounce() const override { return true; }
50 EffectChain::EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool)
51 : aspect_nom(aspect_nom),
52 aspect_denom(aspect_denom),
53 output_color_rgba(false),
54 num_output_color_ycbcr(0),
55 dither_effect(nullptr),
56 ycbcr_conversion_effect_node(nullptr),
57 intermediate_format(GL_RGBA16F),
58 intermediate_transformation(NO_FRAMEBUFFER_TRANSFORMATION),
60 output_origin(OUTPUT_ORIGIN_BOTTOM_LEFT),
62 resource_pool(resource_pool),
63 do_phase_timing(false) {
64 if (resource_pool == nullptr) {
65 this->resource_pool = new ResourcePool();
66 owns_resource_pool = true;
68 owns_resource_pool = false;
71 // Generate a VBO with some data in (shared position and texture coordinate data).
77 vbo = generate_vbo(2, GL_FLOAT, sizeof(vertices), vertices);
80 EffectChain::~EffectChain()
82 for (unsigned i = 0; i < nodes.size(); ++i) {
83 delete nodes[i]->effect;
86 for (unsigned i = 0; i < phases.size(); ++i) {
87 resource_pool->release_glsl_program(phases[i]->glsl_program_num);
90 if (owns_resource_pool) {
93 glDeleteBuffers(1, &vbo);
97 Input *EffectChain::add_input(Input *input)
100 inputs.push_back(input);
105 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
108 assert(!output_color_rgba);
109 output_format = format;
110 output_alpha_format = alpha_format;
111 output_color_rgba = true;
114 void EffectChain::add_ycbcr_output(const ImageFormat &format, OutputAlphaFormat alpha_format,
115 const YCbCrFormat &ycbcr_format, YCbCrOutputSplitting output_splitting,
119 assert(num_output_color_ycbcr < 2);
120 output_format = format;
121 output_alpha_format = alpha_format;
123 if (num_output_color_ycbcr == 1) {
124 // Check that the format is the same.
125 assert(output_ycbcr_format.luma_coefficients == ycbcr_format.luma_coefficients);
126 assert(output_ycbcr_format.full_range == ycbcr_format.full_range);
127 assert(output_ycbcr_format.num_levels == ycbcr_format.num_levels);
128 assert(output_ycbcr_format.chroma_subsampling_x == 1);
129 assert(output_ycbcr_format.chroma_subsampling_y == 1);
130 assert(output_ycbcr_type == output_type);
132 output_ycbcr_format = ycbcr_format;
133 output_ycbcr_type = output_type;
135 output_ycbcr_splitting[num_output_color_ycbcr++] = output_splitting;
137 assert(ycbcr_format.chroma_subsampling_x == 1);
138 assert(ycbcr_format.chroma_subsampling_y == 1);
141 void EffectChain::change_ycbcr_output_format(const YCbCrFormat &ycbcr_format)
143 assert(num_output_color_ycbcr > 0);
144 assert(output_ycbcr_format.chroma_subsampling_x == 1);
145 assert(output_ycbcr_format.chroma_subsampling_y == 1);
147 output_ycbcr_format = ycbcr_format;
149 YCbCrConversionEffect *effect = (YCbCrConversionEffect *)(ycbcr_conversion_effect_node->effect);
150 effect->change_output_format(ycbcr_format);
154 Node *EffectChain::add_node(Effect *effect)
156 for (unsigned i = 0; i < nodes.size(); ++i) {
157 assert(nodes[i]->effect != effect);
160 Node *node = new Node;
161 node->effect = effect;
162 node->disabled = false;
163 node->output_color_space = COLORSPACE_INVALID;
164 node->output_gamma_curve = GAMMA_INVALID;
165 node->output_alpha_type = ALPHA_INVALID;
166 node->needs_mipmaps = Effect::DOES_NOT_NEED_MIPMAPS;
167 node->one_to_one_sampling = false;
168 node->strong_one_to_one_sampling = false;
170 nodes.push_back(node);
171 node_map[effect] = node;
172 effect->inform_added(this);
176 void EffectChain::connect_nodes(Node *sender, Node *receiver)
178 sender->outgoing_links.push_back(receiver);
179 receiver->incoming_links.push_back(sender);
182 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
184 new_receiver->incoming_links = old_receiver->incoming_links;
185 old_receiver->incoming_links.clear();
187 for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
188 Node *sender = new_receiver->incoming_links[i];
189 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
190 if (sender->outgoing_links[j] == old_receiver) {
191 sender->outgoing_links[j] = new_receiver;
197 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
199 new_sender->outgoing_links = old_sender->outgoing_links;
200 old_sender->outgoing_links.clear();
202 for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
203 Node *receiver = new_sender->outgoing_links[i];
204 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
205 if (receiver->incoming_links[j] == old_sender) {
206 receiver->incoming_links[j] = new_sender;
212 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
214 for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
215 if (sender->outgoing_links[i] == receiver) {
216 sender->outgoing_links[i] = middle;
217 middle->incoming_links.push_back(sender);
220 for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
221 if (receiver->incoming_links[i] == sender) {
222 receiver->incoming_links[i] = middle;
223 middle->outgoing_links.push_back(receiver);
227 assert(middle->incoming_links.size() == middle->effect->num_inputs());
230 GLenum EffectChain::get_input_sampler(Node *node, unsigned input_num) const
232 assert(node->effect->needs_texture_bounce());
233 assert(input_num < node->incoming_links.size());
234 assert(node->incoming_links[input_num]->bound_sampler_num >= 0);
235 assert(node->incoming_links[input_num]->bound_sampler_num < 8);
236 return GL_TEXTURE0 + node->incoming_links[input_num]->bound_sampler_num;
239 GLenum EffectChain::has_input_sampler(Node *node, unsigned input_num) const
241 assert(input_num < node->incoming_links.size());
242 return node->incoming_links[input_num]->bound_sampler_num >= 0 &&
243 node->incoming_links[input_num]->bound_sampler_num < 8;
246 void EffectChain::find_all_nonlinear_inputs(Node *node, vector<Node *> *nonlinear_inputs)
248 if (node->output_gamma_curve == GAMMA_LINEAR &&
249 node->effect->effect_type_id() != "GammaCompressionEffect") {
252 if (node->effect->num_inputs() == 0) {
253 nonlinear_inputs->push_back(node);
255 assert(node->effect->num_inputs() == node->incoming_links.size());
256 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
257 find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
262 Effect *EffectChain::add_effect(Effect *effect, const vector<Effect *> &inputs)
265 assert(inputs.size() == effect->num_inputs());
266 Node *node = add_node(effect);
267 for (unsigned i = 0; i < inputs.size(); ++i) {
268 assert(node_map.count(inputs[i]) != 0);
269 connect_nodes(node_map[inputs[i]], node);
274 // ESSL doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
275 string replace_prefix(const string &text, const string &prefix)
280 while (start < text.size()) {
281 size_t pos = text.find("PREFIX(", start);
282 if (pos == string::npos) {
283 output.append(text.substr(start, string::npos));
287 output.append(text.substr(start, pos - start));
288 output.append(prefix);
291 pos += strlen("PREFIX(");
293 // Output stuff until we find the matching ), which we then eat.
295 size_t end_arg_pos = pos;
296 while (end_arg_pos < text.size()) {
297 if (text[end_arg_pos] == '(') {
299 } else if (text[end_arg_pos] == ')') {
307 output.append(text.substr(pos, end_arg_pos - pos));
318 void extract_uniform_declarations(const vector<Uniform<T>> &effect_uniforms,
319 const string &type_specifier,
320 const string &effect_id,
321 vector<Uniform<T>> *phase_uniforms,
324 for (unsigned i = 0; i < effect_uniforms.size(); ++i) {
325 phase_uniforms->push_back(effect_uniforms[i]);
326 phase_uniforms->back().prefix = effect_id;
328 *glsl_string += string("uniform ") + type_specifier + " " + effect_id
329 + "_" + effect_uniforms[i].name + ";\n";
334 void extract_uniform_array_declarations(const vector<Uniform<T>> &effect_uniforms,
335 const string &type_specifier,
336 const string &effect_id,
337 vector<Uniform<T>> *phase_uniforms,
340 for (unsigned i = 0; i < effect_uniforms.size(); ++i) {
341 phase_uniforms->push_back(effect_uniforms[i]);
342 phase_uniforms->back().prefix = effect_id;
345 snprintf(buf, sizeof(buf), "uniform %s %s_%s[%d];\n",
346 type_specifier.c_str(), effect_id.c_str(),
347 effect_uniforms[i].name.c_str(),
348 int(effect_uniforms[i].num_values));
354 void collect_uniform_locations(GLuint glsl_program_num, vector<Uniform<T>> *phase_uniforms)
356 for (unsigned i = 0; i < phase_uniforms->size(); ++i) {
357 Uniform<T> &uniform = (*phase_uniforms)[i];
358 uniform.location = get_uniform_location(glsl_program_num, uniform.prefix, uniform.name);
364 void EffectChain::compile_glsl_program(Phase *phase)
366 string frag_shader_header;
367 if (phase->is_compute_shader) {
368 frag_shader_header = read_file("header.comp");
370 frag_shader_header = read_version_dependent_file("header", "frag");
372 string frag_shader = "";
374 // Create functions and uniforms for all the texture inputs that we need.
375 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
376 Node *input = phase->inputs[i]->output_node;
378 sprintf(effect_id, "in%u", i);
379 phase->effect_ids.insert(make_pair(make_pair(input, IN_ANOTHER_PHASE), effect_id));
381 frag_shader += string("uniform sampler2D tex_") + effect_id + ";\n";
382 frag_shader += string("vec4 ") + effect_id + "(vec2 tc) {\n";
383 frag_shader += "\tvec4 tmp = tex2D(tex_" + string(effect_id) + ", tc);\n";
385 if (intermediate_transformation == SQUARE_ROOT_FRAMEBUFFER_TRANSFORMATION &&
386 phase->inputs[i]->output_node->output_gamma_curve == GAMMA_LINEAR) {
387 frag_shader += "\ttmp.rgb *= tmp.rgb;\n";
390 frag_shader += "\treturn tmp;\n";
391 frag_shader += "}\n";
394 Uniform<int> uniform;
395 uniform.name = effect_id;
396 uniform.value = &phase->input_samplers[i];
397 uniform.prefix = "tex";
398 uniform.num_values = 1;
399 uniform.location = -1;
400 phase->uniforms_sampler2d.push_back(uniform);
403 // Give each effect in the phase its own ID.
404 for (unsigned i = 0; i < phase->effects.size(); ++i) {
405 Node *node = phase->effects[i];
407 sprintf(effect_id, "eff%u", i);
408 bool inserted = phase->effect_ids.insert(make_pair(make_pair(node, IN_SAME_PHASE), effect_id)).second;
412 for (unsigned i = 0; i < phase->effects.size(); ++i) {
413 Node *node = phase->effects[i];
414 const string effect_id = phase->effect_ids[make_pair(node, IN_SAME_PHASE)];
415 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
416 if (node->incoming_links.size() == 1) {
417 frag_shader += "#define INPUT";
420 sprintf(buf, "#define INPUT%d", j + 1);
424 Node *input = node->incoming_links[j];
425 NodeLinkType link_type = node->incoming_link_type[j];
427 input->effect->is_compute_shader() &&
428 node->incoming_link_type[j] == IN_SAME_PHASE) {
429 // First effect after the compute shader reads the value
430 // that cs_output() wrote to a global variable,
431 // ignoring the tc (since all such effects have to be
432 // strong one-to-one).
433 frag_shader += "(tc) CS_OUTPUT_VAL\n";
435 frag_shader += string(" ") + phase->effect_ids[make_pair(input, link_type)] + "\n";
440 frag_shader += string("#define FUNCNAME ") + effect_id + "\n";
441 if (node->effect->is_compute_shader()) {
442 frag_shader += string("#define NORMALIZE_TEXTURE_COORDS(tc) ((tc) * ") + effect_id + "_inv_output_size + " + effect_id + "_output_texcoord_adjust)\n";
444 frag_shader += replace_prefix(node->effect->output_fragment_shader(), effect_id);
445 frag_shader += "#undef FUNCNAME\n";
446 if (node->incoming_links.size() == 1) {
447 frag_shader += "#undef INPUT\n";
449 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
451 sprintf(buf, "#undef INPUT%d\n", j + 1);
457 if (phase->is_compute_shader) {
458 frag_shader += string("#define INPUT ") + phase->effect_ids[make_pair(phase->compute_shader_node, IN_SAME_PHASE)] + "\n";
459 if (phase->compute_shader_node == phase->effects.back()) {
460 // No postprocessing.
461 frag_shader += "#define CS_POSTPROC(tc) CS_OUTPUT_VAL\n";
463 frag_shader += string("#define CS_POSTPROC ") + phase->effect_ids[make_pair(phase->effects.back(), IN_SAME_PHASE)] + "\n";
466 frag_shader += string("#define INPUT ") + phase->effect_ids[make_pair(phase->effects.back(), IN_SAME_PHASE)] + "\n";
469 // If we're the last phase, add the right #defines for Y'CbCr multi-output as needed.
470 vector<string> frag_shader_outputs; // In order.
471 if (phase->output_node->outgoing_links.empty() && num_output_color_ycbcr > 0) {
472 switch (output_ycbcr_splitting[0]) {
473 case YCBCR_OUTPUT_INTERLEAVED:
475 frag_shader_outputs.push_back("FragColor");
477 case YCBCR_OUTPUT_SPLIT_Y_AND_CBCR:
478 frag_shader += "#define YCBCR_OUTPUT_SPLIT_Y_AND_CBCR 1\n";
479 frag_shader_outputs.push_back("Y");
480 frag_shader_outputs.push_back("Chroma");
482 case YCBCR_OUTPUT_PLANAR:
483 frag_shader += "#define YCBCR_OUTPUT_PLANAR 1\n";
484 frag_shader_outputs.push_back("Y");
485 frag_shader_outputs.push_back("Cb");
486 frag_shader_outputs.push_back("Cr");
492 if (num_output_color_ycbcr > 1) {
493 switch (output_ycbcr_splitting[1]) {
494 case YCBCR_OUTPUT_INTERLEAVED:
495 frag_shader += "#define SECOND_YCBCR_OUTPUT_INTERLEAVED 1\n";
496 frag_shader_outputs.push_back("YCbCr2");
498 case YCBCR_OUTPUT_SPLIT_Y_AND_CBCR:
499 frag_shader += "#define SECOND_YCBCR_OUTPUT_SPLIT_Y_AND_CBCR 1\n";
500 frag_shader_outputs.push_back("Y2");
501 frag_shader_outputs.push_back("Chroma2");
503 case YCBCR_OUTPUT_PLANAR:
504 frag_shader += "#define SECOND_YCBCR_OUTPUT_PLANAR 1\n";
505 frag_shader_outputs.push_back("Y2");
506 frag_shader_outputs.push_back("Cb2");
507 frag_shader_outputs.push_back("Cr2");
514 if (output_color_rgba) {
515 // Note: Needs to come in the header, because not only the
516 // output needs to see it (YCbCrConversionEffect and DitherEffect
518 frag_shader_header += "#define YCBCR_ALSO_OUTPUT_RGBA 1\n";
519 frag_shader_outputs.push_back("RGBA");
523 // If we're bouncing to a temporary texture, signal transformation if desired.
524 if (!phase->output_node->outgoing_links.empty()) {
525 if (intermediate_transformation == SQUARE_ROOT_FRAMEBUFFER_TRANSFORMATION &&
526 phase->output_node->output_gamma_curve == GAMMA_LINEAR) {
527 frag_shader += "#define SQUARE_ROOT_TRANSFORMATION 1\n";
531 if (phase->is_compute_shader) {
532 frag_shader.append(read_file("footer.comp"));
533 phase->compute_shader_node->effect->register_uniform_ivec2("output_size", phase->uniform_output_size);
534 phase->compute_shader_node->effect->register_uniform_vec2("inv_output_size", (float *)&phase->inv_output_size);
535 phase->compute_shader_node->effect->register_uniform_vec2("output_texcoord_adjust", (float *)&phase->output_texcoord_adjust);
537 frag_shader.append(read_file("footer.frag"));
540 // Collect uniforms from all effects and output them. Note that this needs
541 // to happen after output_fragment_shader(), even though the uniforms come
542 // before in the output source, since output_fragment_shader() is allowed
543 // to register new uniforms (e.g. arrays that are of unknown length until
544 // finalization time).
545 // TODO: Make a uniform block for platforms that support it.
546 string frag_shader_uniforms = "";
547 for (unsigned i = 0; i < phase->effects.size(); ++i) {
548 Node *node = phase->effects[i];
549 Effect *effect = node->effect;
550 const string effect_id = phase->effect_ids[make_pair(node, IN_SAME_PHASE)];
551 extract_uniform_declarations(effect->uniforms_image2d, "image2D", effect_id, &phase->uniforms_image2d, &frag_shader_uniforms);
552 extract_uniform_declarations(effect->uniforms_sampler2d, "sampler2D", effect_id, &phase->uniforms_sampler2d, &frag_shader_uniforms);
553 extract_uniform_declarations(effect->uniforms_bool, "bool", effect_id, &phase->uniforms_bool, &frag_shader_uniforms);
554 extract_uniform_declarations(effect->uniforms_int, "int", effect_id, &phase->uniforms_int, &frag_shader_uniforms);
555 extract_uniform_declarations(effect->uniforms_ivec2, "ivec2", effect_id, &phase->uniforms_ivec2, &frag_shader_uniforms);
556 extract_uniform_declarations(effect->uniforms_float, "float", effect_id, &phase->uniforms_float, &frag_shader_uniforms);
557 extract_uniform_declarations(effect->uniforms_vec2, "vec2", effect_id, &phase->uniforms_vec2, &frag_shader_uniforms);
558 extract_uniform_declarations(effect->uniforms_vec3, "vec3", effect_id, &phase->uniforms_vec3, &frag_shader_uniforms);
559 extract_uniform_declarations(effect->uniforms_vec4, "vec4", effect_id, &phase->uniforms_vec4, &frag_shader_uniforms);
560 extract_uniform_array_declarations(effect->uniforms_float_array, "float", effect_id, &phase->uniforms_float, &frag_shader_uniforms);
561 extract_uniform_array_declarations(effect->uniforms_vec2_array, "vec2", effect_id, &phase->uniforms_vec2, &frag_shader_uniforms);
562 extract_uniform_array_declarations(effect->uniforms_vec3_array, "vec3", effect_id, &phase->uniforms_vec3, &frag_shader_uniforms);
563 extract_uniform_array_declarations(effect->uniforms_vec4_array, "vec4", effect_id, &phase->uniforms_vec4, &frag_shader_uniforms);
564 extract_uniform_declarations(effect->uniforms_mat3, "mat3", effect_id, &phase->uniforms_mat3, &frag_shader_uniforms);
567 string vert_shader = read_version_dependent_file("vs", "vert");
569 // If we're the last phase and need to flip the picture to compensate for
570 // the origin, tell the vertex or compute shader so.
572 if (has_dummy_effect) {
573 is_last_phase = (phase->output_node->outgoing_links.size() == 1 &&
574 phase->output_node->outgoing_links[0]->effect->effect_type_id() == "ComputeShaderOutputDisplayEffect");
576 is_last_phase = phase->output_node->outgoing_links.empty();
578 if (is_last_phase && output_origin == OUTPUT_ORIGIN_TOP_LEFT) {
579 if (phase->is_compute_shader) {
580 frag_shader_header += "#define FLIP_ORIGIN 1\n";
582 const string needle = "#define FLIP_ORIGIN 0";
583 size_t pos = vert_shader.find(needle);
584 assert(pos != string::npos);
586 vert_shader[pos + needle.size() - 1] = '1';
590 frag_shader = frag_shader_header + frag_shader_uniforms + frag_shader;
592 if (phase->is_compute_shader) {
593 phase->glsl_program_num = resource_pool->compile_glsl_compute_program(frag_shader);
595 Uniform<int> uniform;
596 uniform.name = "outbuf";
597 uniform.value = &phase->outbuf_image_unit;
598 uniform.prefix = "tex";
599 uniform.num_values = 1;
600 uniform.location = -1;
601 phase->uniforms_image2d.push_back(uniform);
603 phase->glsl_program_num = resource_pool->compile_glsl_program(vert_shader, frag_shader, frag_shader_outputs);
605 GLint position_attribute_index = glGetAttribLocation(phase->glsl_program_num, "position");
606 GLint texcoord_attribute_index = glGetAttribLocation(phase->glsl_program_num, "texcoord");
607 if (position_attribute_index != -1) {
608 phase->attribute_indexes.insert(position_attribute_index);
610 if (texcoord_attribute_index != -1) {
611 phase->attribute_indexes.insert(texcoord_attribute_index);
614 // Collect the resulting location numbers for each uniform.
615 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_image2d);
616 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_sampler2d);
617 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_bool);
618 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_int);
619 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_ivec2);
620 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_float);
621 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec2);
622 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec3);
623 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec4);
624 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_mat3);
627 // Construct GLSL programs, starting at the given effect and following
628 // the chain from there. We end a program every time we come to an effect
629 // marked as "needs texture bounce", one that is used by multiple other
630 // effects, every time we need to bounce due to output size change
631 // (not all size changes require ending), and of course at the end.
633 // We follow a quite simple depth-first search from the output, although
634 // without recursing explicitly within each phase.
635 Phase *EffectChain::construct_phase(Node *output, map<Node *, Phase *> *completed_effects)
637 if (completed_effects->count(output)) {
638 return (*completed_effects)[output];
641 Phase *phase = new Phase;
642 phase->output_node = output;
643 phase->is_compute_shader = false;
644 phase->compute_shader_node = nullptr;
646 // If the output effect has one-to-one sampling, we try to trace this
647 // status down through the dependency chain. This is important in case
648 // we hit an effect that changes output size (and not sets a virtual
649 // output size); if we have one-to-one sampling, we don't have to break
651 output->one_to_one_sampling = output->effect->one_to_one_sampling();
652 output->strong_one_to_one_sampling = output->effect->strong_one_to_one_sampling();
654 // Effects that we have yet to calculate, but that we know should
655 // be in the current phase.
656 stack<Node *> effects_todo_this_phase;
657 effects_todo_this_phase.push(output);
659 while (!effects_todo_this_phase.empty()) {
660 Node *node = effects_todo_this_phase.top();
661 effects_todo_this_phase.pop();
663 assert(node->effect->one_to_one_sampling() >= node->effect->strong_one_to_one_sampling());
665 if (node->effect->needs_mipmaps() != Effect::DOES_NOT_NEED_MIPMAPS) {
666 // Can't have incompatible requirements imposed on us from a dependent effect;
667 // if so, it should have started a new phase instead.
668 assert(node->needs_mipmaps == Effect::DOES_NOT_NEED_MIPMAPS ||
669 node->needs_mipmaps == node->effect->needs_mipmaps());
670 node->needs_mipmaps = node->effect->needs_mipmaps();
673 // This should currently only happen for effects that are inputs
674 // (either true inputs or phase outputs). We special-case inputs,
675 // and then deduplicate phase outputs below.
676 if (node->effect->num_inputs() == 0) {
677 if (find(phase->effects.begin(), phase->effects.end(), node) != phase->effects.end()) {
681 assert(completed_effects->count(node) == 0);
684 phase->effects.push_back(node);
685 if (node->effect->is_compute_shader()) {
686 assert(phase->compute_shader_node == nullptr ||
687 phase->compute_shader_node == node);
688 phase->is_compute_shader = true;
689 phase->compute_shader_node = node;
692 // Find all the dependencies of this effect, and add them to the stack.
693 vector<Node *> deps = node->incoming_links;
694 assert(node->effect->num_inputs() == deps.size());
695 for (unsigned i = 0; i < deps.size(); ++i) {
696 bool start_new_phase = false;
698 if (node->effect->needs_texture_bounce() &&
699 !deps[i]->effect->is_single_texture() &&
700 !deps[i]->effect->override_disable_bounce()) {
701 start_new_phase = true;
704 // Propagate information about needing mipmaps down the chain,
705 // breaking the phase if we notice an incompatibility.
707 // Note that we cannot do this propagation as a normal pass,
708 // because it needs information about where the phases end
709 // (we should not propagate the flag across phases).
710 if (node->needs_mipmaps != Effect::DOES_NOT_NEED_MIPMAPS) {
711 // The node can have a value set (ie. not DOES_NOT_NEED_MIPMAPS)
712 // if we have diamonds in the graph; if so, choose that.
713 // If not, the effect on the node can also decide (this is the
714 // more common case).
715 Effect::MipmapRequirements dep_mipmaps = deps[i]->needs_mipmaps;
716 if (dep_mipmaps == Effect::DOES_NOT_NEED_MIPMAPS) {
717 if (deps[i]->effect->num_inputs() == 0) {
718 Input *input = static_cast<Input *>(deps[i]->effect);
719 dep_mipmaps = input->can_supply_mipmaps() ? Effect::DOES_NOT_NEED_MIPMAPS : Effect::CANNOT_ACCEPT_MIPMAPS;
721 dep_mipmaps = deps[i]->effect->needs_mipmaps();
724 if (dep_mipmaps == Effect::DOES_NOT_NEED_MIPMAPS) {
725 deps[i]->needs_mipmaps = node->needs_mipmaps;
726 } else if (dep_mipmaps != node->needs_mipmaps) {
727 // The dependency cannot supply our mipmap demands
728 // (either because it's an input that can't do mipmaps,
729 // or because there's a conflict between mipmap-needing
730 // and mipmap-refusing effects somewhere in the graph),
731 // so they cannot be in the same phase.
732 start_new_phase = true;
736 if (deps[i]->outgoing_links.size() > 1) {
737 if (!deps[i]->effect->is_single_texture()) {
738 // More than one effect uses this as the input,
739 // and it is not a texture itself.
740 // The easiest thing to do (and probably also the safest
741 // performance-wise in most cases) is to bounce it to a texture
742 // and then let the next passes read from that.
743 start_new_phase = true;
745 assert(deps[i]->effect->num_inputs() == 0);
747 // For textures, we try to be slightly more clever;
748 // if none of our outputs need a bounce, we don't bounce
749 // but instead simply use the effect many times.
751 // Strictly speaking, we could bounce it for some outputs
752 // and use it directly for others, but the processing becomes
753 // somewhat simpler if the effect is only used in one such way.
754 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
755 Node *rdep = deps[i]->outgoing_links[j];
756 start_new_phase |= rdep->effect->needs_texture_bounce();
761 if (deps[i]->effect->is_compute_shader()) {
762 if (phase->is_compute_shader) {
763 // Only one compute shader per phase.
764 start_new_phase = true;
765 } else if (!node->strong_one_to_one_sampling) {
766 // If all nodes so far are strong one-to-one, we can put them after
767 // the compute shader (ie., process them on the output).
768 start_new_phase = true;
770 phase->is_compute_shader = true;
771 phase->compute_shader_node = deps[i];
773 } else if (deps[i]->effect->sets_virtual_output_size()) {
774 assert(deps[i]->effect->changes_output_size());
775 // If the next effect sets a virtual size to rely on OpenGL's
776 // bilinear sampling, we'll really need to break the phase here.
777 start_new_phase = true;
778 } else if (deps[i]->effect->changes_output_size() && !node->one_to_one_sampling) {
779 // If the next effect changes size and we don't have one-to-one sampling,
780 // we also need to break here.
781 start_new_phase = true;
784 if (start_new_phase) {
785 phase->inputs.push_back(construct_phase(deps[i], completed_effects));
787 effects_todo_this_phase.push(deps[i]);
789 // Propagate the one-to-one status down through the dependency.
790 deps[i]->one_to_one_sampling = node->one_to_one_sampling &&
791 deps[i]->effect->one_to_one_sampling();
792 deps[i]->strong_one_to_one_sampling = node->strong_one_to_one_sampling &&
793 deps[i]->effect->strong_one_to_one_sampling();
796 node->incoming_link_type.push_back(start_new_phase ? IN_ANOTHER_PHASE : IN_SAME_PHASE);
800 // No more effects to do this phase. Take all the ones we have,
801 // and create a GLSL program for it.
802 assert(!phase->effects.empty());
804 // Deduplicate the inputs, but don't change the ordering e.g. by sorting;
805 // that would be nondeterministic and thus reduce cacheability.
806 // TODO: Make this even more deterministic.
807 vector<Phase *> dedup_inputs;
808 set<Phase *> seen_inputs;
809 for (size_t i = 0; i < phase->inputs.size(); ++i) {
810 if (seen_inputs.insert(phase->inputs[i]).second) {
811 dedup_inputs.push_back(phase->inputs[i]);
814 swap(phase->inputs, dedup_inputs);
816 // Allocate samplers for each input.
817 phase->input_samplers.resize(phase->inputs.size());
819 // We added the effects from the output and back, but we need to output
820 // them in topological sort order in the shader.
821 phase->effects = topological_sort(phase->effects);
823 // Figure out if we need mipmaps or not, and if so, tell the inputs that.
824 // (RTT inputs have different logic, which is checked in execute_phase().)
825 for (unsigned i = 0; i < phase->effects.size(); ++i) {
826 Node *node = phase->effects[i];
827 if (node->effect->num_inputs() == 0) {
828 Input *input = static_cast<Input *>(node->effect);
829 assert(node->needs_mipmaps != Effect::NEEDS_MIPMAPS || input->can_supply_mipmaps());
830 CHECK(input->set_int("needs_mipmaps", node->needs_mipmaps == Effect::NEEDS_MIPMAPS));
834 // Tell each node which phase it ended up in, so that the unit test
835 // can check that the phases were split in the right place.
836 // Note that this ignores that effects may be part of multiple phases;
837 // if the unit tests need to test such cases, we'll reconsider.
838 for (unsigned i = 0; i < phase->effects.size(); ++i) {
839 phase->effects[i]->containing_phase = phase;
842 // Actually make the shader for this phase.
843 compile_glsl_program(phase);
845 // Initialize timers.
846 if (movit_timer_queries_supported) {
847 phase->time_elapsed_ns = 0;
848 phase->num_measured_iterations = 0;
851 assert(completed_effects->count(output) == 0);
852 completed_effects->insert(make_pair(output, phase));
853 phases.push_back(phase);
857 void EffectChain::output_dot(const char *filename)
859 if (movit_debug_level != MOVIT_DEBUG_ON) {
863 FILE *fp = fopen(filename, "w");
869 fprintf(fp, "digraph G {\n");
870 fprintf(fp, " output [shape=box label=\"(output)\"];\n");
871 for (unsigned i = 0; i < nodes.size(); ++i) {
872 // Find out which phase this event belongs to.
873 vector<int> in_phases;
874 for (unsigned j = 0; j < phases.size(); ++j) {
875 const Phase* p = phases[j];
876 if (find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
877 in_phases.push_back(j);
881 if (in_phases.empty()) {
882 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
883 } else if (in_phases.size() == 1) {
884 fprintf(fp, " n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
885 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
886 (in_phases[0] % 8) + 1);
888 // If we had new enough Graphviz, style="wedged" would probably be ideal here.
890 fprintf(fp, " n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
891 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
892 (in_phases[0] % 8) + 1);
895 char from_node_id[256];
896 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
898 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
899 char to_node_id[256];
900 snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
902 vector<string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
903 output_dot_edge(fp, from_node_id, to_node_id, labels);
906 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
908 vector<string> labels = get_labels_for_edge(nodes[i], nullptr);
909 output_dot_edge(fp, from_node_id, "output", labels);
917 vector<string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
919 vector<string> labels;
921 if (to != nullptr && to->effect->needs_texture_bounce()) {
922 labels.push_back("needs_bounce");
924 if (from->effect->changes_output_size()) {
925 labels.push_back("resize");
928 switch (from->output_color_space) {
929 case COLORSPACE_INVALID:
930 labels.push_back("spc[invalid]");
932 case COLORSPACE_REC_601_525:
933 labels.push_back("spc[rec601-525]");
935 case COLORSPACE_REC_601_625:
936 labels.push_back("spc[rec601-625]");
942 switch (from->output_gamma_curve) {
944 labels.push_back("gamma[invalid]");
947 labels.push_back("gamma[sRGB]");
949 case GAMMA_REC_601: // and GAMMA_REC_709
950 labels.push_back("gamma[rec601/709]");
956 switch (from->output_alpha_type) {
958 labels.push_back("alpha[invalid]");
961 labels.push_back("alpha[blank]");
963 case ALPHA_POSTMULTIPLIED:
964 labels.push_back("alpha[postmult]");
973 void EffectChain::output_dot_edge(FILE *fp,
974 const string &from_node_id,
975 const string &to_node_id,
976 const vector<string> &labels)
978 if (labels.empty()) {
979 fprintf(fp, " %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
981 string label = labels[0];
982 for (unsigned k = 1; k < labels.size(); ++k) {
983 label += ", " + labels[k];
985 fprintf(fp, " %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
989 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
991 unsigned scaled_width, scaled_height;
993 if (float(width) * aspect_denom >= float(height) * aspect_nom) {
994 // Same aspect, or W/H > aspect (image is wider than the frame).
995 // In either case, keep width, and adjust height.
996 scaled_width = width;
997 scaled_height = lrintf(width * aspect_denom / aspect_nom);
999 // W/H < aspect (image is taller than the frame), so keep height,
1000 // and adjust width.
1001 scaled_width = lrintf(height * aspect_nom / aspect_denom);
1002 scaled_height = height;
1005 // We should be consistently larger or smaller then the existing choice,
1006 // since we have the same aspect.
1007 assert(!(scaled_width < *output_width && scaled_height > *output_height));
1008 assert(!(scaled_height < *output_height && scaled_width > *output_width));
1010 if (scaled_width >= *output_width && scaled_height >= *output_height) {
1011 *output_width = scaled_width;
1012 *output_height = scaled_height;
1016 // Propagate input texture sizes throughout, and inform effects downstream.
1017 // (Like a lot of other code, we depend on effects being in topological order.)
1018 void EffectChain::inform_input_sizes(Phase *phase)
1020 // All effects that have a defined size (inputs and RTT inputs)
1021 // get that. Reset all others.
1022 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1023 Node *node = phase->effects[i];
1024 if (node->effect->num_inputs() == 0) {
1025 Input *input = static_cast<Input *>(node->effect);
1026 node->output_width = input->get_width();
1027 node->output_height = input->get_height();
1028 assert(node->output_width != 0);
1029 assert(node->output_height != 0);
1031 node->output_width = node->output_height = 0;
1034 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
1035 Phase *input = phase->inputs[i];
1036 input->output_node->output_width = input->virtual_output_width;
1037 input->output_node->output_height = input->virtual_output_height;
1038 assert(input->output_node->output_width != 0);
1039 assert(input->output_node->output_height != 0);
1042 // Now propagate from the inputs towards the end, and inform as we go.
1043 // The rules are simple:
1045 // 1. Don't touch effects that already have given sizes (ie., inputs
1046 // or effects that change the output size).
1047 // 2. If all of your inputs have the same size, that will be your output size.
1048 // 3. Otherwise, your output size is 0x0.
1049 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1050 Node *node = phase->effects[i];
1051 if (node->effect->num_inputs() == 0) {
1054 unsigned this_output_width = 0;
1055 unsigned this_output_height = 0;
1056 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1057 Node *input = node->incoming_links[j];
1058 node->effect->inform_input_size(j, input->output_width, input->output_height);
1060 this_output_width = input->output_width;
1061 this_output_height = input->output_height;
1062 } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
1064 this_output_width = 0;
1065 this_output_height = 0;
1068 if (node->effect->changes_output_size()) {
1069 // We cannot call get_output_size() before we've done inform_input_size()
1071 unsigned real_width, real_height;
1072 node->effect->get_output_size(&real_width, &real_height,
1073 &node->output_width, &node->output_height);
1074 assert(node->effect->sets_virtual_output_size() ||
1075 (real_width == node->output_width &&
1076 real_height == node->output_height));
1078 node->output_width = this_output_width;
1079 node->output_height = this_output_height;
1084 // Note: You should call inform_input_sizes() before this, as the last effect's
1085 // desired output size might change based on the inputs.
1086 void EffectChain::find_output_size(Phase *phase)
1088 Node *output_node = phase->is_compute_shader ? phase->compute_shader_node : phase->effects.back();
1090 // If the last effect explicitly sets an output size, use that.
1091 if (output_node->effect->changes_output_size()) {
1092 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
1093 &phase->virtual_output_width, &phase->virtual_output_height);
1094 assert(output_node->effect->sets_virtual_output_size() ||
1095 (phase->output_width == phase->virtual_output_width &&
1096 phase->output_height == phase->virtual_output_height));
1100 // If all effects have the same size, use that.
1101 unsigned output_width = 0, output_height = 0;
1102 bool all_inputs_same_size = true;
1104 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
1105 Phase *input = phase->inputs[i];
1106 assert(input->output_width != 0);
1107 assert(input->output_height != 0);
1108 if (output_width == 0 && output_height == 0) {
1109 output_width = input->virtual_output_width;
1110 output_height = input->virtual_output_height;
1111 } else if (output_width != input->virtual_output_width ||
1112 output_height != input->virtual_output_height) {
1113 all_inputs_same_size = false;
1116 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1117 Effect *effect = phase->effects[i]->effect;
1118 if (effect->num_inputs() != 0) {
1122 Input *input = static_cast<Input *>(effect);
1123 if (output_width == 0 && output_height == 0) {
1124 output_width = input->get_width();
1125 output_height = input->get_height();
1126 } else if (output_width != input->get_width() ||
1127 output_height != input->get_height()) {
1128 all_inputs_same_size = false;
1132 if (all_inputs_same_size) {
1133 assert(output_width != 0);
1134 assert(output_height != 0);
1135 phase->virtual_output_width = phase->output_width = output_width;
1136 phase->virtual_output_height = phase->output_height = output_height;
1140 // If not, fit all the inputs into the current aspect, and select the largest one.
1143 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
1144 Phase *input = phase->inputs[i];
1145 assert(input->output_width != 0);
1146 assert(input->output_height != 0);
1147 size_rectangle_to_fit(input->output_width, input->output_height, &output_width, &output_height);
1149 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1150 Effect *effect = phase->effects[i]->effect;
1151 if (effect->num_inputs() != 0) {
1155 Input *input = static_cast<Input *>(effect);
1156 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
1158 assert(output_width != 0);
1159 assert(output_height != 0);
1160 phase->virtual_output_width = phase->output_width = output_width;
1161 phase->virtual_output_height = phase->output_height = output_height;
1164 void EffectChain::sort_all_nodes_topologically()
1166 nodes = topological_sort(nodes);
1169 vector<Node *> EffectChain::topological_sort(const vector<Node *> &nodes)
1171 set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
1172 vector<Node *> sorted_list;
1173 for (unsigned i = 0; i < nodes.size(); ++i) {
1174 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
1176 reverse(sorted_list.begin(), sorted_list.end());
1180 void EffectChain::topological_sort_visit_node(Node *node, set<Node *> *nodes_left_to_visit, vector<Node *> *sorted_list)
1182 if (nodes_left_to_visit->count(node) == 0) {
1185 nodes_left_to_visit->erase(node);
1186 for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
1187 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
1189 sorted_list->push_back(node);
1192 void EffectChain::find_color_spaces_for_inputs()
1194 for (unsigned i = 0; i < nodes.size(); ++i) {
1195 Node *node = nodes[i];
1196 if (node->disabled) {
1199 if (node->incoming_links.size() == 0) {
1200 Input *input = static_cast<Input *>(node->effect);
1201 node->output_color_space = input->get_color_space();
1202 node->output_gamma_curve = input->get_gamma_curve();
1204 Effect::AlphaHandling alpha_handling = input->alpha_handling();
1205 switch (alpha_handling) {
1206 case Effect::OUTPUT_BLANK_ALPHA:
1207 node->output_alpha_type = ALPHA_BLANK;
1209 case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
1210 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1212 case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
1213 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1215 case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
1216 case Effect::DONT_CARE_ALPHA_TYPE:
1221 if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
1222 assert(node->output_gamma_curve == GAMMA_LINEAR);
1228 // Propagate gamma and color space information as far as we can in the graph.
1229 // The rules are simple: Anything where all the inputs agree, get that as
1230 // output as well. Anything else keeps having *_INVALID.
1231 void EffectChain::propagate_gamma_and_color_space()
1233 // We depend on going through the nodes in order.
1234 sort_all_nodes_topologically();
1236 for (unsigned i = 0; i < nodes.size(); ++i) {
1237 Node *node = nodes[i];
1238 if (node->disabled) {
1241 assert(node->incoming_links.size() == node->effect->num_inputs());
1242 if (node->incoming_links.size() == 0) {
1243 assert(node->output_color_space != COLORSPACE_INVALID);
1244 assert(node->output_gamma_curve != GAMMA_INVALID);
1248 Colorspace color_space = node->incoming_links[0]->output_color_space;
1249 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
1250 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
1251 if (node->incoming_links[j]->output_color_space != color_space) {
1252 color_space = COLORSPACE_INVALID;
1254 if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
1255 gamma_curve = GAMMA_INVALID;
1259 // The conversion effects already have their outputs set correctly,
1260 // so leave them alone.
1261 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
1262 node->output_color_space = color_space;
1264 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
1265 node->effect->effect_type_id() != "GammaExpansionEffect") {
1266 node->output_gamma_curve = gamma_curve;
1271 // Propagate alpha information as far as we can in the graph.
1272 // Similar to propagate_gamma_and_color_space().
1273 void EffectChain::propagate_alpha()
1275 // We depend on going through the nodes in order.
1276 sort_all_nodes_topologically();
1278 for (unsigned i = 0; i < nodes.size(); ++i) {
1279 Node *node = nodes[i];
1280 if (node->disabled) {
1283 assert(node->incoming_links.size() == node->effect->num_inputs());
1284 if (node->incoming_links.size() == 0) {
1285 assert(node->output_alpha_type != ALPHA_INVALID);
1289 // The alpha multiplication/division effects are special cases.
1290 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
1291 assert(node->incoming_links.size() == 1);
1292 assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
1293 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1296 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
1297 assert(node->incoming_links.size() == 1);
1298 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1299 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1303 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
1304 // because they are the only one that _need_ postmultiplied alpha.
1305 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
1306 node->effect->effect_type_id() == "GammaExpansionEffect") {
1307 assert(node->incoming_links.size() == 1);
1308 if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
1309 node->output_alpha_type = ALPHA_BLANK;
1310 } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
1311 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1313 node->output_alpha_type = ALPHA_INVALID;
1318 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
1319 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
1320 // taken care of above. Rationale: Even if you could imagine
1321 // e.g. an effect that took in an image and set alpha=1.0
1322 // unconditionally, it wouldn't make any sense to have it as
1323 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
1324 // got its input pre- or postmultiplied, so it wouldn't know
1325 // whether to divide away the old alpha or not.
1326 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
1327 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1328 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
1329 alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1331 // If the node has multiple inputs, check that they are all valid and
1333 bool any_invalid = false;
1334 bool any_premultiplied = false;
1335 bool any_postmultiplied = false;
1337 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1338 switch (node->incoming_links[j]->output_alpha_type) {
1343 // Blank is good as both pre- and postmultiplied alpha,
1344 // so just ignore it.
1346 case ALPHA_PREMULTIPLIED:
1347 any_premultiplied = true;
1349 case ALPHA_POSTMULTIPLIED:
1350 any_postmultiplied = true;
1358 node->output_alpha_type = ALPHA_INVALID;
1362 // Inputs must be of the same type.
1363 if (any_premultiplied && any_postmultiplied) {
1364 node->output_alpha_type = ALPHA_INVALID;
1368 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1369 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1370 // This combination (requiring premultiplied alpha, but _not_ requiring
1371 // linear light) is illegal, since the combination of premultiplied alpha
1372 // and nonlinear inputs is meaningless.
1373 assert(node->effect->needs_linear_light());
1375 // If the effect has asked for premultiplied alpha, check that it has got it.
1376 if (any_postmultiplied) {
1377 node->output_alpha_type = ALPHA_INVALID;
1378 } else if (!any_premultiplied &&
1379 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1380 // Blank input alpha, and the effect preserves blank alpha.
1381 node->output_alpha_type = ALPHA_BLANK;
1383 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1386 // OK, all inputs are the same, and this effect is not going
1388 assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1389 if (any_premultiplied) {
1390 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1391 } else if (any_postmultiplied) {
1392 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1394 node->output_alpha_type = ALPHA_BLANK;
1400 bool EffectChain::node_needs_colorspace_fix(Node *node)
1402 if (node->disabled) {
1405 if (node->effect->num_inputs() == 0) {
1409 // propagate_gamma_and_color_space() has already set our output
1410 // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
1411 if (node->output_color_space == COLORSPACE_INVALID) {
1414 return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
1417 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
1418 // the graph. Our strategy is not always optimal, but quite simple:
1419 // Find an effect that's as early as possible where the inputs are of
1420 // unacceptable colorspaces (that is, either different, or, if the effect only
1421 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
1422 // propagate the information anew, and repeat until there are no more such
1424 void EffectChain::fix_internal_color_spaces()
1426 unsigned colorspace_propagation_pass = 0;
1430 for (unsigned i = 0; i < nodes.size(); ++i) {
1431 Node *node = nodes[i];
1432 if (!node_needs_colorspace_fix(node)) {
1436 // Go through each input that is not sRGB, and insert
1437 // a colorspace conversion after it.
1438 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1439 Node *input = node->incoming_links[j];
1440 assert(input->output_color_space != COLORSPACE_INVALID);
1441 if (input->output_color_space == COLORSPACE_sRGB) {
1444 Node *conversion = add_node(new ColorspaceConversionEffect());
1445 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1446 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1447 conversion->output_color_space = COLORSPACE_sRGB;
1448 replace_sender(input, conversion);
1449 connect_nodes(input, conversion);
1452 // Re-sort topologically, and propagate the new information.
1453 propagate_gamma_and_color_space();
1460 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1461 output_dot(filename);
1462 assert(colorspace_propagation_pass < 100);
1463 } while (found_any);
1465 for (unsigned i = 0; i < nodes.size(); ++i) {
1466 Node *node = nodes[i];
1467 if (node->disabled) {
1470 assert(node->output_color_space != COLORSPACE_INVALID);
1474 bool EffectChain::node_needs_alpha_fix(Node *node)
1476 if (node->disabled) {
1480 // propagate_alpha() has already set our output to ALPHA_INVALID if the
1481 // inputs differ or we are otherwise in mismatch, so we can rely on that.
1482 return (node->output_alpha_type == ALPHA_INVALID);
1485 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1486 // the graph. Similar to fix_internal_color_spaces().
1487 void EffectChain::fix_internal_alpha(unsigned step)
1489 unsigned alpha_propagation_pass = 0;
1493 for (unsigned i = 0; i < nodes.size(); ++i) {
1494 Node *node = nodes[i];
1495 if (!node_needs_alpha_fix(node)) {
1499 // If we need to fix up GammaExpansionEffect, then clearly something
1500 // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1502 assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1504 AlphaType desired_type = ALPHA_PREMULTIPLIED;
1506 // GammaCompressionEffect is special; it needs postmultiplied alpha.
1507 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1508 assert(node->incoming_links.size() == 1);
1509 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1510 desired_type = ALPHA_POSTMULTIPLIED;
1513 // Go through each input that is not premultiplied alpha, and insert
1514 // a conversion before it.
1515 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1516 Node *input = node->incoming_links[j];
1517 assert(input->output_alpha_type != ALPHA_INVALID);
1518 if (input->output_alpha_type == desired_type ||
1519 input->output_alpha_type == ALPHA_BLANK) {
1523 if (desired_type == ALPHA_PREMULTIPLIED) {
1524 conversion = add_node(new AlphaMultiplicationEffect());
1526 conversion = add_node(new AlphaDivisionEffect());
1528 conversion->output_alpha_type = desired_type;
1529 replace_sender(input, conversion);
1530 connect_nodes(input, conversion);
1533 // Re-sort topologically, and propagate the new information.
1534 propagate_gamma_and_color_space();
1542 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1543 output_dot(filename);
1544 assert(alpha_propagation_pass < 100);
1545 } while (found_any);
1547 for (unsigned i = 0; i < nodes.size(); ++i) {
1548 Node *node = nodes[i];
1549 if (node->disabled) {
1552 assert(node->output_alpha_type != ALPHA_INVALID);
1556 // Make so that the output is in the desired color space.
1557 void EffectChain::fix_output_color_space()
1559 Node *output = find_output_node();
1560 if (output->output_color_space != output_format.color_space) {
1561 Node *conversion = add_node(new ColorspaceConversionEffect());
1562 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1563 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1564 conversion->output_color_space = output_format.color_space;
1565 connect_nodes(output, conversion);
1567 propagate_gamma_and_color_space();
1571 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1572 void EffectChain::fix_output_alpha()
1574 Node *output = find_output_node();
1575 assert(output->output_alpha_type != ALPHA_INVALID);
1576 if (output->output_alpha_type == ALPHA_BLANK) {
1577 // No alpha output, so we don't care.
1580 if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1581 output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1582 Node *conversion = add_node(new AlphaDivisionEffect());
1583 connect_nodes(output, conversion);
1585 propagate_gamma_and_color_space();
1587 if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1588 output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1589 Node *conversion = add_node(new AlphaMultiplicationEffect());
1590 connect_nodes(output, conversion);
1592 propagate_gamma_and_color_space();
1596 bool EffectChain::node_needs_gamma_fix(Node *node)
1598 if (node->disabled) {
1602 // Small hack since the output is not an explicit node:
1603 // If we are the last node and our output is in the wrong
1604 // space compared to EffectChain's output, we need to fix it.
1605 // This will only take us to linear, but fix_output_gamma()
1606 // will come and take us to the desired output gamma
1609 // This needs to be before everything else, since it could
1610 // even apply to inputs (if they are the only effect).
1611 if (node->outgoing_links.empty() &&
1612 node->output_gamma_curve != output_format.gamma_curve &&
1613 node->output_gamma_curve != GAMMA_LINEAR) {
1617 if (node->effect->num_inputs() == 0) {
1621 // propagate_gamma_and_color_space() has already set our output
1622 // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1623 // except for GammaCompressionEffect.
1624 if (node->output_gamma_curve == GAMMA_INVALID) {
1627 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1628 assert(node->incoming_links.size() == 1);
1629 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1632 return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1635 // Very similar to fix_internal_color_spaces(), but for gamma.
1636 // There is one difference, though; before we start adding conversion nodes,
1637 // we see if we can get anything out of asking the sources to deliver
1638 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1639 // does that part, while fix_internal_gamma_by_inserting_nodes()
1640 // inserts nodes as needed afterwards.
1641 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1643 unsigned gamma_propagation_pass = 0;
1647 for (unsigned i = 0; i < nodes.size(); ++i) {
1648 Node *node = nodes[i];
1649 if (!node_needs_gamma_fix(node)) {
1653 // See if all inputs can give us linear gamma. If not, leave it.
1654 vector<Node *> nonlinear_inputs;
1655 find_all_nonlinear_inputs(node, &nonlinear_inputs);
1656 assert(!nonlinear_inputs.empty());
1659 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1660 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1661 all_ok &= input->can_output_linear_gamma();
1668 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1669 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1670 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1673 // Re-sort topologically, and propagate the new information.
1674 propagate_gamma_and_color_space();
1681 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1682 output_dot(filename);
1683 assert(gamma_propagation_pass < 100);
1684 } while (found_any);
1687 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1689 unsigned gamma_propagation_pass = 0;
1693 for (unsigned i = 0; i < nodes.size(); ++i) {
1694 Node *node = nodes[i];
1695 if (!node_needs_gamma_fix(node)) {
1699 // Special case: We could be an input and still be asked to
1700 // fix our gamma; if so, we should be the only node
1701 // (as node_needs_gamma_fix() would only return true in
1702 // for an input in that case). That means we should insert
1703 // a conversion node _after_ ourselves.
1704 if (node->incoming_links.empty()) {
1705 assert(node->outgoing_links.empty());
1706 Node *conversion = add_node(new GammaExpansionEffect());
1707 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1708 conversion->output_gamma_curve = GAMMA_LINEAR;
1709 connect_nodes(node, conversion);
1712 // If not, go through each input that is not linear gamma,
1713 // and insert a gamma conversion after it.
1714 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1715 Node *input = node->incoming_links[j];
1716 assert(input->output_gamma_curve != GAMMA_INVALID);
1717 if (input->output_gamma_curve == GAMMA_LINEAR) {
1720 Node *conversion = add_node(new GammaExpansionEffect());
1721 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1722 conversion->output_gamma_curve = GAMMA_LINEAR;
1723 replace_sender(input, conversion);
1724 connect_nodes(input, conversion);
1727 // Re-sort topologically, and propagate the new information.
1729 propagate_gamma_and_color_space();
1736 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1737 output_dot(filename);
1738 assert(gamma_propagation_pass < 100);
1739 } while (found_any);
1741 for (unsigned i = 0; i < nodes.size(); ++i) {
1742 Node *node = nodes[i];
1743 if (node->disabled) {
1746 assert(node->output_gamma_curve != GAMMA_INVALID);
1750 // Make so that the output is in the desired gamma.
1751 // Note that this assumes linear input gamma, so it might create the need
1752 // for another pass of fix_internal_gamma().
1753 void EffectChain::fix_output_gamma()
1755 Node *output = find_output_node();
1756 if (output->output_gamma_curve != output_format.gamma_curve) {
1757 Node *conversion = add_node(new GammaCompressionEffect());
1758 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1759 conversion->output_gamma_curve = output_format.gamma_curve;
1760 connect_nodes(output, conversion);
1764 // If the user has requested Y'CbCr output, we need to do this conversion
1765 // _after_ GammaCompressionEffect etc., but before dither (see below).
1766 // This is because Y'CbCr, with the exception of a special optional mode
1767 // in Rec. 2020 (which we currently don't support), is defined to work on
1768 // gamma-encoded data.
1769 void EffectChain::add_ycbcr_conversion_if_needed()
1771 assert(output_color_rgba || num_output_color_ycbcr > 0);
1772 if (num_output_color_ycbcr == 0) {
1775 Node *output = find_output_node();
1776 ycbcr_conversion_effect_node = add_node(new YCbCrConversionEffect(output_ycbcr_format, output_ycbcr_type));
1777 connect_nodes(output, ycbcr_conversion_effect_node);
1780 // If the user has requested dither, add a DitherEffect right at the end
1781 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1782 // since dither is about the only effect that can _not_ be done in linear space.
1783 void EffectChain::add_dither_if_needed()
1785 if (num_dither_bits == 0) {
1788 Node *output = find_output_node();
1789 Node *dither = add_node(new DitherEffect());
1790 CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1791 connect_nodes(output, dither);
1793 dither_effect = dither->effect;
1798 // Whether this effect will cause the phase it is in to become a compute shader phase.
1799 bool induces_compute_shader(Node *node)
1801 if (node->effect->is_compute_shader()) {
1804 if (!node->effect->strong_one_to_one_sampling()) {
1805 // This effect can't be chained after a compute shader.
1808 // If at least one of the effects we depend on is a compute shader,
1809 // one of them will be put in the same phase as us (the other ones,
1810 // if any, will be bounced).
1811 for (Node *dep : node->incoming_links) {
1812 if (induces_compute_shader(dep)) {
1821 // Compute shaders can't output to the framebuffer, so if the last
1822 // phase ends in a compute shader, add a dummy phase at the end that
1823 // only blits directly from the temporary texture.
1824 void EffectChain::add_dummy_effect_if_needed()
1826 Node *output = find_output_node();
1827 if (induces_compute_shader(output)) {
1828 Node *dummy = add_node(new ComputeShaderOutputDisplayEffect());
1829 connect_nodes(output, dummy);
1830 has_dummy_effect = true;
1834 // Find the output node. This is, simply, one that has no outgoing links.
1835 // If there are multiple ones, the graph is malformed (we do not support
1836 // multiple outputs right now).
1837 Node *EffectChain::find_output_node()
1839 vector<Node *> output_nodes;
1840 for (unsigned i = 0; i < nodes.size(); ++i) {
1841 Node *node = nodes[i];
1842 if (node->disabled) {
1845 if (node->outgoing_links.empty()) {
1846 output_nodes.push_back(node);
1849 assert(output_nodes.size() == 1);
1850 return output_nodes[0];
1853 void EffectChain::finalize()
1855 // Output the graph as it is before we do any conversions on it.
1856 output_dot("step0-start.dot");
1858 // Give each effect in turn a chance to rewrite its own part of the graph.
1859 // Note that if more effects are added as part of this, they will be
1860 // picked up as part of the same for loop, since they are added at the end.
1861 for (unsigned i = 0; i < nodes.size(); ++i) {
1862 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1864 output_dot("step1-rewritten.dot");
1866 find_color_spaces_for_inputs();
1867 output_dot("step2-input-colorspace.dot");
1870 output_dot("step3-propagated-alpha.dot");
1872 propagate_gamma_and_color_space();
1873 output_dot("step4-propagated-all.dot");
1875 fix_internal_color_spaces();
1876 fix_internal_alpha(6);
1877 fix_output_color_space();
1878 output_dot("step7-output-colorspacefix.dot");
1880 output_dot("step8-output-alphafix.dot");
1882 // Note that we need to fix gamma after colorspace conversion,
1883 // because colorspace conversions might create needs for gamma conversions.
1884 // Also, we need to run an extra pass of fix_internal_gamma() after
1885 // fixing the output gamma, as we only have conversions to/from linear,
1886 // and fix_internal_alpha() since GammaCompressionEffect needs
1887 // postmultiplied input.
1888 fix_internal_gamma_by_asking_inputs(9);
1889 fix_internal_gamma_by_inserting_nodes(10);
1891 output_dot("step11-output-gammafix.dot");
1893 output_dot("step12-output-alpha-propagated.dot");
1894 fix_internal_alpha(13);
1895 output_dot("step14-output-alpha-fixed.dot");
1896 fix_internal_gamma_by_asking_inputs(15);
1897 fix_internal_gamma_by_inserting_nodes(16);
1899 output_dot("step17-before-ycbcr.dot");
1900 add_ycbcr_conversion_if_needed();
1902 output_dot("step18-before-dither.dot");
1903 add_dither_if_needed();
1905 output_dot("step19-before-dummy-effect.dot");
1906 add_dummy_effect_if_needed();
1908 output_dot("step20-final.dot");
1910 // Construct all needed GLSL programs, starting at the output.
1911 // We need to keep track of which effects have already been computed,
1912 // as an effect with multiple users could otherwise be calculated
1914 map<Node *, Phase *> completed_effects;
1915 construct_phase(find_output_node(), &completed_effects);
1917 output_dot("step21-split-to-phases.dot");
1919 assert(phases[0]->inputs.empty());
1924 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1926 // Save original viewport.
1927 GLuint x = 0, y = 0;
1929 if (width == 0 && height == 0) {
1931 glGetIntegerv(GL_VIEWPORT, viewport);
1934 width = viewport[2];
1935 height = viewport[3];
1938 render(dest_fbo, {}, x, y, width, height);
1941 void EffectChain::render_to_texture(const vector<DestinationTexture> &destinations, unsigned width, unsigned height)
1944 assert(!destinations.empty());
1946 if (!has_dummy_effect) {
1947 // We don't end in a compute shader, so there's nothing specific for us to do.
1948 // Create an FBO for this set of textures, and just render to that.
1949 GLuint texnums[4] = { 0, 0, 0, 0 };
1950 for (unsigned i = 0; i < destinations.size() && i < 4; ++i) {
1951 texnums[i] = destinations[i].texnum;
1953 GLuint dest_fbo = resource_pool->create_fbo(texnums[0], texnums[1], texnums[2], texnums[3]);
1954 render(dest_fbo, {}, 0, 0, width, height);
1955 resource_pool->release_fbo(dest_fbo);
1957 render((GLuint)-1, destinations, 0, 0, width, height);
1961 void EffectChain::render(GLuint dest_fbo, const vector<DestinationTexture> &destinations, unsigned x, unsigned y, unsigned width, unsigned height)
1964 assert(destinations.size() <= 1);
1966 // This needs to be set anew, in case we are coming from a different context
1967 // from when we initialized.
1969 glDisable(GL_DITHER);
1972 const bool final_srgb = glIsEnabled(GL_FRAMEBUFFER_SRGB);
1974 bool current_srgb = final_srgb;
1978 glDisable(GL_BLEND);
1980 glDisable(GL_DEPTH_TEST);
1982 glDepthMask(GL_FALSE);
1985 set<Phase *> generated_mipmaps;
1987 // We keep one texture per output, but only for as long as we actually have any
1988 // phases that need it as an input. (We don't make any effort to reorder phases
1989 // to minimize the number of textures in play, as register allocation can be
1990 // complicated and we rarely have much to gain, since our graphs are typically
1992 map<Phase *, GLuint> output_textures;
1993 map<Phase *, int> ref_counts;
1994 for (Phase *phase : phases) {
1995 for (Phase *input : phase->inputs) {
1996 ++ref_counts[input];
2000 size_t num_phases = phases.size();
2001 if (destinations.empty()) {
2002 assert(dest_fbo != (GLuint)-1);
2004 assert(has_dummy_effect);
2007 assert(num_phases >= 2);
2008 assert(!phases.back()->is_compute_shader);
2009 assert(phases.back()->effects.size() == 1);
2010 assert(phases.back()->effects[0]->effect->effect_type_id() == "ComputeShaderOutputDisplayEffect");
2012 // We are rendering to a set of textures, so we can run the compute shader
2013 // directly and skip the dummy phase.
2017 for (unsigned phase_num = 0; phase_num < num_phases; ++phase_num) {
2018 Phase *phase = phases[phase_num];
2020 if (do_phase_timing) {
2021 GLuint timer_query_object;
2022 if (phase->timer_query_objects_free.empty()) {
2023 glGenQueries(1, &timer_query_object);
2025 timer_query_object = phase->timer_query_objects_free.front();
2026 phase->timer_query_objects_free.pop_front();
2028 glBeginQuery(GL_TIME_ELAPSED, timer_query_object);
2029 phase->timer_query_objects_running.push_back(timer_query_object);
2031 bool last_phase = (phase_num == num_phases - 1);
2033 // Last phase goes to the output the user specified.
2034 if (!phase->is_compute_shader) {
2035 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
2037 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
2038 assert(status == GL_FRAMEBUFFER_COMPLETE);
2039 glViewport(x, y, width, height);
2041 if (dither_effect != nullptr) {
2042 CHECK(dither_effect->set_int("output_width", width));
2043 CHECK(dither_effect->set_int("output_height", height));
2047 // Enable sRGB rendering for intermediates in case we are
2048 // rendering to an sRGB format.
2049 // TODO: Support this for compute shaders.
2050 bool needs_srgb = last_phase ? final_srgb : true;
2051 if (needs_srgb && !current_srgb) {
2052 glEnable(GL_FRAMEBUFFER_SRGB);
2054 current_srgb = true;
2055 } else if (!needs_srgb && current_srgb) {
2056 glDisable(GL_FRAMEBUFFER_SRGB);
2058 current_srgb = true;
2061 // Find a texture for this phase.
2062 inform_input_sizes(phase);
2063 find_output_size(phase);
2064 vector<DestinationTexture> phase_destinations;
2066 GLuint tex_num = resource_pool->create_2d_texture(intermediate_format, phase->output_width, phase->output_height);
2067 output_textures.insert(make_pair(phase, tex_num));
2068 phase_destinations.push_back(DestinationTexture{ tex_num, intermediate_format });
2070 // The output texture needs to have valid state to be written to by a compute shader.
2071 glActiveTexture(GL_TEXTURE0);
2073 glBindTexture(GL_TEXTURE_2D, tex_num);
2075 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2077 } else if (phase->is_compute_shader) {
2078 assert(!destinations.empty());
2079 phase_destinations = destinations;
2082 execute_phase(phase, output_textures, phase_destinations, &generated_mipmaps);
2083 if (do_phase_timing) {
2084 glEndQuery(GL_TIME_ELAPSED);
2087 // Drop any input textures we don't need anymore.
2088 for (Phase *input : phase->inputs) {
2089 assert(ref_counts[input] > 0);
2090 if (--ref_counts[input] == 0) {
2091 resource_pool->release_2d_texture(output_textures[input]);
2092 output_textures.erase(input);
2097 for (const auto &phase_and_texnum : output_textures) {
2098 resource_pool->release_2d_texture(phase_and_texnum.second);
2101 glBindFramebuffer(GL_FRAMEBUFFER, 0);
2106 glBindBuffer(GL_ARRAY_BUFFER, 0);
2108 glBindVertexArray(0);
2111 if (do_phase_timing) {
2112 // Get back the timer queries.
2113 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
2114 Phase *phase = phases[phase_num];
2115 for (auto timer_it = phase->timer_query_objects_running.cbegin();
2116 timer_it != phase->timer_query_objects_running.cend(); ) {
2117 GLint timer_query_object = *timer_it;
2119 glGetQueryObjectiv(timer_query_object, GL_QUERY_RESULT_AVAILABLE, &available);
2121 GLuint64 time_elapsed;
2122 glGetQueryObjectui64v(timer_query_object, GL_QUERY_RESULT, &time_elapsed);
2123 phase->time_elapsed_ns += time_elapsed;
2124 ++phase->num_measured_iterations;
2125 phase->timer_query_objects_free.push_back(timer_query_object);
2126 phase->timer_query_objects_running.erase(timer_it++);
2135 void EffectChain::enable_phase_timing(bool enable)
2138 assert(movit_timer_queries_supported);
2140 this->do_phase_timing = enable;
2143 void EffectChain::reset_phase_timing()
2145 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
2146 Phase *phase = phases[phase_num];
2147 phase->time_elapsed_ns = 0;
2148 phase->num_measured_iterations = 0;
2152 void EffectChain::print_phase_timing()
2154 double total_time_ms = 0.0;
2155 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
2156 Phase *phase = phases[phase_num];
2157 double avg_time_ms = phase->time_elapsed_ns * 1e-6 / phase->num_measured_iterations;
2158 printf("Phase %d: %5.1f ms [", phase_num, avg_time_ms);
2159 for (unsigned effect_num = 0; effect_num < phase->effects.size(); ++effect_num) {
2160 if (effect_num != 0) {
2163 printf("%s", phase->effects[effect_num]->effect->effect_type_id().c_str());
2166 total_time_ms += avg_time_ms;
2168 printf("Total: %5.1f ms\n", total_time_ms);
2171 void EffectChain::execute_phase(Phase *phase,
2172 const map<Phase *, GLuint> &output_textures,
2173 const vector<DestinationTexture> &destinations,
2174 set<Phase *> *generated_mipmaps)
2176 // Set up RTT inputs for this phase.
2177 for (unsigned sampler = 0; sampler < phase->inputs.size(); ++sampler) {
2178 glActiveTexture(GL_TEXTURE0 + sampler);
2179 Phase *input = phase->inputs[sampler];
2180 input->output_node->bound_sampler_num = sampler;
2181 const auto it = output_textures.find(input);
2182 assert(it != output_textures.end());
2183 glBindTexture(GL_TEXTURE_2D, it->second);
2186 // See if anything using this RTT input (in this phase) needs mipmaps.
2187 // TODO: It could be that we get conflicting logic here, if we have
2188 // multiple effects with incompatible mipmaps using the same
2189 // RTT input. However, that is obscure enough that we can deal
2190 // with it at some future point (preferably when we have
2191 // universal support for separate sampler objects!). For now,
2192 // an assert is good enough. See also the TODO at bound_sampler_num.
2193 bool any_needs_mipmaps = false, any_refuses_mipmaps = false;
2194 for (Node *node : phase->effects) {
2195 assert(node->incoming_links.size() == node->incoming_link_type.size());
2196 for (size_t i = 0; i < node->incoming_links.size(); ++i) {
2197 if (node->incoming_links[i] == input->output_node &&
2198 node->incoming_link_type[i] == IN_ANOTHER_PHASE) {
2199 if (node->needs_mipmaps == Effect::NEEDS_MIPMAPS) {
2200 any_needs_mipmaps = true;
2201 } else if (node->needs_mipmaps == Effect::CANNOT_ACCEPT_MIPMAPS) {
2202 any_refuses_mipmaps = true;
2207 assert(!(any_needs_mipmaps && any_refuses_mipmaps));
2209 if (any_needs_mipmaps && generated_mipmaps->count(input) == 0) {
2210 glGenerateMipmap(GL_TEXTURE_2D);
2212 generated_mipmaps->insert(input);
2214 setup_rtt_sampler(sampler, any_needs_mipmaps);
2215 phase->input_samplers[sampler] = sampler; // Bind the sampler to the right uniform.
2218 GLuint instance_program_num = resource_pool->use_glsl_program(phase->glsl_program_num);
2221 // And now the output.
2223 if (phase->is_compute_shader) {
2224 assert(!destinations.empty());
2226 // This is currently the only place where we use image units,
2227 // so we can always start at 0. TODO: Support multiple destinations.
2228 phase->outbuf_image_unit = 0;
2229 glBindImageTexture(phase->outbuf_image_unit, destinations[0].texnum, 0, GL_FALSE, 0, GL_WRITE_ONLY, destinations[0].format);
2231 phase->uniform_output_size[0] = phase->output_width;
2232 phase->uniform_output_size[1] = phase->output_height;
2233 phase->inv_output_size.x = 1.0f / phase->output_width;
2234 phase->inv_output_size.y = 1.0f / phase->output_height;
2235 phase->output_texcoord_adjust.x = 0.5f / phase->output_width;
2236 phase->output_texcoord_adjust.y = 0.5f / phase->output_height;
2237 } else if (!destinations.empty()) {
2238 assert(destinations.size() == 1);
2239 fbo = resource_pool->create_fbo(destinations[0].texnum);
2240 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
2241 glViewport(0, 0, phase->output_width, phase->output_height);
2244 // Give the required parameters to all the effects.
2245 unsigned sampler_num = phase->inputs.size();
2246 for (unsigned i = 0; i < phase->effects.size(); ++i) {
2247 Node *node = phase->effects[i];
2248 unsigned old_sampler_num = sampler_num;
2249 node->effect->set_gl_state(instance_program_num, phase->effect_ids[make_pair(node, IN_SAME_PHASE)], &sampler_num);
2252 if (node->effect->is_single_texture()) {
2253 assert(sampler_num - old_sampler_num == 1);
2254 node->bound_sampler_num = old_sampler_num;
2256 node->bound_sampler_num = -1;
2260 if (phase->is_compute_shader) {
2262 phase->compute_shader_node->effect->get_compute_dimensions(phase->output_width, phase->output_height, &x, &y, &z);
2264 // Uniforms need to come after set_gl_state() _and_ get_compute_dimensions(),
2265 // since they can be updated from there.
2266 setup_uniforms(phase);
2267 glDispatchCompute(x, y, z);
2269 glMemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT | GL_TEXTURE_UPDATE_BARRIER_BIT);
2272 // Uniforms need to come after set_gl_state(), since they can be updated
2274 setup_uniforms(phase);
2276 // Bind the vertex data.
2277 GLuint vao = resource_pool->create_vec2_vao(phase->attribute_indexes, vbo);
2278 glBindVertexArray(vao);
2280 glDrawArrays(GL_TRIANGLES, 0, 3);
2283 resource_pool->release_vec2_vao(vao);
2286 for (unsigned i = 0; i < phase->effects.size(); ++i) {
2287 Node *node = phase->effects[i];
2288 node->effect->clear_gl_state();
2291 resource_pool->unuse_glsl_program(instance_program_num);
2294 resource_pool->release_fbo(fbo);
2298 void EffectChain::setup_uniforms(Phase *phase)
2300 // TODO: Use UBO blocks.
2301 for (size_t i = 0; i < phase->uniforms_image2d.size(); ++i) {
2302 const Uniform<int> &uniform = phase->uniforms_image2d[i];
2303 if (uniform.location != -1) {
2304 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2307 for (size_t i = 0; i < phase->uniforms_sampler2d.size(); ++i) {
2308 const Uniform<int> &uniform = phase->uniforms_sampler2d[i];
2309 if (uniform.location != -1) {
2310 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2313 for (size_t i = 0; i < phase->uniforms_bool.size(); ++i) {
2314 const Uniform<bool> &uniform = phase->uniforms_bool[i];
2315 assert(uniform.num_values == 1);
2316 if (uniform.location != -1) {
2317 glUniform1i(uniform.location, *uniform.value);
2320 for (size_t i = 0; i < phase->uniforms_int.size(); ++i) {
2321 const Uniform<int> &uniform = phase->uniforms_int[i];
2322 if (uniform.location != -1) {
2323 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2326 for (size_t i = 0; i < phase->uniforms_ivec2.size(); ++i) {
2327 const Uniform<int> &uniform = phase->uniforms_ivec2[i];
2328 if (uniform.location != -1) {
2329 glUniform2iv(uniform.location, uniform.num_values, uniform.value);
2332 for (size_t i = 0; i < phase->uniforms_float.size(); ++i) {
2333 const Uniform<float> &uniform = phase->uniforms_float[i];
2334 if (uniform.location != -1) {
2335 glUniform1fv(uniform.location, uniform.num_values, uniform.value);
2338 for (size_t i = 0; i < phase->uniforms_vec2.size(); ++i) {
2339 const Uniform<float> &uniform = phase->uniforms_vec2[i];
2340 if (uniform.location != -1) {
2341 glUniform2fv(uniform.location, uniform.num_values, uniform.value);
2344 for (size_t i = 0; i < phase->uniforms_vec3.size(); ++i) {
2345 const Uniform<float> &uniform = phase->uniforms_vec3[i];
2346 if (uniform.location != -1) {
2347 glUniform3fv(uniform.location, uniform.num_values, uniform.value);
2350 for (size_t i = 0; i < phase->uniforms_vec4.size(); ++i) {
2351 const Uniform<float> &uniform = phase->uniforms_vec4[i];
2352 if (uniform.location != -1) {
2353 glUniform4fv(uniform.location, uniform.num_values, uniform.value);
2356 for (size_t i = 0; i < phase->uniforms_mat3.size(); ++i) {
2357 const Uniform<Matrix3d> &uniform = phase->uniforms_mat3[i];
2358 assert(uniform.num_values == 1);
2359 if (uniform.location != -1) {
2360 // Convert to float (GLSL has no double matrices).
2362 for (unsigned y = 0; y < 3; ++y) {
2363 for (unsigned x = 0; x < 3; ++x) {
2364 matrixf[y + x * 3] = (*uniform.value)(y, x);
2367 glUniformMatrix3fv(uniform.location, 1, GL_FALSE, matrixf);
2372 void EffectChain::setup_rtt_sampler(int sampler_num, bool use_mipmaps)
2374 glActiveTexture(GL_TEXTURE0 + sampler_num);
2377 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
2380 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2383 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2385 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2389 } // namespace movit