# simple SDL framerate?

This topic is 1322 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello, I have been doing alot of stuff in Allegro, I want to learn about SDL. I have been having a hard time getting the right type of framerate counter in my SDL program. This is what I did in Allegro:

/* Framerate Processes */
volatile int ticks = 0;
void ticker()
{
ticks++;
}
END_OF_FUNCTION(ticker)
volatile int game_time = 0;
void game_time_ticker()
{
game_time++;
}
END_OF_FUNCTION(game_time_ticker)

/* This is the deltatime, used for timing */
double dt;


inside the main function in my Allegro program, I did this (code has been butchered so you see things related to framerate):

int main(void) {
/* Initialize Allegro */
allegro_init();
install_timer();
/* Initialize Framerate */
LOCK_VARIABLE(ticks);
LOCK_FUNCTION(ticker);
LOCK_VARIABLE(game_time);
LOCK_FUNCTION(game_time_ticker);
install_int_ex(game_time_ticker, BPS_TO_TIMER(10)); /* The game is 1/10 seconds */
int fps = 0;
int frames_done = 0;
int old_time = 0;
int frames_array[10];
int frame_index = 0;
int ii;
for(ii = 0; ii < 10; ii++)
frames_array[ii] = 0;
/* Other stuff*/
other_stuff();
/* Run Game Loop */
while ( quit == false ) {
while(ticks == 0) {
rest(1);
}
while(ticks > 0)
{
int old_ticks = ticks;
ticks--;
if(old_ticks <= ticks)
break;
}
if(game_time >= old_time + 1)
{
fps -= frames_array[frame_index];
frames_array[frame_index] = frames_done;
fps += frames_done;

frame_index = (frame_index + 1) % 10;

frames_done = 0;
old_time += 1;
}
/* do stuff */
do_stuff();
/* set dt */
render_var( 16, 184, TEXT_LEFT, "FPS:", fps, true );
frames_done++;
}
/* Finish up */
return 0;
}
END_OF_MAIN()


