基于GPU的Julia集应用程序

配置好CUDA编译环境之后,vs创建一个CUDA的项目,会自动包含一个.cu文件,可以在当前文件中编写。

因为当前的项目需要用到其他的头文件和库,需要加入对应的路径,这个和别的工程是一样的。

1. 头文件目录

2. 库文件目录

3. 添加库文件名

4. 拷贝DLL到指定的路径

当前实例的结果如下图:

示例代码如下:

/*
* Julia集可以简单的认为时某个复数计算函数的所有点构成的边界
*/
#include "cuda_runtime.h"
#include "cpu_bitmap.h"
#include <device_launch_parameters.h>

#include "stdio.h"
// 图像的维度
#define DIM 1000

// 
struct cuComplex {
	float r;
	float i;
	__device__ cuComplex(float a, float b) :r(a), i(b) {}
	__device__ float magnitude2() { 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;
	// 将复平面的原点定位到图像中心,像素位置平移DIM/2
	// 为了确保图像的范围为 -1~1,将图像的坐标缩放了DIM/2
	// 给定的一个图像点(x,y),可以计算得到复空间中的一个点((DIM/2 - x)/(DIM/2),(DIM/2 - y)/(DIM/2))
	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);
	// 通过迭代之后和阈值的判断,来确认当前的坐标是否是julia值
	for (int i = 0; i < 200; i++) 
	{
		a = a * a + c;
		if (a.magnitude2() > 1000)
		{
			return 0;
		}
	}
	return 1;
}

__global__ void kernel(unsigned char* ptr)
{
	// 因为运行kernel时申请的是二位线程网格
	// 因为声明线程格时,线程格每一维的大小和图像每一维的大小时相等的
	// 因此在(0,0)和(DIM-1,DIM-1)之间的每个像素点(x,y)都能获得一个线程块
	int x = blockIdx.x;
	int y = blockIdx.y;
	// 对于所有的线程块,gridDim是一个常数,用来保存线程格每一维的大小,当前实例中gridDim=(DIM,DIM)
	// 将行索引乘以线程格的宽度,再加上列索引,就是ptr的唯一索引,其取值范围是(DIM*DIM-1)
	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()
{
	// 创建指定尺寸的位图
	CPUBitmap bitmap(DIM, DIM);
	// 设备上数据的副本
	unsigned char* dev_bitmap;
	cudaMalloc((void**)&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);

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值