Too Fast!

I?m creating a simple engine that uses SDL, but I
don?t know how to fix the problem of the things
working too fast. I don?t know how to control
framerate so things aways go in diversified speed and
I don?t want it. How can I adjust the speed of the
engine? I mean, so people (and me) will be able to run
my simple demo?s/test progs at the speed I wanted it
to show at the refresh rate they want. Is that a
simple way of doing it? How can it be incorporated
with a graphic engine? Is it a good idea for an engine
to have something like a “sprite warehouse” where all
the sprites are putted in? Thanks alot! I need to say
this timer thing will need to work with the sound
system too latter.

Do you think I?m the right path for etting anything
done? Sometimes I think it is better to plan
everything before start, than making things work and
slowly improve them.
What do you think about it? The Design of engines? Any
good tip about a book or online material?__________________________________
Do you Yahoo!?
New and Improved Yahoo! Mail - 100MB free storage!
http://promotions.yahoo.com/new_mail

The way, I usually do it (I target slow machines, and then
slow my apps down on the faster machines) is to call SDL_Delay()
at the bottom of my loop.

Say I want 20fps. If, by the end of dealing with events, moving
my monsters, and drawing the screen, I haven’t used up 1000/20 = 50ms,
I wait for the remainder.

I just keep track of ‘what time it is’ at the beginning of the loop
(right after the “do {…” usually), using SDL_GetTicks() (I think?),
and then test-and-pause-if-I-need-to at the end of the loop
(right before the “…} while (!done);” usually) – using SDL_GetTicks()
again, and then calling SDL_Delay() on the remainder, if any…

-bill!On Thu, Aug 05, 2004 at 09:27:25AM -0700, Romulo Gnomo wrote:

I?m creating a simple engine that uses SDL, but I
don?t know how to fix the problem of the things
working too fast. I don?t know how to control
framerate so things aways go in diversified speed and
I don?t want it. How can I adjust the speed of the
engine? I mean, so people (and me) will be able to run
my simple demo?s/test progs at the speed I wanted it
to show at the refresh rate they want. Is that a
simple way of doing it? How can it be incorporated
with a graphic engine?

Although usually you want to write your code in a framerate independant
manner, I have found instances where I have had to lock the frame rate to
certain values in some of my games. The problem with calling Sleep and
SDL_Delay (which I think calls Sleep internally), is that the minimum wait
time varies in different platforms which can give you real ugly problems.
I have a better solution that can wait on millisecond accurate times. I
have written a tutorial on how to do this for windows (see link below):http://home.comcast.net/~willperone/Codetips/accuratesleep.html

Not sure how to convert that code to sdl though, anyone else want to try?

  • Will> I?m creating a simple engine that uses SDL, but I

don?t know how to fix the problem of the things
working too fast. I don?t know how to control
framerate so things aways go in diversified speed and
I don?t want it. How can I adjust the speed of the
engine? I mean, so people (and me) will be able to run
my simple demo?s/test progs at the speed I wanted it
to show at the refresh rate they want. Is that a
simple way of doing it? How can it be incorporated
with a graphic engine? Is it a good idea for an engine
to have something like a “sprite warehouse” where all
the sprites are putted in? Thanks alot! I need to say
this timer thing will need to work with the sound
system too latter.

Do you think I?m the right path for etting anything
done? Sometimes I think it is better to plan
everything before start, than making things work and
slowly improve them.
What do you think about it? The Design of engines? Any
good tip about a book or online material?


Do you Yahoo!?
New and Improved Yahoo! Mail - 100MB free storage!
http://promotions.yahoo.com/new_mail


SDL mailing list
SDL at libsdl.org
http://www.libsdl.org/mailman/listinfo/sdl

I?m creating a simple engine that uses SDL, but I
don?t know how to fix the problem of the things
working too fast. I don?t know how to control
framerate so things aways go in diversified speed and
I don?t want it. How can I adjust the speed of the
engine? I mean, so people (and me) will be able to run
my simple demo?s/test progs at the speed I wanted it
to show at the refresh rate they want. Is that a
simple way of doing it?

