#include "stdafx.h"
#include "FBORenderBuf.h"



void FBORenderBuf::RebuildIfResized(int w, int h)
{
	if (m_BufWidth == w && m_BufHeight == h)
		return;

	ReleaseBuf();

	InitializeOnce(w, h);
}

void FBORenderBuf::InitializeOnce(int w, int h)
{
	if (m_IsInitialized)
		return;

	Initialize(w, h);

	m_IsInitialized = true;
}

void FBORenderBuf::Initialize(int w, int h)
{
	m_BufWidth = w;
	m_BufHeight = h;

	InitializeDethBuffer();

	InitializeColorBuffer();

	AssignFBOToFrameBufObjects();
}

void FBORenderBuf::InitializeDethBuffer(void)
{
	m_DepthBuf.GenerateTexture();
	m_DepthBuf.Bind();
	glTexMinMagFilter2D(GL_LINEAR, GL_LINEAR);
	glTexWrapST2D(GL_CLAMP, GL_CLAMP);

	glTexImage2D(
		GL_TEXTURE_2D,
		0,
		GL_DEPTH_COMPONENT,
		m_BufWidth,
		m_BufHeight,
		0,
		GL_DEPTH_COMPONENT,
		GL_FLOAT,
		0);
}

void FBORenderBuf::InitializeColorBuffer(void)
{
	m_ColorBuf.GenerateTexture();
	m_ColorBuf.Bind();
	glTexMinMagFilter2D(GL_LINEAR, GL_LINEAR);
	glTexWrapST2D(GL_CLAMP, GL_CLAMP);

	glTexImage2D(
		GL_TEXTURE_2D,
		0,
		GL_RGBA,
		m_BufWidth,
		m_BufHeight,
		0,
		GL_RGBA,
		GL_FLOAT,
		0);
}

void FBORenderBuf::AssignFBOToFrameBufObjects(void)
{
	m_Fbo.Generate();
	m_Fbo.BeginFBO();

	// for depth texture
	m_Fbo.BindFboTexture(GL_DEPTH_ATTACHMENT_EXT, m_DepthBuf.GetID(), 0);

	// for color color renderbuffer
	m_Fbo.BindFboTexture(GL_COLOR_ATTACHMENT0_EXT, m_ColorBuf.GetID(), 0);

	m_Fbo.EndFBO();
}

void FBORenderBuf::ReleaseBuf(void)
{
	m_IsInitialized = false;

	m_Fbo.Release();
	m_ColorBuf.ReleaseTexture();
	m_DepthBuf.ReleaseTexture();
}
