# version 440

#define C_FLD 0
#define C_BND 1

// palette
vec4 color(float t)
{
	///float coltab[] = {0.5, 0.5, 0.5,             0.5, 0.65, 0.5, 1.0, 1.0, 1.0,  0.00, 0.33, 0.67};
	float coltab[] = { 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 0.00, 0.10, 0.20 };//!!
																					   //float coltab[] = {0.5, 0.5, 0.5,             0.5, 0.5, 0.5,  1.0, 1.0, 1.0,  0.30, 0.20, 0.20};
																					   //float coltab[] = {0.5, 0.5, 0.5,               0.5, 0.5, 0.5,  1.0, 1.0, 0.5,  0.80, 0.90, 0.30};
																					   //float coltab[] = { 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 1.0, 0.7, 0.4, 0.00, 0.15, 0.20 };//gld
																					   //float coltab[] = {0.5, 0.5, 0.5,             0.5, 0.5, 0.5,  2.0, 1.0, 0.0,  0.50, 0.20, 0.25};
																					   //float coltab[] = {0.8, 0.5, 0.4,             0.2, 0.4, 0.2,  2.0, 1.0, 1.0,  0.00, 0.25, 0.25};
	vec4 col;
	col.r = coltab[0] + coltab[3] * cos(2 * 3.1416 * (coltab[6] * t + coltab[9]));
	col.g = coltab[1] + coltab[4] * cos(2 * 3.1416 * (coltab[7] * t + coltab[10]));
	col.b = coltab[2] + coltab[5] * cos(2 * 3.1416 * (coltab[8] * t + coltab[11]));
	col.a = 1;
	return col;
}

struct Particle
{
	vec4 pos;
	vec4 col;
};

layout(binding = 7) buffer dcF { int F [  ]; };
layout(binding = 8) buffer dcU { float U [  ]; };
layout(binding = 9) buffer dcV { float V [  ]; };
layout(binding = 10) buffer dcW { float W [  ]; }; 
layout(local_size_x = 1000, local_size_y = 1, local_size_z = 1) in;
layout(binding = 11) buffer particle { Particle p []; };

float per(float x, int nx)      // periodic bnd's
{
	if (x < 0) x = nx - 1;
	else
	if (x > nx - 1) x = 0;
	return x;
}

float random(vec2 uv)
{
	return fract(sin(dot(uv, vec2(12.9898, 78.233))) * 43758.5453123);
}

void main()
{
	int NX = 200;
	int NY = 70;
	int NZ = 70;
	int idx = int(gl_GlobalInvocationID.x);
	float px = p[idx].pos.x;
	float py = p[idx].pos.y;
	float pz = p[idx].pos.z;
	int i = int(px);
	int j = int(py);
	int k = int(pz);
	int idxF = i + j * NX + k * NX * NY;

	float dt = 70.0;
	if (F[idxF] != 1)
	{
		px = px + U[idxF] * dt;
		py = py + V[idxF] * dt;
		pz = pz + W[idxF] * dt;
	}
	else
	{
		py = NY * random(vec2(px, pz));
		pz = NZ * random(vec2(py, px));
		px = 0;
	}


	if (px > NX - 1)
	{
		py = NY * random(vec2(px, pz));
		pz = NZ * random(vec2(py, px));
		px = 0;
	}

	px = per(px, NX);
	py = per(py, NY);
	pz = per(pz, NZ);

	float u = U[idxF];
	float v = V[idxF];
	float w = W[idxF];

	//vec4 col = color(30.0 * (u * u + v * v));
	//vec4 col = vec4(120.0 * (u * u + v * v+ w * w));
	vec4 col = color(10 * (u * u + v * v));
	col.a = 4 * (u * u + v * v);
	col.a = 1.9*pow(log(1 + col.a) / log(2), 0.9);
	//col.a=0;
	if (F[idxF] == 1)
	{
		col = vec4(0.3, 0.3, 0.5, 0.0);
	}
	//vec2 particle = p2[i].pos.xy;
	p[idx].pos.x = px;
	p[idx].pos.y = py;
	p[idx].pos.z = pz;
	p[idx].col = 0.01+col;// col;
}

