This is a sequential Mandelbrot Set implementation.
void mandelbrot(PGMData *I)
{
float x0,y0,x,y,xtemp;
int i,j;
int color;
int iter;
int MAX_ITER=1000;
for(i=0; i<I->height; i++)
for(j=0; j<I->width; j++)
{
x0 = (float)j/I->width*(float)3.5-(float)2.5;
y0 = (float)i/I->height*(float)2.0-(float)1.0;
x = 0;
y = 0;
iter = 0;
while((x*x-y*y <= 4) && (iter < MAX_ITER))
{
xtemp = x*x-y*y+x0;
y = 2*x*y+y0;
x = xtemp;
iter++;
}
color = (int)(iter/(float)MAX_ITER*(float)I->max_gray);
I->image[i*I->width+j] = I->max_gray-color;
}
}
I want to paralellize it using CUDA but I seem to have misunderstood something and now I'm stuck. I've tried searching the internet but nothing really great came up.
Kernel:
__global__ void calc(int *pos)
{
int row= blockIdx.y * blockDim.y + threadIdx.y; // WIDTH
int col = blockIdx.x * blockDim.x + threadIdx.x; // HEIGHT
int idx = row * WIDTH + col;
if(col > WIDTH || row > HEIGHT || idx > N) return;
float x0 = (float)row/WIDTH*(float)3.5-(float)2.5;
float y0 = (float)col/HEIGHT*(float)2.0-(float)1.0;
int x = 0, y = 0, iter = 0, xtemp = 0;
while((x*x-y*y <= 4) && (iter < MAX_ITER))
{
xtemp = x*x-y*y+x0;
y = 2*x*y+y0;
x = xtemp;
iter++;
}
int color = 255 - (int)(iter/(float)MAX_ITER*(float)255);
__syncthreads();
pos[idx] = color;//color;// - color;
}
The kernel is initiated this way:
dim3 block_size(16, 16);
dim3 grid_size((N)/block_size.x, (int) N / block_size.y);
calc<<<grid_size,block_size>>>(d_pgmData);
And here are the constants:
#define HEIGHT 512
#define WIDTH 512
#define N (HEIGHT*WIDTH)
The whole GPU function
void mandelbrotGPU(PGMData *I)
{
int *pos = (int *)malloc(HEIGHT*WIDTH*sizeof(int));
int *d_pgmData;
cudaMalloc((void **)&d_pgmData, sizeof(int)*WIDTH*HEIGHT);
cudaMemcpy(d_pgmData, pos ,HEIGHT*WIDTH*sizeof(int) ,cudaMemcpyHostToDevice);
dim3 block_size(16, 16);
dim3 grid_size((N)/block_size.x, (int) N / block_size.y);
calc<<<grid_size,block_size>>>(d_pgmData);
cudaMemcpy(pos,d_pgmData,HEIGHT*WIDTH*sizeof(int) ,cudaMemcpyDeviceToHost);
cudaFree(d_pgmData);
I->image = pos;
}
The problem is: It's either returning garbage or the driver crashes. I would really appreciate some advice because I am really stuck.