4 #include "flat_input.h"
8 FlatInput::FlatInput(ImageFormat image_format, unsigned width, unsigned height)
9 : image_format(image_format),
12 output_linear_gamma(false),
18 register_int("output_linear_gamma", &output_linear_gamma);
19 register_int("needs_mipmaps", &needs_mipmaps);
22 void FlatInput::finalize()
24 // Translate the input format to OpenGL's enums.
25 GLenum internal_format;
26 if (output_linear_gamma) {
27 internal_format = GL_SRGB8;
29 internal_format = GL_RGBA8;
31 if (image_format.pixel_format == FORMAT_RGB) {
34 } else if (image_format.pixel_format == FORMAT_RGBA) {
37 } else if (image_format.pixel_format == FORMAT_BGR) {
40 } else if (image_format.pixel_format == FORMAT_BGRA) {
43 } else if (image_format.pixel_format == FORMAT_GRAYSCALE) {
44 format = GL_LUMINANCE;
50 // Create PBO to hold the texture holding the input image, and then the texture itself.
51 glGenBuffers(1, &pbo);
53 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
55 glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, pitch * height * bytes_per_pixel, NULL, GL_STREAM_DRAW);
57 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
60 glGenTextures(1, &texture_num);
62 glBindTexture(GL_TEXTURE_2D, texture_num);
64 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
66 glPixelStorei(GL_UNPACK_ROW_LENGTH, pitch);
68 // Intel/Mesa seems to have a broken glGenerateMipmap() for non-FBO textures, so do it here
69 // instead of calling glGenerateMipmap().
70 glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, needs_mipmaps);
72 glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0, format, GL_UNSIGNED_BYTE, NULL);
74 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
81 void FlatInput::set_gl_state(GLuint glsl_program_num, const std::string& prefix, unsigned *sampler_num)
83 glActiveTexture(GL_TEXTURE0 + *sampler_num);
85 glBindTexture(GL_TEXTURE_2D, texture_num);
89 // Copy the pixel data into the PBO.
90 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
92 void *mapped_pbo = glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY);
93 memcpy(mapped_pbo, pixel_data, pitch * height * bytes_per_pixel);
94 glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB);
97 // Re-upload the texture from the PBO.
98 glPixelStorei(GL_UNPACK_ROW_LENGTH, pitch);
100 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
102 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
104 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
106 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
108 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
111 needs_update = false;
114 // Bind it to a sampler.
115 set_uniform_int(glsl_program_num, prefix, "tex", *sampler_num);
119 std::string FlatInput::output_fragment_shader()
121 return read_file("flat_input.frag");