cubemapper

view src/texture.cc @ 4:2bfafdced01a

added README, COPYING, and copyright headers
author John Tsiombikas <nuclear@member.fsf.org>
date Sun, 30 Jul 2017 16:11:19 +0300
parents e308561f9889
children
line source
1 /*
2 Cubemapper - a program for converting panoramic images into cubemaps
3 Copyright (C) 2017 John Tsiombikas <nuclear@member.fsf.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18 #include <stdio.h>
19 #include <imago2.h>
20 #include "texture.h"
21 #include "opengl.h"
23 Texture::Texture()
24 {
25 width = height = tex_width = tex_height = 0;
26 tex = 0;
27 }
29 Texture::~Texture()
30 {
31 if(tex) {
32 glDeleteTextures(1, &tex);
33 }
34 }
36 static unsigned int next_pow2(unsigned int x)
37 {
38 --x;
39 x |= x >> 1;
40 x |= x >> 2;
41 x |= x >> 4;
42 x |= x >> 8;
43 x |= x >> 16;
44 return x + 1;
45 }
47 int Texture::get_width() const
48 {
49 return width;
50 }
52 int Texture::get_height() const
53 {
54 return height;
55 }
57 bool Texture::load(const char *fname)
58 {
59 img_pixmap img;
60 img_init(&img);
61 if(img_load(&img, fname) == -1) {
62 fprintf(stderr, "failed to load texture: %s\n", fname);
63 img_destroy(&img);
64 return false;
65 }
67 unsigned int intfmt = img_glintfmt(&img);
68 unsigned int pixfmt = img_glfmt(&img);
69 unsigned int pixtype = img_gltype(&img);
71 width = img.width;
72 height = img.height;
73 tex_width = next_pow2(width);
74 tex_height = next_pow2(height);
76 if(!tex) {
77 glGenTextures(1, &tex);
78 }
79 glBindTexture(GL_TEXTURE_2D, tex);
81 if(GLEW_SGIS_generate_mipmap) {
82 glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
83 } else {
84 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
85 }
87 glTexImage2D(GL_TEXTURE_2D, 0, intfmt, tex_width, tex_height, 0, pixfmt, pixtype, 0);
88 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, pixfmt, pixtype, img.pixels);
90 tmat.scaling((float)width / (float)tex_width, (float)height / (float)tex_height, 1);
91 return true;
92 }
94 const Mat4 &Texture::texture_matrix() const
95 {
96 return tmat;
97 }
99 void Texture::bind(bool loadmat) const
100 {
101 if(!tex) return;
103 if(loadmat) {
104 glMatrixMode(GL_TEXTURE);
105 glLoadMatrixf(tmat[0]);
106 glMatrixMode(GL_MODELVIEW);
107 }
109 glBindTexture(GL_TEXTURE_2D, tex);
110 }