Kill the EffectId enum, on the basis of YAGNI.
[movit] / effect_chain.cpp
1 #define GL_GLEXT_PROTOTYPES 1
2
3 #include <stdio.h>
4 #include <string.h>
5 #include <assert.h>
6
7 #include <GL/gl.h>
8 #include <GL/glext.h>
9
10 #include <algorithm>
11 #include <set>
12 #include <stack>
13 #include <vector>
14
15 #include "util.h"
16 #include "effect_chain.h"
17 #include "gamma_expansion_effect.h"
18 #include "gamma_compression_effect.h"
19 #include "colorspace_conversion_effect.h"
20 #include "input.h"
21
22 EffectChain::EffectChain(unsigned width, unsigned height)
23         : width(width),
24           height(height),
25           finalized(false) {}
26
27 Input *EffectChain::add_input(const ImageFormat &format)
28 {
29         char eff_id[256];
30         sprintf(eff_id, "src_image%u", (unsigned)inputs.size());
31
32         Input *input = new Input(format, width, height);
33         effects.push_back(input);
34         inputs.push_back(input);
35         output_color_space.insert(std::make_pair(input, format.color_space));
36         output_gamma_curve.insert(std::make_pair(input, format.gamma_curve));
37         effect_ids.insert(std::make_pair(input, eff_id));
38         incoming_links.insert(std::make_pair(input, std::vector<Effect *>()));
39         return input;
40 }
41
42 void EffectChain::add_output(const ImageFormat &format)
43 {
44         output_format = format;
45 }
46
47 void EffectChain::add_effect_raw(Effect *effect, const std::vector<Effect *> &inputs)
48 {
49         char effect_id[256];
50         sprintf(effect_id, "eff%u", (unsigned)effects.size());
51
52         effects.push_back(effect);
53         effect_ids.insert(std::make_pair(effect, effect_id));
54         assert(inputs.size() == effect->num_inputs());
55         for (unsigned i = 0; i < inputs.size(); ++i) {
56                 assert(std::find(effects.begin(), effects.end(), inputs[i]) != effects.end());
57                 outgoing_links[inputs[i]].push_back(effect);
58         }
59         incoming_links.insert(std::make_pair(effect, inputs));
60         output_gamma_curve[effect] = output_gamma_curve[last_added_effect()];
61         output_color_space[effect] = output_color_space[last_added_effect()];
62 }
63
64 // Set the "use_srgb_texture_format" option on all inputs that feed into this node,
65 // and update the output_gamma_curve[] map as we go.
66 //
67 // NOTE: We assume that the only way we could actually get GAMMA_sRGB from an
68 // effect (except from GammaCompressionCurve, which should never be inserted
69 // into a chain when this is called) is by pass-through from a texture.
70 // Thus, we can simply feed the flag up towards all inputs.
71 void EffectChain::set_use_srgb_texture_format(Effect *effect)
72 {
73         assert(output_gamma_curve.count(effect) != 0);
74         assert(output_gamma_curve[effect] == GAMMA_sRGB);
75         if (effect->num_inputs() == 0) {
76                 effect->set_int("use_srgb_texture_format", 1);
77         } else {
78                 assert(incoming_links.count(effect) == 1);
79                 std::vector<Effect *> deps = incoming_links[effect];
80                 assert(effect->num_inputs() == deps.size());
81                 for (unsigned i = 0; i < deps.size(); ++i) {
82                         set_use_srgb_texture_format(deps[i]);
83                         assert(output_gamma_curve[deps[i]] == GAMMA_LINEAR);
84                 }
85         }
86         output_gamma_curve[effect] = GAMMA_LINEAR;
87 }
88
89 Effect *EffectChain::normalize_to_linear_gamma(Effect *input)
90 {
91         assert(output_gamma_curve.count(input) != 0);
92         if (output_gamma_curve[input] == GAMMA_sRGB) {
93                 // TODO: check if the extension exists
94                 set_use_srgb_texture_format(input);
95                 output_gamma_curve[input] = GAMMA_LINEAR;
96                 return input;
97         } else {
98                 GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
99                 gamma_conversion->set_int("source_curve", output_gamma_curve[input]);
100                 std::vector<Effect *> inputs;
101                 inputs.push_back(input);
102                 gamma_conversion->add_self_to_effect_chain(this, inputs);
103                 output_gamma_curve[gamma_conversion] = GAMMA_LINEAR;
104                 return gamma_conversion;
105         }
106 }
107
108 Effect *EffectChain::normalize_to_srgb(Effect *input)
109 {
110         assert(output_gamma_curve.count(input) != 0);
111         assert(output_color_space.count(input) != 0);
112         assert(output_gamma_curve[input] == GAMMA_LINEAR);
113         ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
114         colorspace_conversion->set_int("source_space", output_color_space[input]);
115         colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
116         std::vector<Effect *> inputs;
117         inputs.push_back(input);
118         colorspace_conversion->add_self_to_effect_chain(this, inputs);
119         output_color_space[colorspace_conversion] = COLORSPACE_sRGB;
120         return colorspace_conversion;
121 }
122
123 Effect *EffectChain::add_effect(Effect *effect, const std::vector<Effect *> &inputs)
124 {
125         assert(inputs.size() == effect->num_inputs());
126
127         std::vector<Effect *> normalized_inputs = inputs;
128         for (unsigned i = 0; i < normalized_inputs.size(); ++i) {
129                 assert(output_gamma_curve.count(normalized_inputs[i]) != 0);
130                 if (effect->needs_linear_light() && output_gamma_curve[normalized_inputs[i]] != GAMMA_LINEAR) {
131                         normalized_inputs[i] = normalize_to_linear_gamma(normalized_inputs[i]);
132                 }
133                 assert(output_color_space.count(normalized_inputs[i]) != 0);
134                 if (effect->needs_srgb_primaries() && output_color_space[normalized_inputs[i]] != COLORSPACE_sRGB) {
135                         normalized_inputs[i] = normalize_to_srgb(normalized_inputs[i]);
136                 }
137         }
138
139         effect->add_self_to_effect_chain(this, normalized_inputs);
140         return effect;
141 }
142
143 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
144 std::string replace_prefix(const std::string &text, const std::string &prefix)
145 {
146         std::string output;
147         size_t start = 0;
148
149         while (start < text.size()) {
150                 size_t pos = text.find("PREFIX(", start);
151                 if (pos == std::string::npos) {
152                         output.append(text.substr(start, std::string::npos));
153                         break;
154                 }
155
156                 output.append(text.substr(start, pos - start));
157                 output.append(prefix);
158                 output.append("_");
159
160                 pos += strlen("PREFIX(");
161         
162                 // Output stuff until we find the matching ), which we then eat.
163                 int depth = 1;
164                 size_t end_arg_pos = pos;
165                 while (end_arg_pos < text.size()) {
166                         if (text[end_arg_pos] == '(') {
167                                 ++depth;
168                         } else if (text[end_arg_pos] == ')') {
169                                 --depth;
170                                 if (depth == 0) {
171                                         break;
172                                 }
173                         }
174                         ++end_arg_pos;
175                 }
176                 output.append(text.substr(pos, end_arg_pos - pos));
177                 ++end_arg_pos;
178                 assert(depth == 0);
179                 start = end_arg_pos;
180         }
181         return output;
182 }
183
184 EffectChain::Phase EffectChain::compile_glsl_program(const std::vector<Effect *> &inputs, const std::vector<Effect *> &effects)
185 {
186         assert(!effects.empty());
187
188         // Deduplicate the inputs.
189         std::vector<Effect *> true_inputs = inputs;
190         std::sort(true_inputs.begin(), true_inputs.end());
191         true_inputs.erase(std::unique(true_inputs.begin(), true_inputs.end()), true_inputs.end());
192
193         bool input_needs_mipmaps = false;
194         std::string frag_shader = read_file("header.frag");
195
196         // Create functions for all the texture inputs that we need.
197         for (unsigned i = 0; i < true_inputs.size(); ++i) {
198                 Effect *effect = true_inputs[i];
199                 assert(effect_ids.count(effect) != 0);
200                 std::string effect_id = effect_ids[effect];
201         
202                 frag_shader += std::string("uniform sampler2D tex_") + effect_id + ";\n";       
203                 frag_shader += std::string("vec4 ") + effect_id + "(vec2 tc) {\n";
204                 if (effect->num_inputs() == 0) {
205                         // OpenGL's origin is bottom-left, but most graphics software assumes
206                         // a top-left origin. Thus, for inputs that come from the user,
207                         // we flip the y coordinate. However, for FBOs, the origin
208                         // is all correct, so don't do anything.
209                         frag_shader += "\ttc.y = 1.0f - tc.y;\n";
210                 }
211                 frag_shader += "\treturn texture2D(tex_" + effect_id + ", tc);\n";
212                 frag_shader += "}\n";
213                 frag_shader += "\n";
214         }
215
216         std::string last_effect_id;
217         for (unsigned i = 0; i < effects.size(); ++i) {
218                 Effect *effect = effects[i];
219                 assert(effect != NULL);
220                 assert(effect_ids.count(effect) != 0);
221                 std::string effect_id = effect_ids[effect];
222                 last_effect_id = effect_id;
223
224                 if (incoming_links[effect].size() == 1) {
225                         frag_shader += std::string("#define INPUT ") + effect_ids[incoming_links[effect][0]] + "\n";
226                 } else {
227                         for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
228                                 char buf[256];
229                                 sprintf(buf, "#define INPUT%d %s\n", j + 1, effect_ids[incoming_links[effect][j]].c_str());
230                                 frag_shader += buf;
231                         }
232                 }
233         
234                 frag_shader += "\n";
235                 frag_shader += std::string("#define FUNCNAME ") + effect_id + "\n";
236                 frag_shader += replace_prefix(effect->output_convenience_uniforms(), effect_id);
237                 frag_shader += replace_prefix(effect->output_fragment_shader(), effect_id);
238                 frag_shader += "#undef PREFIX\n";
239                 frag_shader += "#undef FUNCNAME\n";
240                 if (incoming_links[effect].size() == 1) {
241                         frag_shader += "#undef INPUT\n";
242                 } else {
243                         for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
244                                 char buf[256];
245                                 sprintf(buf, "#undef INPUT%d\n", j + 1);
246                                 frag_shader += buf;
247                         }
248                 }
249                 frag_shader += "\n";
250
251                 input_needs_mipmaps |= effect->needs_mipmaps();
252         }
253         for (unsigned i = 0; i < effects.size(); ++i) {
254                 Effect *effect = effects[i];
255                 if (effect->num_inputs() == 0) {
256                         effect->set_int("needs_mipmaps", input_needs_mipmaps);
257                 }
258         }
259         assert(!last_effect_id.empty());
260         frag_shader += std::string("#define INPUT ") + last_effect_id + "\n";
261         frag_shader.append(read_file("footer.frag"));
262         printf("%s\n", frag_shader.c_str());
263         
264         GLuint glsl_program_num = glCreateProgram();
265         GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
266         GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
267         glAttachShader(glsl_program_num, vs_obj);
268         check_error();
269         glAttachShader(glsl_program_num, fs_obj);
270         check_error();
271         glLinkProgram(glsl_program_num);
272         check_error();
273
274         Phase phase;
275         phase.glsl_program_num = glsl_program_num;
276         phase.input_needs_mipmaps = input_needs_mipmaps;
277         phase.inputs = true_inputs;
278         phase.effects = effects;
279
280         return phase;
281 }
282
283 // Construct GLSL programs, starting at the given effect and following
284 // the chain from there. We end a program every time we come to an effect
285 // marked as "needs texture bounce", one that is used by multiple other
286 // effects, and of course at the end.
287 //
288 // We follow a quite simple depth-first search from the output, although
289 // without any explicit recursion.
290 void EffectChain::construct_glsl_programs(Effect *output)
291 {
292         // Which effects have already been completed in this phase?
293         // We need to keep track of it, as an effect with multiple outputs
294         // could otherwise be calculate multiple times.
295         std::set<Effect *> completed_effects;
296
297         // Effects in the current phase, as well as inputs (outputs from other phases
298         // that we depend on). Note that since we start iterating from the end,
299         // the effect list will be in the reverse order.
300         std::vector<Effect *> this_phase_inputs;
301         std::vector<Effect *> this_phase_effects;
302
303         // Effects that we have yet to calculate, but that we know should
304         // be in the current phase.
305         std::stack<Effect *> effects_todo_this_phase;
306
307         // Effects that we have yet to calculate, but that come from other phases.
308         // We delay these until we have this phase done in its entirety,
309         // at which point we pick any of them and start a new phase from that.
310         std::stack<Effect *> effects_todo_other_phases;
311
312         effects_todo_this_phase.push(output);
313
314         for ( ;; ) {  // Termination condition within loop.
315                 if (!effects_todo_this_phase.empty()) {
316                         // OK, we have more to do this phase.
317                         Effect *effect = effects_todo_this_phase.top();
318                         effects_todo_this_phase.pop();
319
320                         // This should currently only happen for effects that are phase outputs,
321                         // and we throw those out separately below.
322                         assert(completed_effects.count(effect) == 0);
323
324                         this_phase_effects.push_back(effect);
325                         completed_effects.insert(effect);
326
327                         // Find all the dependencies of this effect, and add them to the stack.
328                         assert(incoming_links.count(effect) == 1);
329                         std::vector<Effect *> deps = incoming_links[effect];
330                         assert(effect->num_inputs() == deps.size());
331                         for (unsigned i = 0; i < deps.size(); ++i) {
332                                 bool start_new_phase = false;
333
334                                 if (effect->needs_texture_bounce()) {
335                                         start_new_phase = true;
336                                 }
337
338                                 assert(outgoing_links.count(deps[i]) == 1);
339                                 if (outgoing_links[deps[i]].size() > 1 && deps[i]->num_inputs() > 0) {
340                                         // More than one effect uses this as the input,
341                                         // and it is not a texture itself.
342                                         // The easiest thing to do (and probably also the safest
343                                         // performance-wise in most cases) is to bounce it to a texture
344                                         // and then let the next passes read from that.
345                                         start_new_phase = true;
346                                 }
347
348                                 if (start_new_phase) {
349                                         effects_todo_other_phases.push(deps[i]);
350                                         this_phase_inputs.push_back(deps[i]);
351                                 } else {
352                                         effects_todo_this_phase.push(deps[i]);
353                                 }
354                         }
355                         continue;
356                 }
357
358                 // No more effects to do this phase. Take all the ones we have,
359                 // and create a GLSL program for it.
360                 if (!this_phase_effects.empty()) {
361                         reverse(this_phase_effects.begin(), this_phase_effects.end());
362                         phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
363                         this_phase_inputs.clear();
364                         this_phase_effects.clear();
365                 }
366                 assert(this_phase_inputs.empty());
367                 assert(this_phase_effects.empty());
368
369                 // If we have no effects left, exit.
370                 if (effects_todo_other_phases.empty()) {
371                         break;
372                 }
373
374                 Effect *effect = effects_todo_other_phases.top();
375                 effects_todo_other_phases.pop();
376
377                 if (completed_effects.count(effect) == 0) {
378                         // Start a new phase, calculating from this effect.
379                         effects_todo_this_phase.push(effect);
380                 }
381         }
382
383         // Finally, since the phases are found from the output but must be executed
384         // from the input(s), reverse them, too.
385         std::reverse(phases.begin(), phases.end());
386 }
387
388 void EffectChain::finalize()
389 {
390         // Find the output effect. This is, simply, one that has no outgoing links.
391         // If there are multiple ones, the graph is malformed (we do not support
392         // multiple outputs right now).
393         std::vector<Effect *> output_effects;
394         for (unsigned i = 0; i < effects.size(); ++i) {
395                 Effect *effect = effects[i];
396                 if (outgoing_links.count(effect) == 0 || outgoing_links[effect].size() == 0) {
397                         output_effects.push_back(effect);
398                 }
399         }
400         assert(output_effects.size() == 1);
401         Effect *output_effect = output_effects[0];
402
403         // Add normalizers to get the output format right.
404         assert(output_gamma_curve.count(output_effect) != 0);
405         assert(output_color_space.count(output_effect) != 0);
406         ColorSpace current_color_space = output_color_space[output_effect];
407         if (current_color_space != output_format.color_space) {
408                 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
409                 colorspace_conversion->set_int("source_space", current_color_space);
410                 colorspace_conversion->set_int("destination_space", output_format.color_space);
411                 std::vector<Effect *> inputs;
412                 inputs.push_back(output_effect);
413                 colorspace_conversion->add_self_to_effect_chain(this, inputs);
414                 output_color_space[colorspace_conversion] = output_format.color_space;
415                 output_effect = colorspace_conversion;
416         }
417         GammaCurve current_gamma_curve = output_gamma_curve[output_effect];
418         if (current_gamma_curve != output_format.gamma_curve) {
419                 if (current_gamma_curve != GAMMA_LINEAR) {
420                         output_effect = normalize_to_linear_gamma(output_effect);
421                         current_gamma_curve = GAMMA_LINEAR;
422                 }
423                 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
424                 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
425                 std::vector<Effect *> inputs;
426                 inputs.push_back(output_effect);
427                 gamma_conversion->add_self_to_effect_chain(this, inputs);
428                 output_gamma_curve[gamma_conversion] = output_format.gamma_curve;
429                 output_effect = gamma_conversion;
430         }
431
432         // Construct all needed GLSL programs, starting at the output.
433         construct_glsl_programs(output_effect);
434
435         // If we have more than one phase, we need intermediate render-to-texture.
436         // Construct an FBO, and then as many textures as we need.
437         // We choose the simplest option of having one texture per output,
438         // since otherwise this turns into an (albeit simple)
439         // register allocation problem.
440         if (phases.size() > 1) {
441                 glGenFramebuffers(1, &fbo);
442
443                 for (unsigned i = 0; i < phases.size() - 1; ++i) {
444                         Effect *output_effect = phases[i].effects.back();
445                         GLuint temp_texture;
446                         glGenTextures(1, &temp_texture);
447                         check_error();
448                         glBindTexture(GL_TEXTURE_2D, temp_texture);
449                         check_error();
450                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
451                         check_error();
452                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
453                         check_error();
454                         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
455                         check_error();
456                         effect_output_textures.insert(std::make_pair(output_effect, temp_texture));
457                 }
458         }
459                 
460         for (unsigned i = 0; i < inputs.size(); ++i) {
461                 inputs[i]->finalize();
462         }
463         
464         finalized = true;
465 }
466
467 void EffectChain::render_to_screen()
468 {
469         assert(finalized);
470
471         // Basic state.
472         glDisable(GL_BLEND);
473         check_error();
474         glDisable(GL_DEPTH_TEST);
475         check_error();
476         glDepthMask(GL_FALSE);
477         check_error();
478
479         glMatrixMode(GL_PROJECTION);
480         glLoadIdentity();
481         glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
482
483         glMatrixMode(GL_MODELVIEW);
484         glLoadIdentity();
485
486         if (phases.size() > 1) {
487                 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
488                 check_error();
489         }
490
491         std::set<Effect *> generated_mipmaps;
492         for (unsigned i = 0; i < inputs.size(); ++i) {
493                 // Inputs generate their own mipmaps if they need to
494                 // (see input.cpp).
495                 generated_mipmaps.insert(inputs[i]);
496         }
497
498         for (unsigned phase = 0; phase < phases.size(); ++phase) {
499                 glUseProgram(phases[phase].glsl_program_num);
500                 check_error();
501
502                 // Set up RTT inputs for this phase.
503                 for (unsigned sampler = 0; sampler < phases[phase].inputs.size(); ++sampler) {
504                         glActiveTexture(GL_TEXTURE0 + sampler);
505                         Effect *input = phases[phase].inputs[sampler];
506                         assert(effect_output_textures.count(input) != 0);
507                         glBindTexture(GL_TEXTURE_2D, effect_output_textures[input]);
508                         check_error();
509                         if (phases[phase].input_needs_mipmaps) {
510                                 if (generated_mipmaps.count(input) == 0) {
511                                         glGenerateMipmap(GL_TEXTURE_2D);
512                                         check_error();
513                                         generated_mipmaps.insert(input);
514                                 }
515                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
516                                 check_error();
517                         } else {
518                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
519                                 check_error();
520                         }
521
522                         assert(effect_ids.count(input));
523                         std::string texture_name = std::string("tex_") + effect_ids[input];
524                         glUniform1i(glGetUniformLocation(phases[phase].glsl_program_num, texture_name.c_str()), sampler);
525                         check_error();
526                 }
527
528                 // And now the output.
529                 if (phase == phases.size() - 1) {
530                         // Last phase goes directly to the screen.
531                         glBindFramebuffer(GL_FRAMEBUFFER, 0);
532                         check_error();
533                 } else {
534                         Effect *last_effect = phases[phase].effects.back();
535                         assert(effect_output_textures.count(last_effect) != 0);
536                         glFramebufferTexture2D(
537                                 GL_FRAMEBUFFER,
538                                 GL_COLOR_ATTACHMENT0,
539                                 GL_TEXTURE_2D,
540                                 effect_output_textures[last_effect],
541                                 0);
542                         check_error();
543                 }
544
545                 // Give the required parameters to all the effects.
546                 unsigned sampler_num = phases[phase].inputs.size();
547                 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
548                         Effect *effect = phases[phase].effects[i];
549                         effect->set_gl_state(phases[phase].glsl_program_num, effect_ids[effect], &sampler_num);
550                 }
551
552                 // Now draw!
553                 glBegin(GL_QUADS);
554
555                 glTexCoord2f(0.0f, 0.0f);
556                 glVertex2f(0.0f, 0.0f);
557
558                 glTexCoord2f(1.0f, 0.0f);
559                 glVertex2f(1.0f, 0.0f);
560
561                 glTexCoord2f(1.0f, 1.0f);
562                 glVertex2f(1.0f, 1.0f);
563
564                 glTexCoord2f(0.0f, 1.0f);
565                 glVertex2f(0.0f, 1.0f);
566
567                 glEnd();
568                 check_error();
569
570                 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
571                         Effect *effect = phases[phase].effects[i];
572                         effect->clear_gl_state();
573                 }
574         }
575 }