#version 460

#extension GL_GOOGLE_include_directive : require

#define VERT_SHADER

#include "gui.layout"

layout (location = 0)  in vec4  in_col_start;
layout (location = 1)  in vec4  in_col_end;
layout (location = 2)  in float in_corner_radius_x0y0;
layout (location = 3)  in float in_corner_radius_x1y0;
layout (location = 4)  in float in_corner_radius_x0y1;
layout (location = 5)  in float in_corner_radius_x1y1;
layout (location = 6)  in vec2  in_dst_start;
layout (location = 7)  in vec2  in_dst_end;
layout (location = 8)  in vec2  in_src_start;
layout (location = 9)  in vec2  in_src_end;
layout (location = 10) in float border_thickness;
layout (location = 11) in float edge_softness;
layout (location = 12) in float raised;
layout (location = 13) in uint  in_has_texture;
layout (location = 14) in uint  in_atlas_index;

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(sampler2D(SpriteAtlas, SamplerNearest), 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_x0y0,
		in_corner_radius_x0y1,
		in_corner_radius_x1y0,
		in_corner_radius_x1y1
	);

	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_start;
	FD.color_end        = in_col_end;
	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.texture         = in_has_texture;
	FDF.atlas_index     = in_atlas_index;

	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);
}
