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)
23 : width(width), height(height), use_srgb_texture_format(false), finalized(false) {}
25 void EffectChain::add_input(const ImageFormat &format)
27 input_format = format;
28 current_color_space = format.color_space;
29 current_gamma_curve = format.gamma_curve;
32 void EffectChain::add_output(const ImageFormat &format)
34 output_format = format;
37 Effect *instantiate_effect(EffectId effect)
40 case EFFECT_GAMMA_EXPANSION:
41 return new GammaExpansionEffect();
42 case EFFECT_GAMMA_COMPRESSION:
43 return new GammaCompressionEffect();
44 case EFFECT_COLOR_SPACE_CONVERSION:
45 return new ColorSpaceConversionEffect();
47 return new SandboxEffect();
48 case EFFECT_LIFT_GAMMA_GAIN:
49 return new LiftGammaGainEffect();
50 case EFFECT_SATURATION:
51 return new SaturationEffect();
53 return new MirrorEffect();
55 return new VignetteEffect();
57 return new BlurEffect();
62 void EffectChain::normalize_to_linear_gamma()
64 if (current_gamma_curve == GAMMA_sRGB) {
65 // TODO: check if the extension exists
66 use_srgb_texture_format = true;
68 GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
69 gamma_conversion->set_int("source_curve", current_gamma_curve);
70 gamma_conversion->add_self_to_effect_chain(&effects);
72 current_gamma_curve = GAMMA_LINEAR;
75 void EffectChain::normalize_to_srgb()
77 assert(current_gamma_curve == GAMMA_LINEAR);
78 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
79 colorspace_conversion->set_int("source_space", current_color_space);
80 colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
81 colorspace_conversion->add_self_to_effect_chain(&effects);
82 current_color_space = COLORSPACE_sRGB;
85 Effect *EffectChain::add_effect(EffectId effect_id)
87 Effect *effect = instantiate_effect(effect_id);
89 if (effect->needs_linear_light() && current_gamma_curve != GAMMA_LINEAR) {
90 normalize_to_linear_gamma();
93 if (effect->needs_srgb_primaries() && current_color_space != COLORSPACE_sRGB) {
97 effect->add_self_to_effect_chain(&effects);
101 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
102 std::string replace_prefix(const std::string &text, const std::string &prefix)
107 while (start < text.size()) {
108 size_t pos = text.find("PREFIX(", start);
109 if (pos == std::string::npos) {
110 output.append(text.substr(start, std::string::npos));
114 output.append(text.substr(start, pos - start));
115 output.append(prefix);
118 pos += strlen("PREFIX(");
120 // Output stuff until we find the matching ), which we then eat.
122 size_t end_arg_pos = pos;
123 while (end_arg_pos < text.size()) {
124 if (text[end_arg_pos] == '(') {
126 } else if (text[end_arg_pos] == ')') {
134 output.append(text.substr(pos, end_arg_pos - pos));
142 EffectChain::Phase EffectChain::compile_glsl_program(unsigned start_index, unsigned end_index)
144 bool input_needs_mipmaps = false;
145 std::string frag_shader = read_file("header.frag");
146 for (unsigned i = start_index; i < end_index; ++i) {
148 sprintf(effect_id, "eff%d", i);
151 frag_shader += std::string("#define FUNCNAME ") + effect_id + "\n";
152 frag_shader += replace_prefix(effects[i]->output_convenience_uniforms(), effect_id);
153 frag_shader += replace_prefix(effects[i]->output_fragment_shader(), effect_id);
154 frag_shader += "#undef PREFIX\n";
155 frag_shader += "#undef FUNCNAME\n";
156 frag_shader += "#undef LAST_INPUT\n";
157 frag_shader += std::string("#define LAST_INPUT ") + effect_id + "\n";
160 input_needs_mipmaps |= effects[i]->needs_mipmaps();
162 frag_shader.append(read_file("footer.frag"));
163 printf("%s\n", frag_shader.c_str());
165 GLuint glsl_program_num = glCreateProgram();
166 GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
167 GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
168 glAttachShader(glsl_program_num, vs_obj);
170 glAttachShader(glsl_program_num, fs_obj);
172 glLinkProgram(glsl_program_num);
176 phase.glsl_program_num = glsl_program_num;
177 phase.input_needs_mipmaps = input_needs_mipmaps;
178 phase.start = start_index;
179 phase.end = end_index;
184 void EffectChain::finalize()
186 // Add normalizers to get the output format right.
187 if (current_color_space != output_format.color_space) {
188 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
189 colorspace_conversion->set_int("source_space", current_color_space);
190 colorspace_conversion->set_int("destination_space", output_format.color_space);
191 effects.push_back(colorspace_conversion);
192 current_color_space = output_format.color_space;
194 if (current_gamma_curve != output_format.gamma_curve) {
195 if (current_gamma_curve != GAMMA_LINEAR) {
196 normalize_to_linear_gamma();
198 assert(current_gamma_curve == GAMMA_LINEAR);
199 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
200 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
201 effects.push_back(gamma_conversion);
202 current_gamma_curve = output_format.gamma_curve;
205 // Construct the GLSL programs. We end a program every time we come
206 // to an effect marked as "needs many samples" (ie. "please let me
207 // sample directly from a texture, with no arithmetic in-between"),
208 // and of course at the end.
210 for (unsigned i = 0; i < effects.size(); ++i) {
211 if (effects[i]->needs_many_samples() && i != start) {
212 phases.push_back(compile_glsl_program(start, i));
216 phases.push_back(compile_glsl_program(start, effects.size()));
218 // If we have more than one phase, we need intermediate render-to-texture.
219 // Construct an FBO, and then as many textures as we need.
220 if (phases.size() > 1) {
221 glGenFramebuffers(1, &fbo);
223 unsigned num_textures = std::max<int>(phases.size() - 1, 2);
224 glGenTextures(num_textures, temp_textures);
226 for (unsigned i = 0; i < num_textures; ++i) {
227 glBindTexture(GL_TEXTURE_2D, temp_textures[i]);
229 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
231 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
233 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
238 // Translate the input format to OpenGL's enums.
239 GLenum internal_format;
240 if (use_srgb_texture_format) {
241 internal_format = GL_SRGB8;
243 internal_format = GL_RGBA8;
245 if (input_format.pixel_format == FORMAT_RGB) {
248 } else if (input_format.pixel_format == FORMAT_RGBA) {
251 } else if (input_format.pixel_format == FORMAT_BGR) {
254 } else if (input_format.pixel_format == FORMAT_BGRA) {
261 // Create PBO to hold the texture holding the input image, and then the texture itself.
262 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 2);
264 glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, width * height * bytes_per_pixel, NULL, GL_STREAM_DRAW);
266 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
269 glGenTextures(1, &source_image_num);
271 glBindTexture(GL_TEXTURE_2D, source_image_num);
273 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
275 glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0, format, GL_UNSIGNED_BYTE, NULL);
281 void EffectChain::render_to_screen(unsigned char *src)
285 // Copy the pixel data into the PBO.
286 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 2);
288 void *mapped_pbo = glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY);
289 memcpy(mapped_pbo, src, width * height * bytes_per_pixel);
290 glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB);
293 // Re-upload the texture from the PBO.
294 glActiveTexture(GL_TEXTURE0);
296 glBindTexture(GL_TEXTURE_2D, source_image_num);
298 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
300 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
302 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
305 // Intel/Mesa seems to have a broken glGenerateMipmap() for non-FBO textures, so do it here.
306 glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, phases[0].input_needs_mipmaps ? GL_TRUE : GL_FALSE);
309 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
315 glDisable(GL_DEPTH_TEST);
317 glDepthMask(GL_FALSE);
320 glMatrixMode(GL_PROJECTION);
322 glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
324 glMatrixMode(GL_MODELVIEW);
327 if (phases.size() > 1) {
328 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
332 for (unsigned phase = 0; phase < phases.size(); ++phase) {
333 // Set up inputs and outputs for this phase.
334 glActiveTexture(GL_TEXTURE0);
336 // First phase reads from the input texture (which is already bound).
338 glBindTexture(GL_TEXTURE_2D, temp_textures[(phase + 1) % 2]);
341 if (phases[phase].input_needs_mipmaps) {
343 // For phase 0, it's done further up.
344 glGenerateMipmap(GL_TEXTURE_2D);
347 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
350 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
354 if (phase == phases.size() - 1) {
355 // Last phase goes directly to the screen.
356 glBindFramebuffer(GL_FRAMEBUFFER, 0);
359 glFramebufferTexture2D(
361 GL_COLOR_ATTACHMENT0,
363 temp_textures[phase % 2],
368 // We have baked an upside-down transform into the quad coordinates,
369 // since the typical graphics program will have the origin at the upper-left,
370 // while OpenGL uses lower-left. In the next ones, however, the origin
371 // is all right, and we need to reverse that.
373 glTranslatef(0.0f, 1.0f, 0.0f);
374 glScalef(1.0f, -1.0f, 1.0f);
377 // Give the required parameters to all the effects.
378 glUseProgram(phases[phase].glsl_program_num);
381 glUniform1i(glGetUniformLocation(phases[phase].glsl_program_num, "input_tex"), 0);
384 unsigned sampler_num = 1;
385 for (unsigned i = phases[phase].start; i < phases[phase].end; ++i) {
387 sprintf(effect_id, "eff%d", i);
388 effects[i]->set_uniforms(phases[phase].glsl_program_num, effect_id, &sampler_num);
394 glTexCoord2f(0.0f, 1.0f);
395 glVertex2f(0.0f, 0.0f);
397 glTexCoord2f(1.0f, 1.0f);
398 glVertex2f(1.0f, 0.0f);
400 glTexCoord2f(1.0f, 0.0f);
401 glVertex2f(1.0f, 1.0f);
403 glTexCoord2f(0.0f, 0.0f);
404 glVertex2f(0.0f, 1.0f);
410 glActiveTexture(GL_TEXTURE0);
411 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
413 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1000);