I am creating a physics simulator of sorts and I have thousands of point-like objects (single pixels) moving at the same time. The way I have this setup currently is each point moving only one pixel per frame, which makes it easy to keep track of them in a two dimensional array and check if they're going to collide. However, this solution doesn't permit frame independent movement, which is necessary, because the collision detection is very slow. What is the most efficient way of doing collision detection in this case?
Okay, first things first:
On any modern OS, your app will be either
Sharing processor time with another app, or the OS itself, which is about the same thing
Doing different amounts of work at different times - like, loading assets in the background, rebuilding collision trees, or playing Pac-Man
Fighting the flying toasters
Also, you never know what kind of hardware your app, if distributed, will be running on. This entails lots of headaches, but the first and foremost is that you never know, at compile time, how much real time has elapsed between frames.
(A funny situation recently arose when a customer wanted an orbital calculation to be correct after he had closed his laptop, got on a plane, and reopened it. Easy enough to fix, but you might want to anticipate a 12 hour per frame situation.)
So, how do you deal with this?
Any framework will provide a timer of some sort. I'm not sure how SDL handles this, but typically, on Windows, you'd use GetTickCount() to get the elapsed milliseconds between frames. Each particle has a velocity, expressed in units per second. (Please use meters. Save the world the pain of Units Of user1868866).
When moving the particle,
pos += velocity * elapsed_time;
Or, as a concrete example, if I am in a car moving at 50 mph,
position += 50 miles/hr * 2 hr = 100 miles.
Doing this will solve the problem where particles are moving in frame time instead of simulation/game/real time.
Now, the collision-detection problem. Since we're working in 2D here...
With more than a handful of objects, you can't compare every object to every other object in a reasonable amount of time to see if they collide.
So, we have fancy things like Quadtrees. The idea is to partition your space recursively into quadrants, each of which is really a data structure that somehow "contains" all of the items that fall within its bounds. Then, you only have to check for collision between items within the same quadtree node.
Implementation of a quadtree for your specific applicatino is way, way too long to be appropriate for an SO answer, but I encourage you to research it, try and implement it, and come back here with any issues you have. Another great resource is gamedev.stackexchange.com, which is more game/graphics focused than SO.
Good luck.
Related
do 2d project simulator life. When there are many organisms, the project begins to hang, resulting in a marked decrease in the speed of organisms. What can you recommend? Perhaps the use of shaders to draw or there is something really useful?
It's gonna be difficult to help you without your code but I can still give you a few advices based on my own experience.
Since you're working with many "entities", there is probably some kind of interaction between these entities. If that is the case, a Quadtree (or a simple grid) could help lower the complexity of your algorithm.
But most of the time, SFML applications are slow due to inefficient rendering. There are a few ways to decrease rendering time :
Drawing everything at once (putting all your vertices in one array and draw that once instead of drawing a thousand rectangles one by one)
Drawing simpler objects (ex.: points instead of rectangles)
Drawing less often; You don't have to draw every time you update. Have a clock measuring the time since the last update and draw when the time (1/60th of a second for 60 FPS) is exceeded.
I don't know much about shaders but they seem a bit overkill for the job you wanna do.
I have built an autonomous RC car that is capable of tracking its location and scanning its environment for obstacles. I am stuck however on how to store/create a map of its environment. The environment would not be fixed in size, as the robot explores it may uncover new areas. My background is on navigation, so that part and determining where obstacles are is the easy part (for me). The hard part is how to store/access the data.
Originally I was going to use a 2D array/matrix with a resolution of 2-5 cm, i.e each cell is 2-5cm wide when projected onto the ground. This however could eat up a lot of memory (it is embedded so I have limited resources, 512mb of RAM right now but may decrease when prototype is finished). As well, I will eventually be moving the system to a quadcopter so I will be working in 3D.
The next solution was to create an obstacle object, which would have a position. However I was unsure on how to: 1. keep track of the size and orientation of the object, i.e. how to tell if the object is a wall or just a table leg (cant avoid a wall, can go around a leg) and 2. how to efficiently search/tell if an obstacle is in the robots way.
I am using c++, and the integration of a camera and ultrasonic sensor to detect the environment. As mentioned, stuck on how to store the environment efficiently. I would like to keep the environment information, whether save to a file or send to a server so I can later use/access the map. Would anyone have any suggestions on what to try, or where to even begin looking, this area is all new to me?
You can use a R-Tree where your initial place is the root of the tree. Each time you can go somewhere, you can add the place you went in your tree.
You could also fusion some neighbour parts together if possible.
From a memory point of view, you are not bounded by your array/matrix limits and you store only valuable data. It is up to you to choose what to store : obstacles or free space.
Searching in that kind of structure is also efficient.
As for implementations, you could take a look a the r-tree in the boost library.
Later on, you could even create a graph based on your tree to be used by path-finding algorithms if you expect your robot to go from one point to another.
I'm learning basic frame independent movement, but I have a necessary need in the implementation.
Right now, I'm searching for C++ code, but I need a complete example inside a GameLoop that allows an increase in speed. Not a gradual increase, but just the ability to move my sprite faster. I have to translate the C++ code to vb .net since there are not many examples. So let me be clear about this ->
I have a simple GameLoop. In the GameLoop, I have two calls to functions
Update()
Render()
I understand that for the Update() function I should put a deltaTime parameter. So it should be
Update(deltaTime As double)
Since this is how most examples on the web are shown, I just copied the idea but I don't have an actual frame independent setup yet.
How can I set this up and call the Render function.
Please keep in mind, that if it works, that's fine - I cut and paste a different example like that before, but there was no way to increase the speed of the moving sprite. I don't even know where to begin with this?
Please note if you only have C++ code, I will do my best to translate it, so for me it's acceptable.
I wont give you code, cause I'm positive that you will be able to fix this with a proper description, but I will gladly explain how to move your sprite without frame rate dependency.
As you said, you already pass a delta-time in to the function.
The delta time is the time that it took between now and the last time the function was called (a frame).
When you move your sprite, you probably move it by a specific number of pixels, instead of doing this every frame, you should multiply the pixel range with the delta time.
This will make into a quite simple formula:
DetlaTime * TheNumberOfPixelsToMoveInASecond.
If you mul it with 10, then the sprite will move 10 pixels in one second. Mul it with 100, it will move 100 pixels in one second.
That deltaTime idea is to allow your game to run in a way where the perceived speed of the gameplay is constant no matter how fast or slow the machine and environment are that are running the game.
You might notice if you run some poorly coded games designed for old hardware on hardware much newer that the gameplay goes way too fast and becomes unplayable on those fast machines without deliberately slowing things down. There are actual slowdown utilities just to deal with that problem, like Mo'Slow and Cpukiller. This is because these old games were coded in a way where things were being changed by a constant amount every frame instead of a variable amount based on the time that has passed.
So to avoid this problem, you move all your sprites each frame by numbers that are multiples of deltaTime. That'll give you the sense of consistent speed regardless of the speed of the machine/environment.
Now if you want an adjustable game speed on top of that where you want to allow users to deliberately make the game faster, then you introduce a second variable on top of deltaTime that you also multiply by, like gameSpeed. So your sprites should move in Update by a multiple of both deltaTime and gameSpeed.
Im trying to do a screen-flashing application, that flashes the screen according to the music(which will be frequencies, such as healing frequencies, etc...).
I already made the player and know how will I make the screen flash, but I need to make the screen flash super fast according to the music, for example if the music speeds up, the screen-flash will flash faster. I understand that I would achieve this by FFT or DSP(as I only need to know when the frequency raises from some Hz, lets say 20 to change the color, making the screen-flash).
But I've found that I understand NOTHING, even less try to implement it to my application.
Can somebody help me out to learn whichever both of them? My email is sismetic_chaos#hotmail.com. I really need help, I've been stucked for like 3 days not coding or doing anything at all, trying to understand, but I dont.
PS:My application is written in C++ and Qt.
PS:Thanks for taking the time to read this and the willingness to help.
Edit: Thanks to all for the answers, the problem is in no way solved yet, but I appreciate all the answers, I didnt thought I would get so many answers and info. Thanks to you all.
This is a difficult problem, requiring more than an FFT. I'll briefly describe how I implemented beat detection when I was writing software for professional DJ equipment.
First of all, you'll need to cut down the amount of data you're dealing with, since there are only two or three beats per second, but tens of thousands of samples. You'll also need to look at different frequency ranges, since some types of music carry the tempo in the bassline, and others in percussion or other instruments. So pass the signal through several band-pass filters (I chose 8 filters, each covering one octave, from low bass to high treble), and then downsample each band by averaging the power over a few hundred samples.
Every few seconds, you'll have a thousand or so samples in each band. Your next tool is an autocorrelation, to identify repetitive patterns in the music. The peaks of the autocorrelation tell you what the beat is more or less likely to be; but you'll need to make up some heuristics to compare all the frequency bands to find a beat that you can be confident in, and to avoid misleading syncopations. If you can manage that, then you'll have a reasonable guess at the tempo, but no idea of the phase (i.e. exactly when to flash the screen).
Now you can look at the a smoothed version of the audio data for peaks, some of which are likely to correspond to beats. Initially, look for the strongest peak over the course of a few seconds and take that as a downbeat. In conjunction with the tempo you estimated in the first stage, you can predict when the next beat is due, and measure where you actually saw something like a beat, and adjust your estimate to more closely match the data. You can also maintain a confidence level based on how well the predicted beats match the measured peaks; if that drops too low, then restart the beat detection from scratch.
There are a lot of fiddly details to this, and it took me some weeks to get it working nicely. It is a difficult problem.
Or for a simple visualisation effect, you could simply detect peaks and flash the screen for each one; it will probably look good enough.
The output of a FFT will give you the frequency spectrum of an audio sample, but extracting the tempo from the FFT output is probably not the way you want to go.
One thing you can do is to use peak detection to identify the volume "spikes" that typically occur on the "down-beats" of the music. If you can identify the down-beats, then you can use a resource like bpmdatabase.com to find the tempo of the song. The tempo will tell you how fast to flash and the peaks you detected will tell you when to start flashing. Have your app monitor your flashes to make sure that they generally occur at the same time as a peak (if the two start to diverge, then the tempo may have changed mid-song).
That may sound straightforward, but this is actually a very non-trivial thing to implement. You might want to read this SO question for more information. There are some quality links in the answers there.
If I'm completely mis-interpreting what you are trying to do and you need to do FFTs for something different, then you might want to look at using one of the existing FFT libraries to do the heavy lifting for you. Some examples are FFTW and KissFFT.
It sounds like maybe you're trying to get your visualizer to flash the screen in time with the
music somehow. I don't think calculating the FFT is going to help you here. At any
given instant, there will be many simultaneous frequency components, all over the audio spectrum (roughly 20 Hz to 20 kHz). But you're likely to be a lot more interested in the
musical tempo (beats per minute -- more like 5 Hz or below), and that's not going to show
up anywhere in an FFT of the raw audio signal.
You probably need something much simpler -- some sort of real-time peak detection.
Whenever you see a peak greater than some threshold above the average volume,
make your screen flash.
Of course, more complicated visualizations might well take advantage of the FFT,
but not the one you're describing.
My recommendation would be to find a library that does this for you. Unless you have a lot of mathematics to back you up, I think you will be wasting a ton of your time trying to learn FFTs when all you really want out is some sort of 'base hits per minute' number out which you can adjust your graphics to accordingly.
Check out this similar post:
here
It took me about three weeks to understand the mathematics behind FFTs and then another week to write something in Matlab using those concepts. If you are discouraged after three days, don't try and roll your own.
I hope this is helpful advice and not discouraging.
-Brian J. Stinar-
As previous answers have noted, an FFT is probably not the tool you need in order to solve your problem, which requires tempo detection rather than spectral analysis.
For an example of what can be done using FFT - and of how a particular FFT implementation was integrated into a Qt application, take a look at this blog post which describes the spectrum analyzer demo I developed. Code for the demo is shipped with Qt itself, in the demos/spectrum directory.
I am programming a game using Visual C++ 2008 Express and the Ogre3D sdk.
My core gameplay logic is designed to run at 100 times/second. For simplicity, I'll say it's a method called 'gamelogic()'. It is not time-based, which means if I want to "advance" game time by 1 second, I have to call 'gamelogic()' 100 times. 'gamelogic()' is lightweight in comparison to the game's screen rendering.
Ogre has a "listener" logic that informs your code when it's about to draw a frame and when it has finished drawing a frame. If I just call 'gamelogic()' just before the frame rendering, then the gameplay will be greatly affected by screen rendering speed, which could vary from 5fps to 120 fps.
The easy solution that comes to mind is : calculate the time elapsed since last rendered frame and call 'gamelogic()' this many times before the next frame: 100 * timeElapsedInSeconds
However, I pressume that the "right" way to do it is with multithreading; have a separate thread that runs 'gamelogic()' 100 times/sec.
The question is, how do I achieve this and what can be done when there is a conflict between the 2 separate threads : gamelogic changing screen content (3d object coordinates) while Ogre is rendering the screen at the same time .
Many thanks in advance.
If this is your first game application, using multi-threading to achieve your results might be more work than you should really tackle on your first game. Sychronizing a game loop and render loop in different threads is not an easy problem to solve.
As you correctly point out, rendering time can greatly affect the "speed" of your game. I would suggest that you do not make your game logic dependent on a set time slice (i.e. 1/100 of a second). Make it dependent on the current frametime (well, the last frametime since you don't know how long your current frame will take to render).
Typically I would write something like below (what I wrote is greatly simplified):
float Frametime = 1.0f / 30.0f;
while(1) {
game_loop(Frametime); // maniuplate objects, etc.
render_loop(); // render the frame
calculate_new_frametime();
}
Where Frametime is the calculcated frametime that the current frame took. When you process your game loop you are using the frametime from the previous frame (so set the initial value to something reasonable, like 1/30th or 1/15th of a second). Running it on the previous frametime is close enough to get you the results that you need. Run your game loop using that time frame, then render your stuff. You might have to change the logic in your game loop to not assume a fixed time interval, but generally those kinds of fixes are pretty easy.
Asynchoronous game/render loops may be something that you ultimately need, but that is a tough problem to solve. It involves taking snapshops of objects and their relevant data, putting those snapshots into a buffer and then passing the buffer to the rendering engine. That memory buffer will have to be correctly partitioned around critical sections to avoid having the game loop write to it while the render loop is reading from it. You'll have to take care to make sure that you copy all relevant data into the buffer before passing to the render loop. Additionally, you'll have to write logic to stall either the game or render loops while waiting for one or the other to complete.
This complexity is why I suggest writing it in a more serial manner first (unless you have experience, which you might). The reason being is that doing it the "easy" way first will force you to learn about how your code works, how the rendering engine works, what kind of data the rendering engine needs, etc. Multithreading knowledge is defintely required in complex game development these days, but knowing how to do it well requires indepth knowledge of how game systems interact with each other.
There's not a whole lot of benefit to your core game logic running faster than the player can respond. About the only time it's really useful is for physics simulations, where running at a fast, fixed time step can make the sim behave more consistently.
Apart from that, just update your game loop once per frame, and pass in a variable time delta instead of relying on the fixed one. The benefit you'll get from doing multithreading is minimal compared to the cost, especially if this is your first game.
Double buffering your render-able objects is an approach you could explore. Meaning, the rendering component is using 1 buffer which is updated when all game actions have updated the relevant object in the 2nd buffer.
But personally I don't like it, I'd (and have, frequently) employ Mark's approach.