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 "lift_gamma_gain_effect.h"
20 #include "colorspace_conversion_effect.h"
21 #include "sandbox_effect.h"
22 #include "saturation_effect.h"
23 #include "mirror_effect.h"
24 #include "vignette_effect.h"
25 #include "blur_effect.h"
26 #include "diffusion_effect.h"
27 #include "glow_effect.h"
28 #include "mix_effect.h"
31 EffectChain::EffectChain(unsigned width, unsigned height)
36 Input *EffectChain::add_input(const ImageFormat &format)
39 sprintf(eff_id, "src_image%u", (unsigned)inputs.size());
41 Input *input = new Input(format, width, height);
42 effects.push_back(input);
43 inputs.push_back(input);
44 output_color_space.insert(std::make_pair(input, format.color_space));
45 output_gamma_curve.insert(std::make_pair(input, format.gamma_curve));
46 effect_ids.insert(std::make_pair(input, eff_id));
47 incoming_links.insert(std::make_pair(input, std::vector<Effect *>()));
51 void EffectChain::add_output(const ImageFormat &format)
53 output_format = format;
56 void EffectChain::add_effect_raw(Effect *effect, const std::vector<Effect *> &inputs)
59 sprintf(effect_id, "eff%u", (unsigned)effects.size());
61 effects.push_back(effect);
62 effect_ids.insert(std::make_pair(effect, effect_id));
63 assert(inputs.size() == effect->num_inputs());
64 for (unsigned i = 0; i < inputs.size(); ++i) {
65 assert(std::find(effects.begin(), effects.end(), inputs[i]) != effects.end());
66 outgoing_links[inputs[i]].push_back(effect);
68 incoming_links.insert(std::make_pair(effect, inputs));
69 output_gamma_curve[effect] = output_gamma_curve[last_added_effect()];
70 output_color_space[effect] = output_color_space[last_added_effect()];
73 Effect *instantiate_effect(EffectId effect)
76 case EFFECT_GAMMA_EXPANSION:
77 return new GammaExpansionEffect();
78 case EFFECT_GAMMA_COMPRESSION:
79 return new GammaCompressionEffect();
80 case EFFECT_COLOR_SPACE_CONVERSION:
81 return new ColorSpaceConversionEffect();
83 return new SandboxEffect();
84 case EFFECT_LIFT_GAMMA_GAIN:
85 return new LiftGammaGainEffect();
86 case EFFECT_SATURATION:
87 return new SaturationEffect();
89 return new MirrorEffect();
91 return new VignetteEffect();
93 return new BlurEffect();
94 case EFFECT_DIFFUSION:
95 return new DiffusionEffect();
97 return new GlowEffect();
99 return new MixEffect();
104 // Set the "use_srgb_texture_format" option on all inputs that feed into this node,
105 // and update the output_gamma_curve[] map as we go.
107 // NOTE: We assume that the only way we could actually get GAMMA_sRGB from an
108 // effect (except from GammaCompressionCurve, which should never be inserted
109 // into a chain when this is called) is by pass-through from a texture.
110 // Thus, we can simply feed the flag up towards all inputs.
111 void EffectChain::set_use_srgb_texture_format(Effect *effect)
113 assert(output_gamma_curve.count(effect) != 0);
114 assert(output_gamma_curve[effect] == GAMMA_sRGB);
115 if (effect->num_inputs() == 0) {
116 effect->set_int("use_srgb_texture_format", 1);
118 assert(incoming_links.count(effect) == 1);
119 std::vector<Effect *> deps = incoming_links[effect];
120 assert(effect->num_inputs() == deps.size());
121 for (unsigned i = 0; i < deps.size(); ++i) {
122 set_use_srgb_texture_format(deps[i]);
123 assert(output_gamma_curve[deps[i]] == GAMMA_LINEAR);
126 output_gamma_curve[effect] = GAMMA_LINEAR;
129 Effect *EffectChain::normalize_to_linear_gamma(Effect *input)
131 assert(output_gamma_curve.count(input) != 0);
132 if (output_gamma_curve[input] == GAMMA_sRGB) {
133 // TODO: check if the extension exists
134 set_use_srgb_texture_format(input);
135 output_gamma_curve[input] = GAMMA_LINEAR;
138 GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
139 gamma_conversion->set_int("source_curve", output_gamma_curve[input]);
140 std::vector<Effect *> inputs;
141 inputs.push_back(input);
142 gamma_conversion->add_self_to_effect_chain(this, inputs);
143 output_gamma_curve[gamma_conversion] = GAMMA_LINEAR;
144 return gamma_conversion;
148 Effect *EffectChain::normalize_to_srgb(Effect *input)
150 assert(output_gamma_curve.count(input) != 0);
151 assert(output_color_space.count(input) != 0);
152 assert(output_gamma_curve[input] == GAMMA_LINEAR);
153 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
154 colorspace_conversion->set_int("source_space", output_color_space[input]);
155 colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
156 std::vector<Effect *> inputs;
157 inputs.push_back(input);
158 colorspace_conversion->add_self_to_effect_chain(this, inputs);
159 output_color_space[colorspace_conversion] = COLORSPACE_sRGB;
160 return colorspace_conversion;
163 Effect *EffectChain::add_effect(EffectId effect_id, const std::vector<Effect *> &inputs)
165 Effect *effect = instantiate_effect(effect_id);
167 assert(inputs.size() == effect->num_inputs());
169 std::vector<Effect *> normalized_inputs = inputs;
170 for (unsigned i = 0; i < normalized_inputs.size(); ++i) {
171 assert(output_gamma_curve.count(normalized_inputs[i]) != 0);
172 if (effect->needs_linear_light() && output_gamma_curve[normalized_inputs[i]] != GAMMA_LINEAR) {
173 normalized_inputs[i] = normalize_to_linear_gamma(normalized_inputs[i]);
175 assert(output_color_space.count(normalized_inputs[i]) != 0);
176 if (effect->needs_srgb_primaries() && output_color_space[normalized_inputs[i]] != COLORSPACE_sRGB) {
177 normalized_inputs[i] = normalize_to_srgb(normalized_inputs[i]);
181 effect->add_self_to_effect_chain(this, normalized_inputs);
185 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
186 std::string replace_prefix(const std::string &text, const std::string &prefix)
191 while (start < text.size()) {
192 size_t pos = text.find("PREFIX(", start);
193 if (pos == std::string::npos) {
194 output.append(text.substr(start, std::string::npos));
198 output.append(text.substr(start, pos - start));
199 output.append(prefix);
202 pos += strlen("PREFIX(");
204 // Output stuff until we find the matching ), which we then eat.
206 size_t end_arg_pos = pos;
207 while (end_arg_pos < text.size()) {
208 if (text[end_arg_pos] == '(') {
210 } else if (text[end_arg_pos] == ')') {
218 output.append(text.substr(pos, end_arg_pos - pos));
226 EffectChain::Phase EffectChain::compile_glsl_program(const std::vector<Effect *> &inputs, const std::vector<Effect *> &effects)
228 assert(!effects.empty());
230 // Deduplicate the inputs.
231 std::vector<Effect *> true_inputs = inputs;
232 std::sort(true_inputs.begin(), true_inputs.end());
233 true_inputs.erase(std::unique(true_inputs.begin(), true_inputs.end()), true_inputs.end());
235 bool input_needs_mipmaps = false;
236 std::string frag_shader = read_file("header.frag");
238 // Create functions for all the texture inputs that we need.
239 for (unsigned i = 0; i < true_inputs.size(); ++i) {
240 Effect *effect = true_inputs[i];
241 assert(effect_ids.count(effect) != 0);
242 std::string effect_id = effect_ids[effect];
244 frag_shader += std::string("uniform sampler2D tex_") + effect_id + ";\n";
245 frag_shader += std::string("vec4 ") + effect_id + "(vec2 tc) {\n";
246 if (effect->num_inputs() == 0) {
247 // OpenGL's origin is bottom-left, but most graphics software assumes
248 // a top-left origin. Thus, for inputs that come from the user,
249 // we flip the y coordinate. However, for FBOs, the origin
250 // is all correct, so don't do anything.
251 frag_shader += "\ttc.y = 1.0f - tc.y;\n";
253 frag_shader += "\treturn texture2D(tex_" + effect_id + ", tc);\n";
254 frag_shader += "}\n";
258 std::string last_effect_id;
259 for (unsigned i = 0; i < effects.size(); ++i) {
260 Effect *effect = effects[i];
261 assert(effect != NULL);
262 assert(effect_ids.count(effect) != 0);
263 std::string effect_id = effect_ids[effect];
264 last_effect_id = effect_id;
266 if (incoming_links[effect].size() == 1) {
267 frag_shader += std::string("#define INPUT ") + effect_ids[incoming_links[effect][0]] + "\n";
269 for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
271 sprintf(buf, "#define INPUT%d %s\n", j + 1, effect_ids[incoming_links[effect][j]].c_str());
277 frag_shader += std::string("#define FUNCNAME ") + effect_id + "\n";
278 frag_shader += replace_prefix(effect->output_convenience_uniforms(), effect_id);
279 frag_shader += replace_prefix(effect->output_fragment_shader(), effect_id);
280 frag_shader += "#undef PREFIX\n";
281 frag_shader += "#undef FUNCNAME\n";
282 if (incoming_links[effect].size() == 1) {
283 frag_shader += "#undef INPUT\n";
285 for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
287 sprintf(buf, "#undef INPUT%d\n", j + 1);
293 input_needs_mipmaps |= effect->needs_mipmaps();
295 for (unsigned i = 0; i < effects.size(); ++i) {
296 Effect *effect = effects[i];
297 if (effect->num_inputs() == 0) {
298 effect->set_int("needs_mipmaps", input_needs_mipmaps);
301 assert(!last_effect_id.empty());
302 frag_shader += std::string("#define INPUT ") + last_effect_id + "\n";
303 frag_shader.append(read_file("footer.frag"));
304 printf("%s\n", frag_shader.c_str());
306 GLuint glsl_program_num = glCreateProgram();
307 GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
308 GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
309 glAttachShader(glsl_program_num, vs_obj);
311 glAttachShader(glsl_program_num, fs_obj);
313 glLinkProgram(glsl_program_num);
317 phase.glsl_program_num = glsl_program_num;
318 phase.input_needs_mipmaps = input_needs_mipmaps;
319 phase.inputs = true_inputs;
320 phase.effects = effects;
325 // Construct GLSL programs, starting at the given effect and following
326 // the chain from there. We end a program every time we come to an effect
327 // marked as "needs texture bounce", one that is used by multiple other
328 // effects, and of course at the end.
330 // We follow a quite simple depth-first search from the output, although
331 // without any explicit recursion.
332 void EffectChain::construct_glsl_programs(Effect *output)
334 // Which effects have already been completed in this phase?
335 // We need to keep track of it, as an effect with multiple outputs
336 // could otherwise be calculate multiple times.
337 std::set<Effect *> completed_effects;
339 // Effects in the current phase, as well as inputs (outputs from other phases
340 // that we depend on). Note that since we start iterating from the end,
341 // the effect list will be in the reverse order.
342 std::vector<Effect *> this_phase_inputs;
343 std::vector<Effect *> this_phase_effects;
345 // Effects that we have yet to calculate, but that we know should
346 // be in the current phase.
347 std::stack<Effect *> effects_todo_this_phase;
349 // Effects that we have yet to calculate, but that come from other phases.
350 // We delay these until we have this phase done in its entirety,
351 // at which point we pick any of them and start a new phase from that.
352 std::stack<Effect *> effects_todo_other_phases;
354 effects_todo_this_phase.push(output);
356 for ( ;; ) { // Termination condition within loop.
357 if (!effects_todo_this_phase.empty()) {
358 // OK, we have more to do this phase.
359 Effect *effect = effects_todo_this_phase.top();
360 effects_todo_this_phase.pop();
362 // This should currently only happen for effects that are phase outputs,
363 // and we throw those out separately below.
364 assert(completed_effects.count(effect) == 0);
366 this_phase_effects.push_back(effect);
367 completed_effects.insert(effect);
369 // Find all the dependencies of this effect, and add them to the stack.
370 assert(incoming_links.count(effect) == 1);
371 std::vector<Effect *> deps = incoming_links[effect];
372 assert(effect->num_inputs() == deps.size());
373 for (unsigned i = 0; i < deps.size(); ++i) {
374 bool start_new_phase = false;
376 if (effect->needs_texture_bounce()) {
377 start_new_phase = true;
380 assert(outgoing_links.count(deps[i]) == 1);
381 if (outgoing_links[deps[i]].size() > 1 && deps[i]->num_inputs() > 0) {
382 // More than one effect uses this as the input,
383 // and it is not a texture itself.
384 // The easiest thing to do (and probably also the safest
385 // performance-wise in most cases) is to bounce it to a texture
386 // and then let the next passes read from that.
387 start_new_phase = true;
390 if (start_new_phase) {
391 effects_todo_other_phases.push(deps[i]);
392 this_phase_inputs.push_back(deps[i]);
394 effects_todo_this_phase.push(deps[i]);
400 // No more effects to do this phase. Take all the ones we have,
401 // and create a GLSL program for it.
402 if (!this_phase_effects.empty()) {
403 reverse(this_phase_effects.begin(), this_phase_effects.end());
404 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
405 this_phase_inputs.clear();
406 this_phase_effects.clear();
408 assert(this_phase_inputs.empty());
409 assert(this_phase_effects.empty());
411 // If we have no effects left, exit.
412 if (effects_todo_other_phases.empty()) {
416 Effect *effect = effects_todo_other_phases.top();
417 effects_todo_other_phases.pop();
419 if (completed_effects.count(effect) == 0) {
420 // Start a new phase, calculating from this effect.
421 effects_todo_this_phase.push(effect);
425 // Finally, since the phases are found from the output but must be executed
426 // from the input(s), reverse them, too.
427 std::reverse(phases.begin(), phases.end());
430 void EffectChain::finalize()
432 // Find the output effect. This is, simply, one that has no outgoing links.
433 // If there are multiple ones, the graph is malformed (we do not support
434 // multiple outputs right now).
435 std::vector<Effect *> output_effects;
436 for (unsigned i = 0; i < effects.size(); ++i) {
437 Effect *effect = effects[i];
438 if (outgoing_links.count(effect) == 0 || outgoing_links[effect].size() == 0) {
439 output_effects.push_back(effect);
442 assert(output_effects.size() == 1);
443 Effect *output_effect = output_effects[0];
445 // Add normalizers to get the output format right.
446 assert(output_gamma_curve.count(output_effect) != 0);
447 assert(output_color_space.count(output_effect) != 0);
448 ColorSpace current_color_space = output_color_space[output_effect];
449 if (current_color_space != output_format.color_space) {
450 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
451 colorspace_conversion->set_int("source_space", current_color_space);
452 colorspace_conversion->set_int("destination_space", output_format.color_space);
453 std::vector<Effect *> inputs;
454 inputs.push_back(output_effect);
455 colorspace_conversion->add_self_to_effect_chain(this, inputs);
456 output_color_space[colorspace_conversion] = output_format.color_space;
457 output_effect = colorspace_conversion;
459 GammaCurve current_gamma_curve = output_gamma_curve[output_effect];
460 if (current_gamma_curve != output_format.gamma_curve) {
461 if (current_gamma_curve != GAMMA_LINEAR) {
462 output_effect = normalize_to_linear_gamma(output_effect);
463 current_gamma_curve = GAMMA_LINEAR;
465 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
466 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
467 std::vector<Effect *> inputs;
468 inputs.push_back(output_effect);
469 gamma_conversion->add_self_to_effect_chain(this, inputs);
470 output_gamma_curve[gamma_conversion] = output_format.gamma_curve;
471 output_effect = gamma_conversion;
474 // Construct all needed GLSL programs, starting at the output.
475 construct_glsl_programs(output_effect);
477 // If we have more than one phase, we need intermediate render-to-texture.
478 // Construct an FBO, and then as many textures as we need.
479 // We choose the simplest option of having one texture per output,
480 // since otherwise this turns into an (albeit simple)
481 // register allocation problem.
482 if (phases.size() > 1) {
483 glGenFramebuffers(1, &fbo);
485 for (unsigned i = 0; i < phases.size() - 1; ++i) {
486 Effect *output_effect = phases[i].effects.back();
488 glGenTextures(1, &temp_texture);
490 glBindTexture(GL_TEXTURE_2D, temp_texture);
492 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
494 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
496 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
498 effect_output_textures.insert(std::make_pair(output_effect, temp_texture));
502 for (unsigned i = 0; i < inputs.size(); ++i) {
503 inputs[i]->finalize();
509 void EffectChain::render_to_screen()
516 glDisable(GL_DEPTH_TEST);
518 glDepthMask(GL_FALSE);
521 glMatrixMode(GL_PROJECTION);
523 glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
525 glMatrixMode(GL_MODELVIEW);
528 if (phases.size() > 1) {
529 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
533 std::set<Effect *> generated_mipmaps;
534 for (unsigned i = 0; i < inputs.size(); ++i) {
535 // Inputs generate their own mipmaps if they need to
537 generated_mipmaps.insert(inputs[i]);
540 for (unsigned phase = 0; phase < phases.size(); ++phase) {
541 glUseProgram(phases[phase].glsl_program_num);
544 // Set up RTT inputs for this phase.
545 for (unsigned sampler = 0; sampler < phases[phase].inputs.size(); ++sampler) {
546 glActiveTexture(GL_TEXTURE0 + sampler);
547 Effect *input = phases[phase].inputs[sampler];
548 assert(effect_output_textures.count(input) != 0);
549 glBindTexture(GL_TEXTURE_2D, effect_output_textures[input]);
551 if (phases[phase].input_needs_mipmaps) {
552 if (generated_mipmaps.count(input) == 0) {
553 glGenerateMipmap(GL_TEXTURE_2D);
555 generated_mipmaps.insert(input);
557 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
560 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
564 assert(effect_ids.count(input));
565 std::string texture_name = std::string("tex_") + effect_ids[input];
566 glUniform1i(glGetUniformLocation(phases[phase].glsl_program_num, texture_name.c_str()), sampler);
570 // And now the output.
571 if (phase == phases.size() - 1) {
572 // Last phase goes directly to the screen.
573 glBindFramebuffer(GL_FRAMEBUFFER, 0);
576 Effect *last_effect = phases[phase].effects.back();
577 assert(effect_output_textures.count(last_effect) != 0);
578 glFramebufferTexture2D(
580 GL_COLOR_ATTACHMENT0,
582 effect_output_textures[last_effect],
587 // Give the required parameters to all the effects.
588 unsigned sampler_num = phases[phase].inputs.size();
589 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
590 Effect *effect = phases[phase].effects[i];
591 effect->set_gl_state(phases[phase].glsl_program_num, effect_ids[effect], &sampler_num);
597 glTexCoord2f(0.0f, 0.0f);
598 glVertex2f(0.0f, 0.0f);
600 glTexCoord2f(1.0f, 0.0f);
601 glVertex2f(1.0f, 0.0f);
603 glTexCoord2f(1.0f, 1.0f);
604 glVertex2f(1.0f, 1.0f);
606 glTexCoord2f(0.0f, 1.0f);
607 glVertex2f(0.0f, 1.0f);
612 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
613 Effect *effect = phases[phase].effects[i];
614 effect->clear_gl_state();