#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord;
layout (location = 2) in int aTileIndex;
layout (location = 3) in int aTextureIndex;
layout (location = 4) in int aTilesPerRow;
layout (location = 5) in int aStartIndex;
layout (location = 6) in vec2 aOriginalSize;
layout (location = 7) in mat4 aModel;
layout (std140) uniform Matrices
{
	mat4 projection;
	mat4 view;
};

uniform vec2 uCanvasSize;

out vec2 texCoord;
flat out int textureIndex;

void main()
{
	int tilesPerRow = aTilesPerRow;
	float tileSize = 1.0 / aTilesPerRow;
	// Slightly stretch the vertices to cover slight gaps
	vec2 expansion = normalize(aPos.xy) * 0.001 * (1.0 / aTilesPerRow);
	vec2 adjusted = aPos.xy + expansion;

	gl_Position = projection * view * aModel * vec4(adjusted, aPos.z, 1.0);
	textureIndex = aTextureIndex;
	if (aTileIndex != 0) 
	{
		vec2 scale = vec2(aOriginalSize.x / uCanvasSize.x, aOriginalSize.y / uCanvasSize.y);

		int index = aTileIndex - aStartIndex;

		int row = index / tilesPerRow;
		int col = index % tilesPerRow;

		texCoord.x = (aTexCoord.x + col) * tileSize;
		texCoord.y = (aTexCoord.y + row) * tileSize;
		texCoord = texCoord * scale;
	}
	else
	{
		texCoord.x = 0.0;
		texCoord.y = 0.0;
	}
}
