68 lines
2.0 KiB
C++
68 lines
2.0 KiB
C++
#include "texture.hpp"
|
|
|
|
void flip_surface(SDL_Surface* surface) {
|
|
if (!surface) {
|
|
std::cerr << "Surface is null, cannot flip" << std::endl;
|
|
return;
|
|
}
|
|
|
|
int pitch = surface->pitch;
|
|
Uint8* pixels = static_cast<Uint8*>(surface->pixels);
|
|
int height = surface->h;
|
|
|
|
for (int y = 0; y < height / 2; ++y) {
|
|
Uint8* top_row = pixels + y * pitch;
|
|
Uint8* bottom_row = pixels + (height - y - 1) * pitch;
|
|
|
|
for (int x = 0; x < pitch; ++x) {
|
|
std::swap(top_row[x], bottom_row[x]);
|
|
}
|
|
}
|
|
}
|
|
|
|
Texture::Texture(const char* file_path) {
|
|
ID = 0;
|
|
SDL_Surface* surface = IMG_Load(file_path);
|
|
if (!surface) {
|
|
std::cerr << "Failed to load texture: " << SDL_GetError() << std::endl;
|
|
return; // Texture loading failed
|
|
}
|
|
|
|
GLenum format = (surface->format == SDL_PIXELFORMAT_RGBA32) ? GL_RGBA : GL_RGB;
|
|
flip_surface(surface); // Flip the surface vertically
|
|
|
|
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, surface->w, surface->h, 0, format, GL_UNSIGNED_BYTE, surface->pixels);
|
|
glGenerateMipmap(GL_TEXTURE_2D);
|
|
|
|
SDL_DestroySurface(surface); // Free the surface after uploading texture data
|
|
}
|
|
|
|
Texture::~Texture() {
|
|
if (ID != 0) {
|
|
glDeleteTextures(1, &ID);
|
|
}
|
|
}
|
|
|
|
void Texture::bind() const {
|
|
glBindTexture(GL_TEXTURE_2D, ID);
|
|
}
|
|
|
|
void Texture::bind(unsigned int unit) const {
|
|
if (unit >= GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS) {
|
|
std::cerr << "Texture unit out of range: " << unit << std::endl;
|
|
return; // Invalid texture unit
|
|
}
|
|
glActiveTexture(GL_TEXTURE0 + unit);
|
|
glBindTexture(GL_TEXTURE_2D, ID);
|
|
}
|
|
|
|
void Texture::unbind() const {
|
|
glBindTexture(GL_TEXTURE_2D, 0);
|
|
} |