4 #include "dither_effect.h"
10 // A simple LCG (linear congruental generator) random generator.
11 // We implement our own so we can be deterministic from frame to frame
12 // and run to run; we don't have special needs for speed or quality,
13 // as long as the period is reasonably long. The output is in range
16 // This comes from http://en.wikipedia.org/wiki/Linear_congruential_generator.
17 unsigned lcg_rand(unsigned x)
19 return (x * 1103515245U + 12345U) & ((1U << 31) - 1);
24 DitherEffect::DitherEffect()
25 : width(1280), height(720), num_bits(8),
26 last_width(-1), last_height(-1), last_num_bits(-1)
28 register_int("output_width", &width);
29 register_int("output_height", &height);
30 register_int("num_bits", &num_bits);
32 glGenTextures(1, &texnum);
35 DitherEffect::~DitherEffect()
37 glDeleteTextures(1, &texnum);
40 std::string DitherEffect::output_fragment_shader()
42 return read_file("dither_effect.frag");
45 void DitherEffect::update_texture(GLuint glsl_program_num, const std::string &prefix, unsigned *sampler_num)
47 float *dither_noise = new float[width * height];
48 float dither_double_amplitude = 1.0f / (1 << num_bits);
50 // Using the resolution as a seed gives us a consistent dither from frame to frame.
51 // It also gives a different dither for e.g. different aspect ratios, which _feels_
52 // good, but probably shouldn't matter.
53 unsigned seed = (width << 16) ^ height;
54 for (int i = 0; i < width * height; ++i) {
55 seed = lcg_rand(seed);
56 float normalized_rand = seed * (1.0f / (1U << 31)) - 0.5; // [-0.5, 0.5>
57 dither_noise[i] = dither_double_amplitude * normalized_rand;
60 glActiveTexture(GL_TEXTURE0 + *sampler_num);
62 glBindTexture(GL_TEXTURE_2D, texnum);
64 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
66 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
68 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
70 glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16F_ARB, width, height, 0, GL_LUMINANCE, GL_FLOAT, dither_noise);
73 delete[] dither_noise;
76 void DitherEffect::set_gl_state(GLuint glsl_program_num, const std::string &prefix, unsigned *sampler_num)
78 Effect::set_gl_state(glsl_program_num, prefix, sampler_num);
80 if (width != last_width || height != last_height || num_bits != last_num_bits) {
81 update_texture(glsl_program_num, prefix, sampler_num);
84 last_num_bits = num_bits;
87 glActiveTexture(GL_TEXTURE0 + *sampler_num);
89 glBindTexture(GL_TEXTURE_2D, texnum);
92 set_uniform_int(glsl_program_num, prefix, "dither_tex", *sampler_num);