#33 - Texture Class C++
Data: 2018-11-03 12:00 - C++
Simple OpenGL Texture Wrapper class for 2D textures.
// Texture.h
#pragma once
#include <string>
#include <memory>
#include "../OpenGL.h"
namespace YourNamespace {
namespace Rendering {
class Texture {
public:
static std::shared_ptr<Texture> getTexture(const std::string& file);
static void unbind(GLenum target = GL_TEXTURE_2D) { glBindTexture(target, NULL); }
private:
GLuint _texId;
GLuint _width;
GLuint _height;
public:
Texture(GLuint texID, GLuint width, GLuint height);
GLuint textureID() const { return _texId; }
GLuint width() const { return _width; }
GLuint height() const { return _height; }
void bind(GLenum target = GL_TEXTURE_2D) const { glBindTexture(target, _texId); }
~Texture() { glDeleteTextures(1, &_texId); }
};
}
}
// Texture.cpp
#include "Texture.h"
#include <SDL/SDL_image.h>
#include "../Logging/Logger.h"
using namespace Texture::Rendering;
std::shared_ptr<Texture> Texture::getTexture(const std::string& file) {
GLuint textureID;
SDL_Surface* surface = IMG_Load(file.c_str());
if (surface == NULL) {
LOG_ERROR("Unable to load texture: " + file);
return nullptr;
}
if (SDL_SetSurfaceAlphaMod(surface, 0) == -1) {
LOG_ERROR("Unable to load texture: " + file + ", surface alpha error.");
return nullptr;
}
GLenum internalFormat = GL_RGBA;
GLenum format;
if (surface->format->BitsPerPixel == 8 && surface->format->Amask == 0) {
format = GL_RED;
internalFormat = GL_RED;
}
else if (surface->format->BitsPerPixel == 24 && surface->format->Amask == 0)
format = GL_RGB;
else if (surface->format->BitsPerPixel == 32 && surface->format->Amask != 0)
format = GL_RGBA;
else {
LOG_ERROR("Unable to load texture: " + file + ", format error!");
return nullptr;
}
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
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);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, surface->w, surface->h, 0, format, GL_UNSIGNED_BYTE, surface->pixels);
std::shared_ptr<Texture> tex = std::make_shared<Texture>(textureID, surface->w, surface->h);
SDL_FreeSurface(surface);
return tex;
}
Texture::Texture(GLuint texID, GLuint width, GLuint height) : _texId(texID), _width(width), _height(height) {
}