1
\$\begingroup\$

Currently I am doing my rendering by using a 3D array window_width x window_height x rgb as a buffer, then looping through the buffer and plotting pixels on screen using SDL2 (SDL_RenderDrawPoint). I know this is horrible and stupidly slow but I am not well experienced in graphics techniques. What is the better way to do this?

\$\endgroup\$
  • \$\begingroup\$ Why not use a 1D array of SDL_Textures that you render using SDL_RenderCopy? Why do you need a buffer of these anyway? \$\endgroup\$ – congusbongus Jun 16 '15 at 4:54
  • \$\begingroup\$ I'm building a ray tracer and my render algorithm puts each calculated pixel into the array, which I then render to screen. Can I put the pixel data into a texture, then copy it using RenderCopy? \$\endgroup\$ – Corydon Jun 16 '15 at 5:06
1
\$\begingroup\$

You can use SDL_LockTexture and SDL_UnlockTexture for write only access to a texture created with the SDL_TEXTUREACCESS_STREAMING flag. Lock, write, unlock, then use SDL_RenderCopy to blit to the screen.

Create the buffer with SDL_CreateTexture (modify to you liking):

SDL_Texture* buffer = SDL_CreateTexture(renderer,
                           SDL_PIXELFORMAT_BGRA8888,
                           SDL_TEXTUREACCESS_STREAMING, 
                           800,
                           600);

Lock with SDL_LockTexture:

SDL_LockTexture(buffer,
                NULL,      // NULL means the *whole texture* here.
                &pixels,
                &pitch);

Where pixels is a int * and pitch is the width of a row of pixels in bytes.

Write your pixel data to pixels. You won't have any of the convenient SDL functions to do this. Just plonk the data in, one pixel after the other until you have done them all. Make sure you write with the correct PIXELFORMAT, otherwise the colours will come out wonky. (In SDL_PIXELFORMAT_BGRA8888, the first byte is blue, second is green, third is red and fourth is alpha. Leave alpha at 255 unless you want transparency)

Clean up with SDL_UnlockTexture:

SDL_UnlockTexture(buffer);

Then you can RenderCopy this texture as normal:

SDL_RenderCopy(renderer, buffer, NULL, NULL);

This assumes the buffer is the same size as your window.

Note you will have to modify this for your own use case.

| improve this answer | |
\$\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.