cubemapper
diff src/texture.cc @ 0:8fc9e1d3aad2
initial commit
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Thu, 27 Jul 2017 20:36:12 +0300 |
parents | |
children | d7a29cb7ac8d |
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/src/texture.cc Thu Jul 27 20:36:12 2017 +0300 1.3 @@ -0,0 +1,103 @@ 1.4 +#include <stdio.h> 1.5 +#include <imago2.h> 1.6 +#include "texture.h" 1.7 +#include "opengl.h" 1.8 + 1.9 +Texture::Texture() 1.10 +{ 1.11 + width = height = tex_width = tex_height = 0; 1.12 + tex = 0; 1.13 +} 1.14 + 1.15 +Texture::~Texture() 1.16 +{ 1.17 + if(tex) { 1.18 + glDeleteTextures(1, &tex); 1.19 + } 1.20 +} 1.21 + 1.22 +static unsigned int next_pow2(unsigned int x) 1.23 +{ 1.24 + --x; 1.25 + x |= x >> 1; 1.26 + x |= x >> 2; 1.27 + x |= x >> 4; 1.28 + x |= x >> 8; 1.29 + x |= x >> 16; 1.30 + return x + 1; 1.31 +} 1.32 + 1.33 +bool Texture::load(const char *fname) 1.34 +{ 1.35 + img_pixmap img; 1.36 + img_init(&img); 1.37 + if(img_load(&img, fname) == -1) { 1.38 + fprintf(stderr, "failed to load texture: %s\n", fname); 1.39 + img_destroy(&img); 1.40 + return false; 1.41 + } 1.42 + 1.43 + unsigned int intfmt = img_glintfmt(&img); 1.44 + unsigned int pixfmt = img_glfmt(&img); 1.45 + unsigned int pixtype = img_gltype(&img); 1.46 + 1.47 + // if we have the sRGB extension, change the internal formats to sRGB 1.48 + if(GLEW_EXT_texture_sRGB) { 1.49 + switch(intfmt) { 1.50 + case 3: 1.51 + case GL_RGB: 1.52 + intfmt = GL_SRGB_EXT; 1.53 + break; 1.54 + case 4: 1.55 + case GL_RGBA: 1.56 + intfmt = GL_SRGB_ALPHA; 1.57 + break; 1.58 + case 1: 1.59 + case GL_LUMINANCE: 1.60 + intfmt = GL_SLUMINANCE; 1.61 + break; 1.62 + default: 1.63 + break; 1.64 + } 1.65 + } 1.66 + 1.67 + width = img.width; 1.68 + height = img.height; 1.69 + tex_width = next_pow2(width); 1.70 + tex_height = next_pow2(height); 1.71 + 1.72 + if(!tex) { 1.73 + glGenTextures(1, &tex); 1.74 + } 1.75 + glBindTexture(GL_TEXTURE_2D, tex); 1.76 + 1.77 + if(GLEW_SGIS_generate_mipmap) { 1.78 + glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE); 1.79 + } else { 1.80 + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 1.81 + } 1.82 + 1.83 + glTexImage2D(GL_TEXTURE_2D, 0, intfmt, tex_width, tex_height, 0, pixfmt, pixtype, 0); 1.84 + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, pixfmt, pixtype, img.pixels); 1.85 + 1.86 + tmat.scaling((float)width / (float)tex_width, (float)height / (float)tex_height, 1); 1.87 + return true; 1.88 +} 1.89 + 1.90 +const Mat4 &Texture::texture_matrix() const 1.91 +{ 1.92 + return tmat; 1.93 +} 1.94 + 1.95 +void Texture::bind(bool loadmat) const 1.96 +{ 1.97 + if(!tex) return; 1.98 + 1.99 + if(loadmat) { 1.100 + glMatrixMode(GL_TEXTURE); 1.101 + glLoadMatrixf(tmat[0]); 1.102 + glMatrixMode(GL_MODELVIEW); 1.103 + } 1.104 + 1.105 + glBindTexture(GL_TEXTURE_2D, tex); 1.106 +}