This is not really a bug but I wondered why this is the case.
This (astonishingly clever) code is the really fast 1/sqrt(x) implementation, I've seen it before and was happy to find it in Box2D's source.
However... it's not used. Anywhere.
Is there any reason why b2Vec2::Normalize is manually taking the Length(), inverting it and then multiplying? The whole reason this function was invented was for normalization. It seems a waste.
I can see two possible reasons:
- slight inaccuracies
- the fact that Normalize() returns the length
but these could be worked around. (You can increase the accuracy by duplicating the x = x * (1.5f - xhalf * x * x); line, which iteratively gets closer to the answer. Length can be found separately or by returning the inverse instead.)
I swapped it over and saw no difference in the simulation. Should I leave it that way?
Code:
inline float32 b2InvSqrt(float32 x)
{
union
{
float32 x;
int32 i;
} convert;
convert.x = x;
float32 xhalf = 0.5f * x;
convert.i = 0x5f3759df - (convert.i >> 1);
x = convert.x;
x = x * (1.5f - xhalf * x * x);
return x;
}
{
union
{
float32 x;
int32 i;
} convert;
convert.x = x;
float32 xhalf = 0.5f * x;
convert.i = 0x5f3759df - (convert.i >> 1);
x = convert.x;
x = x * (1.5f - xhalf * x * x);
return x;
}
This (astonishingly clever) code is the really fast 1/sqrt(x) implementation, I've seen it before and was happy to find it in Box2D's source.
However... it's not used. Anywhere.
Is there any reason why b2Vec2::Normalize is manually taking the Length(), inverting it and then multiplying? The whole reason this function was invented was for normalization. It seems a waste.
I can see two possible reasons:
- slight inaccuracies
- the fact that Normalize() returns the length
but these could be worked around. (You can increase the accuracy by duplicating the x = x * (1.5f - xhalf * x * x); line, which iteratively gets closer to the answer. Length can be found separately or by returning the inverse instead.)
I swapped it over and saw no difference in the simulation. Should I leave it that way?