How to fade out volume naturally? - math

I have experimented with a sigmoid and logarithmic fade out for volume over a period of about half a second to cushion pause and stop and prevent popping noises in my music applications.
However neither of these sound "natural". And by this I mean, they sound botched. Like an amateur engineer was in charge of the sound decks.
I know the ear is logarithmic when it comes to volumes, or at least, twice as much power does not mean twice as loud. Is there a magic formula for volume fading? Thanks.

I spent many of my younger years mixing music recordings, live concerts and being a DJ for my school's radio station and the one thing I can tell you is that where you fade is also important.
Fading in on an intro or out during the end of a song sounds pretty natural as long as there are no vocals, but some of these computerized radio stations will fade ANYWHERE in a song to make the next commercial break ... I don't think there's a way to make that sound good.
In any case, I'll also answer the question you asked ... the logarithmic attenuation used for adjusting audio levels is generally referred to as "audio taper". Here's an excellent article that describes the physiology of human hearing in relation to the electronics we now use for our entertainment. See: http://tangentsoft.net/audio/atten.html.

You'll want to make sure that the end of the fade out is at a "zero crossing" in the waveform.
Half a second is pretty fast. You might just want to extend the amount of time, unless it must be that fast. Generally 2 or 3 seconds is more natural.
More on timing, it should really be with the beat rate of the music, and end at a natural point in the rhythm. Try getting the BPM of the song (this can be calculated roughly), and fading out over an interval equal to a whole or half note in that timing.
You might also try slowing down the playback speed while you're fading out. This will give a more natural vinyl record or magnetic tape sounding stop/pause. Linearly reduce playback speed while logarithmically reducing volume over the period of 1 second.

If you're just looking to get a clean sound sound when pausing or stopping playback then there's no need to fade at all - just find a zero-crossing point and stop there (or more realistically just fill the rest of that final buffer with silence). Fading out when the user expects the sound to stop immediately will sound unnatural, as you've noticed, because the result is decoupled from the action.
The reason for stopping at a zero-crossing point is that zero is the steady state value while the audio is stopped, so the transition between the two states is seamless. If you stop playback when the last sample's amplitude is large then you are effectively introducing transients into the audio from the point of view of the audio hardware when it reconstructs the analogue signal, which will be audible as pops and/or clicks.
Another approach is to fade to zero very fast (~< 10mS), which effectively achieves the same thing as the zero-crossing technique.

Related

How do I generate a waypoint map in a 2D platformer without expensive jump simulations?

