/
BasicTexture.cpp
59 lines (55 loc) · 1.33 KB
/
BasicTexture.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
#include "BasicTexture.h"
#include "stb_image.h"
#include <cstdlib>
#include <GL\glew.h>
BasicTexture::BasicTexture(char* filename)
: imgData(0),
glID(0),
Width(width),
Height(height)
{
this->filename = (char*)malloc(strlen(filename));
strcpy(this->filename, filename);
}
BasicTexture::~BasicTexture(void)
{
}
void BasicTexture::LoadFromFile()
{
printf("opening file: %s\n", this->filename);
FILE* file = fopen(this->filename, "rb");
if (!file)
{
printf("couldn't open file: %s\n", this->filename);
return;
}
printf("%s opened\n", this->filename);
imgData = stbi_load_from_file(file, &width, &height, &components, 4);
if (!imgData)
{
printf("could not load image from file!\n");
return;
}
printf("loaded data from file\n");
glGenTextures(1, &glID);
printf("generated texture name\n");
glBindTexture(GL_TEXTURE_2D, glID);
printf("bound texture to opengl context\n");
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imgData);
printf("loaded texture to GPU\n");
glEnable(GL_TEXTURE_2D);
glGenerateMipmap(GL_TEXTURE_2D);
printf("generated mipmaps\n");
stbi_image_free(imgData);
printf("freed image data\n");
fclose(file);
printf("closed file\n");
glBindTexture(GL_TEXTURE_2D, 0);
}
void BasicTexture::Load()
{
if (glID > 0)
glDeleteTextures(1, &glID);
glID = 0;
LoadFromFile();
}