You can restrict the rendering (and logic) frame rate to some
arbitrary value, but I’d recommend against it for three reasons:

1) It eliminates all chances of utilizing "spare"
   rendering power for smoother animation.

2) The resulting frame rate is likely to interfere
   with the refresh rate of the display, which
   cannot safely or reliably be changed.

3) It doesn't solve the situation where rendering
   is too slow, so your game logic may run too
   slow on slower machines, unless you deal with
   that specifically.

The best and most robust solution is to separate the game logic from
the rendering frame rate. There are some different approaches to
this, including:

* Fixed logic frame rate with timer driven thread. (Game
  logic is handled in a separate thread that is driven at
  a fixed rate - say 100 Hz - by a timer of some sort.)
	+ Simple - at least in theory.
	+ Easy to design exact (repeatable) game logic.
	+ Fixed frame rate ==> simple and robust game logic.
	- Depends totally on OS scheduling accuracy and
	  granularity for smooth animation.
	- Threading issues complicates the code.
	- Threading overhead. (Virtually zero on some
	  platforms, though.)
	- Needs interpolation for smooth animation at all
	  rendering frame rates.
	- Interpolation is hard to get right, since there
	  is no hard synchronization between the logic and
	  rendering threads.

* Fixed logic frame rate with frameskipping and/or
  interpolation. (Game logic runs in the rendering thread,
  but is throttled so that it runs at the correct average
  frame rate.)
	+ Fixed frame rate ==> simple and robust game logic.
	+ Easy to design exact (repeatable) game logic.
	+ No multithreading complexity
	+ Interpolation is easy to implement, since there
	  are no asyncronous buffering issues.
	+ A very high logic frame rate (say 1 kHz) is an
	  easy hack if you want to avoid interpolation.
	- Needs interpolation or very high logic frame rates
	  for smooth animation at all rendering frame rates.

* Time based logic. (Logic frame rate == rendering frame
  rate, but speed, acceleration etc is scaled based on the
  delta times between frames.)
	+ Accurate positions and smooth animation,
	  regardless of frame rate.
	+ No need for interpolation for perfectly smooth
	  (even sub-pixel accurate) rendering.
	- Exact/repeatable game logic is hard to implement.
	- Special measures must be taken to ensure that
	  collision detection works properly at low frame
	  rates.
	- Game logic is complicated by extra math for the
	  time scaling.

(Note: My personal favvourite for 2D action games is the second one;
fixed logic frame rate + interpolation. That’s what I use in Kobo
Deluxe and Fixed Rate Pig, both found on my site.)

How can it be incorporated
with a graphic engine?

That depends on how you deal with the game logic timing. It’s rather
trivial as long as you keep the game logic in the same thread as the
rendering engine. It gets a bit trickier with interpolation (need to
buffer some old coordinates for each object and do the actual
interpolation to get the graphics coordinates for each frame), and
perhaps even worse with a multithreaded approach, due to the sync
issues. (Can’t just share variables. At best, you’ll get occasional
jittering.)

Is it a good idea for an engine
to have something like a “sprite warehouse” where all
the sprites are putted in?

Why not? I have something like that in Kobo Deluxe and Fixed Rate Pig,
and it’s turned out to be rather handy when dealing with groups of
related sprite images, animations and stuff. (Integer indices rather
than pointers, so all you need is start and count.)

Anyway, it depends on the rest of your design. For example, a script
driven engine wouldn’t really need any centralized bank like that, as
you can just manage images on a per-object basis, in whatever way
suits each object. High level languages usually do a good job of
making that easy anyway, so why second guess your scripting engine?

Thanks alot! I need to say
this timer thing will need to work with the sound
system too latter.

