1、申请pbo资源,由于是用于显示的,所以使用GL_PIXEL_UNPACK_BUFFER_ARB和GL_STREAM_DRAW_ARB,使用4个语句
glGenBuffersARB(1, &pbo);
//使用GL_PIXEL_UNPACK_BUFFER_ARB因为是要用于显示的
glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, width*height*sizeof(GLubyte)*4, 0, GL_STREAM_DRAW_ARB);//source 为0,只分配规定大小的空间
glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);//用于取消该绑定,防止后面的不经意修改
2、注册pbo资源(不一定只是pbo资源),用于被cuda访问。被注册的资源用cuda_pbo_resource返回
Registers the buffer object specified by buffer for access by CUDA. A handle to the registered object is returned as resource. The register flags flags specify the intended usage, as follows:
cudaGraphicsRegisterFlagsNone: Specifies no hints about how this resource will be used. It is therefore assumed that this resource will be read from and written to by CUDA. This is the default value.
cudaGraphicsRegisterFlagsReadOnly: Specifies that CUDA will not write to this resource.
cudaGraphicsRegisterFlagsWriteDiscard: Specifies that CUDA will not read from this resource and will write over the entire contents of the resource, so none of the data previously stored in the resource will be preserved.
使用一句话:
cutilSafeCall(cudaGraphicsGLRegisterBuffer(&cuda_pbo_resource, pbo, cudaGraphicsMapFlagsWriteDiscard));
3、申请count个图形资源,这个资源必须注册过,这个资源将被cuda使用,直至unmap。1句:
Maps the count graphics resources in resources for access by CUDA.
The resources in resources may be accessed by CUDA until they are unmapped.
The graphics API from which resources were registered should not access any resources while they are mapped by CUDA.
If an application does so, the results are undefined.
cutilSafeCall(cudaGraphicsMapResources(1, &cuda_pbo_resource, 0));
4、获得可以操作的指针,一般为void**。
返回存在void** devPtr,指向映射的图像资源resource ,size是byte形式的memory的大小
这些资源将通过devPtr来访问
cutilSafeCall(cudaGraphicsResourceGetMappedPointer((void **)&d_output, &num_bytes, cuda_pbo_resource));
5、在d_output上进行操作,cuda并行计算和绘制
6、绘制结束,取消在cuda上的映射,cuda不对此数据进行操作了,数据存于d_output中,1句:
Unmaps the count graphics resources in resources.
Once unmapped, the resources in resources may not be accessed by CUDA until they are mapped again.
This function provides the synchronization guarantee that any CUDA work issued in stream before cudaGraphicsUnmapResources() will complete before any subsequently issued graphics work begins.
If resources contains any duplicate entries then cudaErrorInvalidResourceHandle is returned. If any of resources are not presently mapped for access by Cuda then cudaErrorUnknown is returned.
cutilSafeCall(cudaGraphicsUnmapResources(1, &cuda_pbo_resource, 0));
7、显示,改变光栅位置,绑定pbo,这时,opengl已经自动把数据写入pbo中,只要使用glDrawPixel就可以了
glRasterPos2i(0, 0);//这里坐标使用的opengl的坐标,改变光栅位置。光栅(Raster):由像素构成的一个矩形网格。要在光栅上显示的数据保存于帧缓存内。
glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
glDrawPixels(width, height, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);