1 #define GL_GLEXT_PROTOTYPES 1
16 #include "effect_chain.h"
17 #include "gamma_expansion_effect.h"
18 #include "gamma_compression_effect.h"
19 #include "colorspace_conversion_effect.h"
22 EffectChain::EffectChain(unsigned width, unsigned height)
27 Input *EffectChain::add_input(Input *input)
30 sprintf(eff_id, "src_image%u", (unsigned)inputs.size());
32 effects.push_back(input);
33 inputs.push_back(input);
34 output_color_space.insert(std::make_pair(input, input->get_color_space()));
35 output_gamma_curve.insert(std::make_pair(input, input->get_gamma_curve()));
36 effect_ids.insert(std::make_pair(input, eff_id));
37 incoming_links.insert(std::make_pair(input, std::vector<Effect *>()));
41 void EffectChain::add_output(const ImageFormat &format)
43 output_format = format;
46 void EffectChain::add_effect_raw(Effect *effect, const std::vector<Effect *> &inputs)
49 sprintf(effect_id, "eff%u", (unsigned)effects.size());
51 effects.push_back(effect);
52 effect_ids.insert(std::make_pair(effect, effect_id));
53 assert(inputs.size() == effect->num_inputs());
54 for (unsigned i = 0; i < inputs.size(); ++i) {
55 assert(std::find(effects.begin(), effects.end(), inputs[i]) != effects.end());
56 outgoing_links[inputs[i]].push_back(effect);
58 incoming_links.insert(std::make_pair(effect, inputs));
59 output_gamma_curve[effect] = output_gamma_curve[last_added_effect()];
60 output_color_space[effect] = output_color_space[last_added_effect()];
63 // Set the "use_srgb_texture_format" option on all inputs that feed into this node,
64 // and update the output_gamma_curve[] map as we go.
66 // NOTE: We assume that the only way we could actually get GAMMA_sRGB from an
67 // effect (except from GammaCompressionCurve, which should never be inserted
68 // into a chain when this is called) is by pass-through from a texture.
69 // Thus, we can simply feed the flag up towards all inputs.
70 void EffectChain::set_use_srgb_texture_format(Effect *effect)
72 assert(output_gamma_curve.count(effect) != 0);
73 assert(output_gamma_curve[effect] == GAMMA_sRGB);
74 if (effect->num_inputs() == 0) {
75 effect->set_int("use_srgb_texture_format", 1);
77 assert(incoming_links.count(effect) == 1);
78 std::vector<Effect *> deps = incoming_links[effect];
79 assert(effect->num_inputs() == deps.size());
80 for (unsigned i = 0; i < deps.size(); ++i) {
81 set_use_srgb_texture_format(deps[i]);
82 assert(output_gamma_curve[deps[i]] == GAMMA_LINEAR);
85 output_gamma_curve[effect] = GAMMA_LINEAR;
88 Effect *EffectChain::normalize_to_linear_gamma(Effect *input)
90 assert(output_gamma_curve.count(input) != 0);
91 if (output_gamma_curve[input] == GAMMA_sRGB) {
92 // TODO: check if the extension exists
93 set_use_srgb_texture_format(input);
94 output_gamma_curve[input] = GAMMA_LINEAR;
97 GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
98 gamma_conversion->set_int("source_curve", output_gamma_curve[input]);
99 std::vector<Effect *> inputs;
100 inputs.push_back(input);
101 gamma_conversion->add_self_to_effect_chain(this, inputs);
102 output_gamma_curve[gamma_conversion] = GAMMA_LINEAR;
103 return gamma_conversion;
107 Effect *EffectChain::normalize_to_srgb(Effect *input)
109 assert(output_gamma_curve.count(input) != 0);
110 assert(output_color_space.count(input) != 0);
111 assert(output_gamma_curve[input] == GAMMA_LINEAR);
112 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
113 colorspace_conversion->set_int("source_space", output_color_space[input]);
114 colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
115 std::vector<Effect *> inputs;
116 inputs.push_back(input);
117 colorspace_conversion->add_self_to_effect_chain(this, inputs);
118 output_color_space[colorspace_conversion] = COLORSPACE_sRGB;
119 return colorspace_conversion;
122 Effect *EffectChain::add_effect(Effect *effect, const std::vector<Effect *> &inputs)
124 assert(inputs.size() == effect->num_inputs());
126 std::vector<Effect *> normalized_inputs = inputs;
127 for (unsigned i = 0; i < normalized_inputs.size(); ++i) {
128 assert(output_gamma_curve.count(normalized_inputs[i]) != 0);
129 if (effect->needs_linear_light() && output_gamma_curve[normalized_inputs[i]] != GAMMA_LINEAR) {
130 normalized_inputs[i] = normalize_to_linear_gamma(normalized_inputs[i]);
132 assert(output_color_space.count(normalized_inputs[i]) != 0);
133 if (effect->needs_srgb_primaries() && output_color_space[normalized_inputs[i]] != COLORSPACE_sRGB) {
134 normalized_inputs[i] = normalize_to_srgb(normalized_inputs[i]);
138 effect->add_self_to_effect_chain(this, normalized_inputs);
142 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
143 std::string replace_prefix(const std::string &text, const std::string &prefix)
148 while (start < text.size()) {
149 size_t pos = text.find("PREFIX(", start);
150 if (pos == std::string::npos) {
151 output.append(text.substr(start, std::string::npos));
155 output.append(text.substr(start, pos - start));
156 output.append(prefix);
159 pos += strlen("PREFIX(");
161 // Output stuff until we find the matching ), which we then eat.
163 size_t end_arg_pos = pos;
164 while (end_arg_pos < text.size()) {
165 if (text[end_arg_pos] == '(') {
167 } else if (text[end_arg_pos] == ')') {
175 output.append(text.substr(pos, end_arg_pos - pos));
183 EffectChain::Phase EffectChain::compile_glsl_program(const std::vector<Effect *> &inputs, const std::vector<Effect *> &effects)
185 assert(!effects.empty());
187 // Deduplicate the inputs.
188 std::vector<Effect *> true_inputs = inputs;
189 std::sort(true_inputs.begin(), true_inputs.end());
190 true_inputs.erase(std::unique(true_inputs.begin(), true_inputs.end()), true_inputs.end());
192 bool input_needs_mipmaps = false;
193 std::string frag_shader = read_file("header.frag");
195 // Create functions for all the texture inputs that we need.
196 for (unsigned i = 0; i < true_inputs.size(); ++i) {
197 Effect *effect = true_inputs[i];
198 assert(effect_ids.count(effect) != 0);
199 std::string effect_id = effect_ids[effect];
201 frag_shader += std::string("uniform sampler2D tex_") + effect_id + ";\n";
202 frag_shader += std::string("vec4 ") + effect_id + "(vec2 tc) {\n";
203 if (effect->num_inputs() == 0) {
204 // OpenGL's origin is bottom-left, but most graphics software assumes
205 // a top-left origin. Thus, for inputs that come from the user,
206 // we flip the y coordinate. However, for FBOs, the origin
207 // is all correct, so don't do anything.
208 frag_shader += "\ttc.y = 1.0f - tc.y;\n";
210 frag_shader += "\treturn texture2D(tex_" + effect_id + ", tc);\n";
211 frag_shader += "}\n";
215 std::string last_effect_id;
216 for (unsigned i = 0; i < effects.size(); ++i) {
217 Effect *effect = effects[i];
218 assert(effect != NULL);
219 assert(effect_ids.count(effect) != 0);
220 std::string effect_id = effect_ids[effect];
221 last_effect_id = effect_id;
223 if (incoming_links[effect].size() == 1) {
224 frag_shader += std::string("#define INPUT ") + effect_ids[incoming_links[effect][0]] + "\n";
226 for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
228 sprintf(buf, "#define INPUT%d %s\n", j + 1, effect_ids[incoming_links[effect][j]].c_str());
234 frag_shader += std::string("#define FUNCNAME ") + effect_id + "\n";
235 frag_shader += replace_prefix(effect->output_convenience_uniforms(), effect_id);
236 frag_shader += replace_prefix(effect->output_fragment_shader(), effect_id);
237 frag_shader += "#undef PREFIX\n";
238 frag_shader += "#undef FUNCNAME\n";
239 if (incoming_links[effect].size() == 1) {
240 frag_shader += "#undef INPUT\n";
242 for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
244 sprintf(buf, "#undef INPUT%d\n", j + 1);
250 input_needs_mipmaps |= effect->needs_mipmaps();
252 for (unsigned i = 0; i < effects.size(); ++i) {
253 Effect *effect = effects[i];
254 if (effect->num_inputs() == 0) {
255 effect->set_int("needs_mipmaps", input_needs_mipmaps);
258 assert(!last_effect_id.empty());
259 frag_shader += std::string("#define INPUT ") + last_effect_id + "\n";
260 frag_shader.append(read_file("footer.frag"));
261 printf("%s\n", frag_shader.c_str());
263 GLuint glsl_program_num = glCreateProgram();
264 GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
265 GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
266 glAttachShader(glsl_program_num, vs_obj);
268 glAttachShader(glsl_program_num, fs_obj);
270 glLinkProgram(glsl_program_num);
274 phase.glsl_program_num = glsl_program_num;
275 phase.input_needs_mipmaps = input_needs_mipmaps;
276 phase.inputs = true_inputs;
277 phase.effects = effects;
282 // Construct GLSL programs, starting at the given effect and following
283 // the chain from there. We end a program every time we come to an effect
284 // marked as "needs texture bounce", one that is used by multiple other
285 // effects, and of course at the end.
287 // We follow a quite simple depth-first search from the output, although
288 // without any explicit recursion.
289 void EffectChain::construct_glsl_programs(Effect *output)
291 // Which effects have already been completed in this phase?
292 // We need to keep track of it, as an effect with multiple outputs
293 // could otherwise be calculate multiple times.
294 std::set<Effect *> completed_effects;
296 // Effects in the current phase, as well as inputs (outputs from other phases
297 // that we depend on). Note that since we start iterating from the end,
298 // the effect list will be in the reverse order.
299 std::vector<Effect *> this_phase_inputs;
300 std::vector<Effect *> this_phase_effects;
302 // Effects that we have yet to calculate, but that we know should
303 // be in the current phase.
304 std::stack<Effect *> effects_todo_this_phase;
306 // Effects that we have yet to calculate, but that come from other phases.
307 // We delay these until we have this phase done in its entirety,
308 // at which point we pick any of them and start a new phase from that.
309 std::stack<Effect *> effects_todo_other_phases;
311 effects_todo_this_phase.push(output);
313 for ( ;; ) { // Termination condition within loop.
314 if (!effects_todo_this_phase.empty()) {
315 // OK, we have more to do this phase.
316 Effect *effect = effects_todo_this_phase.top();
317 effects_todo_this_phase.pop();
319 // This should currently only happen for effects that are phase outputs,
320 // and we throw those out separately below.
321 assert(completed_effects.count(effect) == 0);
323 this_phase_effects.push_back(effect);
324 completed_effects.insert(effect);
326 // Find all the dependencies of this effect, and add them to the stack.
327 assert(incoming_links.count(effect) == 1);
328 std::vector<Effect *> deps = incoming_links[effect];
329 assert(effect->num_inputs() == deps.size());
330 for (unsigned i = 0; i < deps.size(); ++i) {
331 bool start_new_phase = false;
333 if (effect->needs_texture_bounce()) {
334 start_new_phase = true;
337 assert(outgoing_links.count(deps[i]) == 1);
338 if (outgoing_links[deps[i]].size() > 1 && deps[i]->num_inputs() > 0) {
339 // More than one effect uses this as the input,
340 // and it is not a texture itself.
341 // The easiest thing to do (and probably also the safest
342 // performance-wise in most cases) is to bounce it to a texture
343 // and then let the next passes read from that.
344 start_new_phase = true;
347 if (start_new_phase) {
348 effects_todo_other_phases.push(deps[i]);
349 this_phase_inputs.push_back(deps[i]);
351 effects_todo_this_phase.push(deps[i]);
357 // No more effects to do this phase. Take all the ones we have,
358 // and create a GLSL program for it.
359 if (!this_phase_effects.empty()) {
360 reverse(this_phase_effects.begin(), this_phase_effects.end());
361 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
362 this_phase_inputs.clear();
363 this_phase_effects.clear();
365 assert(this_phase_inputs.empty());
366 assert(this_phase_effects.empty());
368 // If we have no effects left, exit.
369 if (effects_todo_other_phases.empty()) {
373 Effect *effect = effects_todo_other_phases.top();
374 effects_todo_other_phases.pop();
376 if (completed_effects.count(effect) == 0) {
377 // Start a new phase, calculating from this effect.
378 effects_todo_this_phase.push(effect);
382 // Finally, since the phases are found from the output but must be executed
383 // from the input(s), reverse them, too.
384 std::reverse(phases.begin(), phases.end());
387 void EffectChain::finalize()
389 // Find the output effect. This is, simply, one that has no outgoing links.
390 // If there are multiple ones, the graph is malformed (we do not support
391 // multiple outputs right now).
392 std::vector<Effect *> output_effects;
393 for (unsigned i = 0; i < effects.size(); ++i) {
394 Effect *effect = effects[i];
395 if (outgoing_links.count(effect) == 0 || outgoing_links[effect].size() == 0) {
396 output_effects.push_back(effect);
399 assert(output_effects.size() == 1);
400 Effect *output_effect = output_effects[0];
402 // Add normalizers to get the output format right.
403 assert(output_gamma_curve.count(output_effect) != 0);
404 assert(output_color_space.count(output_effect) != 0);
405 ColorSpace current_color_space = output_color_space[output_effect];
406 if (current_color_space != output_format.color_space) {
407 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
408 colorspace_conversion->set_int("source_space", current_color_space);
409 colorspace_conversion->set_int("destination_space", output_format.color_space);
410 std::vector<Effect *> inputs;
411 inputs.push_back(output_effect);
412 colorspace_conversion->add_self_to_effect_chain(this, inputs);
413 output_color_space[colorspace_conversion] = output_format.color_space;
414 output_effect = colorspace_conversion;
416 GammaCurve current_gamma_curve = output_gamma_curve[output_effect];
417 if (current_gamma_curve != output_format.gamma_curve) {
418 if (current_gamma_curve != GAMMA_LINEAR) {
419 output_effect = normalize_to_linear_gamma(output_effect);
420 current_gamma_curve = GAMMA_LINEAR;
422 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
423 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
424 std::vector<Effect *> inputs;
425 inputs.push_back(output_effect);
426 gamma_conversion->add_self_to_effect_chain(this, inputs);
427 output_gamma_curve[gamma_conversion] = output_format.gamma_curve;
428 output_effect = gamma_conversion;
431 // Construct all needed GLSL programs, starting at the output.
432 construct_glsl_programs(output_effect);
434 // If we have more than one phase, we need intermediate render-to-texture.
435 // Construct an FBO, and then as many textures as we need.
436 // We choose the simplest option of having one texture per output,
437 // since otherwise this turns into an (albeit simple)
438 // register allocation problem.
439 if (phases.size() > 1) {
440 glGenFramebuffers(1, &fbo);
442 for (unsigned i = 0; i < phases.size() - 1; ++i) {
443 Effect *output_effect = phases[i].effects.back();
445 glGenTextures(1, &temp_texture);
447 glBindTexture(GL_TEXTURE_2D, temp_texture);
449 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
451 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
453 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
455 effect_output_textures.insert(std::make_pair(output_effect, temp_texture));
459 for (unsigned i = 0; i < inputs.size(); ++i) {
460 inputs[i]->finalize();
466 void EffectChain::render_to_screen()
473 glDisable(GL_DEPTH_TEST);
475 glDepthMask(GL_FALSE);
478 glMatrixMode(GL_PROJECTION);
480 glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
482 glMatrixMode(GL_MODELVIEW);
485 if (phases.size() > 1) {
486 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
490 std::set<Effect *> generated_mipmaps;
491 for (unsigned i = 0; i < inputs.size(); ++i) {
492 // Inputs generate their own mipmaps if they need to
494 generated_mipmaps.insert(inputs[i]);
497 for (unsigned phase = 0; phase < phases.size(); ++phase) {
498 glUseProgram(phases[phase].glsl_program_num);
501 // Set up RTT inputs for this phase.
502 for (unsigned sampler = 0; sampler < phases[phase].inputs.size(); ++sampler) {
503 glActiveTexture(GL_TEXTURE0 + sampler);
504 Effect *input = phases[phase].inputs[sampler];
505 assert(effect_output_textures.count(input) != 0);
506 glBindTexture(GL_TEXTURE_2D, effect_output_textures[input]);
508 if (phases[phase].input_needs_mipmaps) {
509 if (generated_mipmaps.count(input) == 0) {
510 glGenerateMipmap(GL_TEXTURE_2D);
512 generated_mipmaps.insert(input);
514 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
517 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
521 assert(effect_ids.count(input));
522 std::string texture_name = std::string("tex_") + effect_ids[input];
523 glUniform1i(glGetUniformLocation(phases[phase].glsl_program_num, texture_name.c_str()), sampler);
527 // And now the output.
528 if (phase == phases.size() - 1) {
529 // Last phase goes directly to the screen.
530 glBindFramebuffer(GL_FRAMEBUFFER, 0);
533 Effect *last_effect = phases[phase].effects.back();
534 assert(effect_output_textures.count(last_effect) != 0);
535 glFramebufferTexture2D(
537 GL_COLOR_ATTACHMENT0,
539 effect_output_textures[last_effect],
544 // Give the required parameters to all the effects.
545 unsigned sampler_num = phases[phase].inputs.size();
546 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
547 Effect *effect = phases[phase].effects[i];
548 effect->set_gl_state(phases[phase].glsl_program_num, effect_ids[effect], &sampler_num);
554 glTexCoord2f(0.0f, 0.0f);
555 glVertex2f(0.0f, 0.0f);
557 glTexCoord2f(1.0f, 0.0f);
558 glVertex2f(1.0f, 0.0f);
560 glTexCoord2f(1.0f, 1.0f);
561 glVertex2f(1.0f, 1.0f);
563 glTexCoord2f(0.0f, 1.0f);
564 glVertex2f(0.0f, 1.0f);
569 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
570 Effect *effect = phases[phase].effects[i];
571 effect->clear_gl_state();