1 #include "Texture.h"
2 
Texture(int width,int height,GLenum type,GLint filter)3 Texture::Texture(int width, int height, GLenum type, GLint filter):
4 	m_type(type) {
5 	m_width = width;
6 	m_height = height;
7 
8 	char* colorBits = new char[width * height * 3];
9 
10 	glGenTextures(1, &m_textureId);
11 	glBindTexture(m_type, m_textureId);
12 
13 	glTexParameteri(m_type, GL_TEXTURE_MIN_FILTER, filter);
14 	glTexParameteri(m_type, GL_TEXTURE_MAG_FILTER, filter);
15 
16 	glTexImage2D(m_type, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE,
17 			colorBits);
18 
19 	delete[] colorBits;
20 }
21 
Texture(SDL_Surface * surface,GLenum type,GLint filter,bool takeCareOfSurface)22 Texture::Texture(SDL_Surface *surface, GLenum type, GLint filter,
23 		bool takeCareOfSurface):
24 	m_type(type) {
25 	m_width = surface->w;
26 	m_height = surface->h;
27 
28 	GLint nOfColors;
29 	GLenum texture_format;
30 
31 	nOfColors = surface->format->BytesPerPixel;
32 	if (nOfColors == 4) {
33 		if (surface->format ->Rmask == 0x000000ff) {
34 			texture_format = GL_RGBA;
35 		} else {
36 			texture_format = GL_BGRA;
37 		}
38 	} else if (nOfColors == 3) {
39 		if (surface->format->Rmask == 0x000000ff)
40 			texture_format = GL_RGB;
41 		else
42 			texture_format = GL_BGR;
43 	} else {
44 		std::cout << "Couldn't create GL texture from the SDL surface!" << std::endl;
45 		throw 1;
46 	}
47 
48 	glGenTextures(1, &m_textureId);
49 	glBindTexture(m_type, m_textureId);
50 
51 	glTexParameteri(m_type, GL_TEXTURE_MIN_FILTER, filter);
52 	glTexParameteri(m_type, GL_TEXTURE_MAG_FILTER, filter);
53 
54 	glTexImage2D(m_type, 0, nOfColors, surface->w, surface->h, 0,
55 			texture_format, GL_UNSIGNED_BYTE, surface->pixels);
56 
57 	if (surface && takeCareOfSurface) {
58 		SDL_FreeSurface(surface);
59 	}
60 }
61 
~Texture()62 Texture::~Texture() {
63 	glDeleteTextures(1, &m_textureId);
64 }
65