#include <psemek/gfx/effect/overlay.hpp>
#include <psemek/gfx/program.hpp>
#include <psemek/gfx/array.hpp>

#include <psemek/util/pimpl.hpp>

namespace psemek::gfx
{

	static char const overlay_vs[] =
R"(#version 330

const vec4 vertices[6] = vec4[6](
	vec4(-1.0, -1.0, 0.0, 1.0),
	vec4( 1.0, -1.0, 0.0, 1.0),
	vec4( 1.0,  1.0, 0.0, 1.0),

	vec4(-1.0, -1.0, 0.0, 1.0),
	vec4( 1.0,  1.0, 0.0, 1.0),
	vec4(-1.0,  1.0, 0.0, 1.0)
);

out vec2 texcoord;

void main()
{
	gl_Position = vertices[gl_VertexID];
	texcoord = vertices[gl_VertexID].xy * 0.5 + vec2(0.5);
}
)";

	static char const overlay_fs[] =
R"(#version 330

uniform sampler2D u_texture;

in vec2 texcoord;

out vec4 out_color;

void main()
{
	out_color = texture(u_texture, texcoord);
}
)";

	struct overlay::impl
	{
		gfx::program program{overlay_vs, overlay_fs};
		gfx::array array;
	};

	overlay::overlay()
		: pimpl_{make_impl()}
	{
		impl().program.bind();
		impl().program["u_texture"] = 0;
	}

	overlay::~overlay() = default;

	void overlay::invoke(texture_2d const & src, render_target const & dst)
	{
		gl::Disable(gl::DEPTH_TEST);
		gl::Disable(gl::CULL_FACE);

		dst.bind();
		gl::ActiveTexture(gl::TEXTURE0);
		src.bind();
		impl().array.bind();
		impl().program.bind();
		gl::DrawArrays(gl::TRIANGLES, 0, 6);
	}

}
