我正在用 Haskell 和 OpenCL 编写路径跟踪器,但在将 image2d_t 传递给内核以将输出写入时遇到问题。也就是说,get_image_*
在 image2d_t 上调用 OpenCL 中的任何函数都会返回无意义的值(通常是 0 或 2^24-1),并且write_imagef
什么也不做。这只发生在 GPU 上运行时——CPU 运行良好。调用clGetImageInfo
主机返回正确的值。OpenCL 的 Haskell 绑定将错误代码转换为异常,因此不必忘记检查错误。clinfo 将我的版本报告为“OpenCL 1.2 AMD-APP (1084.2)”。我应该注意到我遇到(并报告了)多个导致 OpenCL 编译器出现段错误或无法链接的错误,所以这可能是我的代码中的错误而不是错误的结果。
我像这样初始化 OpenCL(希望对不了解 Haskell 的人来说应该比较容易理解):
(platform:_) <- clGetPlatformIDs
(device:_) <- clGetDeviceIDs platform CL_DEVICE_TYPE_GPU
glContext <- glXGetCurrentContext
glDisplay <- glXGetCurrentDisplay
context <- clCreateContext [CL_GL_CONTEXT_KHR glContext, CL_GLX_DISPLAY_KHR glDisplay] [device] putStrLn
queue <- clCreateCommandQueue context device []
source <- readFile "pt.cl"
program <- clCreateProgramWithSource context source
clBuildProgram program [device] "-cl-strict-aliasing"
`catch` (λe -> case (e :: CLError) of
CL_BUILD_PROGRAM_FAILURE -> putStrLn "Building OpenCL program failed:"
>> clGetProgramBuildLog program device >>= putStrLn
>> throw e
_ -> return ())
kernel <- clCreateKernel program "sample"
pCorners <- mallocArray 4
buffer <- clCreateBuffer context [CL_MEM_READ_ONLY, CL_MEM_USE_HOST_PTR] (4*sizeOf (undefined :: V.Vec4F), castPtr pCorners)
clSetKernelArgSto kernel 1 buffer
tex@(TextureObject texid) <- head <$> (genObjectNames 1)
activeTexture $= TextureUnit 0
textureBinding Texture2D $= Just tex
textureFilter Texture2D $= ((Nearest, Nothing), Nearest)
textureWrapMode Texture2D S $= (Repeated, Clamp)
textureWrapMode Texture2D T $= (Repeated, Clamp)
texImage2D Nothing NoProxy 0 RGBA′ (TextureSize2D initialWidth initialHeight) 0 (PixelData RGBA UnsignedByte nullPtr)
image <- clCreateFromGLTexture2D context [CL_MEM_READ_WRITE] gl_TEXTURE_2D 0 texid
clSetKernelArgSto kernel 2 image
我称之为(稍微简化)来运行内核并渲染结果:
clSetKernelArgSto kernel 0 position
pokeArray pCorners orientedCorners -- update the pCorners array
finish -- This is glFinish()
clEnqueueAcquireGLObjects queue [image] []
clEnqueueNDRangeKernel queue kernel [width, height] [] []
clEnqueueReleaseGLObjects queue [image] []
clFinish queue
drawElements TriangleFan 4 UnsignedInt offset0
swapBuffers
最后,测试内核:
__kernel void sample(float3 position, __constant float3 corner[4], image2d_t output) {
write_imagef(output, (int2)(get_global_id(0), get_global_id(1)), (float4)(0, 0.5f, 1, 1));
}
其输出是一个全屏四边形,显示 GPU 内存的随机未初始化区域。它应该是全屏青色四边形。我在那里有一些printf
s 来显示get_image_*
函数的结果,但是它们已经开始导致程序挂起。