#include <glerminal.h>

#include <cstdlib>
#include <cmath>

namespace
{
	void init()
	{
		srand(0);
		
		glerminal_load_sprites_file("resources/towers.png");


		for (int i = 0; i < GRID_WIDTH + 2; i++)
		{
			for (int j = 0; j < GRID_HEIGHT + 2; j++)
			{
				const int c = rand() % (LAYER_COUNT * 3 / 4) + LAYER_COUNT / 4;
				for (int k = 0; k < c; k++)
				{
					glerminal_set(i, j, k, 1);
				}

				for (int k = 0; k < LAYER_COUNT; k++)
				{
					constexpr unsigned char min = 16;
					const unsigned char v = (255 - min) * powf((256 / LAYER_COUNT * k - 1) / 256.0f, 2.0f) + min;
					const unsigned int col = (0xFF << 24) | (v << 16) | (v << 8) | v;
					glerminal_color(i, j, k, col);
					glerminal_scale(i, j, k, k / static_cast<float>(LAYER_COUNT) + 1);
				}
			}
		}
	}

	void mainloop(double dt)
	{
		static double time = 0;

		time += dt;

		const float cx = (GRID_WIDTH / 2.0f) * cosf(time / 3.1415f) + (GRID_WIDTH / 2.0f) + 0.5f;
		const float cy = (GRID_HEIGHT / 2.0f) * sinf(time / 3.1415f) + (GRID_HEIGHT / 2.0f) + 0.5f;

		for (int i = 0; i < GRID_WIDTH + 2; i++)
		{
			for (int j = 0; j < GRID_WIDTH + 2; j++)
			{
				for (int k = 0; k < LAYER_COUNT; k++)
				{
					const float ox = (256.0f / LAYER_COUNT) * 0.0025f * k * (i - cx);
					const float oy = (256.0f / LAYER_COUNT) * 0.0025f * k * (j - cy);
					const float sx = (1 + (256.0f / LAYER_COUNT) * 0.002f * k) * cosf(i + k * 6.2832f / 128.0f + 3.1415f * time / 1.5f);
					const float sy = (1 + (256.0f / LAYER_COUNT) * 0.002f * k) * sinf(j + k * 6.2832f / 128.0f + 3.1415f * time / 1.5f);
					glerminal_offset(i, j, k, ox + sx, oy + sy);
				}
			}
		}

		glerminal_flush();
	}
}

int main(int argc, char** argv)
{
	glerminal_run({init, mainloop});
}