#include "StdAfx.h"
#include "GlTexture.h"

#include <C2/gl/GlApiExt.h>
#include <C2/gl/SDL/SDLImageExt.h>

#include <C2/graph/SDL_ImageLoadExt.h>



namespace gl
{


GlTexture::GlTexture(void)
{
	m_TexSDL = NULL;
}

GlTexture::~GlTexture(void)
{
	FinalizeTexture();
}


bool GlTexture::InitializeTexture(void)
{
	if (!m_TexObject.GenerateTexture())
		return false;

	return true;
}

void GlTexture::FinalizeTexture(void)
{
	ReleaseImage();

	m_TexObject.ReleaseTexture();
}

// テクスチャオブジェクトをプライマリに指定する
void GlTexture::BindGL(void)
{
	m_TexObject.Bind();
}

void GlTexture::SetTextureGL(const TextureConfig& config)
{
	assert(m_TexSDL != NULL);

	BindGL();

	if(config.m_EnableMipmap)
		glTexMinMagFilter2D(GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR);
	else
		glTexMinMagFilter2D(GL_LINEAR, GL_LINEAR);

	lib_gl::TEXTURE_MODE     texmode  = (config.m_EnableMipmap ? lib_gl::TEXTURE_MIPMAP : lib_gl::TEXTURE_NORMAL);
	lib_gl::TEXTURE_COMPRESS compress = (config.m_EnableCompress ? lib_gl::TEXCOMP_ENABLE : lib_gl::TEXCOMP_DISABLE);
	lib_gl::SetSDLTexture(m_TexSDL, texmode, compress);
}

//! OpenGLにテクスチャオブジェクトを登録した後, 画像バッファをクリアする
void GlTexture::SetTextureGLAndReleaseImage(const TextureConfig& config)
{
	SetTextureGL(config);
	ReleaseOnlyBuffer();
}

void GlTexture::ReleaseImage(void)
{
	if (m_TexSDL == NULL)
		return;

	SDL_FreeSurface(m_TexSDL);
	m_TexSDL = NULL;

	m_Name = "";
	m_SourceFile = "";
}

bool GlTexture::HasImage(void) const
{
	return (m_TexSDL != NULL);
}

bool GlTexture::HasTextureObject(void) const
{
	return m_TexObject.IsValid();
}

bool GlTexture::LoadTextureFromFile(const char* filename, bool flip_y)
{
	ReleaseImage();

	m_TexSDL = lib_graph::LoadSDLSurface(filename);
	if (m_TexSDL == NULL)
		return false;

	if( flip_y )
		lib_gl::SDL_FlipY(m_TexSDL);

	m_SourceFile = filename;

	return true;
}

bool GlTexture::SetFromSDLSurface(SDL_Surface* surface)
{
	ReleaseImage();

	if(surface == NULL)
		return false;

	m_TexSDL = surface;
	return true;
}


void GlTexture::ReleaseOnlyBuffer(void)
{
	ReleaseImage();
}


}
