SparrowRenderer/texture.cpp

84 lines
2.3 KiB
C++

#include "texture.h"
#include "glassert.h"
#include "image.h"
Texture::Texture(GLenum format,
GLenum internal_format,
int width,
int height,
GLenum dataType,
GLenum texTarget) :
target(texTarget)
{
glAssert(glGenTextures(1, &texId));
glAssert(glBindTexture(target, texId));
glAssert(glTexImage2D(target, 0, internal_format, width, height, 0, format, dataType, NULL));
setWrap(GL_REPEAT);
setFiltering(GL_LINEAR);
}
Texture::Texture(Image* myImage) : target(GL_TEXTURE_2D)
{
glAssert(glGenTextures(1, &texId));
glAssert(glBindTexture(target, texId));
initPixels(myImage, GL_TEXTURE_2D);
setWrap(GL_REPEAT);
setFiltering(GL_LINEAR);
}
Texture::Texture(Image* myCubemapImages[6]) : target(GL_TEXTURE_CUBE_MAP)
{
glAssert(glActiveTexture(GL_TEXTURE0));
glAssert(glGenTextures(1, &texId));
glAssert(glBindTexture(target, texId));
for(int i=0; i<6; ++i)
{
initPixels(myCubemapImages[i], GL_TEXTURE_CUBE_MAP_POSITIVE_X + i);
setWrap(GL_CLAMP_TO_EDGE);
setFiltering(GL_LINEAR);
}
}
Texture::~Texture()
{
glAssert(glDeleteTextures(1, &texId));
}
void Texture::initPixels(Image* myImage, GLenum target)
{
switch(myImage->depth)
{
case 32:
glAssert(glTexImage2D(target, 0, GL_RGBA, myImage->width, myImage->height, 0, GL_BGRA, GL_UNSIGNED_BYTE, myImage->pixels));
break;
case 24:
glAssert(glTexImage2D(target, 0, GL_RGB, myImage->width, myImage->height, 0, GL_BGR, GL_UNSIGNED_BYTE, myImage->pixels));
break;
case 8:
glAssert(glTexImage2D(target, 0, GL_R8, myImage->width, myImage->height, 0, GL_RED, GL_UNSIGNED_BYTE, myImage->pixels));
break;
}
}
void Texture::setWrap(GLint wrap)
{
glAssert(glTexParameteri(target, GL_TEXTURE_WRAP_S, wrap));
glAssert(glTexParameteri(target, GL_TEXTURE_WRAP_T, wrap));
glAssert(glTexParameteri(target, GL_TEXTURE_WRAP_R, wrap));
}
void Texture::setFiltering(GLint filter)
{
glAssert(glTexParameteri(target, GL_TEXTURE_MIN_FILTER, filter));
glAssert(glTexParameteri(target, GL_TEXTURE_MAG_FILTER, filter));
}
void Texture::bind(int slot)
{
GLenum texSlot = GL_TEXTURE0+slot;
glAssert(glActiveTexture(texSlot));
glAssert(glBindTexture(target, texId));
}