Yeah, another tricky detail… The easy way is to just send
asynchronous messages from the game logic to the sound engine
(perhaps using a lock-free FIFO, as I do in Kobo Deluxe) - but that
obviously means that sound timing is quantized to the physical logic
frame rate (same as the rendering frame rate unless you have a
separate logic thread) and/or audio buffer size.

In recent (not officially released) versions of Kobo Deluxe, I’ve
introduced a timestamped interface that keeps a “constant” latency,
rather than the random jittering and quantization effects of previous
versions. Very simple stuff in theory, but things are complicated by
the timing jitter caused by OS scheduling granularity, rendering time
fluctuations and stuff. That’s handled by a slowly decreasing time
offset that’s adjusted slightly whenever the engine realizes the
delay is smaller than the minimal latency.

Do you think I?m the right path for etting anything
done?

The single most important factor is motivation; if you really want
to get something done, you will, one way or another. Anyway, your
thinking makes sense, so chances are good, I think. :slight_smile:

Sometimes I think it is better to plan
everything before start, than making things work and
slowly improve them.
What do you think about it? The Design of engines?

Well, there are different “scools”. Some say you should definitely
design everything before coding anything, whereas others say you
should basically start coding as soon as you know the set of problems
to solve.

Personally, I think the former approach is most suitable for low level
languages (C or asm) and/or environments or situations where
incremental coding and testing is hard. It may also have some
relevance to high level design (APIs and stuff) in large projects
with many developers. As for my own personal and work related
projects, I’ve realized that I’ve drifted more and more towards a way
of working that resembles Extreme Programming a great deal.

Any
good tip about a book or online material?

There are some SDL examples, tutorials and articles around. You can
find some of them on the SDL site, but there’s probably more out
there.

//David Olofson - Programmer, Composer, Open Source Advocate

