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 that does nothing.
38 class IdentityEffect : public Effect {
41 virtual string effect_type_id() const { return "IdentityEffect"; }
42 string output_fragment_shader() { return read_file("identity.frag"); }
47 EffectChain::EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool)
48 : aspect_nom(aspect_nom),
49 aspect_denom(aspect_denom),
50 output_color_rgba(false),
51 num_output_color_ycbcr(0),
52 dither_effect(nullptr),
53 ycbcr_conversion_effect_node(nullptr),
54 intermediate_format(GL_RGBA16F),
55 intermediate_transformation(NO_FRAMEBUFFER_TRANSFORMATION),
57 output_origin(OUTPUT_ORIGIN_BOTTOM_LEFT),
59 resource_pool(resource_pool),
60 do_phase_timing(false) {
61 if (resource_pool == nullptr) {
62 this->resource_pool = new ResourcePool();
63 owns_resource_pool = true;
65 owns_resource_pool = false;
68 // Generate a VBO with some data in (shared position and texture coordinate data).
74 vbo = generate_vbo(2, GL_FLOAT, sizeof(vertices), vertices);
77 EffectChain::~EffectChain()
79 for (unsigned i = 0; i < nodes.size(); ++i) {
80 delete nodes[i]->effect;
83 for (unsigned i = 0; i < phases.size(); ++i) {
84 resource_pool->release_glsl_program(phases[i]->glsl_program_num);
87 if (owns_resource_pool) {
90 glDeleteBuffers(1, &vbo);
94 Input *EffectChain::add_input(Input *input)
97 inputs.push_back(input);
102 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
105 assert(!output_color_rgba);
106 output_format = format;
107 output_alpha_format = alpha_format;
108 output_color_rgba = true;
111 void EffectChain::add_ycbcr_output(const ImageFormat &format, OutputAlphaFormat alpha_format,
112 const YCbCrFormat &ycbcr_format, YCbCrOutputSplitting output_splitting,
116 assert(num_output_color_ycbcr < 2);
117 output_format = format;
118 output_alpha_format = alpha_format;
120 if (num_output_color_ycbcr == 1) {
121 // Check that the format is the same.
122 assert(output_ycbcr_format.luma_coefficients == ycbcr_format.luma_coefficients);
123 assert(output_ycbcr_format.full_range == ycbcr_format.full_range);
124 assert(output_ycbcr_format.num_levels == ycbcr_format.num_levels);
125 assert(output_ycbcr_format.chroma_subsampling_x == 1);
126 assert(output_ycbcr_format.chroma_subsampling_y == 1);
127 assert(output_ycbcr_type == output_type);
129 output_ycbcr_format = ycbcr_format;
130 output_ycbcr_type = output_type;
132 output_ycbcr_splitting[num_output_color_ycbcr++] = output_splitting;
134 assert(ycbcr_format.chroma_subsampling_x == 1);
135 assert(ycbcr_format.chroma_subsampling_y == 1);
138 void EffectChain::change_ycbcr_output_format(const YCbCrFormat &ycbcr_format)
140 assert(num_output_color_ycbcr > 0);
141 assert(output_ycbcr_format.chroma_subsampling_x == 1);
142 assert(output_ycbcr_format.chroma_subsampling_y == 1);
144 output_ycbcr_format = ycbcr_format;
146 YCbCrConversionEffect *effect = (YCbCrConversionEffect *)(ycbcr_conversion_effect_node->effect);
147 effect->change_output_format(ycbcr_format);
151 Node *EffectChain::add_node(Effect *effect)
153 for (unsigned i = 0; i < nodes.size(); ++i) {
154 assert(nodes[i]->effect != effect);
157 Node *node = new Node;
158 node->effect = effect;
159 node->disabled = false;
160 node->output_color_space = COLORSPACE_INVALID;
161 node->output_gamma_curve = GAMMA_INVALID;
162 node->output_alpha_type = ALPHA_INVALID;
163 node->needs_mipmaps = false;
164 node->one_to_one_sampling = false;
166 nodes.push_back(node);
167 node_map[effect] = node;
168 effect->inform_added(this);
172 void EffectChain::connect_nodes(Node *sender, Node *receiver)
174 sender->outgoing_links.push_back(receiver);
175 receiver->incoming_links.push_back(sender);
178 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
180 new_receiver->incoming_links = old_receiver->incoming_links;
181 old_receiver->incoming_links.clear();
183 for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
184 Node *sender = new_receiver->incoming_links[i];
185 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
186 if (sender->outgoing_links[j] == old_receiver) {
187 sender->outgoing_links[j] = new_receiver;
193 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
195 new_sender->outgoing_links = old_sender->outgoing_links;
196 old_sender->outgoing_links.clear();
198 for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
199 Node *receiver = new_sender->outgoing_links[i];
200 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
201 if (receiver->incoming_links[j] == old_sender) {
202 receiver->incoming_links[j] = new_sender;
208 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
210 for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
211 if (sender->outgoing_links[i] == receiver) {
212 sender->outgoing_links[i] = middle;
213 middle->incoming_links.push_back(sender);
216 for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
217 if (receiver->incoming_links[i] == sender) {
218 receiver->incoming_links[i] = middle;
219 middle->outgoing_links.push_back(receiver);
223 assert(middle->incoming_links.size() == middle->effect->num_inputs());
226 GLenum EffectChain::get_input_sampler(Node *node, unsigned input_num) const
228 assert(node->effect->needs_texture_bounce());
229 assert(input_num < node->incoming_links.size());
230 assert(node->incoming_links[input_num]->bound_sampler_num >= 0);
231 assert(node->incoming_links[input_num]->bound_sampler_num < 8);
232 return GL_TEXTURE0 + node->incoming_links[input_num]->bound_sampler_num;
235 GLenum EffectChain::has_input_sampler(Node *node, unsigned input_num) const
237 assert(input_num < node->incoming_links.size());
238 return node->incoming_links[input_num]->bound_sampler_num >= 0 &&
239 node->incoming_links[input_num]->bound_sampler_num < 8;
242 void EffectChain::find_all_nonlinear_inputs(Node *node, vector<Node *> *nonlinear_inputs)
244 if (node->output_gamma_curve == GAMMA_LINEAR &&
245 node->effect->effect_type_id() != "GammaCompressionEffect") {
248 if (node->effect->num_inputs() == 0) {
249 nonlinear_inputs->push_back(node);
251 assert(node->effect->num_inputs() == node->incoming_links.size());
252 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
253 find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
258 Effect *EffectChain::add_effect(Effect *effect, const vector<Effect *> &inputs)
261 assert(inputs.size() == effect->num_inputs());
262 Node *node = add_node(effect);
263 for (unsigned i = 0; i < inputs.size(); ++i) {
264 assert(node_map.count(inputs[i]) != 0);
265 connect_nodes(node_map[inputs[i]], node);
270 // ESSL doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
271 string replace_prefix(const string &text, const string &prefix)
276 while (start < text.size()) {
277 size_t pos = text.find("PREFIX(", start);
278 if (pos == string::npos) {
279 output.append(text.substr(start, string::npos));
283 output.append(text.substr(start, pos - start));
284 output.append(prefix);
287 pos += strlen("PREFIX(");
289 // Output stuff until we find the matching ), which we then eat.
291 size_t end_arg_pos = pos;
292 while (end_arg_pos < text.size()) {
293 if (text[end_arg_pos] == '(') {
295 } else if (text[end_arg_pos] == ')') {
303 output.append(text.substr(pos, end_arg_pos - pos));
314 void extract_uniform_declarations(const vector<Uniform<T>> &effect_uniforms,
315 const string &type_specifier,
316 const string &effect_id,
317 vector<Uniform<T>> *phase_uniforms,
320 for (unsigned i = 0; i < effect_uniforms.size(); ++i) {
321 phase_uniforms->push_back(effect_uniforms[i]);
322 phase_uniforms->back().prefix = effect_id;
324 *glsl_string += string("uniform ") + type_specifier + " " + effect_id
325 + "_" + effect_uniforms[i].name + ";\n";
330 void extract_uniform_array_declarations(const vector<Uniform<T>> &effect_uniforms,
331 const string &type_specifier,
332 const string &effect_id,
333 vector<Uniform<T>> *phase_uniforms,
336 for (unsigned i = 0; i < effect_uniforms.size(); ++i) {
337 phase_uniforms->push_back(effect_uniforms[i]);
338 phase_uniforms->back().prefix = effect_id;
341 snprintf(buf, sizeof(buf), "uniform %s %s_%s[%d];\n",
342 type_specifier.c_str(), effect_id.c_str(),
343 effect_uniforms[i].name.c_str(),
344 int(effect_uniforms[i].num_values));
350 void collect_uniform_locations(GLuint glsl_program_num, vector<Uniform<T>> *phase_uniforms)
352 for (unsigned i = 0; i < phase_uniforms->size(); ++i) {
353 Uniform<T> &uniform = (*phase_uniforms)[i];
354 uniform.location = get_uniform_location(glsl_program_num, uniform.prefix, uniform.name);
360 void EffectChain::compile_glsl_program(Phase *phase)
362 string frag_shader_header;
363 if (phase->is_compute_shader) {
364 frag_shader_header = read_file("header.comp");
366 frag_shader_header = read_version_dependent_file("header", "frag");
368 string frag_shader = "";
370 // Create functions and uniforms for all the texture inputs that we need.
371 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
372 Node *input = phase->inputs[i]->output_node;
374 sprintf(effect_id, "in%u", i);
375 phase->effect_ids.insert(make_pair(input, effect_id));
377 frag_shader += string("uniform sampler2D tex_") + effect_id + ";\n";
378 frag_shader += string("vec4 ") + effect_id + "(vec2 tc) {\n";
379 frag_shader += "\tvec4 tmp = tex2D(tex_" + string(effect_id) + ", tc);\n";
381 if (intermediate_transformation == SQUARE_ROOT_FRAMEBUFFER_TRANSFORMATION &&
382 phase->inputs[i]->output_node->output_gamma_curve == GAMMA_LINEAR) {
383 frag_shader += "\ttmp.rgb *= tmp.rgb;\n";
386 frag_shader += "\treturn tmp;\n";
387 frag_shader += "}\n";
390 Uniform<int> uniform;
391 uniform.name = effect_id;
392 uniform.value = &phase->input_samplers[i];
393 uniform.prefix = "tex";
394 uniform.num_values = 1;
395 uniform.location = -1;
396 phase->uniforms_sampler2d.push_back(uniform);
399 // Give each effect in the phase its own ID.
400 for (unsigned i = 0; i < phase->effects.size(); ++i) {
401 Node *node = phase->effects[i];
403 sprintf(effect_id, "eff%u", i);
404 phase->effect_ids.insert(make_pair(node, effect_id));
407 for (unsigned i = 0; i < phase->effects.size(); ++i) {
408 Node *node = phase->effects[i];
409 const string effect_id = phase->effect_ids[node];
410 if (node->incoming_links.size() == 1) {
411 frag_shader += string("#define INPUT ") + phase->effect_ids[node->incoming_links[0]] + "\n";
413 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
415 sprintf(buf, "#define INPUT%d %s\n", j + 1, phase->effect_ids[node->incoming_links[j]].c_str());
421 frag_shader += string("#define FUNCNAME ") + effect_id + "\n";
422 if (node->effect->is_compute_shader()) {
423 frag_shader += string("#define NORMALIZE_TEXTURE_COORDS(tc) ((tc) * ") + effect_id + "_inv_output_size + " + effect_id + "_output_texcoord_adjust)\n";
425 frag_shader += replace_prefix(node->effect->output_fragment_shader(), effect_id);
426 frag_shader += "#undef FUNCNAME\n";
427 if (node->incoming_links.size() == 1) {
428 frag_shader += "#undef INPUT\n";
430 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
432 sprintf(buf, "#undef INPUT%d\n", j + 1);
438 frag_shader += string("#define INPUT ") + phase->effect_ids[phase->effects.back()] + "\n";
440 // If we're the last phase, add the right #defines for Y'CbCr multi-output as needed.
441 vector<string> frag_shader_outputs; // In order.
442 if (phase->output_node->outgoing_links.empty() && num_output_color_ycbcr > 0) {
443 switch (output_ycbcr_splitting[0]) {
444 case YCBCR_OUTPUT_INTERLEAVED:
446 frag_shader_outputs.push_back("FragColor");
448 case YCBCR_OUTPUT_SPLIT_Y_AND_CBCR:
449 frag_shader += "#define YCBCR_OUTPUT_SPLIT_Y_AND_CBCR 1\n";
450 frag_shader_outputs.push_back("Y");
451 frag_shader_outputs.push_back("Chroma");
453 case YCBCR_OUTPUT_PLANAR:
454 frag_shader += "#define YCBCR_OUTPUT_PLANAR 1\n";
455 frag_shader_outputs.push_back("Y");
456 frag_shader_outputs.push_back("Cb");
457 frag_shader_outputs.push_back("Cr");
463 if (num_output_color_ycbcr > 1) {
464 switch (output_ycbcr_splitting[1]) {
465 case YCBCR_OUTPUT_INTERLEAVED:
466 frag_shader += "#define SECOND_YCBCR_OUTPUT_INTERLEAVED 1\n";
467 frag_shader_outputs.push_back("YCbCr2");
469 case YCBCR_OUTPUT_SPLIT_Y_AND_CBCR:
470 frag_shader += "#define SECOND_YCBCR_OUTPUT_SPLIT_Y_AND_CBCR 1\n";
471 frag_shader_outputs.push_back("Y2");
472 frag_shader_outputs.push_back("Chroma2");
474 case YCBCR_OUTPUT_PLANAR:
475 frag_shader += "#define SECOND_YCBCR_OUTPUT_PLANAR 1\n";
476 frag_shader_outputs.push_back("Y2");
477 frag_shader_outputs.push_back("Cb2");
478 frag_shader_outputs.push_back("Cr2");
485 if (output_color_rgba) {
486 // Note: Needs to come in the header, because not only the
487 // output needs to see it (YCbCrConversionEffect and DitherEffect
489 frag_shader_header += "#define YCBCR_ALSO_OUTPUT_RGBA 1\n";
490 frag_shader_outputs.push_back("RGBA");
494 // If we're bouncing to a temporary texture, signal transformation if desired.
495 if (!phase->output_node->outgoing_links.empty()) {
496 if (intermediate_transformation == SQUARE_ROOT_FRAMEBUFFER_TRANSFORMATION &&
497 phase->output_node->output_gamma_curve == GAMMA_LINEAR) {
498 frag_shader += "#define SQUARE_ROOT_TRANSFORMATION 1\n";
502 if (phase->is_compute_shader) {
503 frag_shader.append(read_file("footer.compute"));
504 phase->output_node->effect->register_uniform_vec2("inv_output_size", (float *)&phase->inv_output_size);
505 phase->output_node->effect->register_uniform_vec2("output_texcoord_adjust", (float *)&phase->output_texcoord_adjust);
507 frag_shader.append(read_file("footer.frag"));
510 // Collect uniforms from all effects and output them. Note that this needs
511 // to happen after output_fragment_shader(), even though the uniforms come
512 // before in the output source, since output_fragment_shader() is allowed
513 // to register new uniforms (e.g. arrays that are of unknown length until
514 // finalization time).
515 // TODO: Make a uniform block for platforms that support it.
516 string frag_shader_uniforms = "";
517 for (unsigned i = 0; i < phase->effects.size(); ++i) {
518 Node *node = phase->effects[i];
519 Effect *effect = node->effect;
520 const string effect_id = phase->effect_ids[node];
521 extract_uniform_declarations(effect->uniforms_image2d, "image2D", effect_id, &phase->uniforms_image2d, &frag_shader_uniforms);
522 extract_uniform_declarations(effect->uniforms_sampler2d, "sampler2D", effect_id, &phase->uniforms_sampler2d, &frag_shader_uniforms);
523 extract_uniform_declarations(effect->uniforms_bool, "bool", effect_id, &phase->uniforms_bool, &frag_shader_uniforms);
524 extract_uniform_declarations(effect->uniforms_int, "int", effect_id, &phase->uniforms_int, &frag_shader_uniforms);
525 extract_uniform_declarations(effect->uniforms_float, "float", effect_id, &phase->uniforms_float, &frag_shader_uniforms);
526 extract_uniform_declarations(effect->uniforms_vec2, "vec2", effect_id, &phase->uniforms_vec2, &frag_shader_uniforms);
527 extract_uniform_declarations(effect->uniforms_vec3, "vec3", effect_id, &phase->uniforms_vec3, &frag_shader_uniforms);
528 extract_uniform_declarations(effect->uniforms_vec4, "vec4", effect_id, &phase->uniforms_vec4, &frag_shader_uniforms);
529 extract_uniform_array_declarations(effect->uniforms_float_array, "float", effect_id, &phase->uniforms_float, &frag_shader_uniforms);
530 extract_uniform_array_declarations(effect->uniforms_vec2_array, "vec2", effect_id, &phase->uniforms_vec2, &frag_shader_uniforms);
531 extract_uniform_array_declarations(effect->uniforms_vec3_array, "vec3", effect_id, &phase->uniforms_vec3, &frag_shader_uniforms);
532 extract_uniform_array_declarations(effect->uniforms_vec4_array, "vec4", effect_id, &phase->uniforms_vec4, &frag_shader_uniforms);
533 extract_uniform_declarations(effect->uniforms_mat3, "mat3", effect_id, &phase->uniforms_mat3, &frag_shader_uniforms);
536 frag_shader = frag_shader_header + frag_shader_uniforms + frag_shader;
538 string vert_shader = read_version_dependent_file("vs", "vert");
540 // If we're the last phase and need to flip the picture to compensate for
541 // the origin, tell the vertex shader so.
542 if (phase->output_node->outgoing_links.empty() && output_origin == OUTPUT_ORIGIN_TOP_LEFT) {
543 const string needle = "#define FLIP_ORIGIN 0";
544 size_t pos = vert_shader.find(needle);
545 assert(pos != string::npos);
547 vert_shader[pos + needle.size() - 1] = '1';
550 if (phase->is_compute_shader) {
551 phase->glsl_program_num = resource_pool->compile_glsl_compute_program(frag_shader);
553 Uniform<int> uniform;
554 uniform.name = "outbuf";
555 uniform.value = &phase->outbuf_image_unit;
556 uniform.prefix = "tex";
557 uniform.num_values = 1;
558 uniform.location = -1;
559 phase->uniforms_image2d.push_back(uniform);
561 phase->glsl_program_num = resource_pool->compile_glsl_program(vert_shader, frag_shader, frag_shader_outputs);
563 GLint position_attribute_index = glGetAttribLocation(phase->glsl_program_num, "position");
564 GLint texcoord_attribute_index = glGetAttribLocation(phase->glsl_program_num, "texcoord");
565 if (position_attribute_index != -1) {
566 phase->attribute_indexes.insert(position_attribute_index);
568 if (texcoord_attribute_index != -1) {
569 phase->attribute_indexes.insert(texcoord_attribute_index);
572 // Collect the resulting location numbers for each uniform.
573 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_image2d);
574 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_sampler2d);
575 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_bool);
576 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_int);
577 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_float);
578 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec2);
579 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec3);
580 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec4);
581 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_mat3);
584 // Construct GLSL programs, starting at the given effect and following
585 // the chain from there. We end a program every time we come to an effect
586 // marked as "needs texture bounce", one that is used by multiple other
587 // effects, every time we need to bounce due to output size change
588 // (not all size changes require ending), and of course at the end.
590 // We follow a quite simple depth-first search from the output, although
591 // without recursing explicitly within each phase.
592 Phase *EffectChain::construct_phase(Node *output, map<Node *, Phase *> *completed_effects)
594 if (completed_effects->count(output)) {
595 return (*completed_effects)[output];
598 Phase *phase = new Phase;
599 phase->output_node = output;
600 phase->is_compute_shader = output->effect->is_compute_shader();
602 // If the output effect has one-to-one sampling, we try to trace this
603 // status down through the dependency chain. This is important in case
604 // we hit an effect that changes output size (and not sets a virtual
605 // output size); if we have one-to-one sampling, we don't have to break
607 output->one_to_one_sampling = output->effect->one_to_one_sampling();
609 // Effects that we have yet to calculate, but that we know should
610 // be in the current phase.
611 stack<Node *> effects_todo_this_phase;
612 effects_todo_this_phase.push(output);
614 while (!effects_todo_this_phase.empty()) {
615 Node *node = effects_todo_this_phase.top();
616 effects_todo_this_phase.pop();
618 if (node->effect->needs_mipmaps()) {
619 node->needs_mipmaps = true;
622 // This should currently only happen for effects that are inputs
623 // (either true inputs or phase outputs). We special-case inputs,
624 // and then deduplicate phase outputs below.
625 if (node->effect->num_inputs() == 0) {
626 if (find(phase->effects.begin(), phase->effects.end(), node) != phase->effects.end()) {
630 assert(completed_effects->count(node) == 0);
633 phase->effects.push_back(node);
635 // Find all the dependencies of this effect, and add them to the stack.
636 vector<Node *> deps = node->incoming_links;
637 assert(node->effect->num_inputs() == deps.size());
638 for (unsigned i = 0; i < deps.size(); ++i) {
639 bool start_new_phase = false;
641 if (node->effect->needs_texture_bounce() &&
642 !deps[i]->effect->is_single_texture() &&
643 !deps[i]->effect->override_disable_bounce()) {
644 start_new_phase = true;
647 // Compute shaders currently always end phases.
648 // (We might loosen this up in some cases in the future.)
649 if (deps[i]->effect->is_compute_shader()) {
650 start_new_phase = true;
653 // Propagate information about needing mipmaps down the chain,
654 // breaking the phase if we notice an incompatibility.
656 // Note that we cannot do this propagation as a normal pass,
657 // because it needs information about where the phases end
658 // (we should not propagate the flag across phases).
659 if (node->needs_mipmaps) {
660 if (deps[i]->effect->num_inputs() == 0) {
661 Input *input = static_cast<Input *>(deps[i]->effect);
662 start_new_phase |= !input->can_supply_mipmaps();
664 deps[i]->needs_mipmaps = true;
668 if (deps[i]->outgoing_links.size() > 1) {
669 if (!deps[i]->effect->is_single_texture()) {
670 // More than one effect uses this as the input,
671 // and it is not a texture itself.
672 // The easiest thing to do (and probably also the safest
673 // performance-wise in most cases) is to bounce it to a texture
674 // and then let the next passes read from that.
675 start_new_phase = true;
677 assert(deps[i]->effect->num_inputs() == 0);
679 // For textures, we try to be slightly more clever;
680 // if none of our outputs need a bounce, we don't bounce
681 // but instead simply use the effect many times.
683 // Strictly speaking, we could bounce it for some outputs
684 // and use it directly for others, but the processing becomes
685 // somewhat simpler if the effect is only used in one such way.
686 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
687 Node *rdep = deps[i]->outgoing_links[j];
688 start_new_phase |= rdep->effect->needs_texture_bounce();
693 if (deps[i]->effect->sets_virtual_output_size()) {
694 assert(deps[i]->effect->changes_output_size());
695 // If the next effect sets a virtual size to rely on OpenGL's
696 // bilinear sampling, we'll really need to break the phase here.
697 start_new_phase = true;
698 } else if (deps[i]->effect->changes_output_size() && !node->one_to_one_sampling) {
699 // If the next effect changes size and we don't have one-to-one sampling,
700 // we also need to break here.
701 start_new_phase = true;
704 if (start_new_phase) {
705 phase->inputs.push_back(construct_phase(deps[i], completed_effects));
707 effects_todo_this_phase.push(deps[i]);
709 // Propagate the one-to-one status down through the dependency.
710 deps[i]->one_to_one_sampling = node->one_to_one_sampling &&
711 deps[i]->effect->one_to_one_sampling();
716 // No more effects to do this phase. Take all the ones we have,
717 // and create a GLSL program for it.
718 assert(!phase->effects.empty());
720 // Deduplicate the inputs, but don't change the ordering e.g. by sorting;
721 // that would be nondeterministic and thus reduce cacheability.
722 // TODO: Make this even more deterministic.
723 vector<Phase *> dedup_inputs;
724 set<Phase *> seen_inputs;
725 for (size_t i = 0; i < phase->inputs.size(); ++i) {
726 if (seen_inputs.insert(phase->inputs[i]).second) {
727 dedup_inputs.push_back(phase->inputs[i]);
730 swap(phase->inputs, dedup_inputs);
732 // Allocate samplers for each input.
733 phase->input_samplers.resize(phase->inputs.size());
735 // We added the effects from the output and back, but we need to output
736 // them in topological sort order in the shader.
737 phase->effects = topological_sort(phase->effects);
739 // Figure out if we need mipmaps or not, and if so, tell the inputs that.
740 phase->input_needs_mipmaps = false;
741 for (unsigned i = 0; i < phase->effects.size(); ++i) {
742 Node *node = phase->effects[i];
743 phase->input_needs_mipmaps |= node->effect->needs_mipmaps();
745 for (unsigned i = 0; i < phase->effects.size(); ++i) {
746 Node *node = phase->effects[i];
747 if (node->effect->num_inputs() == 0) {
748 Input *input = static_cast<Input *>(node->effect);
749 assert(!phase->input_needs_mipmaps || input->can_supply_mipmaps());
750 CHECK(input->set_int("needs_mipmaps", phase->input_needs_mipmaps));
754 // Tell each node which phase it ended up in, so that the unit test
755 // can check that the phases were split in the right place.
756 // Note that this ignores that effects may be part of multiple phases;
757 // if the unit tests need to test such cases, we'll reconsider.
758 for (unsigned i = 0; i < phase->effects.size(); ++i) {
759 phase->effects[i]->containing_phase = phase;
762 // Actually make the shader for this phase.
763 compile_glsl_program(phase);
765 // Initialize timers.
766 if (movit_timer_queries_supported) {
767 phase->time_elapsed_ns = 0;
768 phase->num_measured_iterations = 0;
771 assert(completed_effects->count(output) == 0);
772 completed_effects->insert(make_pair(output, phase));
773 phases.push_back(phase);
777 void EffectChain::output_dot(const char *filename)
779 if (movit_debug_level != MOVIT_DEBUG_ON) {
783 FILE *fp = fopen(filename, "w");
789 fprintf(fp, "digraph G {\n");
790 fprintf(fp, " output [shape=box label=\"(output)\"];\n");
791 for (unsigned i = 0; i < nodes.size(); ++i) {
792 // Find out which phase this event belongs to.
793 vector<int> in_phases;
794 for (unsigned j = 0; j < phases.size(); ++j) {
795 const Phase* p = phases[j];
796 if (find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
797 in_phases.push_back(j);
801 if (in_phases.empty()) {
802 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
803 } else if (in_phases.size() == 1) {
804 fprintf(fp, " n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
805 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
806 (in_phases[0] % 8) + 1);
808 // If we had new enough Graphviz, style="wedged" would probably be ideal here.
810 fprintf(fp, " n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
811 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
812 (in_phases[0] % 8) + 1);
815 char from_node_id[256];
816 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
818 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
819 char to_node_id[256];
820 snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
822 vector<string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
823 output_dot_edge(fp, from_node_id, to_node_id, labels);
826 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
828 vector<string> labels = get_labels_for_edge(nodes[i], nullptr);
829 output_dot_edge(fp, from_node_id, "output", labels);
837 vector<string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
839 vector<string> labels;
841 if (to != nullptr && to->effect->needs_texture_bounce()) {
842 labels.push_back("needs_bounce");
844 if (from->effect->changes_output_size()) {
845 labels.push_back("resize");
848 switch (from->output_color_space) {
849 case COLORSPACE_INVALID:
850 labels.push_back("spc[invalid]");
852 case COLORSPACE_REC_601_525:
853 labels.push_back("spc[rec601-525]");
855 case COLORSPACE_REC_601_625:
856 labels.push_back("spc[rec601-625]");
862 switch (from->output_gamma_curve) {
864 labels.push_back("gamma[invalid]");
867 labels.push_back("gamma[sRGB]");
869 case GAMMA_REC_601: // and GAMMA_REC_709
870 labels.push_back("gamma[rec601/709]");
876 switch (from->output_alpha_type) {
878 labels.push_back("alpha[invalid]");
881 labels.push_back("alpha[blank]");
883 case ALPHA_POSTMULTIPLIED:
884 labels.push_back("alpha[postmult]");
893 void EffectChain::output_dot_edge(FILE *fp,
894 const string &from_node_id,
895 const string &to_node_id,
896 const vector<string> &labels)
898 if (labels.empty()) {
899 fprintf(fp, " %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
901 string label = labels[0];
902 for (unsigned k = 1; k < labels.size(); ++k) {
903 label += ", " + labels[k];
905 fprintf(fp, " %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
909 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
911 unsigned scaled_width, scaled_height;
913 if (float(width) * aspect_denom >= float(height) * aspect_nom) {
914 // Same aspect, or W/H > aspect (image is wider than the frame).
915 // In either case, keep width, and adjust height.
916 scaled_width = width;
917 scaled_height = lrintf(width * aspect_denom / aspect_nom);
919 // W/H < aspect (image is taller than the frame), so keep height,
921 scaled_width = lrintf(height * aspect_nom / aspect_denom);
922 scaled_height = height;
925 // We should be consistently larger or smaller then the existing choice,
926 // since we have the same aspect.
927 assert(!(scaled_width < *output_width && scaled_height > *output_height));
928 assert(!(scaled_height < *output_height && scaled_width > *output_width));
930 if (scaled_width >= *output_width && scaled_height >= *output_height) {
931 *output_width = scaled_width;
932 *output_height = scaled_height;
936 // Propagate input texture sizes throughout, and inform effects downstream.
937 // (Like a lot of other code, we depend on effects being in topological order.)
938 void EffectChain::inform_input_sizes(Phase *phase)
940 // All effects that have a defined size (inputs and RTT inputs)
941 // get that. Reset all others.
942 for (unsigned i = 0; i < phase->effects.size(); ++i) {
943 Node *node = phase->effects[i];
944 if (node->effect->num_inputs() == 0) {
945 Input *input = static_cast<Input *>(node->effect);
946 node->output_width = input->get_width();
947 node->output_height = input->get_height();
948 assert(node->output_width != 0);
949 assert(node->output_height != 0);
951 node->output_width = node->output_height = 0;
954 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
955 Phase *input = phase->inputs[i];
956 input->output_node->output_width = input->virtual_output_width;
957 input->output_node->output_height = input->virtual_output_height;
958 assert(input->output_node->output_width != 0);
959 assert(input->output_node->output_height != 0);
962 // Now propagate from the inputs towards the end, and inform as we go.
963 // The rules are simple:
965 // 1. Don't touch effects that already have given sizes (ie., inputs
966 // or effects that change the output size).
967 // 2. If all of your inputs have the same size, that will be your output size.
968 // 3. Otherwise, your output size is 0x0.
969 for (unsigned i = 0; i < phase->effects.size(); ++i) {
970 Node *node = phase->effects[i];
971 if (node->effect->num_inputs() == 0) {
974 unsigned this_output_width = 0;
975 unsigned this_output_height = 0;
976 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
977 Node *input = node->incoming_links[j];
978 node->effect->inform_input_size(j, input->output_width, input->output_height);
980 this_output_width = input->output_width;
981 this_output_height = input->output_height;
982 } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
984 this_output_width = 0;
985 this_output_height = 0;
988 if (node->effect->changes_output_size()) {
989 // We cannot call get_output_size() before we've done inform_input_size()
991 unsigned real_width, real_height;
992 node->effect->get_output_size(&real_width, &real_height,
993 &node->output_width, &node->output_height);
994 assert(node->effect->sets_virtual_output_size() ||
995 (real_width == node->output_width &&
996 real_height == node->output_height));
998 node->output_width = this_output_width;
999 node->output_height = this_output_height;
1004 // Note: You should call inform_input_sizes() before this, as the last effect's
1005 // desired output size might change based on the inputs.
1006 void EffectChain::find_output_size(Phase *phase)
1008 Node *output_node = phase->effects.back();
1010 // If the last effect explicitly sets an output size, use that.
1011 if (output_node->effect->changes_output_size()) {
1012 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
1013 &phase->virtual_output_width, &phase->virtual_output_height);
1014 assert(output_node->effect->sets_virtual_output_size() ||
1015 (phase->output_width == phase->virtual_output_width &&
1016 phase->output_height == phase->virtual_output_height));
1020 // If all effects have the same size, use that.
1021 unsigned output_width = 0, output_height = 0;
1022 bool all_inputs_same_size = true;
1024 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
1025 Phase *input = phase->inputs[i];
1026 assert(input->output_width != 0);
1027 assert(input->output_height != 0);
1028 if (output_width == 0 && output_height == 0) {
1029 output_width = input->virtual_output_width;
1030 output_height = input->virtual_output_height;
1031 } else if (output_width != input->virtual_output_width ||
1032 output_height != input->virtual_output_height) {
1033 all_inputs_same_size = false;
1036 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1037 Effect *effect = phase->effects[i]->effect;
1038 if (effect->num_inputs() != 0) {
1042 Input *input = static_cast<Input *>(effect);
1043 if (output_width == 0 && output_height == 0) {
1044 output_width = input->get_width();
1045 output_height = input->get_height();
1046 } else if (output_width != input->get_width() ||
1047 output_height != input->get_height()) {
1048 all_inputs_same_size = false;
1052 if (all_inputs_same_size) {
1053 assert(output_width != 0);
1054 assert(output_height != 0);
1055 phase->virtual_output_width = phase->output_width = output_width;
1056 phase->virtual_output_height = phase->output_height = output_height;
1060 // If not, fit all the inputs into the current aspect, and select the largest one.
1063 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
1064 Phase *input = phase->inputs[i];
1065 assert(input->output_width != 0);
1066 assert(input->output_height != 0);
1067 size_rectangle_to_fit(input->output_width, input->output_height, &output_width, &output_height);
1069 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1070 Effect *effect = phase->effects[i]->effect;
1071 if (effect->num_inputs() != 0) {
1075 Input *input = static_cast<Input *>(effect);
1076 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
1078 assert(output_width != 0);
1079 assert(output_height != 0);
1080 phase->virtual_output_width = phase->output_width = output_width;
1081 phase->virtual_output_height = phase->output_height = output_height;
1084 void EffectChain::sort_all_nodes_topologically()
1086 nodes = topological_sort(nodes);
1089 vector<Node *> EffectChain::topological_sort(const vector<Node *> &nodes)
1091 set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
1092 vector<Node *> sorted_list;
1093 for (unsigned i = 0; i < nodes.size(); ++i) {
1094 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
1096 reverse(sorted_list.begin(), sorted_list.end());
1100 void EffectChain::topological_sort_visit_node(Node *node, set<Node *> *nodes_left_to_visit, vector<Node *> *sorted_list)
1102 if (nodes_left_to_visit->count(node) == 0) {
1105 nodes_left_to_visit->erase(node);
1106 for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
1107 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
1109 sorted_list->push_back(node);
1112 void EffectChain::find_color_spaces_for_inputs()
1114 for (unsigned i = 0; i < nodes.size(); ++i) {
1115 Node *node = nodes[i];
1116 if (node->disabled) {
1119 if (node->incoming_links.size() == 0) {
1120 Input *input = static_cast<Input *>(node->effect);
1121 node->output_color_space = input->get_color_space();
1122 node->output_gamma_curve = input->get_gamma_curve();
1124 Effect::AlphaHandling alpha_handling = input->alpha_handling();
1125 switch (alpha_handling) {
1126 case Effect::OUTPUT_BLANK_ALPHA:
1127 node->output_alpha_type = ALPHA_BLANK;
1129 case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
1130 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1132 case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
1133 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1135 case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
1136 case Effect::DONT_CARE_ALPHA_TYPE:
1141 if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
1142 assert(node->output_gamma_curve == GAMMA_LINEAR);
1148 // Propagate gamma and color space information as far as we can in the graph.
1149 // The rules are simple: Anything where all the inputs agree, get that as
1150 // output as well. Anything else keeps having *_INVALID.
1151 void EffectChain::propagate_gamma_and_color_space()
1153 // We depend on going through the nodes in order.
1154 sort_all_nodes_topologically();
1156 for (unsigned i = 0; i < nodes.size(); ++i) {
1157 Node *node = nodes[i];
1158 if (node->disabled) {
1161 assert(node->incoming_links.size() == node->effect->num_inputs());
1162 if (node->incoming_links.size() == 0) {
1163 assert(node->output_color_space != COLORSPACE_INVALID);
1164 assert(node->output_gamma_curve != GAMMA_INVALID);
1168 Colorspace color_space = node->incoming_links[0]->output_color_space;
1169 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
1170 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
1171 if (node->incoming_links[j]->output_color_space != color_space) {
1172 color_space = COLORSPACE_INVALID;
1174 if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
1175 gamma_curve = GAMMA_INVALID;
1179 // The conversion effects already have their outputs set correctly,
1180 // so leave them alone.
1181 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
1182 node->output_color_space = color_space;
1184 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
1185 node->effect->effect_type_id() != "GammaExpansionEffect") {
1186 node->output_gamma_curve = gamma_curve;
1191 // Propagate alpha information as far as we can in the graph.
1192 // Similar to propagate_gamma_and_color_space().
1193 void EffectChain::propagate_alpha()
1195 // We depend on going through the nodes in order.
1196 sort_all_nodes_topologically();
1198 for (unsigned i = 0; i < nodes.size(); ++i) {
1199 Node *node = nodes[i];
1200 if (node->disabled) {
1203 assert(node->incoming_links.size() == node->effect->num_inputs());
1204 if (node->incoming_links.size() == 0) {
1205 assert(node->output_alpha_type != ALPHA_INVALID);
1209 // The alpha multiplication/division effects are special cases.
1210 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
1211 assert(node->incoming_links.size() == 1);
1212 assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
1213 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1216 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
1217 assert(node->incoming_links.size() == 1);
1218 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1219 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1223 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
1224 // because they are the only one that _need_ postmultiplied alpha.
1225 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
1226 node->effect->effect_type_id() == "GammaExpansionEffect") {
1227 assert(node->incoming_links.size() == 1);
1228 if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
1229 node->output_alpha_type = ALPHA_BLANK;
1230 } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
1231 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1233 node->output_alpha_type = ALPHA_INVALID;
1238 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
1239 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
1240 // taken care of above. Rationale: Even if you could imagine
1241 // e.g. an effect that took in an image and set alpha=1.0
1242 // unconditionally, it wouldn't make any sense to have it as
1243 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
1244 // got its input pre- or postmultiplied, so it wouldn't know
1245 // whether to divide away the old alpha or not.
1246 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
1247 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1248 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
1249 alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1251 // If the node has multiple inputs, check that they are all valid and
1253 bool any_invalid = false;
1254 bool any_premultiplied = false;
1255 bool any_postmultiplied = false;
1257 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1258 switch (node->incoming_links[j]->output_alpha_type) {
1263 // Blank is good as both pre- and postmultiplied alpha,
1264 // so just ignore it.
1266 case ALPHA_PREMULTIPLIED:
1267 any_premultiplied = true;
1269 case ALPHA_POSTMULTIPLIED:
1270 any_postmultiplied = true;
1278 node->output_alpha_type = ALPHA_INVALID;
1282 // Inputs must be of the same type.
1283 if (any_premultiplied && any_postmultiplied) {
1284 node->output_alpha_type = ALPHA_INVALID;
1288 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1289 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1290 // This combination (requiring premultiplied alpha, but _not_ requiring
1291 // linear light) is illegal, since the combination of premultiplied alpha
1292 // and nonlinear inputs is meaningless.
1293 assert(node->effect->needs_linear_light());
1295 // If the effect has asked for premultiplied alpha, check that it has got it.
1296 if (any_postmultiplied) {
1297 node->output_alpha_type = ALPHA_INVALID;
1298 } else if (!any_premultiplied &&
1299 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1300 // Blank input alpha, and the effect preserves blank alpha.
1301 node->output_alpha_type = ALPHA_BLANK;
1303 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1306 // OK, all inputs are the same, and this effect is not going
1308 assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1309 if (any_premultiplied) {
1310 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1311 } else if (any_postmultiplied) {
1312 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1314 node->output_alpha_type = ALPHA_BLANK;
1320 bool EffectChain::node_needs_colorspace_fix(Node *node)
1322 if (node->disabled) {
1325 if (node->effect->num_inputs() == 0) {
1329 // propagate_gamma_and_color_space() has already set our output
1330 // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
1331 if (node->output_color_space == COLORSPACE_INVALID) {
1334 return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
1337 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
1338 // the graph. Our strategy is not always optimal, but quite simple:
1339 // Find an effect that's as early as possible where the inputs are of
1340 // unacceptable colorspaces (that is, either different, or, if the effect only
1341 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
1342 // propagate the information anew, and repeat until there are no more such
1344 void EffectChain::fix_internal_color_spaces()
1346 unsigned colorspace_propagation_pass = 0;
1350 for (unsigned i = 0; i < nodes.size(); ++i) {
1351 Node *node = nodes[i];
1352 if (!node_needs_colorspace_fix(node)) {
1356 // Go through each input that is not sRGB, and insert
1357 // a colorspace conversion after it.
1358 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1359 Node *input = node->incoming_links[j];
1360 assert(input->output_color_space != COLORSPACE_INVALID);
1361 if (input->output_color_space == COLORSPACE_sRGB) {
1364 Node *conversion = add_node(new ColorspaceConversionEffect());
1365 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1366 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1367 conversion->output_color_space = COLORSPACE_sRGB;
1368 replace_sender(input, conversion);
1369 connect_nodes(input, conversion);
1372 // Re-sort topologically, and propagate the new information.
1373 propagate_gamma_and_color_space();
1380 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1381 output_dot(filename);
1382 assert(colorspace_propagation_pass < 100);
1383 } while (found_any);
1385 for (unsigned i = 0; i < nodes.size(); ++i) {
1386 Node *node = nodes[i];
1387 if (node->disabled) {
1390 assert(node->output_color_space != COLORSPACE_INVALID);
1394 bool EffectChain::node_needs_alpha_fix(Node *node)
1396 if (node->disabled) {
1400 // propagate_alpha() has already set our output to ALPHA_INVALID if the
1401 // inputs differ or we are otherwise in mismatch, so we can rely on that.
1402 return (node->output_alpha_type == ALPHA_INVALID);
1405 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1406 // the graph. Similar to fix_internal_color_spaces().
1407 void EffectChain::fix_internal_alpha(unsigned step)
1409 unsigned alpha_propagation_pass = 0;
1413 for (unsigned i = 0; i < nodes.size(); ++i) {
1414 Node *node = nodes[i];
1415 if (!node_needs_alpha_fix(node)) {
1419 // If we need to fix up GammaExpansionEffect, then clearly something
1420 // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1422 assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1424 AlphaType desired_type = ALPHA_PREMULTIPLIED;
1426 // GammaCompressionEffect is special; it needs postmultiplied alpha.
1427 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1428 assert(node->incoming_links.size() == 1);
1429 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1430 desired_type = ALPHA_POSTMULTIPLIED;
1433 // Go through each input that is not premultiplied alpha, and insert
1434 // a conversion before it.
1435 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1436 Node *input = node->incoming_links[j];
1437 assert(input->output_alpha_type != ALPHA_INVALID);
1438 if (input->output_alpha_type == desired_type ||
1439 input->output_alpha_type == ALPHA_BLANK) {
1443 if (desired_type == ALPHA_PREMULTIPLIED) {
1444 conversion = add_node(new AlphaMultiplicationEffect());
1446 conversion = add_node(new AlphaDivisionEffect());
1448 conversion->output_alpha_type = desired_type;
1449 replace_sender(input, conversion);
1450 connect_nodes(input, conversion);
1453 // Re-sort topologically, and propagate the new information.
1454 propagate_gamma_and_color_space();
1462 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1463 output_dot(filename);
1464 assert(alpha_propagation_pass < 100);
1465 } while (found_any);
1467 for (unsigned i = 0; i < nodes.size(); ++i) {
1468 Node *node = nodes[i];
1469 if (node->disabled) {
1472 assert(node->output_alpha_type != ALPHA_INVALID);
1476 // Make so that the output is in the desired color space.
1477 void EffectChain::fix_output_color_space()
1479 Node *output = find_output_node();
1480 if (output->output_color_space != output_format.color_space) {
1481 Node *conversion = add_node(new ColorspaceConversionEffect());
1482 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1483 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1484 conversion->output_color_space = output_format.color_space;
1485 connect_nodes(output, conversion);
1487 propagate_gamma_and_color_space();
1491 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1492 void EffectChain::fix_output_alpha()
1494 Node *output = find_output_node();
1495 assert(output->output_alpha_type != ALPHA_INVALID);
1496 if (output->output_alpha_type == ALPHA_BLANK) {
1497 // No alpha output, so we don't care.
1500 if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1501 output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1502 Node *conversion = add_node(new AlphaDivisionEffect());
1503 connect_nodes(output, conversion);
1505 propagate_gamma_and_color_space();
1507 if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1508 output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1509 Node *conversion = add_node(new AlphaMultiplicationEffect());
1510 connect_nodes(output, conversion);
1512 propagate_gamma_and_color_space();
1516 bool EffectChain::node_needs_gamma_fix(Node *node)
1518 if (node->disabled) {
1522 // Small hack since the output is not an explicit node:
1523 // If we are the last node and our output is in the wrong
1524 // space compared to EffectChain's output, we need to fix it.
1525 // This will only take us to linear, but fix_output_gamma()
1526 // will come and take us to the desired output gamma
1529 // This needs to be before everything else, since it could
1530 // even apply to inputs (if they are the only effect).
1531 if (node->outgoing_links.empty() &&
1532 node->output_gamma_curve != output_format.gamma_curve &&
1533 node->output_gamma_curve != GAMMA_LINEAR) {
1537 if (node->effect->num_inputs() == 0) {
1541 // propagate_gamma_and_color_space() has already set our output
1542 // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1543 // except for GammaCompressionEffect.
1544 if (node->output_gamma_curve == GAMMA_INVALID) {
1547 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1548 assert(node->incoming_links.size() == 1);
1549 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1552 return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1555 // Very similar to fix_internal_color_spaces(), but for gamma.
1556 // There is one difference, though; before we start adding conversion nodes,
1557 // we see if we can get anything out of asking the sources to deliver
1558 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1559 // does that part, while fix_internal_gamma_by_inserting_nodes()
1560 // inserts nodes as needed afterwards.
1561 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1563 unsigned gamma_propagation_pass = 0;
1567 for (unsigned i = 0; i < nodes.size(); ++i) {
1568 Node *node = nodes[i];
1569 if (!node_needs_gamma_fix(node)) {
1573 // See if all inputs can give us linear gamma. If not, leave it.
1574 vector<Node *> nonlinear_inputs;
1575 find_all_nonlinear_inputs(node, &nonlinear_inputs);
1576 assert(!nonlinear_inputs.empty());
1579 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1580 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1581 all_ok &= input->can_output_linear_gamma();
1588 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1589 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1590 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1593 // Re-sort topologically, and propagate the new information.
1594 propagate_gamma_and_color_space();
1601 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1602 output_dot(filename);
1603 assert(gamma_propagation_pass < 100);
1604 } while (found_any);
1607 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1609 unsigned gamma_propagation_pass = 0;
1613 for (unsigned i = 0; i < nodes.size(); ++i) {
1614 Node *node = nodes[i];
1615 if (!node_needs_gamma_fix(node)) {
1619 // Special case: We could be an input and still be asked to
1620 // fix our gamma; if so, we should be the only node
1621 // (as node_needs_gamma_fix() would only return true in
1622 // for an input in that case). That means we should insert
1623 // a conversion node _after_ ourselves.
1624 if (node->incoming_links.empty()) {
1625 assert(node->outgoing_links.empty());
1626 Node *conversion = add_node(new GammaExpansionEffect());
1627 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1628 conversion->output_gamma_curve = GAMMA_LINEAR;
1629 connect_nodes(node, conversion);
1632 // If not, go through each input that is not linear gamma,
1633 // and insert a gamma conversion after it.
1634 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1635 Node *input = node->incoming_links[j];
1636 assert(input->output_gamma_curve != GAMMA_INVALID);
1637 if (input->output_gamma_curve == GAMMA_LINEAR) {
1640 Node *conversion = add_node(new GammaExpansionEffect());
1641 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1642 conversion->output_gamma_curve = GAMMA_LINEAR;
1643 replace_sender(input, conversion);
1644 connect_nodes(input, conversion);
1647 // Re-sort topologically, and propagate the new information.
1649 propagate_gamma_and_color_space();
1656 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1657 output_dot(filename);
1658 assert(gamma_propagation_pass < 100);
1659 } while (found_any);
1661 for (unsigned i = 0; i < nodes.size(); ++i) {
1662 Node *node = nodes[i];
1663 if (node->disabled) {
1666 assert(node->output_gamma_curve != GAMMA_INVALID);
1670 // Make so that the output is in the desired gamma.
1671 // Note that this assumes linear input gamma, so it might create the need
1672 // for another pass of fix_internal_gamma().
1673 void EffectChain::fix_output_gamma()
1675 Node *output = find_output_node();
1676 if (output->output_gamma_curve != output_format.gamma_curve) {
1677 Node *conversion = add_node(new GammaCompressionEffect());
1678 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1679 conversion->output_gamma_curve = output_format.gamma_curve;
1680 connect_nodes(output, conversion);
1684 // If the user has requested Y'CbCr output, we need to do this conversion
1685 // _after_ GammaCompressionEffect etc., but before dither (see below).
1686 // This is because Y'CbCr, with the exception of a special optional mode
1687 // in Rec. 2020 (which we currently don't support), is defined to work on
1688 // gamma-encoded data.
1689 void EffectChain::add_ycbcr_conversion_if_needed()
1691 assert(output_color_rgba || num_output_color_ycbcr > 0);
1692 if (num_output_color_ycbcr == 0) {
1695 Node *output = find_output_node();
1696 ycbcr_conversion_effect_node = add_node(new YCbCrConversionEffect(output_ycbcr_format, output_ycbcr_type));
1697 connect_nodes(output, ycbcr_conversion_effect_node);
1700 // If the user has requested dither, add a DitherEffect right at the end
1701 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1702 // since dither is about the only effect that can _not_ be done in linear space.
1703 void EffectChain::add_dither_if_needed()
1705 if (num_dither_bits == 0) {
1708 Node *output = find_output_node();
1709 Node *dither = add_node(new DitherEffect());
1710 CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1711 connect_nodes(output, dither);
1713 dither_effect = dither->effect;
1716 // Compute shaders can't output to the framebuffer, so if the last
1717 // phase ends in a compute shader, add a dummy phase at the end that
1718 // only blits directly from the temporary texture.
1720 // TODO: Add an API for rendering directly to textures, for the cases
1721 // where we're only rendering to an FBO anyway.
1722 void EffectChain::add_dummy_effect_if_needed()
1724 Node *output = find_output_node();
1725 if (output->effect->is_compute_shader()) {
1726 Node *dummy = add_node(new IdentityEffect());
1727 connect_nodes(output, dummy);
1731 // Find the output node. This is, simply, one that has no outgoing links.
1732 // If there are multiple ones, the graph is malformed (we do not support
1733 // multiple outputs right now).
1734 Node *EffectChain::find_output_node()
1736 vector<Node *> output_nodes;
1737 for (unsigned i = 0; i < nodes.size(); ++i) {
1738 Node *node = nodes[i];
1739 if (node->disabled) {
1742 if (node->outgoing_links.empty()) {
1743 output_nodes.push_back(node);
1746 assert(output_nodes.size() == 1);
1747 return output_nodes[0];
1750 void EffectChain::finalize()
1752 // Output the graph as it is before we do any conversions on it.
1753 output_dot("step0-start.dot");
1755 // Give each effect in turn a chance to rewrite its own part of the graph.
1756 // Note that if more effects are added as part of this, they will be
1757 // picked up as part of the same for loop, since they are added at the end.
1758 for (unsigned i = 0; i < nodes.size(); ++i) {
1759 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1761 output_dot("step1-rewritten.dot");
1763 find_color_spaces_for_inputs();
1764 output_dot("step2-input-colorspace.dot");
1767 output_dot("step3-propagated-alpha.dot");
1769 propagate_gamma_and_color_space();
1770 output_dot("step4-propagated-all.dot");
1772 fix_internal_color_spaces();
1773 fix_internal_alpha(6);
1774 fix_output_color_space();
1775 output_dot("step7-output-colorspacefix.dot");
1777 output_dot("step8-output-alphafix.dot");
1779 // Note that we need to fix gamma after colorspace conversion,
1780 // because colorspace conversions might create needs for gamma conversions.
1781 // Also, we need to run an extra pass of fix_internal_gamma() after
1782 // fixing the output gamma, as we only have conversions to/from linear,
1783 // and fix_internal_alpha() since GammaCompressionEffect needs
1784 // postmultiplied input.
1785 fix_internal_gamma_by_asking_inputs(9);
1786 fix_internal_gamma_by_inserting_nodes(10);
1788 output_dot("step11-output-gammafix.dot");
1790 output_dot("step12-output-alpha-propagated.dot");
1791 fix_internal_alpha(13);
1792 output_dot("step14-output-alpha-fixed.dot");
1793 fix_internal_gamma_by_asking_inputs(15);
1794 fix_internal_gamma_by_inserting_nodes(16);
1796 output_dot("step17-before-ycbcr.dot");
1797 add_ycbcr_conversion_if_needed();
1799 output_dot("step18-before-dither.dot");
1800 add_dither_if_needed();
1802 output_dot("step19-before-dummy-effect.dot");
1803 add_dummy_effect_if_needed();
1805 output_dot("step20-final.dot");
1807 // Construct all needed GLSL programs, starting at the output.
1808 // We need to keep track of which effects have already been computed,
1809 // as an effect with multiple users could otherwise be calculated
1811 map<Node *, Phase *> completed_effects;
1812 construct_phase(find_output_node(), &completed_effects);
1814 output_dot("step21-split-to-phases.dot");
1816 assert(phases[0]->inputs.empty());
1821 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1825 // This needs to be set anew, in case we are coming from a different context
1826 // from when we initialized.
1828 glDisable(GL_DITHER);
1831 const bool final_srgb = glIsEnabled(GL_FRAMEBUFFER_SRGB);
1833 bool current_srgb = final_srgb;
1835 // Save original viewport.
1836 GLuint x = 0, y = 0;
1838 if (width == 0 && height == 0) {
1840 glGetIntegerv(GL_VIEWPORT, viewport);
1843 width = viewport[2];
1844 height = viewport[3];
1849 glDisable(GL_BLEND);
1851 glDisable(GL_DEPTH_TEST);
1853 glDepthMask(GL_FALSE);
1856 set<Phase *> generated_mipmaps;
1858 // We choose the simplest option of having one texture per output,
1859 // since otherwise this turns into an (albeit simple) register allocation problem.
1860 map<Phase *, GLuint> output_textures;
1862 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1863 Phase *phase = phases[phase_num];
1865 if (do_phase_timing) {
1866 GLuint timer_query_object;
1867 if (phase->timer_query_objects_free.empty()) {
1868 glGenQueries(1, &timer_query_object);
1870 timer_query_object = phase->timer_query_objects_free.front();
1871 phase->timer_query_objects_free.pop_front();
1873 glBeginQuery(GL_TIME_ELAPSED, timer_query_object);
1874 phase->timer_query_objects_running.push_back(timer_query_object);
1876 if (phase_num == phases.size() - 1) {
1877 // Last phase goes to the output the user specified.
1878 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1880 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1881 assert(status == GL_FRAMEBUFFER_COMPLETE);
1882 glViewport(x, y, width, height);
1883 if (dither_effect != nullptr) {
1884 CHECK(dither_effect->set_int("output_width", width));
1885 CHECK(dither_effect->set_int("output_height", height));
1888 bool last_phase = (phase_num == phases.size() - 1);
1890 // Enable sRGB rendering for intermediates in case we are
1891 // rendering to an sRGB format.
1892 bool needs_srgb = last_phase ? final_srgb : true;
1893 if (needs_srgb && !current_srgb) {
1894 glEnable(GL_FRAMEBUFFER_SRGB);
1896 current_srgb = true;
1897 } else if (!needs_srgb && current_srgb) {
1898 glDisable(GL_FRAMEBUFFER_SRGB);
1900 current_srgb = true;
1903 execute_phase(phase, last_phase, &output_textures, &generated_mipmaps);
1904 if (do_phase_timing) {
1905 glEndQuery(GL_TIME_ELAPSED);
1909 for (const auto &phase_and_texnum : output_textures) {
1910 resource_pool->release_2d_texture(phase_and_texnum.second);
1913 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1918 glBindBuffer(GL_ARRAY_BUFFER, 0);
1920 glBindVertexArray(0);
1923 if (do_phase_timing) {
1924 // Get back the timer queries.
1925 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1926 Phase *phase = phases[phase_num];
1927 for (auto timer_it = phase->timer_query_objects_running.cbegin();
1928 timer_it != phase->timer_query_objects_running.cend(); ) {
1929 GLint timer_query_object = *timer_it;
1931 glGetQueryObjectiv(timer_query_object, GL_QUERY_RESULT_AVAILABLE, &available);
1933 GLuint64 time_elapsed;
1934 glGetQueryObjectui64v(timer_query_object, GL_QUERY_RESULT, &time_elapsed);
1935 phase->time_elapsed_ns += time_elapsed;
1936 ++phase->num_measured_iterations;
1937 phase->timer_query_objects_free.push_back(timer_query_object);
1938 phase->timer_query_objects_running.erase(timer_it++);
1947 void EffectChain::enable_phase_timing(bool enable)
1950 assert(movit_timer_queries_supported);
1952 this->do_phase_timing = enable;
1955 void EffectChain::reset_phase_timing()
1957 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1958 Phase *phase = phases[phase_num];
1959 phase->time_elapsed_ns = 0;
1960 phase->num_measured_iterations = 0;
1964 void EffectChain::print_phase_timing()
1966 double total_time_ms = 0.0;
1967 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1968 Phase *phase = phases[phase_num];
1969 double avg_time_ms = phase->time_elapsed_ns * 1e-6 / phase->num_measured_iterations;
1970 printf("Phase %d: %5.1f ms [", phase_num, avg_time_ms);
1971 for (unsigned effect_num = 0; effect_num < phase->effects.size(); ++effect_num) {
1972 if (effect_num != 0) {
1975 printf("%s", phase->effects[effect_num]->effect->effect_type_id().c_str());
1978 total_time_ms += avg_time_ms;
1980 printf("Total: %5.1f ms\n", total_time_ms);
1983 void EffectChain::execute_phase(Phase *phase, bool last_phase,
1984 map<Phase *, GLuint> *output_textures,
1985 set<Phase *> *generated_mipmaps)
1989 // Find a texture for this phase.
1990 inform_input_sizes(phase);
1992 find_output_size(phase);
1994 GLuint tex_num = resource_pool->create_2d_texture(intermediate_format, phase->output_width, phase->output_height);
1995 output_textures->insert(make_pair(phase, tex_num));
1997 // The output texture needs to have valid state to be written to by a compute shader.
1998 if (phase->is_compute_shader) {
1999 glActiveTexture(GL_TEXTURE0);
2001 glBindTexture(GL_TEXTURE_2D, (*output_textures)[phase]);
2003 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2008 // Set up RTT inputs for this phase.
2009 for (unsigned sampler = 0; sampler < phase->inputs.size(); ++sampler) {
2010 glActiveTexture(GL_TEXTURE0 + sampler);
2011 Phase *input = phase->inputs[sampler];
2012 input->output_node->bound_sampler_num = sampler;
2013 glBindTexture(GL_TEXTURE_2D, (*output_textures)[input]);
2015 if (phase->input_needs_mipmaps && generated_mipmaps->count(input) == 0) {
2016 glGenerateMipmap(GL_TEXTURE_2D);
2018 generated_mipmaps->insert(input);
2020 setup_rtt_sampler(sampler, phase->input_needs_mipmaps);
2021 phase->input_samplers[sampler] = sampler; // Bind the sampler to the right uniform.
2024 GLuint instance_program_num = resource_pool->use_glsl_program(phase->glsl_program_num);
2027 // And now the output.
2028 if (phase->is_compute_shader) {
2029 // This is currently the only place where we use image units,
2030 // so we can always use 0.
2031 phase->outbuf_image_unit = 0;
2032 glBindImageTexture(phase->outbuf_image_unit, (*output_textures)[phase], 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA16F);
2034 phase->inv_output_size.x = 1.0f / phase->output_width;
2035 phase->inv_output_size.y = 1.0f / phase->output_height;
2036 phase->output_texcoord_adjust.x = 0.5f / phase->output_width;
2037 phase->output_texcoord_adjust.y = 0.5f / phase->output_height;
2039 // (Already set up for us if it is the last phase.)
2041 fbo = resource_pool->create_fbo((*output_textures)[phase]);
2042 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
2043 glViewport(0, 0, phase->output_width, phase->output_height);
2047 // Give the required parameters to all the effects.
2048 unsigned sampler_num = phase->inputs.size();
2049 for (unsigned i = 0; i < phase->effects.size(); ++i) {
2050 Node *node = phase->effects[i];
2051 unsigned old_sampler_num = sampler_num;
2052 node->effect->set_gl_state(instance_program_num, phase->effect_ids[node], &sampler_num);
2055 if (node->effect->is_single_texture()) {
2056 assert(sampler_num - old_sampler_num == 1);
2057 node->bound_sampler_num = old_sampler_num;
2059 node->bound_sampler_num = -1;
2064 if (phase->is_compute_shader) {
2066 phase->output_node->effect->get_compute_dimensions(phase->output_width, phase->output_height, &x, &y, &z);
2068 // Uniforms need to come after set_gl_state() _and_ get_compute_dimensions(),
2069 // since they can be updated from there.
2070 setup_uniforms(phase);
2071 glDispatchCompute(x, y, z);
2073 // Uniforms need to come after set_gl_state(), since they can be updated
2075 setup_uniforms(phase);
2077 // Bind the vertex data.
2078 GLuint vao = resource_pool->create_vec2_vao(phase->attribute_indexes, vbo);
2079 glBindVertexArray(vao);
2081 glDrawArrays(GL_TRIANGLES, 0, 3);
2084 resource_pool->release_vec2_vao(vao);
2087 for (unsigned i = 0; i < phase->effects.size(); ++i) {
2088 Node *node = phase->effects[i];
2089 node->effect->clear_gl_state();
2092 resource_pool->unuse_glsl_program(instance_program_num);
2094 if (!last_phase && !phase->is_compute_shader) {
2095 resource_pool->release_fbo(fbo);
2099 void EffectChain::setup_uniforms(Phase *phase)
2101 // TODO: Use UBO blocks.
2102 for (size_t i = 0; i < phase->uniforms_image2d.size(); ++i) {
2103 const Uniform<int> &uniform = phase->uniforms_image2d[i];
2104 if (uniform.location != -1) {
2105 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2108 for (size_t i = 0; i < phase->uniforms_sampler2d.size(); ++i) {
2109 const Uniform<int> &uniform = phase->uniforms_sampler2d[i];
2110 if (uniform.location != -1) {
2111 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2114 for (size_t i = 0; i < phase->uniforms_bool.size(); ++i) {
2115 const Uniform<bool> &uniform = phase->uniforms_bool[i];
2116 assert(uniform.num_values == 1);
2117 if (uniform.location != -1) {
2118 glUniform1i(uniform.location, *uniform.value);
2121 for (size_t i = 0; i < phase->uniforms_int.size(); ++i) {
2122 const Uniform<int> &uniform = phase->uniforms_int[i];
2123 if (uniform.location != -1) {
2124 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2127 for (size_t i = 0; i < phase->uniforms_float.size(); ++i) {
2128 const Uniform<float> &uniform = phase->uniforms_float[i];
2129 if (uniform.location != -1) {
2130 glUniform1fv(uniform.location, uniform.num_values, uniform.value);
2133 for (size_t i = 0; i < phase->uniforms_vec2.size(); ++i) {
2134 const Uniform<float> &uniform = phase->uniforms_vec2[i];
2135 if (uniform.location != -1) {
2136 glUniform2fv(uniform.location, uniform.num_values, uniform.value);
2139 for (size_t i = 0; i < phase->uniforms_vec3.size(); ++i) {
2140 const Uniform<float> &uniform = phase->uniforms_vec3[i];
2141 if (uniform.location != -1) {
2142 glUniform3fv(uniform.location, uniform.num_values, uniform.value);
2145 for (size_t i = 0; i < phase->uniforms_vec4.size(); ++i) {
2146 const Uniform<float> &uniform = phase->uniforms_vec4[i];
2147 if (uniform.location != -1) {
2148 glUniform4fv(uniform.location, uniform.num_values, uniform.value);
2151 for (size_t i = 0; i < phase->uniforms_mat3.size(); ++i) {
2152 const Uniform<Matrix3d> &uniform = phase->uniforms_mat3[i];
2153 assert(uniform.num_values == 1);
2154 if (uniform.location != -1) {
2155 // Convert to float (GLSL has no double matrices).
2157 for (unsigned y = 0; y < 3; ++y) {
2158 for (unsigned x = 0; x < 3; ++x) {
2159 matrixf[y + x * 3] = (*uniform.value)(y, x);
2162 glUniformMatrix3fv(uniform.location, 1, GL_FALSE, matrixf);
2167 void EffectChain::setup_rtt_sampler(int sampler_num, bool use_mipmaps)
2169 glActiveTexture(GL_TEXTURE0 + sampler_num);
2172 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
2175 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2178 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2180 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2184 } // namespace movit