日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

CUDA Samples: Ray Tracking

發(fā)布時間:2023/11/27 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 CUDA Samples: Ray Tracking 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

以下CUDA sample是分別用C++和CUDA實現(xiàn)的生成光線跟蹤圖像,并對其中使用到的CUDA函數(shù)進行了解說,code參考了《GPU高性能編程CUDA實戰(zhàn)》一書的第六章,CUDA各實現(xiàn)包括了使用常量內(nèi)存和不使用常量內(nèi)存兩種方法,各個文件內(nèi)容如下:

funset.cpp:

#include "funset.hpp"
#include <random>
#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include "common.hpp"
#include <opencv2/opencv.hpp>int test_ray_tracking()
{const int spheres{ 20 };std::unique_ptr<float[]> A(new float[spheres * 3]);std::unique_ptr<float[]> B(new float[spheres * 3]);std::unique_ptr<float[]> C(new float[spheres]);generator_random_number(A.get(), spheres * 3, 0.f, 1.f);generator_random_number(B.get(), spheres * 3, -400.f, 400.f);generator_random_number(C.get(), spheres, 20.f, 120.f);float elapsed_time1{ 0.f }, elapsed_time2{ 0.f }; // millisecondsconst int width{ 512 }, height = width;cv::Mat mat1(height, width, CV_8UC4), mat2(height, width, CV_8UC4);int ret = ray_tracking_cpu(A.get(), B.get(), C.get(), spheres, mat1.data, width, height, &elapsed_time1);if (ret != 0) PRINT_ERROR_INFO(ray_tracking_cpu);ret = ray_tracking_gpu(A.get(), B.get(), C.get(), spheres, mat2.data, width, height, &elapsed_time2);if (ret != 0) PRINT_ERROR_INFO(ray_tracking_gpu);for (int y = 0; y < height; ++y) {for (int x = 0; x < width; ++x) {cv::Vec4b val1 = mat1.at<cv::Vec4b>(y, x);cv::Vec4b val2 = mat2.at<cv::Vec4b>(y, x);for (int i = 0; i < 4; ++i) {if (val1[i] != val2[i]) {fprintf(stderr, "their values are different at (%d, %d), i: %d, val1: %d, val2: %d\n",x, y, i, val1[i], val2[i]);//return -1;}}}}const std::string save_image_name{ "E:/GitCode/CUDA_Test/ray_tracking.jpg" };cv::imwrite(save_image_name, mat2);fprintf(stderr, "ray tracking: cpu run time: %f ms, gpu run time: %f ms\n", elapsed_time1, elapsed_time2);return 0;
}
ray_tracking.cpp:

#include "funset.hpp"
#include <chrono>
#include <memory>
#include "common.hpp"// 通過一個數(shù)據(jù)結(jié)構(gòu)對球面建模
struct Sphere {float r, b, g;float radius;float x, y, z;float hit(float ox, float oy, float *n){float dx = ox - x;float dy = oy - y;if (dx*dx + dy*dy < radius*radius) {float dz = sqrtf(radius*radius - dx*dx - dy*dy);*n = dz / sqrtf(radius * radius);return dz + z;}return -INF;}
};int ray_tracking_cpu(const float* a, const float* b, const float* c, int sphere_num, unsigned char* ptr, int width, int height, float* elapsed_time)
{auto start = std::chrono::steady_clock::now();std::unique_ptr<Sphere[]> spheres(new Sphere[sphere_num]);for (int i = 0, t = 0; i < sphere_num; ++i, t+=3) {spheres[i].r = a[t];spheres[i].g = a[t+1];spheres[i].b = a[t+2];spheres[i].x = b[t];spheres[i].y = b[t+1];spheres[i].z = b[t+2];spheres[i].radius = c[i];}for (int y = 0; y < height; ++y) {for (int x = 0; x < width; ++x) {int offset = x + y * width;float ox{ (x - width / 2.f) };float oy{ (y - height / 2.f) };float r{ 0 }, g{ 0 }, b{ 0 };float maxz{ -INF };for (int i = 0; i < sphere_num; ++i) {float n;float t = spheres[i].hit(ox, oy, &n);if (t > maxz) {float fscale = n;r = spheres[i].r * fscale;g = spheres[i].g * fscale;b = spheres[i].b * fscale;maxz = t;}}ptr[offset * 4 + 0] = static_cast<unsigned char>(r * 255);ptr[offset * 4 + 1] = static_cast<unsigned char>(g * 255);ptr[offset * 4 + 2] = static_cast<unsigned char>(b * 255);ptr[offset * 4 + 3] = 255;}}auto end = std::chrono::steady_clock::now();auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);*elapsed_time = duration.count() * 1.0e-6;return 0;
}
ray_tracking.cu:

