I'm not really sure what the correct term is, but how are time-based programs like games and simulations made? I've just realized that I've only wrote programs that wait for input, then do something, and am amazed that I have no idea how I would write something like pong :)
How would something like a flight simulator be coded? It obviously wouldn't run as fast as the computer could run it. I'm guessing everything is executed on some kind of cycle. But how do you handle it when a computation takes longer than the cycle.
Also, what is the correct term for this? Searching "time-based programming" doesn't really give me helpful results.
Games are split into simulation (decide what appears, disappears or moves) and rendering (show it on the screen, play sounds). Simulation is designed to be time-dependent: you can tell the simulator "50ms have elapsed" and it will compute 50ms worth of simulation. A typical game loop will render (which takes an arbitrary amount of time), then run the simulator for the duration since the last time the simulator was run.
If the code runs fast, then the simulator steps will be short (only a few ms) and the game will render the scene more often.
If the code runs slowly, the simulator steps will have longer steps and there will be proportionally fewer renders.
If the simulator runs slower than the simulation itself (it takes 100ms to compute 50ms worth of simulation) then the game cannot run. But this is an exceedingly rare situation, and games sometimes have emergency systems that drop the quality of the simulation to improve performance when this happens.
Note that time-dependent does not necessarily mean millisecond-level precision. Some systems implement simulations using time-based functions (traveled distance equals speed times elapsed time), while others run fixed-duration simulation steps.
I think the correct term is "Real-time application".
For the first question, I'm with spender's answer.
If you know the elapsed time between two frames, you can calculate (with physics, for example) the new position of the elements based on the previous ones.
There are two approaches to this, each with advantages and disadvantages.
You can either go frame based, whereby a timer signals n new frames every second. You calculate movement simply by counting elapsed frames. In the case that computation exceeds the available time, the game slows down.
...or, keeping the frame concept, but this time you keep an absolute measure of time, when the next frame is signalled, you calculate world movement via the amount of elapsed time. This means that stuff happens in real-time, but in the case of severe CPU starvation, gameplay will become choppy.
There's an old saying that "the clock is an actor". Time-based programs are event-driven programs, but the clock is a constant source of events. At least, that's a fairly common and reasonably easy way of doing things. It falls down if you're doing hard realtime or very high performance things.
This is where you can learn the basics:
http://www.gamedev.net/reference/start_here/
Nearly all of the games are programmed in real time architecture and the computer capabilities(and the coding of course :)) determine the frame rate.
Game programming is a really complex job including object modeling, scripting, math calculations, fast and nice rendering algorithms and some other stuff like pixel shaders.
So i would recommend you to check out available engines in the first place.(just google "free game engine")
Basic logic is to create an infinite loop (while(true){}) and the loop should:
Listen for the callbacks - you get the keyb, mouse and system messages here.
Do the physics due to the time passed till the previous frame and user inputs.
Render the new frame (gdi, derictX or openGL)
Have fun
Basically, there are 2 different approaches that allow you to add animation to a game:
Frame-based Animation: easier to understand and implement but has some serious disadvantages. Think about it this way: imagine your game runs at 60FPS and it takes 2 seconds to draw a ball that goes from one side of the screen to the other. In other words, the game needs 120 frames to move the ball along the screen. If you run this game on a slow computer that's only able to render 30FPS, it means that after 2 seconds the ball will be at the middle of the screen. So the problem of this approach is that rendering (drawing the objects) and simulation (updating the positions of the objects) are done by the same function.
Time-based Animation: a sophisticated approach that separates the simulation code from the rendering code. The amount of FPS the computer can render will not influence the amount of movement (animation) that has to be done in 2 seconds.
Steven Lambert wrote a fantastic article about these techniques, as well as 3rd approach that solves a few problems with Time-based Animation.
Some time ago I wrote a C++/Qt application to demonstrate all these approaches and you can find a video of the prototype running here:
Source code is available on Github.
Searching for time-based movement will give you better results.
Basically, you either have a timer loop or an event triggered on a regular clock, depending on your language. If it's a loop, you check the time and only react every 1/60th of a second or so.
Some sites
http://www.cppgameprogramming.com/
Ruby game programming
PyGame
Flight Simulation is one of the more complex examples of real-time simulations. The understanding of fluid dynamics, control systems, and numerical methods can be overwhelming.
As an introduction to the subject of flight simulation, I recommend Build Your Own Flight Sim in C++. It is out of print, but seems to be available used. This book is from 1996, and is horribly dated. It assumes a DOS environment. However, it provides a good overview of the topics, covers numerical integration, basic flight mechanics and control systems. The code examples are simplistic, reasonably complete, and do not assume the more common toolsets used for graphics today. As with most things, I think it is easier to learn the subject with a more basic reference.
A more advanced text (college senior, first year graduate school) is Principles of Flight Simulation provides excellent coverage of the breadth of topics involved in making a flight simulation. This book would make an excellent reference for anyone seriously interested in flight simulation as an engineering task, or for more realistic game development.
Related
we're attempting to track a streaming video with SiteCatalyst.The issue comes in as this video has obsviously no end and the s.media Module can't know how to set the seconds or milestones segment views.This is resulting in no tracking calls except for the starting one.Could a possible solution be the usage of s.media.monitor custom functions?Here's explained how to use them together with the basic Media module settings.Maybe a timing deployment of "sendRequest()" method could help...?I use this occasion to ask a brief how-to example of media.monitor methods, because I've been just using the basic settings till now, as below:
s.loadModule("Media");
s.Media.autoTrack = false;
s.Media.trackMilestones = "25,50";
s.Media.segmentByMilestones = true;... ...Thanks a lot
Yeah.. i really, really dislike the Media module. Video tracking is getting more and more popular with the clients, so it has become the biggest thorn in my side, because the nature of videos over the internet is a big mess with all kinds of moving parts internally, that make it extremely difficult to get truly accurate tracking beyond basic "start" and "stop". (actually I take that back.. I think mobile/sdk tracking is quickly becoming the thing i shake my angry fist at the most, but that's a different post!)
I think Adobe has made some heroic efforts to automate video tracking and it more or less works okay if you just have a regular (not flash) object or html5 tag embedded on the page but in practice, MOST of the time, sites implement their videos through 3rd party scripts (e.g. jwplayer, vimeo, youtube api) and the Media module automation basically goes down the drain on that count.
I understand that it needs to know how long a video is to know when to autopop the events, but I swear, 99% of the time in practice, the way Media module expects things to pop in certain orders etc.. it just doesn't align with how videos work in the real world. Even if you attempt to do it the "manual" way, more often than not it's still buggy,e.g. autoplay and buffering ALWAYS seem to screw up the open+play sequence that MUST happen in that order.
Basically, the Media module desperately needs to be rewritten to better handle streaming videos, and also just "manually" using it in general. Anyways..
Two things I have done in your situation. Overall, neither one of these options are a perfect 1:1 to normal videos with a duration, but then, streaming videos aren't really the same, so it doesn't really make sense to treat them the same.
Option #1: Use an estimated duration for your streaming video. So you said it yourself: your streaming videos have no end. Well as I mentioned, you can't calculate percent viewed unless you have a duration, pretty basic math. So, estimate a duration.
I have clients that have streaming webinars or whatever and it's true that there's technically no duration according to the player, but in reality they don't really conduct that webinar 24/7 forever. In reality it's for a set amount of time like 30 minutes or an hour or something. So, just specify the duration as that.
Yes, this will require extra custom work on your end to store/associate an estimated duration. And yes, this does have the potential for being misleading (e.g. if a webinar ends early or runs late). This option is generally good for sites that have set windows for the stream to actually be active.
Option #2: Ditch the notion of % viewed, record it as n time consumed. So the overall point of the milestones is to know how much of a video was actually watched, yes? Well, who said it has to be measured by % viewed?
How about instead, you just record n seconds consumed every n seconds. You can do this with an incrementor eVar, and/or counter event. (Part of the normal video tracking actually does include a counter event "Video Time", or a.media.timePlayed).
So basically, you'd basically just pop the events/props/eVars yourself, and ignore milestone/segment reports.
Note: This option only really works if you are using the older style video tracking that has events/props/eVars assigned for it. If you are using the newer style video tracking that does not use events/props/eVars.. well, AA does not currently offer an official way to manually pop that stuff directly. It is surely possible to unofficially do so, but I have not yet reverse engineered the latest Media module to figure out how to do that. So, in this case your only option is #1.
I just started studying Unity scripting and I'm having a hard time to understand why some people prefer coroutines over state machines.
I do understand that the code might be more readable for some programmers, but I can't understand why some people say that using coroutines are preferable for performance.
I'm using C# in Unity, and from what I understand the C# compiler converts the IEnumerator into a state machine.
So maybe I'm missing something here. Is it better for runtime performance to use Coroutines instead of a FSM loop for handling behavior and states? If yes, why?
Using coroutines is faster in some circumstances because you can conveniently schedule Unity to perform operations at certain intervals rather than doing them every frame, thus saving processing time. It's really the scheduling that saves time, not coroutines as such.
Take the example you highlighted (in you comment in the other answer) from the Unity documentation, where it says:
Use Coroutines. The problem with Update calls is that they happen every frame. Quite possibly checking the distance to the player could be performed only every 5 seconds. This would save a lot of processing power.
This is saying that a coroutine that uses WaitForSeconds( 5f ) will be faster then checking the distance every frame. It doesn't mean that doing so would necessarily be faster than having your own Update logic that only checks distance every five seconds.
Having said that, I wouldn't be surprised if the coroutine approach is still faster (though less dramatically so) than Update-based checking-every-five-seconds logic, because you'd still save on checking the current frame's time every frame in your game code. Yes, somewhere in Unity's engine loop this time check is still happening and being used to determine whether to go to the next coroutine step, but it's likely highly optimized and it's happening anyways, so the coroutine isn't adding as much extra time checking logic as the Update-based approach.
By the way, for a nice outline of how Unity is likely implementing coroutines, see this blog post.
You have to be careful about what you're using coroutines for. They are great for long-running operations that you don't want to hang the game.
However you have to be very careful about how often you yield in the coroutine. Every time you yield, it takes some time (multiple frames) for the coroutine to resume. If you yield too much, your coroutine will be processing slower than it needs to be. For example, I was working on a pathfinding system. I was using a coroutine to periodically yield while it was running the pathfinding algorithm. This was causing the pathfinding code to take much longer than it should have. I found it worked much faster to just do it in Update.
Coroutines are nice for doing long-running asynchronous tasks like a web request, or downloading something in the background, etc. I don't know that I would recommend using coroutines for your main game processing loop. (especially for input)
I don't think that there is a universal answer to that. It very much depends on what you are doing in your code. A badly written Coroutine might be slower than a well-written FSM and vice versa. I'd say readability and understandability of your code always wins over potential (and at this state intanglible) performance gains. If you got a specific performance issue tackle it when you encounter it. So I'd suggest you use the approach that is most intuitive to you and your team.
OK,
So we want our robot - roomba (the nice vacuum cleaner) to know it's location in a given room.
That means we have the map of the room and the robot is put somewhere and needs to know in a short time where it is located.
We saw a lot of algorithms - where the most relevant one was MCL (monte carlo algorithm) for localization of robots in space.
We are afraid that it is too big for us and don't know where to start from.
We would like to write the code in MATLAB.
So if anyone have any idea where we can find a code - we would apprecate it a lot.
We are open minded about the algorithm - so if you have a better one or something that might work, that will be great. That goes to the language we are writing it in.
Thanks.
Liron.
Interesting.
I've read a lot about trying to keep track of where the roomba is, but it seems like every system that has used only "internal" feedback from the roomba has ended disastrously. Meaning they try to keep track of the wheel locations etc... The main problem is that you can't take into consideration the wheel slip you get and will drastically change based on surface and other factors.
I would recommend using either a stationary based sensor that the roomba can locate from, on-board diagnostic sensors (such as a camera, wiskers, ultrasonic), or a combination of the two.
STAMP makes a great ultrasonic sensor package called the PING((( that can sense up to 6ft. I've used it up to 15 feet, but it works great in close proximity for mapping.
hope this helps!
I find that most game development requires a main game loop, but I don't know why it's necessary. Couldn't we implement an event listener and respond to every user action? Animations (etc.) could then be played when a event occurs.
What is the purpose of a main game loop?
The argument that you "need a loop because otherwise what calls the event listener" does not hold water. Admittedly on any mainstream OS, you do indeed have such a loop, and event listeners do work that way, but it is entirely possible to make an interrupt driven system that works without any loops of any kind.
But you still would not want to structure a game that way.
The thing that makes a loop the most appealing solution is that your loop becomes what in real-time programming is referred to as a 'cyclic executive'. The idea is that you can make the relative execution rates of the various system activities deterministic with respect to one another. The overall rate of the loop may be controlled by a timer, and that timer may ultimately be an interrupt, but with modern OS's, you will likely see evidence of that interrupt as code that waits for a semaphore (or some other synchronization mechanism) as part of your "main loop".
So why do you want deterministic behavior? Consider the relative rates of processing of your user's inputs and the baddies AIs. If you put everything into a purely event based system, there's no guarantee that the AIs won't get more CPU time than your user, or the other way round, unless you have some control over thread priorities, and even then, you're apt to have difficulty keeping timing consistent.
Put everything in a loop, however, and you guarantee that your AIs time-lines are going to proceed in fixed relationship with respect to your user's time. This is accomplished by making a call out from your loop to give the AIs a timeslice in which to decide what to do, a call out to your user input routines, to poll the input devices to find out how your user wants to behave, and call out to do your rendering.
With such a loop, you have to watch that you are not taking more time processing each pass than actually goes by in real time. If you're trying to cycle your loop at 100Hz, all your loop's processing had better finish up in under 10msec, otherwise your system is going to get jerky. In real-time programming, it's called overrunning your time frame. A good system will let you monitor how close you are to overrunning, and you can then mitigate the processing load however you see fit.
An event listener is also dependent on some invocation loop whether you see it or not. Who else is going to call the listener?
Building an explicit game loop gives you absolute control on what's going on so you won't be dependent on whatever some toolkit/event handling library does in its event loop.
A game loop (highly simplified is as follows)
initialise
do
input
update
render
loop
clean up
This will happen every frame the game is drawn. So for games that run at 60fps the above is performed sixty times every second.
This means the game runs smoothly, the game stays in sync and the updates/draws per cycle happen frequently enough. Animation is simply a trick of the eye, objects move between locations but when played quickly enough they appear to be travelling between these locations.
If you were to only update on user input, the game would only react when the user was providing input. Other game components such as A.I game objects would not react on their own. A loop is therefore the easiest and best way of updating a game.
It's not true that all kind of games require a dedicated main game loop.
Action games need such a loop due to frequent object updates and game input precision.
On the other hand, I implemented a minesweeper game and I used window
messages for the notifications.
It's because current operating systems aren't fully event based. Even though things are often represented as events, you'll still have to create a loop where you wait for the next event and process it indefinitely (as an example the Windows event loop). Unix signals are probably the closest thing you get to events on an OS level, but they're not really efficient enough for things like this.
In practical terms, as other people have indicated, a loop is needed.
However, your idea is theoretically sound. You don't need a loop. You need event-based operations.
At a simple level, you can conceptualize the CPU to have a several timers;
one fires on the rising edge of 60Hz and calls the blitting code.
Another might be ticking at 60kHz and be rendering the latest updates of the objects in the game world to the blitter buffer.
Another might be ticking at 10kHz and be taking input from the user. (pretty high resolution, lol)
Another might be the game 'heartbeat' and ticks at 60MHz; AI and physics might operate at heartbeat time.
Of course these timers can be tuned.
Practically, what would be happening is your would be (somewhat elided) like this:
void int_handler1();
//...
int main()
{
//install interrupt handlers
//configure settings
while(1);
}
The nature of games is that they're typically simulations, and are not just reacting based on external events but on internal processes as well. You could represent these internal processes by recurring events instead of polling, but they're practically equivalent:
schedule(updateEvent, 33ms)
function updateEvent:
for monster in game:
monster.update()
render()
vs:
while 1:
for monster in game:
monster.update()
wait(33ms)
render()
Interestingly, pyglet implements the event-based method instead of the more traditional loop. And while this works well a lot of the time, sometimes it causes performance problems or unpredictable behaviour caused by the clock resolution, vsync, etc. The loop is more predictable and easier to understand (unless you come from an exclusively web programming background, perhaps).
Any program that can just sit there indefinitely and respond to user's input needs some kind of loop. Otherwise it will just reach the end of program and will exit.
The main loop calls the event listener. If you are lucky enough to have an event-driven operating system or window manager, the event loop resides there. Otherwise, you write a main loop to mediate the "impedance mismatch" between an system-call interfaces that is based on I/O, poll, or select, and a traditional event-driven application.
P.S. Since you tagged your question with functional-programming, you might want to check out Functional Reactive Programming, which does a great job connecting high-level abstractions to low-level, event-based implementations.
A game needs to run in real-time, so it works best if it is running on one CPU/core continuously. An event-driven application will typically yield the CPU to another thread when there is no event in the queue. There may be a considerable wait before the CPU switches back to your process. In a game, this would mean brief stalls and jittery animation.
Two reasons -
Even event driven systems usually need a loop of some kind that reads events from a queue of some kind and dispatches them to a handler so you end up with an event loop in windows for example anyway and might was well extend it.
For the purposes of animation you'd need to handle some kind of even for every frame of the animation. You could certainly do this with a timer or some kind of idle event, but you'd probably end up creating those in some kind of loop anyway so it's just easier to use the loop
directly.
I've seen systems that do handle it all using events, they have a frame listener that listens to an event dispatched at the start of each frame. They still have a tiny game loop internally but it does little more than handle windowing system events, and create frame events,
I would like to create a baseball simulation game.
Are these sports management games based on luck? A management game entirely based on luck is not fair, but it cannot be too predictable either. How does the logic behind these games work?
It's all about probability and statistics. You set the chance of something happening based on some attributes you assign, and then the random factor comes in during play to make things less predictable and more fun. Generally you get a load of statistics from some external source, encode them into your game's database, and write a system that compares random numbers to these statistics to generate results that approximate the real-life observations that the stats were based on.
Oversimplified example: say your game has Babe Ruth who hits a home run 8.5% of the time, and some lesser guy who hits one 4% of the time. These are the attributes you test against. So for each pitch you simulate, pick a random number between 0 and 100%. If it's less than or equal to the attribute, the batter scores a home run, if it's greater than the attribute, they don't. After a few pitches you'll start to see Babe Ruth's quality show relative to the other guy as he will tend to hit over twice as many home runs.
In reality you'd have more than 1 attribute for this, depending on the kind of pitching for example. And the other player might get to choose which relief pitchers to use to try and exploit weaknesses in the batter's abilities. So the gameplay comes from the interplay between these various attributes, with you trying to maximise the chance that the attribute tests work in your favour.
PS. Apologies for any mistakes regarding baseball: I'm English so can't be expected to understand these things. ;)
As you have already figured out, the core component of such games is the match simulation engine. As Spence said so, you want that simulation to "look right" rather than to "be right".
I worked on a rugby game simulation some time ago and there's an approach that works quite well. Your match is a finite state machine. Each game phase is a state, has an outcome which translates to a phase transition or changes in game state (score, replacements, ...).
Add in a event/listener system to handle things that are not strictly related to the structure of the game you're simulating and you have a good structure (everytime something happens in your simulation, a foul for instance, fire an event; the listeners can be a comment-generation system or an AI responsible for teams' strategies).
You can start with a rough simulation engine that handles things at a team level using an average of your players' stats and then move on to something more detailed that's simulating things at a player level. I think that kind of iterative approach suits a game simulation very well because you want it to look right, and as soon as an element looks right you can stop iterating on it and work on another part of your system.
Random is of course part of the game because as you said so, you don't want games to be too predictable. A very simple thing to do is to have virtual dice rolls against a player and team statistics when they are performing a particular action (throwing the ball for instance).
Edit: I make the assumption that we're talking about management games like Hattrick, where you're managing a roster and simulating game results rather than 2D/3D graphical simulations.
Usually timing plus a randomness to make the game replayable EDIT To clarify I mean in terms of when the pitch comes at you, if it was exact you could learn to play it perfectly, you would need a small randomness around the exact time that you swing to make the game have some chance). AI has a big part in this if you do things like curve balls, add the ability to steal bases etc.
Getting games "right" isn't a factor of design or maths so much as a feel. You will try something, play it, and see if it was fun. If it isn't try different algorithms or gameplay until you get it right.
A simulation is very much about an imagined world in that you create classes that represent all aspects of an imagined world. You need to model the players, specify the game rules, and game dynamics.
http://cplus.about.com/b/2008/05/31/nathans-zombie-simulator-in-c.htm
Look here for agent based model: http://www.montemagno.com/projects.html
One great thing about creating your own game is that you get to decide how the game logic is going to work. If you want the game to have a high degree of luck you can design that in. If you don't want the game to have a high degree of luck then you can design it out.
It's your game, you get to make up the rules.
Are you talking about a baseball game you play or a game simulator? Baseball games can be arcade-like or fantasy sports like or a blend.
I was at Dynamix when Front Page Sports Baseball was made. It was stats-based, meaning that you could play out games and seasons using the stats of the various players. That meant licensing Major League data. It used stats to influence outcomes.
There was a regular mode and a "fast-sim" mode that could breeze through the games faster.
I think Kylotan has the right strategy. Baseball has stats for everything. Simulate a game to the most detailed level you can manage. Combine player stats to determine a percentage chance for every outcome. Use randomness to decide the outcome.
For instance: The chance of a hit is based on Batting Average, Pitcher's ERA, etc. The opposing team's feilding percent determines the chance an out becomes an error.
Every stat you display to the 'manager' when selecting lineups should have some effect on gameplay - otherwise the manager is making decisions based on misleading information.
you ought to check out franchise ball. there is a browsable demo.
http://promo.franchiseball.com