generation

Coordinator
Apr 24, 2011 at 2:05 PM
Edited Apr 24, 2011 at 2:06 PM

This compute shader changes the cell color based on how many generations it lives.

 


 

static const int2 g_sumIndex[8] = {
    {-1, -1},
    { 0, -1},
    { 1, -1},
    {-1,  0},
    { 1,  0},
    {-1,  1},
    { 0,  1},
    { 1,  1},
};

static const float3 g_rainbow[7] = {
    {1.0, 0.0, 0.0},
    {1.0, 0.5, 0.0},
    {1.0, 1.0, 0.0},
    {0.0, 0.6, 0.0},
    {0.0, 0.0, 1.0},
    {0.0, 0.0, 0.8},
    {0.4, 0.0, 0.8},
};

cbuffer CBParams : register(b0)
{
	int width;
	int height;
	int r1;
	int r2;
	int r3;
	int r4;
};

struct Data {
	int alive;
	float3 color;
};

StructuredBuffer<Data> current : register(t0);
RWStructuredBuffer<Data> next : register(t1);

[numthreads(1, 1, 1)]
void main( uint3 tid : SV_DispatchThreadID )
{
	int cx = tid.x % width;
	int cy = tid.x / width;
	
	int sum = 0;
	for(int i = 0; i < 8; ++i) {
		int x = cx + g_sumIndex[i].x;
		int y = cy + g_sumIndex[i].y;
		if(0 <= x && x < width && 0 <= y && y < height) {
			int id = x + y * width;
			if(current[id].alive != 0) {
				sum++;
			}
		}
	}

	if(current[tid.x].alive == 0 && sum >= 3 && sum <= 3) {
		next[tid.x].alive = 1;
		next[tid.x].color = float3(0.0, 0.0, 1.0);
	}
	else if(current[tid.x].alive != 0 && (sum > 3 || sum < 2)) {
		next[tid.x].alive = 0;
		next[tid.x].color = 0.0f;
	}
	else if(current[tid.x].alive != 0) {
		next[tid.x].alive = current[tid.x].alive + 1;
		float a = saturate(next[tid.x].alive / 8.0);
		next[tid.x].color = float3(a, 0.0, 1.0 - a);
	}
	else {
		next[tid.x].alive = current[tid.x].alive;
		next[tid.x].color = current[tid.x].color;
	}
}