CUDA - JuliaSet



简单的入门示例

#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include "cpu_bitmap.h"
#include "book.h"


#define DIM 1000

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;

	for (i = 0; i < 200 ; i++)
	{
		a = a*a + c ;
		if (a.magnitude2() > 1000)
			return 0;
	}

	return 1;
}

__global__ void kernel(unsigned char *ptr)
{
	int x = blockIdx.x;
	int y = blockIdx.y;

	int offset = x + y * gridDim.x;


	int juliaValue = julia( x,y);

	ptr[offset*4 + 0] = 255*juliaValue;
	ptr[offset*4 + 1] = 0;
	ptr[offset*4 + 2] = 0;
	ptr[offset*4 + 3] = 255;
}

int main ( void )
{
	CPUBitmap bitmap( DIM, DIM);

	unsigned char *dev_bitmap;

	HANDLE_ERROR( cudaMalloc( (void **) &dev_bitmap, bitmap.image_size() ));

	dim3 grid(DIM, DIM);

	kernel<<<grid, 1>>>(dev_bitmap);

	HANDLE_ERROR( cudaMemcpy( bitmap.get_ptr(),
		dev_bitmap,
		bitmap.image_size(),
		cudaMemcpyDeviceToHost)
	);


	bitmap.display_and_exit();

	cudaFree( dev_bitmap );
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值