#include "texture_quad.h"

/* Draws a textured quad. */
void
texture_quad_draw(Renderer* renderer, Shader* shader, Atlas* atlas, mat4 model, vec2 size, vec4 color)
{
	vec2 uvMin;
	vec2 uvMax;
	mat4 view;
	mat4 projection;

	atlas_uv_get(atlas, uvMin, uvMax);

	f32 vertices[4][5] = 
	{
		{0.0f   , 0.0f   , 0.0f, uvMin[0], uvMin[1]},
		{0.0f   , size[1], 0.0f, uvMin[0], uvMax[1]},
		{size[0], size[1], 0.0f, uvMax[0], uvMax[1]},
		{size[0], 0.0f   , 0.0f, uvMax[0], uvMin[1]},
	};

	u32 indices[2][3] = 
	{
		{1, 2, 3},
		{0, 1, 3}
	};

	camera_view_get(&renderer->camera, view);
	camera_projection_get(&renderer->camera, projection);

	vao_bind(&renderer->vao);

	vbo_bind(&renderer->vbo);
	vbo_buffer(&renderer->vbo, sizeof(vertices), vertices);

	vbo_bind(&renderer->ebo);
	vbo_buffer(&renderer->ebo, sizeof(indices), indices);

	vertex_attribute_set(0, 3, GL_FLOAT, 5 * sizeof(f32), 0);
	vertex_attribute_set(1, 2, GL_FLOAT, 5 * sizeof(f32), 3 * sizeof(f32));

	vao_bind(&renderer->vao);

	renderer_shader_use(renderer, shader);

	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_BLEND);

	shader_uniform_mat4_set(shader, TEXTURE_QUAD_UNIFORM_VIEW, view);
	shader_uniform_mat4_set(shader, TEXTURE_QUAD_UNIFORM_PROJECTION, projection);
	shader_uniform_mat4_set(shader, TEXTURE_QUAD_UNIFORM_MODEL, model);
	shader_uniform_vec4_set(shader, TEXTURE_QUAD_UNIFORM_COLOR, color);
	shader_uniform_texture_set(shader, TEXTURE_QUAD_UNIFORM_TEXTURE, &atlas->texture, 0);

	glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

	vao_unbind();
}	
