1 #define GL_GLEXT_PROTOTYPES 1
11 #include "effect_chain.h"
12 #include "gamma_expansion_effect.h"
13 #include "gamma_compression_effect.h"
14 #include "lift_gamma_gain_effect.h"
15 #include "colorspace_conversion_effect.h"
16 #include "sandbox_effect.h"
17 #include "saturation_effect.h"
18 #include "mirror_effect.h"
19 #include "vignette_effect.h"
20 #include "blur_effect.h"
22 EffectChain::EffectChain(unsigned width, unsigned height)
25 last_added_effect(NULL),
26 use_srgb_texture_format(false),
29 void EffectChain::add_input(const ImageFormat &format)
31 input_format = format;
32 output_color_space.insert(std::make_pair(static_cast<Effect *>(NULL), format.color_space));
33 output_gamma_curve.insert(std::make_pair(static_cast<Effect *>(NULL), format.gamma_curve));
36 void EffectChain::add_output(const ImageFormat &format)
38 output_format = format;
41 void EffectChain::add_effect_raw(Effect *effect, const std::vector<Effect *> &inputs)
43 effects.push_back(effect);
44 assert(inputs.size() == effect->num_inputs());
45 for (unsigned i = 0; i < inputs.size(); ++i) {
46 outgoing_links.insert(std::make_pair(inputs[i], effect));
47 incoming_links.insert(std::make_pair(effect, inputs[i]));
49 last_added_effect = effect;
52 Effect *instantiate_effect(EffectId effect)
55 case EFFECT_GAMMA_EXPANSION:
56 return new GammaExpansionEffect();
57 case EFFECT_GAMMA_COMPRESSION:
58 return new GammaCompressionEffect();
59 case EFFECT_COLOR_SPACE_CONVERSION:
60 return new ColorSpaceConversionEffect();
62 return new SandboxEffect();
63 case EFFECT_LIFT_GAMMA_GAIN:
64 return new LiftGammaGainEffect();
65 case EFFECT_SATURATION:
66 return new SaturationEffect();
68 return new MirrorEffect();
70 return new VignetteEffect();
72 return new BlurEffect();
77 Effect *EffectChain::normalize_to_linear_gamma(Effect *input)
79 GammaCurve current_gamma_curve = output_gamma_curve[input];
80 if (current_gamma_curve == GAMMA_sRGB) {
81 // TODO: check if the extension exists
82 use_srgb_texture_format = true;
83 current_gamma_curve = GAMMA_LINEAR;
86 GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
87 gamma_conversion->set_int("source_curve", current_gamma_curve);
88 std::vector<Effect *> inputs;
89 inputs.push_back(input);
90 gamma_conversion->add_self_to_effect_chain(this, inputs);
91 current_gamma_curve = GAMMA_LINEAR;
92 return gamma_conversion;
96 Effect *EffectChain::normalize_to_srgb(Effect *input)
98 GammaCurve current_gamma_curve = output_gamma_curve[input];
99 ColorSpace current_color_space = output_color_space[input];
100 assert(current_gamma_curve == GAMMA_LINEAR);
101 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
102 colorspace_conversion->set_int("source_space", current_color_space);
103 colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
104 std::vector<Effect *> inputs;
105 inputs.push_back(input);
106 colorspace_conversion->add_self_to_effect_chain(this, inputs);
107 current_color_space = COLORSPACE_sRGB;
108 return colorspace_conversion;
111 Effect *EffectChain::add_effect(EffectId effect_id, const std::vector<Effect *> &inputs)
113 Effect *effect = instantiate_effect(effect_id);
115 assert(inputs.size() == effect->num_inputs());
117 std::vector<Effect *> normalized_inputs = inputs;
118 for (unsigned i = 0; i < normalized_inputs.size(); ++i) {
119 if (effect->needs_linear_light() && output_gamma_curve[normalized_inputs[i]] != GAMMA_LINEAR) {
120 normalized_inputs[i] = normalize_to_linear_gamma(normalized_inputs[i]);
122 if (effect->needs_srgb_primaries() && output_color_space[normalized_inputs[i]] != COLORSPACE_sRGB) {
123 normalized_inputs[i] = normalize_to_srgb(normalized_inputs[i]);
127 effect->add_self_to_effect_chain(this, normalized_inputs);
131 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
132 std::string replace_prefix(const std::string &text, const std::string &prefix)
137 while (start < text.size()) {
138 size_t pos = text.find("PREFIX(", start);
139 if (pos == std::string::npos) {
140 output.append(text.substr(start, std::string::npos));
144 output.append(text.substr(start, pos - start));
145 output.append(prefix);
148 pos += strlen("PREFIX(");
150 // Output stuff until we find the matching ), which we then eat.
152 size_t end_arg_pos = pos;
153 while (end_arg_pos < text.size()) {
154 if (text[end_arg_pos] == '(') {
156 } else if (text[end_arg_pos] == ')') {
164 output.append(text.substr(pos, end_arg_pos - pos));
172 EffectChain::Phase EffectChain::compile_glsl_program(unsigned start_index, unsigned end_index)
174 bool input_needs_mipmaps = false;
175 std::string frag_shader = read_file("header.frag");
176 for (unsigned i = start_index; i < end_index; ++i) {
178 sprintf(effect_id, "eff%d", i);
181 frag_shader += std::string("#define FUNCNAME ") + effect_id + "\n";
182 frag_shader += replace_prefix(effects[i]->output_convenience_uniforms(), effect_id);
183 frag_shader += replace_prefix(effects[i]->output_fragment_shader(), effect_id);
184 frag_shader += "#undef PREFIX\n";
185 frag_shader += "#undef FUNCNAME\n";
186 frag_shader += "#undef INPUT\n";
187 frag_shader += std::string("#define INPUT ") + effect_id + "\n";
190 input_needs_mipmaps |= effects[i]->needs_mipmaps();
192 frag_shader.append(read_file("footer.frag"));
193 printf("%s\n", frag_shader.c_str());
195 GLuint glsl_program_num = glCreateProgram();
196 GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
197 GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
198 glAttachShader(glsl_program_num, vs_obj);
200 glAttachShader(glsl_program_num, fs_obj);
202 glLinkProgram(glsl_program_num);
206 phase.glsl_program_num = glsl_program_num;
207 phase.input_needs_mipmaps = input_needs_mipmaps;
208 phase.start = start_index;
209 phase.end = end_index;
214 void EffectChain::finalize()
216 // Add normalizers to get the output format right.
217 GammaCurve current_gamma_curve = output_gamma_curve[last_added_effect]; // FIXME
218 ColorSpace current_color_space = output_color_space[last_added_effect]; // FIXME
219 if (current_color_space != output_format.color_space) {
220 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
221 colorspace_conversion->set_int("source_space", current_color_space);
222 colorspace_conversion->set_int("destination_space", output_format.color_space);
223 effects.push_back(colorspace_conversion);
224 current_color_space = output_format.color_space;
226 if (current_gamma_curve != output_format.gamma_curve) {
227 if (current_gamma_curve != GAMMA_LINEAR) {
228 normalize_to_linear_gamma(last_added_effect); // FIXME
230 assert(current_gamma_curve == GAMMA_LINEAR);
231 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
232 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
233 effects.push_back(gamma_conversion);
234 current_gamma_curve = output_format.gamma_curve;
237 // Construct the GLSL programs. We end a program every time we come
238 // to an effect marked as "needs many samples" (ie. "please let me
239 // sample directly from a texture, with no arithmetic in-between"),
240 // and of course at the end.
242 for (unsigned i = 0; i < effects.size(); ++i) {
243 if (effects[i]->needs_texture_bounce() && i != start) {
244 phases.push_back(compile_glsl_program(start, i));
248 phases.push_back(compile_glsl_program(start, effects.size()));
250 // If we have more than one phase, we need intermediate render-to-texture.
251 // Construct an FBO, and then as many textures as we need.
252 if (phases.size() > 1) {
253 glGenFramebuffers(1, &fbo);
255 unsigned num_textures = std::max<int>(phases.size() - 1, 2);
256 glGenTextures(num_textures, temp_textures);
258 for (unsigned i = 0; i < num_textures; ++i) {
259 glBindTexture(GL_TEXTURE_2D, temp_textures[i]);
261 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
263 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
265 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
270 // Translate the input format to OpenGL's enums.
271 GLenum internal_format;
272 if (use_srgb_texture_format) {
273 internal_format = GL_SRGB8;
275 internal_format = GL_RGBA8;
277 if (input_format.pixel_format == FORMAT_RGB) {
280 } else if (input_format.pixel_format == FORMAT_RGBA) {
283 } else if (input_format.pixel_format == FORMAT_BGR) {
286 } else if (input_format.pixel_format == FORMAT_BGRA) {
293 // Create PBO to hold the texture holding the input image, and then the texture itself.
294 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 2);
296 glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, width * height * bytes_per_pixel, NULL, GL_STREAM_DRAW);
298 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
301 glGenTextures(1, &source_image_num);
303 glBindTexture(GL_TEXTURE_2D, source_image_num);
305 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
307 // Intel/Mesa seems to have a broken glGenerateMipmap() for non-FBO textures, so do it here.
308 glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, phases[0].input_needs_mipmaps ? GL_TRUE : GL_FALSE);
310 glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0, format, GL_UNSIGNED_BYTE, NULL);
316 void EffectChain::render_to_screen(unsigned char *src)
320 // Copy the pixel data into the PBO.
321 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 2);
323 void *mapped_pbo = glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY);
324 memcpy(mapped_pbo, src, width * height * bytes_per_pixel);
325 glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB);
328 // Re-upload the texture from the PBO.
329 glActiveTexture(GL_TEXTURE0);
331 glBindTexture(GL_TEXTURE_2D, source_image_num);
333 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
335 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
337 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
339 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
345 glDisable(GL_DEPTH_TEST);
347 glDepthMask(GL_FALSE);
350 glMatrixMode(GL_PROJECTION);
352 glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
354 glMatrixMode(GL_MODELVIEW);
357 if (phases.size() > 1) {
358 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
362 for (unsigned phase = 0; phase < phases.size(); ++phase) {
363 // Set up inputs and outputs for this phase.
364 glActiveTexture(GL_TEXTURE0);
366 // First phase reads from the input texture (which is already bound).
368 glBindTexture(GL_TEXTURE_2D, temp_textures[(phase + 1) % 2]);
371 if (phases[phase].input_needs_mipmaps) {
373 // For phase 0, it's done further up.
374 glGenerateMipmap(GL_TEXTURE_2D);
377 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
380 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
384 if (phase == phases.size() - 1) {
385 // Last phase goes directly to the screen.
386 glBindFramebuffer(GL_FRAMEBUFFER, 0);
389 glFramebufferTexture2D(
391 GL_COLOR_ATTACHMENT0,
393 temp_textures[phase % 2],
398 // We have baked an upside-down transform into the quad coordinates,
399 // since the typical graphics program will have the origin at the upper-left,
400 // while OpenGL uses lower-left. In the next ones, however, the origin
401 // is all right, and we need to reverse that.
403 glTranslatef(0.0f, 1.0f, 0.0f);
404 glScalef(1.0f, -1.0f, 1.0f);
407 // Give the required parameters to all the effects.
408 glUseProgram(phases[phase].glsl_program_num);
411 glUniform1i(glGetUniformLocation(phases[phase].glsl_program_num, "input_tex"), 0);
414 unsigned sampler_num = 1;
415 for (unsigned i = phases[phase].start; i < phases[phase].end; ++i) {
417 sprintf(effect_id, "eff%d", i);
418 effects[i]->set_uniforms(phases[phase].glsl_program_num, effect_id, &sampler_num);
424 glTexCoord2f(0.0f, 1.0f);
425 glVertex2f(0.0f, 0.0f);
427 glTexCoord2f(1.0f, 1.0f);
428 glVertex2f(1.0f, 0.0f);
430 glTexCoord2f(1.0f, 0.0f);
431 glVertex2f(1.0f, 1.0f);
433 glTexCoord2f(0.0f, 0.0f);
434 glVertex2f(0.0f, 1.0f);
440 glActiveTexture(GL_TEXTURE0);
441 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
443 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1000);