summaryrefslogtreecommitdiff
path: root/texture.cpp
blob: ba7d9c7c32539aa45f0306652b351ad1c45c994a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <stdexcept>
#include "texture.h"
#include "stb_image.h"
#include "gl.h"

Texture::Texture() {
	glGenTextures(1, &texture);
}

Texture::Texture(const std::string& filename) {
	glGenTextures(1, &texture);
	load(filename);
}

void Texture::load(const std::string& filename) {
	int w, h, ch;
	uint8_t* data = stbi_load(filename.c_str(), &w, &h, &ch, 4);
	
	unsigned int format;
	if(ch == 4) {
		format = GL_RGBA;
	} else {
		format = GL_RGB;
	}
	
	build(data, format, w, h);
	
	stbi_image_free(data);
}

void Texture::bind() const {
	glBindTexture(GL_TEXTURE_2D, texture);
}

unsigned int Texture::tex() const {
	return texture;
}

unsigned int Texture::w() const {
	return width;
}

unsigned int Texture::h() const {
	return height;
}

void Texture::build(void* data, unsigned int format, unsigned int w, unsigned int h) {
	if(!data) {
		throw(std::runtime_error("No texture data"));
	}
	
	width = w;
	height = h;
	
	glBindTexture(GL_TEXTURE_2D, texture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	gluBuild2DMipmaps(GL_TEXTURE_2D, 4, width, height, format, GL_UNSIGNED_BYTE, data);
}