在这里,我有两个不同版本的代码。
第一个是来自 CUDA SDK 的完整 CUDA 程序。在内核中,tex3D 运行良好。
第二个版本更复杂,有很多 OpenGL 函数和 OpenGL 纹理。它的 .cu 文件与第一个相同。但是,我在同一个内核函数中使用 cudaMalloc 变量从 tex3D 获取值,我发现 tex3D 函数没有返回任何内容。实际上,两个程序使用相同的方式来创建 3D 纹理,如下代码所示:
#define SIZE_X 128 //numbers in elements
#define SIZE_Y 128
#define SIZE_Z 128
typedef float VolumeType;
cudaExtent volumeSize = make_cudaExtent(SIZE_X, SIZE_Y, SIZE_Z);
cudaArray *d_volumeArray = 0; //for tex
cudaArray *d_transferFuncArray; //for transferTex
texture<VolumeType, 3, cudaReadModeElementType> tex; // 3D texture
texture<float4, 1, cudaReadModeElementType> transferTex; // 1D transfer function texture
//initialize the 3d texture "tex" with a 3D array "d_volumeArray"
cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc<VolumeType>();
cutilSafeCall( cudaMalloc3DArray(&d_volumeArray, &channelDesc, volumeSize) );
// set texture parameters
tex.normalized = true; // access with normalized texture coordinates
tex.filterMode = cudaFilterModeLinear; // linear interpolation
tex.addressMode[0] = cudaAddressModeClamp; // clamp texture coordinates
tex.addressMode[1] = cudaAddressModeClamp;
CUDA_SAFE_CALL(cudaBindTextureToArray(tex, d_volumeArray, channelDesc));// bind array to 3D texture
//get the real value for 3D texture "tex"
float *d_volumeMem;
cutilSafeCall(cudaMalloc((void**)&d_volumeMem, SIZE_X*SIZE_Y*SIZE_Z*sizeof(float)));
.....//assign value to d_volumeMem in GPU. I've already checked the d_volumeMem is valid
//copy d_volumeMem to 3DArray
cudaMemcpy3DParms copyParams = {0};
copyParams.srcPtr = make_cudaPitchedPtr((void*)d_volumeMem, SIZE_X*sizeof(VolumeType), SIZE_X, SIZE_Y);
copyParams.dstArray = d_volumeArray;
copyParams.extent = volumeSize;
copyParams.kin = cudaMemcpyDeviceToDevice;
cutilSafeCall( cudaMemcpy3D(©Params) );
下面的代码是调用 tex3D 的内核函数。实际上,它和 CUDA SDK volumeRender 的内核一样,都是光线投射的实现。
__global__ void d_render(....)
{
......//ray-casting progress
float temp = tex3D(tex, pos1, pos2, pos3);
//pos1 pos2 pos3 is valid
//Here actually I use a cudaMalloc variable "s" to store the temp
//In the first version, s has different value for different position
//In the second version, temp is 0 all the time
......//ray-casting progress
}
我认为这些代码很好,因为它们中的大多数来自 CUDA SDK volumeRender,并且在我的第一个版本代码中运行良好。
但我不知道为什么在第二个版本中 tex3D 突然无效。也许其他一些OpenGL纹理有一些负面影响?