-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTexture.cpp
More file actions
105 lines (88 loc) · 2.62 KB
/
Texture.cpp
File metadata and controls
105 lines (88 loc) · 2.62 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include "Texture.h"
#include <SDL2/SDL_image.h>
Texture::Texture(const std::string& imageFilePath)
{
SDL_Surface* image = IMG_Load(imageFilePath.c_str());
init(image);
}
Texture::Texture(SDL_Surface* image)
{
init(image);
}
Texture::Texture(FT_Bitmap* image)
{
// Bitmap glyph image is tightly packed
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// Create the OpenGL texture
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
// Using immutable texture storage, since it is recommended when not using mipmaps
glTexStorage2D(
GL_TEXTURE_2D,
1,
GL_RED,
image->width,
image->rows
);
glTexSubImage2D(
GL_TEXTURE_2D,
0,
0,
0,
image->width,
image->rows,
GL_RED,
GL_UNSIGNED_BYTE,
image->buffer
);
// Texture Params
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
void Texture::init(SDL_Surface* tex)
{
// Allow direct reading of the image pixels
SDL_LockSurface(tex);
// For convenience
w = tex->w;
h = tex->h;
// Flip image so OpenGL doesn't diplay it upside-down
flipSDLSurface(tex);
// Create the OpenGL texture from the loaded image
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0,
GL_RGBA, GL_UNSIGNED_BYTE, tex->pixels);
// Texture Params
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_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
// Mipmaps!
glGenerateMipmap(GL_TEXTURE_2D);
// Cleanup
SDL_UnlockSurface(tex);
}
// Note: surf is already locked when this is called
void Texture::flipSDLSurface(SDL_Surface* surf)
{
int pitch = surf->pitch;
char* temp = new char[pitch];
char* pixels = (char*)surf->pixels;
// Switch rows
for (int i = 0; i < h / 2; ++i)
{
char* top = pixels + i * pitch;
char* bot = pixels + (h - i - 1) * pitch;
// Top row to temp
memcpy(temp, top, pitch);
// Bottom row to top
memcpy(top, bot, pitch);
// Temp (top row) to bottom
memcpy(bot, temp, pitch);
}
// Don't leak!
delete[] temp;
}