.- Audiality -----------------------------------------------.
| Free/Open Source audio engine for games and multimedia. |
| MIDI, modular synthesis, real time effects, scripting,… |
`-----------------------------------> http://audiality.org -’
http://olofson.nethttp://www.reologica.se —On Thursday 05 August 2004 18.27, Romulo Gnomo wrote:

In my Game[1], I do lock the game logic and frame rate to a
fixed value. After having problems with different scheduling
granularities, I arrived at the following combination of Sleeping and
busy-waiting…

I planned to find the values of SLEEP_MIN and SLEEP_GRAN at runtime, but
20/10 works good enough for now.

#define SPEED 70 /* Ticks per Frame /
#define SLEEP_MIN 20 /
Minimum time a sleep takes, usually 2*GRAN /
#define SLEEP_GRAN 10 /
Granularity of sleep */

int frames; /* Number of frames displayed /
Uint32 t_start,t_end,t_left;
Uint32 q; /
Dummy */

while(1){
frames++;
t_start=SDL_GetTicks();

// Do a single frame worth of work here....

t_end=t_start+SPEED;
t_left=t_start-SDL_GetTicks+SPEED;

if(t_left>0){
if(t_left>SLEEP_MIN) 
    SDL_Delay(t_left-SLEEP_GRAN); 
while(SDL_GetTicks()<t_end){ q++; }; 
}else{
printf("CPU to slow by %d ticks/round\n",-t_left);
};

};

Perhaps this helps someone :slight_smile:

CU,
Sec

[1] Not yet finished, but playable. See http://brillion.sf.net/On Thu, Aug 05, 2004 at 12:48 -0700, wperone at digipen.edu wrote:

Although usually you want to write your code in a framerate independant
manner, I have found instances where I have had to lock the frame rate to
certain values in some of my games. The problem with calling Sleep and
SDL_Delay (which I think calls Sleep internally), is that the minimum wait
time varies in different platforms which can give you real ugly problems.
I have a better solution that can wait on millisecond accurate times. I
have written a tutorial on how to do this for windows (see link below):
http://home.comcast.net/~willperone/Codetips/accuratesleep.html


All parts should go together without forcing. You must remember that the
parts you are reassembling were disassembled by you. Therefore, if you
can’t get them together again, there must be a reason. By all means, do
not use a hammer. – IBM maintenance manual, 1925

this is a good idea.
how do you get min/gran at runtime?

Stefan Sec Zehl wrote:> On Thu, Aug 05, 2004 at 12:48 -0700, wperone at digipen.edu wrote:

Although usually you want to write your code in a framerate independant
manner, I have found instances where I have had to lock the frame rate to
certain values in some of my games. The problem with calling Sleep and
SDL_Delay (which I think calls Sleep internally), is that the minimum wait
time varies in different platforms which can give you real ugly problems.
I have a better solution that can wait on millisecond accurate times. I
have written a tutorial on how to do this for windows (see link below):
http://home.comcast.net/~willperone/Codetips/accuratesleep.html

In my Game[1], I do lock the game logic and frame rate to a
fixed value. After having problems with different scheduling
granularities, I arrived at the following combination of Sleeping and
busy-waiting…

I planned to find the values of SLEEP_MIN and SLEEP_GRAN at runtime, but
20/10 works good enough for now.

#define SPEED 70 /* Ticks per Frame /
#define SLEEP_MIN 20 /
Minimum time a sleep takes, usually 2*GRAN /
#define SLEEP_GRAN 10 /
Granularity of sleep */

int frames; /* Number of frames displayed /
Uint32 t_start,t_end,t_left;
Uint32 q; /
Dummy */

while(1){
frames++;
t_start=SDL_GetTicks();

// Do a single frame worth of work here....

t_end=t_start+SPEED;
t_left=t_start-SDL_GetTicks+SPEED;

if(t_left>0){

if(t_left>SLEEP_MIN)
SDL_Delay(t_left-SLEEP_GRAN);
while(SDL_GetTicks()<t_end){ q++; };
}else{
printf(“CPU to slow by %d ticks/round\n”,-t_left);
};
};

Perhaps this helps someone :slight_smile:

CU,
Sec

[1] Not yet finished, but playable. See http://brillion.sf.net/

Hi,On Fri, Aug 06, 2004 at 15:06 +0200, Florian Hufsky wrote:

this is a good idea.
how do you get min/gran at runtime?

I was bored yesterday, and wrote code to do that…

/* These depend on you scheduler, I try to figure them out at runtime.
100/50 is my worst-case-estimate
20/10 on my FreeBSD box
1/1 on my WinXP box
*/

Uint32 sleep_min=100; /* Minimum possible sleep time in msec /
Uint32 sleep_gran=50; /
granularity of the sleep time in msec */

#define TEST_TIMES 100 /* Number of tests */

void init_delay(void){
int frames=0;

Uint32 t_start,t_end,ticks;

printf("Sleep_min: ");
ticks=SDL_GetTicks();
while(frames++<TEST_TIMES){
    t_start=SDL_GetTicks();

    SDL_Delay(1);

    t_end=SDL_GetTicks();

    if(t_end-t_start < sleep_min)
        sleep_min=t_end-t_start;

    /*printf("%d,", t_end-t_start);*/
};
printf("Sleep_min=%d\n", sleep_min);
printf(" avg. = %f\n", (float)(t_end-ticks)/TEST_TIMES);

printf("Sleep_gran: ");
frames=0; ticks=SDL_GetTicks();
while(frames++<TEST_TIMES){
    t_start=SDL_GetTicks();

    SDL_Delay(sleep_min+1);

    t_end=SDL_GetTicks();

    if(t_end-t_start-sleep_min < sleep_gran)
        sleep_gran=t_end-t_start-sleep_min;

    /*printf("%d,", t_end-t_start-sleep_min);*/
};
printf("Sleep_gran=%d\n", sleep_gran);
printf(" avg. = %f\n", (float)(t_end-ticks)/TEST_TIMES - sleep_min);

};

Hope that helps…

CU,
Sec

Cooking without animal products is like doing sysadmin work without vi.