-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTexture.cpp
More file actions
86 lines (64 loc) · 2.27 KB
/
Texture.cpp
File metadata and controls
86 lines (64 loc) · 2.27 KB
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
79
80
81
82
83
84
85
86
#include "Texture.h"
Texture::Texture(const char* image, const char* texType, GLuint slot)
{
type = texType;
int widthImg, heightImg, numColCh;
//Flips the image so it doesn't show upside down
stbi_set_flip_vertically_on_load(true);
//Reads an image
unsigned char* bytes = stbi_load(image, &widthImg, &heightImg, &numColCh, 0);
//Generating Texture object
glGenTextures(1, &ID);
//Assigning the texture to a Texture unit
glActiveTexture(GL_TEXTURE0 + slot);
unit = slot;
glBindTexture(GL_TEXTURE_2D, ID);
//Configuring the type of algorithm to be used when changing the image size
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//Configuring how OpenGL handles repetition of the image
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
//Checking the number of channels the texture has and using the corresponding loading function
if (numColCh == 4)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, widthImg, heightImg, 0, GL_RGBA, GL_UNSIGNED_BYTE, bytes);
}
else if (numColCh == 3)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, widthImg, heightImg, 0, GL_RGB, GL_UNSIGNED_BYTE, bytes);
}
else if (numColCh == 1)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, widthImg, heightImg, 0, GL_RED, GL_UNSIGNED_BYTE, bytes);
}
else throw std::invalid_argument("Automatic Texture type recognition failed");
//Assigning the image to OpenGL texture object
glGenerateMipmap(GL_TEXTURE_2D);
//Deleting the image data as it's already copied to OpenGL texture object
stbi_image_free(bytes);
//Unbinding the OpenGL texture object so it's not modified anymore
glBindTexture(GL_TEXTURE_2D, 0);
}
void Texture::TexUnit(Shader& shader, const char* uniform, GLuint unit)
{
//Gets uniform location
GLuint diffuse0Uniform = glGetUniformLocation(shader.ID, uniform);
//Activating shader before changing the unfiform value
shader.Activate();
//Setting value for uniform
glUniform1i(diffuse0Uniform, unit);
}
void Texture::Bind()
{
glActiveTexture(GL_TEXTURE0 + unit);
glBindTexture(GL_TEXTURE_2D, ID);
}
void Texture::Unbind()
{
glBindTexture(GL_TEXTURE_2D, 0);
}
void Texture::Delete()
{
glDeleteTextures(1, &ID);
}