Would you, dear all, suggest me best practices to get constant animation speed not depending on computer's real speed? Frames may be skipped.
There are two types of animation - frame based and time based and the names suggest the obvious.
What you are looking for is time-based where you call the display() function (the function which draws frames) is called continuously. Within the display function you set a global variable or a static variable(depends on language) to store the TIME(preferably in micro or milliseconds) when the previous occurrence to this call was made. We compare the current time and the saved time to find difference in time, dt, and the function must draw based on dt(time elapsed).
Related
I'm not sure if the title is right but...
I want to animate (with html + canvas + javascript) a section of a road with a given density/flow/speed configuration. For that, I need to have a "source" of vehicles in one end, and a "sink" in the other end. Then, a certain parameter would determine how many vehicles per time unit are created, and their (constant) speed. Then, I guess I should have a "clock" loop, to increment the position of the vehicles at a given frame-rate. Preferrably, a user could change some values in a form, and the running animation would update accordingly.
The end result should be a (much more sophisticated, hopefully) variation of this (sorry for the blinking):
Actually this is a very common problem, there are thousands of screen-savers that use this effect, most notably the "star field", which has parameters for star generation and star movement. So, I believe there must be some "design pattern", or more widespread form (maybe even a name) for this algoritm. What would solve my problem would be some example or tutorial on how to achieve this with common control flows (loops, counters, ifs).
Any idea is much appreciated!
I'm not sure of your question, this doesn't seem an algorithm question, more like programming advice. I have a game which needs exactly this (for monsters not cars), this is what I did. It is in a sort of .Net psuedocode but similar stuff exists in other environments.
If you are running an animation by hand, you essentially need a "game-loop".
while (noinput):
timenow = getsystemtime();
timedelta = timenow - timeprevious;
update_object_positions(timedelta);
draw_stuff_to_screen();
timeprevious = timenow;
noinput = check_for_input()
The update_object_positions(timedelta) moves everything along timedelta, which is how long since this loop last executed. It will run flat-out redrawing every timedelta. If you want it to run at a constant speed, say once every 20 mS, you can stick in a thread.sleep(20-timedelta) to pad out the time to 20mS.
Returning to your question. I had a car class that included its speed, lane, type etc as well as the time it appears. I had a finite number of "cars" so these were pre-generated. I held these in a list which I sorted by the time they appeared. Then in the update_object_position(time) routine, I saw if the next car had a start time before the current time, and if so I popped cars off the list until the first (next) car had a start time in the future.
You want (I guess) an infinite number of cars. This requires only a slight variation. Generate the first car for each lane, record its start time. When you call update_object_position(), if you start a car, find the next car for that lane and its time and make that the next car. If you have patterns that you want to repeat, generate the whole pattern in one go into a list, and then generate a new pattern when that list is emptied. This would also work well in terms of letting users specify variable pattern flows.
Finally, have you looked at what happens in real traffic flows as the volume mounts? Random small braking activities cause cars behind to slightly over-react, and as the slight over-reactions accumulate it turns into cars completely stopping a kilometre back up the road. Its quite strange, and so might be a great effect in your wallpaper/screensaver whatever as well as being a proper simulation.
Clarification: I am not trying to calculate friendly times (e.g., "8 seconds ago") by using a timestamp and the current time.
I need to create a timeline of events in my data model, but where these events are only relative to each other. For example, I have events A, B, and C. They happen in order, so it may be that B occurs 20 seconds after A, and that C occurs 20 years after B.
I don't care about the unit of time. For my purpose, there is no time, just relativity.
I intend to model this like a linked list, where each event is a node:
Event
id
name
prev_event
next_event
Is this the most efficient way to model relative events?
All time recorded by computers is relative time, nominally it is relative to an epoch as an offset in milliseconds. Normally this epoch is an offset from 1970/01/01 as is the case with Unix.
If you store normal everyday timestamp values, you already have relative time between events if they are all sequential, you just need to subtract them to get intervals which are what you are calling relative times but they are actually intervals.
You can use whatever resolution you need to use, milliseconds is what most things use, if you are sampling things at sub-millisecond resolution, you would use nanoseconds
I don't think you need to link to previous and next event, why not just use a timestamp and order by the timestamp?
If you can have multiple, simultaneous event timelines, then you would use some kind of identifier to identify the timeline (int, guid, whatever) and key that in witht the timestamp. No id is even necessary unless you need to refer to it by an single number.
Something like this:
Event
TimeLineID (key)
datetime (key)
Name
I want to change the parameters of a block when the model is running and simultaneously see the changes in the output.
For eg.I have a sine block connected to a Scope.and when i start the simulation.I want to change the frequency of the sine wave and see the corresponding frequency changed wave on the scope output.I want to do this as i want to see how my model behaves for different frequencies.
Somebody please help me in this regard....Please comment and let me know..I will be grateful to who answer my question...
Whether you can vary a parameter during runtime depends on whether that parameter is tunable. Tunable parameters are those that can be changed after the simulation has started, however, you must pause the simulation to be able to do so.
Run your model simulation, then hit the pause button and open up the Sine block dialog. If the frequency edit box is not disabled you can change the frequency and resume the simulation.
If edit box is disabled it means that the frequency is not a tunable parameter. In this case, you can create your own Sine block using a MATLAB function call back and the sin function, by feeding the blocking the desired frequency.
In this particular case, you could use a chirp signal.
I'm having trouble creating a solid game engine for my OpenGL application. It's a game which consists of several sprites with a lot of action.
I created objects which are basically all of my sprites. Another object called "gameEngine" loops through a set of calculations every something of a second (a timer), resulting in new game variables. After that, the sprite objects now know their drawing data.
The problem is, that after collecting all of my drawing data, the drawing should take place at exactly the right moment in time, resulting in a steady animation. Depending on the complexity of the current scene, the game calculations take an undetermined amount of time. So, the actual drawing takes place at different moments in time. How would I prevent that from happening?
To clarify, my approach goes something like:
// Every something of a second I call tick
-(void)tick
{
drawingData = gameEngine();
draw(drawingData);
}
There must be a best practice for building game engines like this I'm not aware of?
Game loops come in many varieties but the better ones separate the animation from the drawing or in more classic terminology model and view. Basically you want to construct a model of your game where you can establish the passing of time and update the model (physics framerate) and then independently render a snapshot of the model at consecutive moments in time (rendering framerate).
Here are a couple of articles which give a more detailed explanation of some of the variations on game loops and their pros and cons. There is source code too. I hope it helps.
Fix Your Timestep! and
deWiTTERS Game Loop Article
This really isn't about OpenGL; it's more to do with the operating system or system APIs you're using (i.e. Carbon/Cocoa/Win32). But the really, really simple case is this (pseudocode):
checkTime = currentTime
while not exitCondition
if currentTime - checkTime >= 50 milliseconds
checkTime = checkTime + 50 milliseconds
updateScene
else drawScene
You are drawing as often as you can, but only doing the updates every 50 milliseconds (i.e. 20 times per second). There are obviously a lot of other things to think about, especially in terms of what you do when you fall behind (skipping frames).
The best place to get into OpenGL stuff is Nehe's lessons:
http://nehe.gamedev.net/lesson.asp?index=01
They're getting a little dated, but the sample code at the bottom of each lesson is a great place to start, and it's available in many languages and for many operating systems.
The best solution would be a multi threaded application - one thread calculating the drawing data into a buffer and one rendering the data.
If you are looking for a realy simple solution, just invert the order of calculation and rendering.
void Initialize()
{
DrawingData = GameEngine();
}
void Tick()
{
Draw(DrawingData);
DrawingData = GameEngine();
}
You calculate the first drawing data on application start up and when the timer fires you just draw it. After that you have all the time up to the next timer event to calculate the drawing data again.
But in general it may be a better solution to render at a variable frame rate - you avoid the problems if the machine is to slow for your desired frame rate and you provide high frame rates on fast machines.
void Main()
{
StartTime = Now();
while (!ExitRequested)
{
DrawingData = GameEngine(Now() - StartTime);
Draw(DrawingData);
}
}
You render frames as fast as possible - not with a fixed interval between each frame but instead with the real time the application is running. That means do not advance your objects by 20 milliseconds every frame, just move them to the position the current running time says.
It's somewhat platform dependent, but one basic approach that usually works is to use a high performance timer in your render loop, and use it to help you sleep between frames in order to have a stable, steady framerate.
You can time your frame's rendering, and then sleep by the amount to maintain a stable framerate.
However, if your platform can't keep up with the framerate you want to achieve, you'll need to start looking at ways to optimize your game engine. This only works to slow down things to make them consistent and smooth - not to speed it up.
--- Clarification ----
-(void)tick
{
time = now() // from high perf. timer
drawingData = gameEngine();
newTime = now()
// pause for the time required to make the framerate consistent
Sleep(totalTimeForTickToBeStable - newTime + time)
draw(drawingData);
}
How can you make the display frames per second be independent from the game logic? That is so the game logic runs the same speed no matter how fast the video card can render.
I think the question reveals a bit of misunderstanding of how game engines should be designed. Which is perfectly ok, because they are damn complex things that are difficult to get right ;)
You are under the correct impression that you want what is called Frame Rate Independence. But this does not only refer to Rendering Frames.
A Frame in single threaded game engines is commonly referred to as a Tick. Every Tick you process input, process game logic, and render a frame based off of the results of the processing.
What you want to do is be able to process your game logic at any FPS (Frames Per Second) and have a deterministic result.
This becomes a problem in the following case:
Check input:
- Input is key: 'W' which means we move the player character forward 10 units:
playerPosition += 10;
Now since you are doing this every frame, if you are running at 30 FPS you will move 300 units per second.
But if you are instead running at 10 FPS, you will only move 100 units per second. And thus your game logic is not Frame Rate Independent.
Happily, to solve this problem and make your game play logic Frame Rate Independent is a rather simple task.
First, you need a timer which will count the time each frame takes to render. This number in terms of seconds (so 0.001 seconds to complete a Tick) is then multiplied by what ever it is that you want to be Frame Rate Independent. So in this case:
When holding 'W'
playerPosition += 10 * frameTimeDelta;
(Delta is a fancy word for "Change In Something")
So your player will move some fraction of 10 in a single Tick, and after a full second of Ticks, you will have moved the full 10 units.
However, this will fall down when it comes to properties where the rate of change also changes over time, for example an accelerating vehicle. This can be resolved by using a more advanced integrator, such as "Verlet".
Multithreaded Approach
If you are still interested in an answer to your question (since I didn't answer it but presented an alternative), here it is. Separating Game Logic and Rendering into different threads. It has it's draw backs though. Enough so that the vast majority of Game Engines remain single threaded.
That's not to say there is only ever one thread running in so called single threaded engines. But all significant tasks are usually in one central thread. Some things like Collision Detection may be multithreaded, but generally the Collision phase of a Tick blocks until all the threads have returned, and the engine is back to a single thread of execution.
Multithreading presents a whole, very large class of issues, even some performance ones since everything, even containers, must be thread safe. And Game Engines are very complex programs to begin with, so it is rarely worth the added complication of multithreading them.
Fixed Time Step Approach
Lastly, as another commenter noted, having a Fixed size time step, and controlling how often you "step" the game logic can also be a very effective way of handling this with many benefits.
Linked here for completeness, but the other commenter also links to it:
Fix Your Time Step
Koen Witters has a very detailed article about different game loop setups.
He covers:
FPS dependent on Constant Game Speed
Game Speed dependent on Variable FPS
Constant Game Speed with Maximum FPS
Constant Game Speed independent of Variable FPS
(These are the headings pulled from the article, in order of desirability.)
You could make your game loop look like:
int lastTime = GetCurrentTime();
while(1) {
// how long is it since we last updated?
int currentTime = GetCurrentTime();
int dt = currentTime - lastTime;
lastTime = currentTime;
// now do the game logic
Update(dt);
// and you can render
Draw();
}
Then you just have to write your Update() function to take into account the time differential; e.g., if you've got an object moving at some speed v, then update its position by v * dt every frame.
There was an excellent article on flipcode about this back in the day. I would like to dig it up and present it for you.
http://www.flipcode.com/archives/Main_Loop_with_Fixed_Time_Steps.shtml
It's a nicely thought out loop for running a game:
Single threaded
At a fixed game clock
With graphics as fast as possible using an interpolated clock
Well, at least that's what I think it is. :-) Too bad the discussion that pursued after this posting is harder to find. Perhaps the wayback machine can help there.
time0 = getTickCount();
do
{
time1 = getTickCount();
frameTime = 0;
int numLoops = 0;
while ((time1 - time0) TICK_TIME && numLoops < MAX_LOOPS)
{
GameTickRun();
time0 += TICK_TIME;
frameTime += TICK_TIME;
numLoops++;
// Could this be a good idea? We're not doing it, anyway.
// time1 = getTickCount();
}
IndependentTickRun(frameTime);
// If playing solo and game logic takes way too long, discard pending
time.
if (!bNetworkGame && (time1 - time0) TICK_TIME)
time0 = time1 - TICK_TIME;
if (canRender)
{
// Account for numLoops overflow causing percent 1.
float percentWithinTick = Min(1.f, float(time1 - time0)/TICK_TIME);
GameDrawWithInterpolation(percentWithinTick);
}
}
while (!bGameDone);
Enginuity has a slightly different, but interesting approach: the Task Pool.
Single-threaded solutions with time delays before displaying graphics are fine, but I think the progressive way is to run game logic in one thread, and displaying in other thread.
But you should synchronize threads right way ;) It'll take a long time to implement, so if your game is not too big, single-threaded solution will be fine.
Also, extracting GUI into separate thread seems to be great approach. Have you ever seen "Mission complete" pop-up message while units are moving around in RTS games? That's what I'm talking about :)
This doesn' cover the higher program abstraction stuff, i.e. state machines etc.
It's fine to control movement and acceleration by adjusting those with your frame time lapse.
But how about stuff like triggering a sound 2.55 seconds after this or that, or changing
game level 18.25 secs later, etc.
That can be tied up to an elapsed frame time accumulator (counter), BUT these timings can
get screwed up if your frame rate falls below your state script resolution
i.e if your higher logic needs 0.05 sec granularity and you fall below 20fps.
Determinism can be kept if the game logic is run on a separate "thread"
(at the software level, which I would prefer for this, or OS level) with a fixed time-slice, independent of fps.
The penalty might be that you might waste cpu time in-between frames if not much is happening,
but I think it's probably worth it.
From my experience (not much) Jesse and Adam's answers should put you on the right track.
If you are after further information and insight into how this works, i found that the sample applications for TrueVision 3D were very useful.