SDL image tearing / stuttering

964 views Asked by At

First of all, let me make some things clear:

  1. My monitor is at 60 hertz
  2. I cap my FPS to 60, and it seems to be working correctly
  3. I have the double buffering flag active
  4. I made a backbuffer myself, and made sure to draw to it, and afterwards to the screen
  5. This problem happens both in fullscreen and windowed mode

This is my main function (it contains all the code):

SDL_Init(SDL_INIT_EVERYTHING);

SDL_Surface * backbuffer = NULL;
SDL_Surface * screen = NULL;
SDL_Surface * box = NULL;
SDL_Surface * background = NULL;

SDL_Rect * rect = new SDL_Rect();

double FPS = 60;
double next_time;
bool drawn = false;

rect->x = 0;
rect->y = 0;

screen = SDL_SetVideoMode(1920, 1080, 32, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_FULLSCREEN);
if(screen == NULL) {
    return 0;
}
background = SDL_LoadBMP("background.bmp");
box = SDL_LoadBMP("box.bmp");
if((background == NULL) || (box == NULL)) {
    return 0;
}

background = SDL_DisplayFormat(background);
box = SDL_DisplayFormat(box);

backbuffer = SDL_CreateRGBSurface(SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_FULLSCREEN,
    1920,
    1080,
    32,
    0,
    0,
    0,
    0);

if(backbuffer == NULL) {
    return 0;
}
next_time = (double)SDL_GetTicks() + (1000.0 / FPS);
while(true) {
    if(!drawn) {
        SDL_BlitSurface(background, NULL, backbuffer, NULL);
        SDL_BlitSurface(box, NULL, backbuffer, rect);
        rect->x += 3;
        drawn = true;
    }
    if((Uint32)next_time <= SDL_GetTicks()) {
        SDL_BlitSurface(backbuffer, NULL, screen, NULL);
        SDL_Flip(screen);
        next_time += 1000.0 / FPS;
        drawn = false;
    }
}

SDL_FreeSurface(backbuffer);
SDL_FreeSurface(background);
SDL_FreeSurface(box);
SDL_FreeSurface(screen);
SDL_Quit();
return 0;

I know this code isn't looking great, it was just a test to see why this happens to me whenever I write anything in SDL.

Please ignore the ugly code, and let me know if you have any idea of what might be causing the image of the moving white square over the black background to have weird artifacts and to seem to be tearing / stuttering.

If you need any more information let me know, and I'll update what's needed.

EDIT:

  • If I don't cap my FPS, it runs at 200-400 fps, which probably means SDL_Flip isn't waiting for the screen refresh.

  • I don't know if the flags I write, are actually used.

  • I checked my flags, and it seems like I can't get the SDL_HWSURFACE and SDL_DOUBLEBUF flags. It might cause the problem?

1

There are 1 answers

1
Roy Spector On

SDL Double buffering on HW_SURFACE

This is the solution to my problem. All I had to do was add this line:

SDL_putenv("SDL_VIDEODRIVER=directx");

Thanks for the comments, they helped me find the solution. :D

I guess I should check SDL 2.0 out too...