I'm working on a game (using Game Maker: Studio Professional v1.99.355) that needs to have both user-modifiable level geometry and AI pathfinding based on platformer physics. Because of this, I need a way to dynamically figure out which platforms can be reached from which other platforms in order to build a node graph I can feed to A*.
My current approach is, more or less, this:
For each platform consider each other platform in the level.
For each of those platforms, if it is obviously unreachable (due to being higher than the maximum jump height, for example) do not form a link and move on to next platform.
If a link seems possible, place an ai_character instance on the starting platform and (within the current step event) simulate a jump attempt.
3.a Repeat this jump attempt for each possible starting position on the starting platform.
If this attempt is successful, record the data necessary to replicate it in real time and move on to the next platform.
If not, do not form a link.
Repeat for all platforms.
This approach works, more or less, and produces a link structure that when visualised looks like this:
linked platforms (Hyperlink because no rep.)
In this example the mostly-concealed pink ghost in the lower right corner is trying to reach the black and white box. The light blue rectangles are just there to highlight where recognised platforms are, the actual platforms are the rows of grey boxes. Link lines are green at the origin and red at the destination.
The huge, glaring problem with this approach is that for a level of only 17 platforms (as shown above) it takes over a second to generate the node graph. The reason for this is obvious, the yellow text in the screen centre shows us how long it took to build the graph: over 24,000(!) simulated frames, each with attendant collision checks against every block - I literally just run the character's step event in a while loop so everything it would normally do to handle platformer movement in a frame it now does 24,000 times.
This is, clearly, unacceptable. If it scales this badly at a mere 17 platforms then it'll be a joke at the hundreds I need to support. Heck, at this geometric time cost it might take years.
In an effort to speed things up, I've focused on the other important debugging number, the tests counter: 239. If I simply tried every possible combination of starting and destination platforms, I would need to run 17 * 16 = 272 tests. By figuring out various ways to predict whether a jump is impossible I have managed to lower the number of expensive tests run by a whopping 33 (12%!). However the more exceptions and special cases I add to the code the more convinced I am that the actual problem is in the jump simulation code, which brings me at long last to my question:
How would you determine, with complete reliability, whether it is possible for a character to jump from one platform to another, preferably without needing to simulate the whole jump?
My specific platform physics:
Jumps are fixed height, unless you hit a ceiling.
Horizontal movement has no acceleration or inertia.
Horizontal air control is allowed.
Further info:
I found this video, which describes a similar problem but which doesn't provide a good solution. This is literally the only resource I've found.
You could limit the amount of comparisons by only comparing nearby platforms. I would probably only check the horizontal distance between platforms, and if it is wider than the longest jump possible, then don't bother checking for a link between those two. But you might have done this since you checked for the max height of a jump.
I glanced at the video and it gave me an idea. Instead of looking at all platforms to find which jumps are impossible, what if you did the opposite? Try placing an AI character on all platforms and see which other platforms they can reach. That's certainly easier to implement if your enemies can't change direction in midair though. Oh well, brainstorming is the key to finding something.
Several ideas you could try out:
Limit the amount of comparisons you need to make by using a spatial data structure, like a quad tree. This would allow you to severely limit how many platforms you're even trying to check. This is mostly the same as what you're currently doing, but a bit more generic.
Try to pre-compute some jump trajectories ahead of time. This will not catch all use cases that you have - as you allow for full horizontal control - but might allow you to catch some common cases more quickly
Consider some kind of walkability grid instead of a link generation scheme. When geometry is modified, compute which parts of the level are walkable and which are not, with some resolution (something similar to the dimensions of your agent might be good starting point). You could also filter them with a height, so that grid tiles that are higher than your jump height, and you can't drop from a higher place on to them, are marked as unwalkable. Then, when you compute your pathfinding, as part of your pathfinding step you can compute when you start a jump, if a path is actually executable ('start a jump, I can go vertically no more than 5 tiles, and after the peak of the jump, i always fall down vertically with some speed).

Image capturing continuously

I am a final year student making a project in which I take a image from camera placed at car and my objective is through image processing on Matlab. I have to take image of different colour ball until my desired image (which is red) comes and the car stop through micro controller. How can I continuously take a image of ball with millisecond time delay?
The For-A VFC-1000SB High Speed -- only about $12k :-)
However, on the "cheap" end there is the Exilim line (e.g. EX-F1). One of the features is a movie mode up to 1200fps. Note that as the fps goes up the resolution goes down. I know nothing more about this other than the adverting. YMMV.
Now, even if the camera can take frames at this speed, getting it to the host and processed "somewhat timely" is unlikely without additional specialty hardware (and I doubt it is doable at all with the Exilim).

Flex: Would a computational engine for a Connect-4 type game be too slow?

OK, I was just fooling around in my spare time and have made this cool interface and game-playing code for a Connect-4 type game, written in Flex and playable by 2 human players in Flash. It accurately detects wins, etc. I'm smart enough to know that I've done the easy part.
Before I dig into an AI for game play, I wanted to ask if this is the kind of thing that can really be handled computationally by a Flash plugin. It seems to me that for every turn up until the end there are 8 possible moves, 8 responses to each move, etc. So wouldn't a perfect engine have to be able to potentially see 8^8 moves (over 16 million), and a fairly good engine see up to a million? I don't know game coding so this is new to me. What's a reasonable move horizon for such a game to be able to see?
Connect-4 has been solved mathmatically, so your AI could win every time (if it plays first) with the right database of correct moves.
Otherwise, your brute-force 'looking ahead' scenario would not be as easy as you suggest: connect-4 has a 7 wide by 6 high board (yours may be different) - so the longest game could take 42 turns (7 possible moves each time, or fewer towards the end), so a perfect engine might potentially need nearly 7^42 moves (ie more than 3x10^35)... this is obviously a LOT more than 16 million.
It would still be an interesting project, though...

