#version 460

#extension GL_GOOGLE_include_directive : require

#define VERT_SHADER

#include "gui.layout"

layout (location = 0) in vec4  in_col;
layout (location = 1) in vec4  in_corner_radius;
layout (location = 2) in vec2  in_dst_start;
layout (location = 3) in vec2  in_dst_end;
layout (location = 4) in vec2  in_src_start;
layout (location = 5) in vec2  in_src_end;
layout (location = 6) in float border_thickness;
layout (location = 7) in float edge_softness;
layout (location = 8) in float raised;
layout (location = 9) in uint  has_texture; 

layout (location = 0) FragDataFlat
{
	vec2 atlas_size;
	uint has_texture;
} FDF;

layout (location = 2) FragData
{
	vec4  color;
	vec2  uv;
	vec2  dst_pos;
	vec2  dst_center;
	vec2  dst_half_size;
	vec2  sdf_sample_pos;
	float corner_radius;
	float softness;
	float raised;
	float border_thickness;
} FD;

vec2 Vertices[4] = vec2[4](
	vec2(-1.0, -1.0),
	vec2(-1.0, +1.0),
	vec2(+1.0, -1.0),
	vec2(+1.0, +1.0)
);

vec2 rotate(vec2 coords, float theta)
{
	return mat2(cos(theta), sin(theta), -sin(theta), cos(theta)) * coords;
}

void main()
{
	ivec2 tex_size = textureSize(SpriteAtlas, 0);

	vec4 pos_start = vec4(in_dst_start.x, in_dst_start.y - raised, 0.0, 1.0);
	vec4 pos_end = vec4(in_dst_end.x, in_dst_end.y, 0.0, 1.0);

	vec2 half_size = ((pos_end.xy - pos_start.xy) / 2);
	vec2 center = ((pos_end.xy + pos_start.xy) / 2);
	vec2 pos = (Vertices[gl_VertexIndex] * half_size + center);

	vec2 src_half_size = (in_src_end - in_src_start) / 2;
	vec2 src_center = (in_src_end + in_src_start) / 2;
	vec2 src_pos = (Vertices[gl_VertexIndex] * src_half_size + src_center);

	vec2 uvs[4] = vec2[4](
		vec2(in_src_start.x, in_src_start.y),
		vec2(in_src_start.x, in_src_end.y),
		vec2(in_src_end.x,   in_src_start.y),
		vec2(in_src_end.x,   in_src_end.y)
	);

	float corner_radius[4] = float[4](
		in_corner_radius.x,
		in_corner_radius.z,
		in_corner_radius.y,
		in_corner_radius.w
	);

	vec2 dst_verts_pct = vec2(bool(gl_VertexIndex >> 1) ? 1.0f : 0.0f, 
													  bool(gl_VertexIndex &  1) ? 0.0f : 1.0f);

	FD.color            = in_col;
	FD.uv               = uvs[gl_VertexIndex] / tex_size;
	FD.dst_pos          = pos;
	FD.dst_center       = center;
	FD.dst_half_size    = half_size;
	FD.corner_radius    = corner_radius[gl_VertexIndex];
	FD.softness         = edge_softness;
	FD.raised           = raised;
	FD.border_thickness = border_thickness;
	FD.sdf_sample_pos   = (2.0f * dst_verts_pct - 1.0f) * half_size;
	FDF.has_texture     = has_texture;
	FDF.atlas_size      = in_src_end - in_src_start;

	vec4 v_pos = PC.projection * vec4(pos.x, pos.y, 0, 1);
	gl_Position = vec4(v_pos.x, v_pos.y, v_pos.z, 1);
}
