#include "StdAfx.h"
#include "BackBuffer.h"


void BackBuffer::InitializeBuffer(int width, int height)
{
	ReleaseBuffer();

	m_Width = width;
	m_Height = height;

	CreateTextureRGB(m_TexColor, GL_RGB, width, height);
	CreateTextureRGB(m_TexDepth, GL_DEPTH_COMPONENT, width, height);

	m_FBO.Generate();
	m_FBO.BeginFBO();

	glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT , GL_COLOR_ATTACHMENT0_EXT , GL_TEXTURE_2D , m_TexColor.GetID() , 0 );
	glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT , GL_DEPTH_ATTACHMENT_EXT , GL_TEXTURE_2D , m_TexDepth.GetID() , 0 );

	m_FBO.EndFBO();
}

void BackBuffer::CreateTextureRGB(lib_gl::GlTextureObject& tex, GLint internalformat, int width, int height)
{
	tex.GenerateTexture();
	tex.Bind();

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

	glPixelStorei( GL_UNPACK_ALIGNMENT , 1 );

	glTexImage2D( GL_TEXTURE_2D
	            , 0
	            , internalformat
	            , width , height
	            , 0
	            , internalformat , GL_UNSIGNED_BYTE
	            , 0
	            );
}

void BackBuffer::ReleaseBuffer(void)
{
	m_FBO.Release();
	m_TexColor.ReleaseTexture();
	m_TexDepth.ReleaseTexture();
}


void BackBuffer::BeginFBO(void)
{
	m_FBO.BeginFBO();
}

void BackBuffer::EndFBO(void)
{
	m_FBO.EndFBO();
}


void BackBuffer::GetPixels(lm::matrix<lib_graph::color3f>& buf)
{
	BeginFBO();

	buf.resize( m_Width , m_Height );
	if( buf.empty() )
		return;

	glReadPixels(0, 0, m_Width, m_Height, GL_RGB, GL_FLOAT, &buf(0,0));

	EndFBO();
}
