OpenCL pixels to the screen

I use OpenCL to generate the window’s whole framebuffer, then I copy the framebuffer from the GPU to have SDL convert and copy that buffer using SDL_UpdateTexture, SDL_RenderClear, SDL_RenderCopy and SDL_RenderPresent.

Since there’s no reason for me to transfer the framebuffer back and forth from and to the GPU I’d like to figure out the best way to display it as directly as possible. Here’s how my OpenCL kernel works:

kernel void draw_framebuffer(global float *data, global uchar4 *framebuffer)
const int index = get_global_id(1) * get_global_size(0) + get_global_id(0);

float4 pv = math_magic_goes_here(data, framebuffer);

framebuffer[index] = linear_to_srgb(pv);


From the C code the on-GPU framebuffer appears as a cl_mem.

I suppose I’d have to use OpenGL to do what I want, I’ve never used it though and I can’t find online what’s a direct way for doing this.

I’m not sure about using the SDL texture objects to do this kind of thing, but it’s definitely doable with OpenGL if you’re willing to go that route. OpenGL seems daunting at first (and stays that way for a while) but if you already understand how to use your GPU as a compute device then you’re at a good place to start.

What you want to do is create an OpenGL texture (which allocates GPU memory), and then map that texture to OpenCL memory. The process of mapping OpenGL memory to memory used by your compute framework (OpenCL) uses Context Sharing to share the memory between OpenCL and OpenGL.

The toughest part about all that, to be honest, is setting up the OpenGL texture and displaying it. That will be your first hurdle, I think. I would go about this as follows:

  1. Learn how to create a rectangle and draw it with OpenGL.
  2. Learn how to create texture coordinates for that rectangle’s vertices, and use those to map an image from disk to the rectangle.
  3. Learn how to map OpenGL texture memory to an OpenCL buffer and back again. Once you can do that you can pass the texture memory to your kernel.

I wish I could give you a concrete tutorial, but I’m not aware of one off hand. There are plenty of tutorials for drawing a rectangle with OpenGL; lazyfoo’s modern OpenGL section of his SDL2 tutorials has a decent example, and he does some texture mapping there as well. In terms of context sharing this powerpoint ( should get you going in the right direction, along with anything else you can find on Google.

Wish I could be more help, but to some that up I think using OpenGL would be a good route.