How many game updates per second? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
What update rate should I run my fixed-rate game logic at?
I've used 60 updates per second in the past, but that's hard because it's not an even number of updates per second (16.666666). My current games uses 100, but that seems like overkill for most things.
None of the above. For the smoothest gameplay possible, your game should be time-based, not frame-locked. Frame-locking works for simple games where you can tweak the logic and lock down the framerate. It doesn't do so well with modern 3D titles where the framerate jumps all over the board and the screen may not be VSynced.
All you need to do is figure out how fast an object should be going (i.e. virtual units per second), compute the amount of time since the last frame, scale the number of virtual units to match the amount of time that has passed, then add those values to your object's position. Voila! Time-based movement.
I used to maintain a Quake3 mod and this was a constant source of user-questions.
Q3 uses 20 'ticks per second' by default - the graphics subsystem interpolates so you get smooth motion on the screen. I initially thought this was way low, but it turns out to be fine, and there really aren't many games at all with faster action than q3
I'd personally go with the "good enough for john carmack, good enough for me"
I like 50 for fixed rate pc games. I can't really tell the difference between 50 and 60 (and if you are making a game that can/cares you should probably be at 100).
you'll notice the question is 'fixed-rate game logic' and not 'draw loop'. For clarity, the code will look something like:
while(1)
{
while(CurrentTime() < lastUpdate + TICK_LENGTH)
{
UpdateGame();
lastUpdate += TICK_LENGTH;
}
Draw();
}
The question is what should TICK_LENGTH be?
Bear in mind that unless your code is measured down to the cycle, not each game loop will take the same number of milliseconds to complete - so 16.6666 being irrational is not an issue really as you will need to time and compensate anyway. Besides it's not 16.6666 updates per second, but the average number of milliseconds your game loop should be targeting.
Such variables are generally best found via the guess and check strategy.
Implement your game logic in such a way that is refresh agnostic (Say for instance, exposing the ms/update as a variable, and using it in any calculations), then play around with the refresh until it works, and then keep it there.
As a short term solution, if you want an even update rate but don't care about the evenness of the updates per second, 15ms is close to 60 updates/sec. While if you are about both, your closest options is 20ms or 50 updates/sec is probably the closest you are going to get.
In either case, I would simply treat time as a double (Or a long with high-resolution), and provide the rate to your game as a variable, rather then hard coding them.
The ideal is to run at the same refresh-rate as the monitor. That way your visuals and the game updates don't go in and out of phase with each other. The fact that each frame doesn't last an integral number of milliseconds shouldn't matter to you; why is that a problem?
I usually use 30 or 33. It's often enough for the user to feel the flow and rare enough not to hog the CPU too much.
Normally I don't limit the FPS of the game, instead I change all my logic to take the time elapsed from last frame as input.
As far as fixed-rate goes, unless you need a high rate for any reason, you should use something like 25/30. That should be enough rate, and will be making your game a little lighter on CPU usage.
Your engine should both "tick" (update) and draw at 60fps with vertical sync (vsync). This refresh rate is enough to provide:
low input lag for a feeling of responsiveness,
and smooth motion even when the player and scene are moving rapidly.
Both the game physics and the renderer should be able to drop frames if they need to, but optimize your game to run as close to this 60hz standard as possible. Also, some subsystems like AI can tick closer to 10-20fps, and make sure your physics are interpolated on a frame-to-frame time delta, like this: http://gafferongames.com/game-physics/fix-your-timestep/

