#include "externals.hh"
#include "combine.hh"
#include "bloom.hh"
#include "profiling.hh"
#include "globals.hh"

namespace {
	static const std::string Name_( "Combine" );
}

#define PSTART() Globals::Profiler( ).start( Name_ )
#define PEND() do { glFinish( ); Globals::Profiler( ).end( Name_ ); } while ( 0 )


T_CombinePass::T_CombinePass(
		__rw__ T_Texture& image ,
		__rw__ T_Texture& bloom )
	: txImage_( image ) , txBloom_( bloom ) ,
		bloomStrength_( 0.45 ) ,
		bloomAttenuation_( 0.3 )
{
	program_ = Globals::Shaders( ).pipeline({
			"fullscreen.v.glsl" , "combine.f.glsl" });
}

void T_CombinePass::render( )
{
	PSTART( );
	T_Rendertarget::MainOutput( );
	glClearColor( 1 , 0 , 1 , 1 );
	glClear( GL_COLOR_BUFFER_BIT );
	if ( program_.valid( ) ) {
		auto& tm( Globals::Textures( ) );
		tm.bind( 0 , txImage_ );
		tm.bind( 1 , txBloom_ );

		const auto id( program_.program( E_ShaderType::FRAGMENT ) );
		program_.enable( );
		glProgramUniform1i( id , 0 , 0 );
		glProgramUniform1i( id , 1 , 1 );
		glProgramUniform2f( id , 2 , txImage_.width( ) , txImage_.height( ) );
		glProgramUniform2f( id , 3 , bloomStrength_ , bloomAttenuation_ );

		glDrawArrays( GL_TRIANGLE_STRIP , 0 , 4 );
	}
	PEND( );
}

void T_CombinePass::makeUI( )
{
	if ( !ImGui::CollapsingHeader( "Combine" ) ) {
		return;
	}

	ImGui::DragFloat( "Bloom strength" , &bloomStrength_ , .001f , 0. , 10 );
	ImGui::DragFloat( "Bloom attenuation" , &bloomAttenuation_ , .001f , 0. , 1 );
}