cubemapper

view src/texture.cc @ 1:d7a29cb7ac8d

resize to the final cubemap face size
author John Tsiombikas <nuclear@member.fsf.org>
date Fri, 28 Jul 2017 07:44:35 +0300
parents 8fc9e1d3aad2
children e308561f9889
line source
1 #include <stdio.h>
2 #include <imago2.h>
3 #include "texture.h"
4 #include "opengl.h"
6 Texture::Texture()
7 {
8 width = height = tex_width = tex_height = 0;
9 tex = 0;
10 }
12 Texture::~Texture()
13 {
14 if(tex) {
15 glDeleteTextures(1, &tex);
16 }
17 }
19 static unsigned int next_pow2(unsigned int x)
20 {
21 --x;
22 x |= x >> 1;
23 x |= x >> 2;
24 x |= x >> 4;
25 x |= x >> 8;
26 x |= x >> 16;
27 return x + 1;
28 }
30 int Texture::get_width() const
31 {
32 return width;
33 }
35 int Texture::get_height() const
36 {
37 return height;
38 }
40 bool Texture::load(const char *fname)
41 {
42 img_pixmap img;
43 img_init(&img);
44 if(img_load(&img, fname) == -1) {
45 fprintf(stderr, "failed to load texture: %s\n", fname);
46 img_destroy(&img);
47 return false;
48 }
50 unsigned int intfmt = img_glintfmt(&img);
51 unsigned int pixfmt = img_glfmt(&img);
52 unsigned int pixtype = img_gltype(&img);
54 // if we have the sRGB extension, change the internal formats to sRGB
55 if(GLEW_EXT_texture_sRGB) {
56 switch(intfmt) {
57 case 3:
58 case GL_RGB:
59 intfmt = GL_SRGB_EXT;
60 break;
61 case 4:
62 case GL_RGBA:
63 intfmt = GL_SRGB_ALPHA;
64 break;
65 case 1:
66 case GL_LUMINANCE:
67 intfmt = GL_SLUMINANCE;
68 break;
69 default:
70 break;
71 }
72 }
74 width = img.width;
75 height = img.height;
76 tex_width = next_pow2(width);
77 tex_height = next_pow2(height);
79 if(!tex) {
80 glGenTextures(1, &tex);
81 }
82 glBindTexture(GL_TEXTURE_2D, tex);
84 if(GLEW_SGIS_generate_mipmap) {
85 glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
86 } else {
87 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
88 }
90 glTexImage2D(GL_TEXTURE_2D, 0, intfmt, tex_width, tex_height, 0, pixfmt, pixtype, 0);
91 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, pixfmt, pixtype, img.pixels);
93 tmat.scaling((float)width / (float)tex_width, (float)height / (float)tex_height, 1);
94 return true;
95 }
97 const Mat4 &Texture::texture_matrix() const
98 {
99 return tmat;
100 }
102 void Texture::bind(bool loadmat) const
103 {
104 if(!tex) return;
106 if(loadmat) {
107 glMatrixMode(GL_TEXTURE);
108 glLoadMatrixf(tmat[0]);
109 glMatrixMode(GL_MODELVIEW);
110 }
112 glBindTexture(GL_TEXTURE_2D, tex);
113 }