I cannot for the life of me figure out how to do the equivalent in SDL, every attempt (that i've deleted as well) always came down to using SDL_Delay(1000/framerate) in the end, and while the speed seemed good, every 1 second the game would stop for one frame, and that really bothered me.

I've spent a couple days looking for a simple SDL framerate example, haven't been able to find any. If you can point me in the right direction (not lazyfoo's, i've tried his, and he is C++ whereas I want to do it in C), that would be great, thanks.

##### Share on other sites

Assuming you're using SDL 2, look up these two functions:

• SDL_GetPerformanceCounter
• SDL_GetPerformanceFrequency

This will give you a high resolution timer you can use to calculate how much time has ellapsed since the last time you checked. With some math you can turn that into frames per second (just make sure to not discard frames that haven't fully ellapsed yet).

##### Share on other sites

Thanks, but do you know what I can look up for SDL 1.2 as well? Thanks

##### Share on other sites

Not really, if I recall correctly there were timers but their resolution was like 1ms (and the documentation warned that it was usually less), that may be enough for framerate if you account for rounding errors I guess.

SDL 1.2 is deprecated and not maintained anymore though, you're better off avoiding it if possible. SDL 2.0 is actively maintained and supports modern platforms (including mobile), and fixes several issues that 1.2 used to have. It also has functions to render stuff using the GPU (SDL 1.2 couldn't do that). The biggest loss is lack of CD Audio support, but does anybody still use that for games?

Edited by Sik_the_hedgehog

##### Share on other sites

The Dreamcast and Wii (not sure about PSP) don't have SDL 2 yet, so for now I just need some SDL 1.2 code.

##### Share on other sites

Here I translated this C++ timing system to ANSI C. Does not work as correctly as I though (doesn't work at all):

http://pastebin.com/Lfixw615

##### Share on other sites

I've spent a couple days looking for a simple SDL framerate example, haven't been able to find any. If you can point me in the right direction (not lazyfoo's, i've tried his, and he is C++ whereas I want to do it in C), that would be great, thanks.

I just read LazyFoo's code. His LTimer class is a VERY simple POD type, you should be able to just slap up a C struct and rewrite the member functions as global functions that take a LTimer * parameter, and you're good to go.

##### Share on other sites

isn't that what I did in the pastebin?

##### Share on other sites

isn't that what I did in the pastebin?

No, it's not. What you did was declare the member variables as global variables and have the global functions manipulate them, treating them like static members of a class. That won't work because in LazyFoo's original code, the member variables are not static at all - each instance of the class has its own member variables, and there are two instances of Timer in main().

##### Share on other sites

Well i'm lost here. It was alot easier making a fps limiter and deltatimer in Allegro than it is in SDL. I know in the long run it'll come out good, but i'm really lost on this.

Edited by DrNicholas

##### Share on other sites

Basically, wrap the C++ class members (startTicks, etc...) into a struct, and have each function take a pointer to such a struct and operate on it (akin to the "this" parameter in C++). This is the simplest example of an "object" in C.

##### Share on other sites

I see. Perhaps I haven't conveyed everything correctly. I apologize if I haven't. Take a look at these:

timer.h: http://pastebin.com/9tqwGasJ
timer.c: http://pastebin.com/3mW61LEf
main.c: http://pastebin.com/hwmrbEax

these work nice, just like lazyfoo's system. The system's themselves aren't bad, I can get a good delta time, and I see the game running at the same speed on an old Dell Dimension 4550 or a newer custom FX-8350 machine with the dt I use. The problem I am having is locking the game to a framerate. Say it runs at 300fps on one pc and 100fps on the other, even though your monitors refresh rate may not be that high. Say I want to record footage from it using fraps, if the framerate was locked at 60, wouldn't it show me 60 in the corner (before it's recording, i think it changes if you are recording at a different frame rate)? Do you know what I mean?

##### Share on other sites
You need to look into fixed-time updated and separating rendering and game logic.

Fixed-Time-Step Implementation

L. Spiro

##### Share on other sites

I had those in my favorites already. I've used those before, but that doesn't still solve the issue of limiting the games framerate. Fraps tells me the timestep game runs at about 3000fps. I am trying to make it so I can have a capped and uncapped framerate, do you know what I mean? It works perfectly fine in Allegro, but not SDL (I am not talking about delta time, that works fine in both cases). Any time I limit the framerate in SDL with SDL_Delay(), everything seems to "tick" as it moves, even if it is moving with a delta time.

##### Share on other sites

But what is the point in that?
Who cares if it runs at 300/3000/100/60 FPS? It’s not correct for you to limit that.
If users want to cap the frame-rate they can force v-sync.

Say it runs at 300fps on one pc and 100fps on the other, even though your monitors refresh rate may not be that high.

So? Then it runs faster than the refresh rate, 300 on 1 and 100 on another.
What is the problem? Why are you trying to fix break this?

L. Spiro

##### Share on other sites

That was a hypothetical scenario. I just want to cap the game's framerate without having this "tick" issue SDL is giving me (Allegro or SFML did not give said issue). You know how console games tend to be capped at anywhere from 30 to 60fps? That's what I want to do. Half-Life 2 is normally uncapped at 300fps when I boot it up, but I can cap it at 30, 60, or any other fps I desire. That's what I want to do.

##### Share on other sites

Game consoles are “capped” because they have v-sync enabled and you can’t disable it.

Again, if the user wants a cap on his or her PC, he or she can enable v-sync.

L. Spiro

Edited by L. Spiro

##### Share on other sites

That was a hypothetical scenario. I just want to cap the game's framerate without having this "tick" issue SDL is giving me (Allegro or SFML did not give said issue). You know how console games tend to be capped at anywhere from 30 to 60fps? That's what I want to do. Half-Life 2 is normally uncapped at 300fps when I boot it up, but I can cap it at 30, 60, or any other fps I desire. That's what I want to do.

You seem to be confusing the concepts of frame rate and game speed (see the article I linked to below).

Ticks in SDL are a solution rather than an issue. As for SFML, did you use sf::RenderWindow::setFramerateLimit() or sf::RenderWindow::setVerticalSyncEnabled()? The first calls sf::sleep(), the latter does what @L. Spiro mentioned. Either way, you need to understand what's going on under the hood.

Consider reading deWiTTERS Game Loop, a well-known article about this topic; in particular, I think the Constant Game Speed with Maximum FPS section could help.

##### Share on other sites

I am really confused now. I'm not sure every console game has vsynch enabled, maybe a buffer, but i'm not sure. You and I may have a different definition of framerate, look at this:

[attachment=22477:timestep_fps.PNG]

fraps shows me the framerate the game is supposedly outputting. Take a look at this:

[attachment=22478:ocarina_fps.jpg]

Ocarina of Time was capped by Nintendo to operate at 20fps. I'm pretty certain not every game on the Nintendo 64 is 20fps. Here's a picture of Half-Life 2 uncapped:

[attachment=22479:hl2_uncapped.jpg]

I can cap it's framerate to 30 if I want, and I can visually tell it's not as smooth as if it were capped at 60fps (or uncapped in general):

[attachment=22480:hl2_capped.jpg]

and it's not vsynched

[attachment=22481:hl2_novsynch.jpg]

So I am really confused all by what you are telling me. Maybe i'm not saying the right words. How is that measurement capped? If I make a game, i'll make a setting so it's capped at 30, 60, or uncapped.

georger.araujo, I saw you replied while I was typing this. I will take a look after I post this.

##### Share on other sites

I'm not sure every console game has vsynch enabled

Every console and mobile device has v-sync forced enabled.
All frame-rate capping is done by syncing to v-blank.

Frame-rate (FPS): Number of times the game is drawn per second. The yellow number in your images.

The question still remains as to why you want to do it on PC (you don’t have a choice on consoles or mobile devices, just a few options as to which cap you can use).

Do you think it is just cool?

Do you think it makes your product “pro”?

When a game company puts a cap on the frame-rate there is a reason.

For example, we developed a bunch of games for Xbox 360 and PlayStation 3.  We aimed at 60 FPS (the max you can do) but in some games in some areas we had to reduce to 30 FPS (every 2nd v-blank).  For Infinite Undiscovery and Radiata Stories there was too much to draw within a single v-blank so again the whole games had to use 2 v-blanks (30 FPS).

If Nintendo made a game run at 20 FPS it is because they needed more time to render, not because, “Oh, FPS caps are the cool new thing.”

Half-Life 2 is doing the same thing.  Their reason (something you lack) is because their games were fairly heavy on the CPU (and GPU) back then and would consume a lot of power.  Forcing the FPS down reduces power consumption and heat generation, but that won’t apply to your games.  You are not a huge team of experienced veterans making a multi-million-dollar AAA title.

And even if you did have a reason to use a cap, it is implemented via v-blank.  It is always implemented in relation to v-blanks to prevent tearing.

If your SDL does not give you v-blank access, give up and move on to the next task.  Any other way of doing it will lead to the same problems you had before (after some time there is a 1-frame jitter), and you don’t even have an actual reason to do it in the first place.  Your time is better spent anywhere else on your project.

L. Spiro

Edited by L. Spiro

##### Share on other sites

>Do you think it is just cool?

>Do you think it makes your product “pro”?

No, I just want to learn how to do it

anywhere else is done for now, this is where I am at

##### Share on other sites

Is it me or is L.Spiro assuming that framerate limiting is only done for hardware limitations and not to simplify gameplay logic? (it's much easier to do things like physics if you know the interval between frames is always the same)

##### Share on other sites

I think so. All I just wanna do is learn how it's done so then I know what to do if it ever comes up or someone in the future brings it up (or looks it up) they can see the solution too. Now while I was eating I got an idea, but not sure how to implement it. But what I was thinking is that just the screen itself is rendered at the desired framerate. Not sure how I could implement that though, but if someone has an idea it would be like:

if( something that allows the screen to be refreshed so many frames per second ) {
SDL_Flip( screen );
}


Any ideas?

##### Share on other sites

I think so. All I just wanna do is learn how it's done so then I know what to do if it ever comes up or someone in the future brings it up (or looks it up) they can see the solution too. Now while I was eating I got an idea, but not sure how to implement it. But what I was thinking is that just the screen itself is rendered at the desired framerate. Not sure how I could implement that though, but if someone has an idea it would be like:

if( something that allows the screen to be refreshed so many frames per second ) {
SDL_Flip( screen );
}


Any ideas?

It doesn't really look like you want to learn at all. You were pointed to 3 good resources (here's the fourth), but apparently did not read any of them. If you're looking for the "fast track", sorry, there isn't one. You really have to read all this stuff, understand it, write code, make mistakes, learn from (and fix) them, and finish with a sense of accomplishment.

But still, let's try and follow the "code monkey" path (hint: you'd rather go for the "software developer" path). The article I linked to in my other reply has what you want. To make a long story short, just call display_game(); after update_game(); inside the while loop instead of after it. That way you'll draw to the screen TICKS_PER_SECOND times every second.

##### Share on other sites

I study by reading code that's already out there. And this is a public forum, so anybody else is free to come find this information. At the moment I am not doing this professionally, not even commercially, I just want to learn how to do something and then move on lol. I sorta made something like:

Uint32 last_frame = SDL_GetTicks();
Uint32 last_run_time = 0;
int fps_capped = true
while( !quit ) {
do stuff...
last_run_time = SDL_GetTicks() - last_frame;
if( fps_cap == true ) {
if( last_run_time > 16 ) {
dt = timer_ticks(&timer);
last_frame += last_run_time;
refresh_screen();
}
} else {
dt = timer_ticks(&timer);
refresh_screen();
}
}