-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjuliaSet.cu
79 lines (66 loc) · 1.62 KB
/
juliaSet.cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include "book.h"
#include "cpu_bitmap.h"
#include <stdio.h>
#define DIM 512
struct cuComplex {
float r;
float i;
__device__ cuComplex(float a, float b) : r(a), i(b) {}
__device__ float magnitude2(void)
{
return r * r + i * i;
}
__device__ cuComplex operator* (const cuComplex &a)
{
return cuComplex(r * a.r - i * a.i, i * a.r + r * a.i);
}
__device__ cuComplex operator+ (const cuComplex &a)
{
return cuComplex(r + a.r, i + a.i);
}
};
__device__ int julia(int x, int y)
{
const float scale = 1.5;
float jx = scale * (float)(DIM / 2 - x) / (DIM / 2);
float jy = scale * (float)(DIM / 2 - y) / (DIM / 2);
cuComplex c(-0.8, 0.156);
cuComplex a(jx, jy);
int i = 0;
// Check if number (jx,jy) is in the Julia set
for (i = 0; i < 200; i++)
{
a = a *a + c;
if (a.magnitude2() > 1000)
{
return 0;
}
}
return 1;
}
__global__ void kernel(unsigned char *ptr)
{
// map from blockIdx to pixel position
int x = blockIdx.x;
int y = blockIdx.y;
int offset = (x + y * gridDim.x) * 4;
int juliaValue = julia(x, y);
// RGB + intensity values
ptr[offset + 0] = 0; // Red
ptr[offset + 1] = 0; // Green
ptr[offset + 2] = 255 * juliaValue; // Blue
ptr[offset + 3] = 255;
}
int main()
{
CPUBitmap bitmap(DIM, DIM);
unsigned char *dev_bitmap;
cudaMalloc(&dev_bitmap, bitmap.image_size());
dim3 grid(DIM, DIM);
kernel<<<grid, 1>>>(dev_bitmap);
cudaMemcpy(bitmap.get_ptr(), dev_bitmap, bitmap.image_size(), cudaMemcpyDeviceToHost);
bitmap.display_and_exit();
cudaFree(dev_bitmap);
}