Fixed vs. variable frame rates in games: what is best, and when?

After working for a while developing games, I've been exposed to both variable frame rates (where you work out how much time has passed since the last tick and update actor movement accordingly) and fixed frame rates (where you work out how much time has passed and choose either to tick a fixed amount of time or sleep until the next window comes).
Which method works best for specific situations? Please consider:
Catering to different system specifications;
Ease of development/maintenance;
Ease of porting;
Final performance.
I lean towards a variable framerate model, but internally some systems are ticked on a fixed timestep. This is quite easy to do by using a time accumulator. Physics is one system which is best run on a fixed timestep, and ticked multiple times per frame if necessary to avoid a loss in stability and keep the simulation smooth.
A bit of code to demonstrate the use of an accumulator:
const float STEP = 60.f / 1000.f;
float accumulator = 0.f;
void Update(float delta)
{
accumulator += delta;
while(accumulator > STEP)
{
Simulate(STEP);
accumulator -= STEP;
}
}
This is not perfect by any means but presents the basic idea - there are many ways to improve on this model. Obviously there are issues to be sorted out when the input framerate is obscenely slow. However, the big advantage is that no matter how fast or slow the delta is, the simulation is moving at a smooth rate in "player time" - which is where any problems will be perceived by the user.
Generally I don't get into the graphics & audio side of things, but I don't think they are affected as much as Physics, input and network code.
It seems that most 3D developers prefer variable FPS: the Quake, Doom and Unreal engines both scale up and down based on system performance.
At the very least you have to compensate for too fast frame rates (unlike 80's games running in the 90's, way too fast)
Your main loop should be parameterized by the timestep anyhow, and as long as it's not too long, a decent integrator like RK4 should handle the physics smoothly Some types of animation (keyframed sprites) could be a pain to parameterize. Network code will need to be smart as well, to avoid players with faster machines from shooting too many bullets for example, but this kind of throttling will need to be done for latency compensation anyhow (the animation parameterization would help hide network lag too)
The timing code will need to be modified for each platform, but it's a small localized change (though some systems make extremely accurate timing difficult, Windows, Mac, Linux seem ok)
Variable frame rates allow for maximum performance. Fixed frame rates allow for consistent performance but will never reach max on all systems (that's seems to be a show stopper for any serious game)
If you are writing a networked 3D game where performance matters I'd have to say, bite the bullet and implement variable frame rates.
If it's a 2D puzzle game you probably can get away with a fixed frame rate, maybe slightly parameterized for super slow computers and next years models.
One option that I, as a user, would like to see more often is dynamically changing the level of detail (in the broad sense, not just the technical sense) when framerates vary outside of a certian envelope. If you are rendering at 5FPS, then turn off bump-mapping. If you are rendering at 90FPS, increase the bells and whistles a bit, and give the user some prettier images to waste their CPU and GPU with.
If done right, the user should get the best experince out of the game without having to go into the settings screen and tweak themselves, and you should have to worry less, as a level designer, about keeping the polygon count the same across difference scenes.
Of course, I say this as a user of games, and not a serious one at that -- I've never attempted to write a nontrivial game.
The main problem I've encountered with variable length frame times is floating point precision, and variable frame times can surprise you in how they bite you.
If, for example, you're adding the frame time * velocity to a position, and frame time gets very small, and position is largish, your objects can slow down or stop moving because all your delta was lost due to precision. You can compensate for this using a separate error accumulator, but it's a pain.
Having fixed (or at least a lower bound on frame length) frame times allows you to control how much FP error you need to take into account.
My experience is fairly limited to somewhat simple games (developed with SDL and C++) but I have found that it is quite easy just to implement a static frame rate. Are you working with 2d or 3d games? I would assume that more complex 3d environments would benefit more from a variable frame rate and that the difficulty would be greater.

Resources