-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtexture.cpp
78 lines (69 loc) · 1.94 KB
/
texture.cpp
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#define STB_IMAGE_IMPLEMENTATION
#include <glad/glad.h>
#include <glcore/texture.h>
#include <iostream>
#include <stb_image.h>
using vec = std::vector<unsigned char>;
Texture::Texture(const vec &data, int width, int height, int nrChannels)
: width_(width), height_(height), nrChannels_(nrChannels) {
build(data.data());
}
Texture::Texture(const std::string &path) {
stbi_set_flip_vertically_on_load(true);
unsigned char *data =
stbi_load(path.c_str(), &width_, &height_, &nrChannels_, 0);
if (data) {
build(data);
} else {
std::cerr << "Failed to load texture (" << path << ")" << std::endl;
}
stbi_image_free(data);
}
Texture::Texture(Texture &&o)
: id_(o.id_), width_(o.width_), height_(o.height_),
nrChannels_(o.nrChannels_) {
o.id_ = 0;
}
Texture &Texture::operator=(Texture &&o) {
if (id_) glDeleteTextures(1, &id_);
id_ = o.id_;
width_ = o.width_;
height_ = o.height_;
nrChannels_ = o.nrChannels_;
o.id_ = 0;
o.width_ = 0;
o.height_ = 0;
o.nrChannels_ = 0;
return *this;
}
Texture::~Texture() {
if (id_) {
glDeleteTextures(1, &id_);
}
}
void Texture::build(const unsigned char *data) {
unsigned int format;
switch (nrChannels_) {
case 3:
format = GL_RGB;
break;
case 4:
format = GL_RGBA;
break;
default:
format = 0;
std::cerr << "Unknown format (" << nrChannels_ << ")" << std::endl;
break;
}
glGenTextures(1, &id_);
glBindTexture(GL_TEXTURE_2D, id_);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, format, width_, height_, 0, format,
GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
void Texture::bind() { glBindTexture(GL_TEXTURE_2D, id_); }