Why is this code like this? (Order of function calls in an equation)

Started by
13 comments, last by Servant of the Lord 11 years, 1 month ago
Maybe they are desperately trying to save money and use tools like Coverity. Where the absurd criteria for the price is "lines of code". But then, I pretty much doubt those tools would support their proprietary language.
In terms of code, whenever something looks very repetitive or has a pattern, I feel the strange urge to change the code (depending on how much performance might be an issue). Things like repeating magic numbers or formulas just irk me somehow.

float BounceEase(float position)
{
    //Optimization for end points, which are the most common spots.
    if(position == 0.0f || position == 1.0f)
    {
        return position;
    }
 
    const float bias[] = {.0f, 1.5f/2.75f, 2.25f/2.75f, 2.625f/2.75f};
    const float offset[] = {.0f, .75f, .9375.f, .984375f};
    unsigned range = 3;
    
    if (position < (1.0f / 2.75f))
        range = 0;
   
    else if (position < (2.0f / 2.75f))
        range = 1;
  
    else if (position < (2.5f / 2.75f))
        range = 2;
 
    position -= bias[range];
    return (7.5625f * position * position + offset[range]);
}
f@dzhttp://festini.device-zero.de
Advertisement

Yeah, what's up with all those magic numbers? Shouldn't they be constants or parameters or something?

I heavily use constants and variables in the code I write, but I'm still trying to understand the equation (which I didn't create) so I haven't messed with it too much. I think the '2.75f' and '7.5625f' are supposed to be variables passed in as parameters, and I think the rest are calculated based off of the '2.75f'. That's my goal for today - to figure out how it actually works, and to make it configurable through parameters like other peoples' implementations.

Servant, when you're done with this easing stuff you should write a journal about it and post the code. I think I could use easing functions for something I am working on. (I have a new version of my bezier curve paths code that supports bezier splines and re-parametrizing for arc length and could apply easing functions to the t-parameter for more natural looking behavior, I think)

Sure - as mentioned, I'm just using Robert Penning's algorithms (what pretty much everyone uses), but doing a C++ port that fits better with my coding style and needs.

I'll post the code on my journal in a few days once I'm satisfied I got it all working.

This topic is closed to new replies.

Advertisement