Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "texture.h"
- #include "debug.h"
- #define STB_IMAGE_IMPLEMENTATION
- #include "stb_image.h"
- Texture::Texture(std::string imagePath) :
- m_id(0), m_wrapS(GL_REPEAT), m_wrapT(GL_REPEAT), m_filterMin(GL_LINEAR_MIPMAP_LINEAR), m_filterMax(GL_LINEAR)
- {
- unsigned char* imageData = stbi_load(imagePath.c_str(), (int*)&m_width, (int*)&m_height, (int*)&m_channelCount, 0);
- if (imageData)
- {
- createTexture((std::byte*)imageData);
- stbi_image_free(imageData);
- }
- }
- Texture::Texture(std::byte * imageData, size_t width, size_t height, size_t channelsCount) :
- m_id(0), m_wrapS(GL_REPEAT), m_wrapT(GL_REPEAT), m_filterMin(GL_LINEAR_MIPMAP_LINEAR), m_filterMax(GL_LINEAR), m_width(width), m_height(height), m_channelCount(channelsCount)
- {
- createTexture(imageData);
- }
- Texture::~Texture()
- {
- glDeleteTextures(1, &m_id);
- }
- GLuint Texture::getId() const
- {
- return m_id;
- }
- size_t Texture::getWidth() const
- {
- return m_width;
- }
- size_t Texture::getHeight() const
- {
- return m_height;
- }
- void Texture::bind(GLenum activeTexture)
- {
- glActiveTexture(activeTexture);
- glBindTexture(GL_TEXTURE_2D, m_id);
- }
- void Texture::createTexture(std::byte * imageData)
- {
- // Texture construction shall not interfere with the current texture unit configuration
- // Retrieve current texture in texture unit 0 and restore it later.
- GLint currentTextureId = 0;
- glActiveTexture(GL_TEXTURE0);
- glGetIntegerv(GL_TEXTURE_BINDING_2D, ¤tTextureId);
- glGenTextures(1, &m_id);
- glBindTexture(GL_TEXTURE_2D, m_id);
- GLenum format = GL_RGB;
- switch (m_channelCount)
- {
- case 3:
- format = GL_RGB;
- break;
- case 4:
- format = GL_RGBA;
- break;
- default:
- ASSERT(1 == 2);
- break;
- }
- glTexImage2D(GL_TEXTURE_2D, 0, format, m_width, m_height, 0, format, GL_UNSIGNED_BYTE, imageData);
- glGenerateMipmap(GL_TEXTURE_2D);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, m_wrapS);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, m_wrapT);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_filterMin);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, m_filterMax);
- glBindTexture(GL_TEXTURE_2D, currentTextureId); // Restore previous config of texture unit 0
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement