Will Scott
Will Scott

Reputation: 77

SDL not rendering pixels

I'm trying to change the background color of my window in SDL with pixel level access (I'm making a particle explosion), but the background is staying white.

First I tried using memset to set the memory of the pixels to 0x00 to change the color to black (I used memset because I am following a tutorial that used it)

memset(buffer, 0x00, SCREEN_WIDTH * SCREEN_HEIGHT * sizeof(Uint32));

Since that didn't work I looked up how to change the draw color of the renderer and came up with:

SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 255);

Here is my Texture, Renderer, and Buffer code, and how I set up the window (SCREEN_WIDTH and SCREEN_HEIGHT are const ints set to 800 and 600 respectively):

SDL_Window* window = SDL_CreateWindow("Fire Particle Explosion", 
    SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
    SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC);
SDL_Texture* texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STATIC, SCREEN_WIDTH, SCREEN_HEIGHT);
Uint32* buffer = new Uint32[SCREEN_WIDTH * SCREEN_HEIGHT];

SDL_UpdateTexture(texture, NULL, buffer, SCREEN_WIDTH * sizeof(Uint32));
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);

How would I properly change the background pixel by pixel, and why do neither of the ways I attempted work?

Upvotes: 1

Views: 1534

Answers (1)

Joseph Paul
Joseph Paul

Reputation: 346

You don't need to manipulate a buffer in memory to achieve that, and you may not need a texture. The recommended way is to use the "2D Accelerated Rendering" functions in SDL2.

First of all, start without the "SDL_RENDERER_PRESENTVSYNC" parameter, use '0' instead. On Linux, some old graphics drivers produce flickering with that flag.

This should erase the screen in black:

SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 255);
SDL_RenderClear(renderer);

I strongly advise you to use SDL_RenderDrawPoint() in order to update the screen pixel by pixel. It is hardware accelerated.

Basically, here is what happens in your game loop:

- set the color to black, then erase the screen with SDL_RenderClear()
- for each point to draw, first set the draw color, then draw the point
- use SDL_RenderPresent()

I have written a small example of SDL2 code in C for making particle explosions: drawpoints

Upvotes: 1

Related Questions