1
\$\begingroup\$

I am making my first foray into SDL. To do this, I would like to have direct access to the framebuffer on the window as a uint32_t *. This is because I have to pass this framebuffer to another file that my friend wrote which only accepts raw framebuffers like this one. I know that to write pixels you have to set up an SDL_Renderer but here I want direct access to the raw framebuffer. How would I do this using only SDL2?

\$\endgroup\$
2
\$\begingroup\$

This is actually covered in the migration guide from SDL1 to SDL2.

First, you'll need a texture that holds your framebuffer: SDL_Texture* framebuffer = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height);

The important bit here is the SDL_TEXTUREACCESS_STREAMING flag. This texture can be quickly changed to point to a different array of pixels. Also make sure you use the correct format flag.

Now you need to manually construct a buffer of pixels: uint32_t* pixels = new uint32_t[width*height];. This is the buffer that you can now freely modify and pass around.

Then, when you want to render the pixels in the buffer, all you have to do is to update the texture with the pixel buffer, and render the texture using the renderer to the screen.

SDL_UpdateTexture(framebuffer , NULL, pixels, width * sizeof (uint32_t));

SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, framebuffer , NULL, NULL);
SDL_RenderPresent(renderer);

Note that this code is untested but it should give you an idea of how to approach this. Implementation details are exactly that, implementation details.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.