Skip to content

Instantly share code, notes, and snippets.

@jfacoustic
Last active October 10, 2016 03:32
Show Gist options
  • Save jfacoustic/be9c06fc561b954410c9573f8f07bb9f to your computer and use it in GitHub Desktop.
Save jfacoustic/be9c06fc561b954410c9573f8f07bb9f to your computer and use it in GitHub Desktop.
Mandelbrot Set calculated with CUDA: using resources from CUDA by Example at https://developer.nvidia.com/cuda-example
#include "../common/book.h"
#include "../common/cpu_bitmap.h"
#define DIM 1000
//From Wikipedia's article on the Mandelbrot Set:
__device__ int mandelbrot( int xa, int ya, float s, float xpos, float ypos) {
float x0 = s * (float) (DIM/2 -xa)/((float)DIM/2) + xpos;
float y0 = s * (float)(DIM/2 -ya )/((float)DIM/2) + ypos;
int m = 0;
float x = 0.0;
float y = 0.0;
int i = 0;
int maxI = 1000;
while (((x*x + y*y) <= 2*2) && (i < maxI)) {
float xtemp = x*x - y*y + x0;
y = 2*x*y + y0;
x = xtemp;
i++;
m = i;
}
return m;
}
__global__ void kernel ( unsigned char *ptr, float s, float xpos, float ypos) {
//map from blockIDx to pixel positio0n
int x = blockIdx.x;
int y = blockIdx.y;
int offset = x + y * gridDim.x;
int mValue = mandelbrot( x, y, s, xpos, ypos);
int red = 0;
int blue = 0;
int green = 0;
if (mValue%3 == 0) blue = 1;
if (mValue%3 == 1) red = 1;
if (mValue%3 == 2) green = 1;
ptr[offset*4 + 0] = red * 255 * mValue / 16;
ptr[offset*4 + 1] = blue * 255 * mValue/16;
ptr[offset*4 + 2] = green * 255 * mValue/16;
ptr[offset*4 + 3] = 255;
}
int main ( int argc,char *argv[] ) {
CPUBitmap bitmap( DIM, DIM );
unsigned char *dev_bitmap;
float s = atof(argv[1]);
float xpos = atof(argv[2]);
float ypos = atof(argv[3]);
HANDLE_ERROR( cudaMalloc( (void**)&dev_bitmap, bitmap.image_size()));
dim3 grid(DIM, DIM);
kernel<<<grid, 1>>>( dev_bitmap, s, xpos, ypos );
HANDLE_ERROR( cudaMemcpy( bitmap.get_ptr(), dev_bitmap, bitmap.image_size(), cudaMemcpyDeviceToHost ) ) ;
bitmap.display_and_exit();
HANDLE_ERROR( cudaFree( dev_bitmap ) );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment