Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SDL rendering too slow

Tags:

c++

sdl

sdl-2

I'm a beginner in both C++ and SDL, and I'm slowly writing a small game following some tutorials to learn some concepts.

I'm having a problem, though: My rendering seems to be really slow. I've used PerformanceCounters to calculate my loops with and without my rendering function. Without it, I get 0~2ish milliseconds per frame; when I add the rendering, it goes up to 65ish ms per frame.

Could someone tell me what is wrong with my rendering function?

SDL_Texture *texture;

...

// gets called by the main loop
void render(int x_offset, int y_offset)
{
  if (texture)
  {
    SDL_DestroyTexture(texture);
  }

  texture = SDL_CreateTexture(renderer,
      SDL_PIXELFORMAT_ARGB8888,
      SDL_TEXTUREACCESS_STREAMING,
      texture_w,
      texture_h);

  if (SDL_LockTexture(texture, NULL, &pixel_memory, &pitch) < 0) {
    printf("Oops! %s\n", SDL_GetError());
  }

  Uint32 *pixel;
  Uint8 *row = (Uint8 *) pixel_memory;

  for (int j = 0; j < texture_h; ++j) {
    pixel = (Uint32 *)((Uint8 *) pixel_memory + j * pitch);
    for (int i = 0; i < texture_w; ++i) {

      Uint8 alpha = 255;
      Uint8 red = 172;
      Uint8 green = 0;
      Uint8 blue = 255;

     *pixel++ = ((alpha << 24) | (red << 16) | (green << 8) | (blue));

    }
  }
  SDL_UnlockTexture(texture);
} 
like image 499
Thyago B. Rodrigues Avatar asked Dec 14 '22 15:12

Thyago B. Rodrigues


1 Answers

It's likely slow because you're destroying and creating the texture every single frame, locking textures/uploading pixel data isn't super fast, but I doubt it's the bottleneck here. I strongly recommend allocating the texture once before entering your main loop and re-using it during rendering, then destroying it before your program exits.

like image 120
Twinklebear Avatar answered Dec 30 '22 08:12

Twinklebear