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 current_color_space = format.color_space;
33 current_gamma_curve = format.gamma_curve;
36 void EffectChain::add_output(const ImageFormat &format)
38 output_format = format;
41 void EffectChain::add_effect_raw(Effect *effect, Effect *input)
43 effects.push_back(effect);
44 outgoing_links.insert(std::make_pair(input, effect));
45 incoming_links.insert(std::make_pair(effect, input));
46 last_added_effect = effect;
49 Effect *instantiate_effect(EffectId effect)
52 case EFFECT_GAMMA_EXPANSION:
53 return new GammaExpansionEffect();
54 case EFFECT_GAMMA_COMPRESSION:
55 return new GammaCompressionEffect();
56 case EFFECT_COLOR_SPACE_CONVERSION:
57 return new ColorSpaceConversionEffect();
59 return new SandboxEffect();
60 case EFFECT_LIFT_GAMMA_GAIN:
61 return new LiftGammaGainEffect();
62 case EFFECT_SATURATION:
63 return new SaturationEffect();
65 return new MirrorEffect();
67 return new VignetteEffect();
69 return new BlurEffect();
74 Effect *EffectChain::normalize_to_linear_gamma(Effect *input)
76 if (current_gamma_curve == GAMMA_sRGB) {
77 // TODO: check if the extension exists
78 use_srgb_texture_format = true;
79 current_gamma_curve = GAMMA_LINEAR;
82 GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
83 gamma_conversion->set_int("source_curve", current_gamma_curve);
84 gamma_conversion->add_self_to_effect_chain(this, input);
85 current_gamma_curve = GAMMA_LINEAR;
86 return gamma_conversion;
90 Effect *EffectChain::normalize_to_srgb(Effect *input)
92 assert(current_gamma_curve == GAMMA_LINEAR);
93 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
94 colorspace_conversion->set_int("source_space", current_color_space);
95 colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
96 colorspace_conversion->add_self_to_effect_chain(this, input);
97 current_color_space = COLORSPACE_sRGB;
98 return colorspace_conversion;
101 Effect *EffectChain::add_effect(EffectId effect_id, Effect *input)
103 Effect *effect = instantiate_effect(effect_id);
105 if (effect->needs_linear_light() && current_gamma_curve != GAMMA_LINEAR) {
106 input = normalize_to_linear_gamma(input);
109 if (effect->needs_srgb_primaries() && current_color_space != COLORSPACE_sRGB) {
110 input = normalize_to_srgb(input);
113 effect->add_self_to_effect_chain(this, input);
117 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
118 std::string replace_prefix(const std::string &text, const std::string &prefix)
123 while (start < text.size()) {
124 size_t pos = text.find("PREFIX(", start);
125 if (pos == std::string::npos) {
126 output.append(text.substr(start, std::string::npos));
130 output.append(text.substr(start, pos - start));
131 output.append(prefix);
134 pos += strlen("PREFIX(");
136 // Output stuff until we find the matching ), which we then eat.
138 size_t end_arg_pos = pos;
139 while (end_arg_pos < text.size()) {
140 if (text[end_arg_pos] == '(') {
142 } else if (text[end_arg_pos] == ')') {
150 output.append(text.substr(pos, end_arg_pos - pos));
158 EffectChain::Phase EffectChain::compile_glsl_program(unsigned start_index, unsigned end_index)
160 bool input_needs_mipmaps = false;
161 std::string frag_shader = read_file("header.frag");
162 for (unsigned i = start_index; i < end_index; ++i) {
164 sprintf(effect_id, "eff%d", i);
167 frag_shader += std::string("#define FUNCNAME ") + effect_id + "\n";
168 frag_shader += replace_prefix(effects[i]->output_convenience_uniforms(), effect_id);
169 frag_shader += replace_prefix(effects[i]->output_fragment_shader(), effect_id);
170 frag_shader += "#undef PREFIX\n";
171 frag_shader += "#undef FUNCNAME\n";
172 frag_shader += "#undef INPUT\n";
173 frag_shader += std::string("#define INPUT ") + effect_id + "\n";
176 input_needs_mipmaps |= effects[i]->needs_mipmaps();
178 frag_shader.append(read_file("footer.frag"));
179 printf("%s\n", frag_shader.c_str());
181 GLuint glsl_program_num = glCreateProgram();
182 GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
183 GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
184 glAttachShader(glsl_program_num, vs_obj);
186 glAttachShader(glsl_program_num, fs_obj);
188 glLinkProgram(glsl_program_num);
192 phase.glsl_program_num = glsl_program_num;
193 phase.input_needs_mipmaps = input_needs_mipmaps;
194 phase.start = start_index;
195 phase.end = end_index;
200 void EffectChain::finalize()
202 // Add normalizers to get the output format right.
203 if (current_color_space != output_format.color_space) {
204 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
205 colorspace_conversion->set_int("source_space", current_color_space);
206 colorspace_conversion->set_int("destination_space", output_format.color_space);
207 effects.push_back(colorspace_conversion);
208 current_color_space = output_format.color_space;
210 if (current_gamma_curve != output_format.gamma_curve) {
211 if (current_gamma_curve != GAMMA_LINEAR) {
212 normalize_to_linear_gamma(last_added_effect); // FIXME
214 assert(current_gamma_curve == GAMMA_LINEAR);
215 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
216 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
217 effects.push_back(gamma_conversion);
218 current_gamma_curve = output_format.gamma_curve;
221 // Construct the GLSL programs. We end a program every time we come
222 // to an effect marked as "needs many samples" (ie. "please let me
223 // sample directly from a texture, with no arithmetic in-between"),
224 // and of course at the end.
226 for (unsigned i = 0; i < effects.size(); ++i) {
227 if (effects[i]->needs_texture_bounce() && i != start) {
228 phases.push_back(compile_glsl_program(start, i));
232 phases.push_back(compile_glsl_program(start, effects.size()));
234 // If we have more than one phase, we need intermediate render-to-texture.
235 // Construct an FBO, and then as many textures as we need.
236 if (phases.size() > 1) {
237 glGenFramebuffers(1, &fbo);
239 unsigned num_textures = std::max<int>(phases.size() - 1, 2);
240 glGenTextures(num_textures, temp_textures);
242 for (unsigned i = 0; i < num_textures; ++i) {
243 glBindTexture(GL_TEXTURE_2D, temp_textures[i]);
245 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
247 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
249 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
254 // Translate the input format to OpenGL's enums.
255 GLenum internal_format;
256 if (use_srgb_texture_format) {
257 internal_format = GL_SRGB8;
259 internal_format = GL_RGBA8;
261 if (input_format.pixel_format == FORMAT_RGB) {
264 } else if (input_format.pixel_format == FORMAT_RGBA) {
267 } else if (input_format.pixel_format == FORMAT_BGR) {
270 } else if (input_format.pixel_format == FORMAT_BGRA) {
277 // Create PBO to hold the texture holding the input image, and then the texture itself.
278 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 2);
280 glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, width * height * bytes_per_pixel, NULL, GL_STREAM_DRAW);
282 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
285 glGenTextures(1, &source_image_num);
287 glBindTexture(GL_TEXTURE_2D, source_image_num);
289 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
291 // Intel/Mesa seems to have a broken glGenerateMipmap() for non-FBO textures, so do it here.
292 glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, phases[0].input_needs_mipmaps ? GL_TRUE : GL_FALSE);
294 glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0, format, GL_UNSIGNED_BYTE, NULL);
300 void EffectChain::render_to_screen(unsigned char *src)
304 // Copy the pixel data into the PBO.
305 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 2);
307 void *mapped_pbo = glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY);
308 memcpy(mapped_pbo, src, width * height * bytes_per_pixel);
309 glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB);
312 // Re-upload the texture from the PBO.
313 glActiveTexture(GL_TEXTURE0);
315 glBindTexture(GL_TEXTURE_2D, source_image_num);
317 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
319 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
321 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
323 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
329 glDisable(GL_DEPTH_TEST);
331 glDepthMask(GL_FALSE);
334 glMatrixMode(GL_PROJECTION);
336 glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
338 glMatrixMode(GL_MODELVIEW);
341 if (phases.size() > 1) {
342 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
346 for (unsigned phase = 0; phase < phases.size(); ++phase) {
347 // Set up inputs and outputs for this phase.
348 glActiveTexture(GL_TEXTURE0);
350 // First phase reads from the input texture (which is already bound).
352 glBindTexture(GL_TEXTURE_2D, temp_textures[(phase + 1) % 2]);
355 if (phases[phase].input_needs_mipmaps) {
357 // For phase 0, it's done further up.
358 glGenerateMipmap(GL_TEXTURE_2D);
361 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
364 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
368 if (phase == phases.size() - 1) {
369 // Last phase goes directly to the screen.
370 glBindFramebuffer(GL_FRAMEBUFFER, 0);
373 glFramebufferTexture2D(
375 GL_COLOR_ATTACHMENT0,
377 temp_textures[phase % 2],
382 // We have baked an upside-down transform into the quad coordinates,
383 // since the typical graphics program will have the origin at the upper-left,
384 // while OpenGL uses lower-left. In the next ones, however, the origin
385 // is all right, and we need to reverse that.
387 glTranslatef(0.0f, 1.0f, 0.0f);
388 glScalef(1.0f, -1.0f, 1.0f);
391 // Give the required parameters to all the effects.
392 glUseProgram(phases[phase].glsl_program_num);
395 glUniform1i(glGetUniformLocation(phases[phase].glsl_program_num, "input_tex"), 0);
398 unsigned sampler_num = 1;
399 for (unsigned i = phases[phase].start; i < phases[phase].end; ++i) {
401 sprintf(effect_id, "eff%d", i);
402 effects[i]->set_uniforms(phases[phase].glsl_program_num, effect_id, &sampler_num);
408 glTexCoord2f(0.0f, 1.0f);
409 glVertex2f(0.0f, 0.0f);
411 glTexCoord2f(1.0f, 1.0f);
412 glVertex2f(1.0f, 0.0f);
414 glTexCoord2f(1.0f, 0.0f);
415 glVertex2f(1.0f, 1.0f);
417 glTexCoord2f(0.0f, 0.0f);
418 glVertex2f(0.0f, 1.0f);
424 glActiveTexture(GL_TEXTURE0);
425 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
427 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1000);