#include "funset.hpp"
#include <iostream>
#include <algorithm>
#include <memory>
#include <vector>
#include <cuda_runtime.h> // For the CUDA runtime routines (prefixed with "cuda_")
#include <device_launch_parameters.h>
#include "common.hpp"// 通過一個數(shù)據(jù)結(jié)構(gòu)對球面建模
struct Sphere {float r, b, g;float radius;float x, y, z;/* __device__: 函數(shù)類型限定符,表明被修飾的函數(shù)在設(shè)備上執(zhí)行,只能從設(shè)備上調(diào)用,但只能在其它__device__函數(shù)或者__global__函數(shù)中調(diào)用;__device__函數(shù)不支持遞歸;__device__函數(shù)的函數(shù)體內(nèi)不能聲明靜態(tài)變量;__device__函數(shù)的參數(shù)數(shù)目是不可變化的;不能對__device__函數(shù)取指針 */__device__ float hit(float ox, float oy, float *n){float dx = ox - x;float dy = oy - y;if (dx*dx + dy*dy < radius*radius) {float dz = sqrtf(radius*radius - dx*dx - dy*dy);*n = dz / sqrtf(radius * radius);return dz + z;}return -INF;}
};// method2: 使用常量內(nèi)存
/* __constant__: 變量類型限定符,或者與__device__限定符連用,這樣聲明的變量:存
在于常數(shù)存儲器空間;與應(yīng)用程序具有相同的生命周期;可以通過運行時庫從主機端訪問,
設(shè)備端的所有線程也可訪問。__constant__變量默認為是靜態(tài)存儲。__constant__不能用
extern關(guān)鍵字聲明為外部變量。__constant__變量只能在文件作用域中聲明,不能再函數(shù)
體內(nèi)聲明。__constant__變量不能從device中賦值,只能從host中通過host運行時函數(shù)賦
值。__constant__將把變量的訪問限制為只讀。與從全局內(nèi)存中讀取數(shù)據(jù)相比,從常量內(nèi)
存中讀取相同的數(shù)據(jù)可以節(jié)約內(nèi)存帶寬。常量內(nèi)存用于保存在核函數(shù)執(zhí)行期間不會發(fā)生變
化的數(shù)據(jù)。
常量內(nèi)存:用于保存在核函數(shù)執(zhí)行期間不會發(fā)生變化的數(shù)據(jù)。NVIDIA硬件提供了64KB的常
量內(nèi)存,并且對常量內(nèi)存采取了不同于標準全局內(nèi)存的處理方式。在某些情況中,用常量
內(nèi)存來替換全局內(nèi)存能有效地減少內(nèi)存帶寬。 在某些情況下,使用常量內(nèi)存將提升應(yīng)用程
序的性能 */
__constant__ Sphere dev_spheres[20]; // 常量內(nèi)存, = sphere_num/* __global__: 函數(shù)類型限定符;在設(shè)備上運行;在主機端調(diào)用,計算能力3.2及以上可以在
設(shè)備端調(diào)用;聲明的函數(shù)的返回值必須是void類型;對此類型函數(shù)的調(diào)用是異步的,即在
設(shè)備完全完成它的運行之前就返回了;對此類型函數(shù)的調(diào)用必須指定執(zhí)行配置,即用于在
設(shè)備上執(zhí)行函數(shù)時的grid和block的維度,以及相關(guān)的流(即插入<<<   >>>運算符);
a kernel,表示此函數(shù)為內(nèi)核函數(shù)(運行在GPU上的CUDA并行計算函數(shù)稱為kernel(內(nèi)核函
數(shù)),內(nèi)核函數(shù)必須通過__global__函數(shù)類型限定符定義); */
__global__ static void ray_tracking(unsigned char* ptr_image, Sphere* ptr_sphere, int width, int height, int sphere_num)
{/* gridDim: 內(nèi)置變量,用于描述線程網(wǎng)格的維度,對于所有線程塊來說,這個變量是一個常數(shù),用來保存線程格每一維的大小,即每個線程格中線程塊的數(shù)量.一個grid最多只有二維,為dim3類型;blockDim: 內(nèi)置變量,用于說明每個block的維度與尺寸.為dim3類型,包含了block在三個維度上的尺寸信息;對于所有線程塊來說,這個變量是一個常數(shù),保存的是線程塊中每一維的線程數(shù)量;blockIdx: 內(nèi)置變量,變量中包含的值就是當前執(zhí)行設(shè)備代碼的線程塊的索引;用于說明當前thread所在的block在整個grid中的位置,blockIdx.x取值范圍是[0,gridDim.x-1],blockIdx.y取值范圍是[0, gridDim.y-1].為uint3類型,包含了一個block在grid中各個維度上的索引信息;threadIdx: 內(nèi)置變量,變量中包含的值就是當前執(zhí)行設(shè)備代碼的線程索引;用于說明當前thread在block中的位置;如果線程是一維的可獲取threadIdx.x,如果是二維的還可獲取threadIdx.y,如果是三維的還可獲取threadIdx.z;為uint3類型,包含了一個thread在block中各個維度的索引信息 */// map from threadIdx/BlockIdx to pixel positionint x = threadIdx.x + blockIdx.x * blockDim.x;int y = threadIdx.y + blockIdx.y * blockDim.y;int offset = x + y * blockDim.x * gridDim.x;float ox{ (x - width / 2.f) };float oy{ (y - height / 2.f) };float r{ 0 }, g{ 0 }, b{ 0 };float maxz{ -INF };for (int i = 0; i < sphere_num; ++i) {float n;float t = ptr_sphere[i].hit(ox, oy, &n);if (t > maxz) {float fscale = n;r = ptr_sphere[i].r * fscale;g = ptr_sphere[i].g * fscale;b = ptr_sphere[i].b * fscale;maxz = t;}}ptr_image[offset * 4 + 0] = static_cast<unsigned char>(r * 255);ptr_image[offset * 4 + 1] = static_cast<unsigned char>(g * 255);ptr_image[offset * 4 + 2] = static_cast<unsigned char>(b * 255);ptr_image[offset * 4 + 3] = 255;
}__global__ static void ray_tracking(unsigned char* ptr_image, int width, int height, int sphere_num)
{int x = threadIdx.x + blockIdx.x * blockDim.x;int y = threadIdx.y + blockIdx.y * blockDim.y;int offset = x + y * blockDim.x * gridDim.x;float ox{ (x - width / 2.f) };float oy{ (y - height / 2.f) };float r{ 0 }, g{ 0 }, b{ 0 };float maxz{ -INF };for (int i = 0; i < sphere_num; ++i) {float n;float t = dev_spheres[i].hit(ox, oy, &n);if (t > maxz) {float fscale = n;r = dev_spheres[i].r * fscale;g = dev_spheres[i].g * fscale;b = dev_spheres[i].b * fscale;maxz = t;}}ptr_image[offset * 4 + 0] = static_cast<unsigned char>(r * 255);ptr_image[offset * 4 + 1] = static_cast<unsigned char>(g * 255);ptr_image[offset * 4 + 2] = static_cast<unsigned char>(b * 255);ptr_image[offset * 4 + 3] = 255;
}int ray_tracking_gpu(const float* a, const float* b, const float* c, int sphere_num, unsigned char* ptr, int width, int height, float* elapsed_time)
{/* cudaEvent_t: CUDA event types,結(jié)構(gòu)體類型, CUDA事件,用于測量GPU在某個任務(wù)上花費的時間,CUDA中的事件本質(zhì)上是一個GPU時間戳,由于CUDA事件是在GPU上實現(xiàn)的,因此它們不適于對同時包含設(shè)備代碼和主機代碼的混合代碼計時 */cudaEvent_t start, stop;// cudaEventCreate: 創(chuàng)建一個事件對象,異步啟動cudaEventCreate(&start);cudaEventCreate(&stop);// cudaEventRecord: 記錄一個事件,異步啟動,start記錄起始時間cudaEventRecord(start, 0);const size_t length{ width * height * 4 * sizeof(unsigned char) };unsigned char* dev_image{ nullptr };std::unique_ptr<Sphere[]> spheres(new Sphere[sphere_num]);for (int i = 0, t = 0; i < sphere_num; ++i, t += 3) {spheres[i].r = a[t];spheres[i].g = a[t + 1];spheres[i].b = a[t + 2];spheres[i].x = b[t];spheres[i].y = b[t + 1];spheres[i].z = b[t + 2];spheres[i].radius = c[i];}// cudaMalloc: 在設(shè)備端分配內(nèi)存cudaMalloc(&dev_image, length);// method1: 沒有使用常量內(nèi)存//Sphere* dev_spheres{ nullptr };//cudaMalloc(&dev_spheres, sizeof(Sphere) * sphere_num);/* cudaMemcpy: 在主機端和設(shè)備端拷貝數(shù)據(jù),此函數(shù)第四個參數(shù)僅能是下面之一:(1). cudaMemcpyHostToHost: 拷貝數(shù)據(jù)從主機端到主機端(2). cudaMemcpyHostToDevice: 拷貝數(shù)據(jù)從主機端到設(shè)備端(3). cudaMemcpyDeviceToHost: 拷貝數(shù)據(jù)從設(shè)備端到主機端(4). cudaMemcpyDeviceToDevice: 拷貝數(shù)據(jù)從設(shè)備端到設(shè)備端(5). cudaMemcpyDefault: 從指針值自動推斷拷貝數(shù)據(jù)方向,需要支持統(tǒng)一虛擬尋址(CUDA6.0及以上版本)cudaMemcpy函數(shù)對于主機是同步的 *///cudaMemcpy(dev_spheres, spheres.get(), sizeof(Sphere) * sphere_num, cudaMemcpyHostToDevice);// method2: 使用常量內(nèi)存/* cudaMemcpyToSymbol: cudaMemcpyToSymbol和cudaMemcpy參數(shù)為cudaMemcpyHostToDevice時的唯一差異在于cudaMemcpyToSymbol會復(fù)制到常量內(nèi)存,而cudaMemcpy會復(fù)制到全局內(nèi)存*/cudaMemcpyToSymbol(dev_spheres, spheres.get(), sizeof(Sphere)* sphere_num);const int threads_block{ 16 };dim3 blocks(width / threads_block, height / threads_block);dim3 threads(threads_block, threads_block);/* <<< >>>: 為CUDA引入的運算符,指定線程網(wǎng)格和線程塊維度等,傳遞執(zhí)行參數(shù)給CUDA編譯器和運行時系統(tǒng),用于說明內(nèi)核函數(shù)中的線程數(shù)量,以及線程是如何組織的;尖括號中這些參數(shù)并不是傳遞給設(shè)備代碼的參數(shù),而是告訴運行時如何啟動設(shè)備代碼,傳遞給設(shè)備代碼本身的參數(shù)是放在圓括號中傳遞的,就像標準的函數(shù)調(diào)用一樣;不同計算能力的設(shè)備對線程的總數(shù)和組織方式有不同的約束;必須先為kernel中用到的數(shù)組或變量分配好足夠的空間,再調(diào)用kernel函數(shù),否則在GPU計算時會發(fā)生錯誤,例如越界等;使用運行時API時,需要在調(diào)用的內(nèi)核函數(shù)名與參數(shù)列表直接以<<<Dg,Db,Ns,S>>>的形式設(shè)置執(zhí)行配置,其中:Dg是一個dim3型變量,用于設(shè)置grid的維度和各個維度上的尺寸.設(shè)置好Dg后,grid中將有Dg.x*Dg.y個block,Dg.z必須為1;Db是一個dim3型變量,用于設(shè)置block的維度和各個維度上的尺寸.設(shè)置好Db后,每個block中將有Db.x*Db.y*Db.z個thread;Ns是一個size_t型變量,指定各塊為此調(diào)用動態(tài)分配的共享存儲器大小,這些動態(tài)分配的存儲器可供聲明為外部數(shù)組(extern __shared__)的其他任何變量使用;Ns是一個可選參數(shù),默認值為0;S為cudaStream_t類型,用于設(shè)置與內(nèi)核函數(shù)關(guān)聯(lián)的流.S是一個可選參數(shù),默認值0. *///ray_tracking << <blocks, threads >> >(dev_image, dev_spheres, width, height, sphere_num); // method1, 不使用常量內(nèi)存ray_tracking << <blocks, threads >> >(dev_image, width, height, sphere_num); // method2, 使用常量內(nèi)存cudaMemcpy(ptr, dev_image, length, cudaMemcpyDeviceToHost);// cudaFree: 釋放設(shè)備上由cudaMalloc函數(shù)分配的內(nèi)存cudaFree(dev_image);//cudaFree(dev_spheres); // 使用method1時需要釋放, 如果使用常量內(nèi)存即method2則不需要釋放// cudaEventRecord: 記錄一個事件,異步啟動,stop記錄結(jié)束時間cudaEventRecord(stop, 0);// cudaEventSynchronize: 事件同步,等待一個事件完成,異步啟動cudaEventSynchronize(stop);// cudaEventElapseTime: 計算兩個事件之間經(jīng)歷的時間,單位為毫秒,異步啟動cudaEventElapsedTime(elapsed_time, start, stop);// cudaEventDestroy: 銷毀事件對象,異步啟動cudaEventDestroy(start);cudaEventDestroy(stop);return 0;
}
生成的結(jié)果圖像如下:


執(zhí)行結(jié)果如下:可見使用C++和CUDA實現(xiàn)的結(jié)果是完全一致的。


GitHub:? https://github.com/fengbingchun/CUDA_Test

總結(jié)

以上是生活随笔為你收集整理的CUDA Samples: Ray Tracking的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。