# Fast distance 3d (Andre LaMothes book)

This topic is 5066 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Does anyone have Tricks of the Windows Game Programming Gurus? If so, would you mind posting the code for his FastDistance3D function (its in the chapter with the collision detection I think). I left my copy of the book in my room in the residences at uni but am at home now... Thanks!!

##### Share on other sites
float Fast_Distance_3D(float fx, float fy, float fz){// this function computes the distance from the origin to x,y,zint temp;  // used for swapingint x,y,z; // used for algorithm// make sure values are all positivex = fabs(fx) * 1024;y = fabs(fy) * 1024;z = fabs(fz) * 1024;// sort valuesif (y < x) SWAP(x,y,temp)if (z < y) SWAP(y,z,temp)if (y < x) SWAP(x,y,temp)int dist = (z + 11*(y >> 5) + (x >> 2) );// compute distance with 8% errorreturn((float)(dist >> 10));} // end Fast_Distance_3D

You acctually get how to use it? I'm stuck in 2D world. Matrix and such just mess my brain up

##### Share on other sites
Have you tried doing a normal distance calculation? It seems unlikely that it turned out to be your bottleneck that needs optimization. If you've already profiled and found the actual distance formula to be too slow, I'm really interested in hearing about the kind of application you're working on and what the distance calculation is being used for.

##### Share on other sites
Suggestions:

- Do you really need a lot of distance calculations? If you use space/plane subdivision (octree or a simple matrix) you can avoid a lot of tests.

- Do you really need dist = sqrt(dist2)? You can use a simple dist2 and avoid sqrt

- Your "fast distance calculation" is SLOWER than a simple
dist = sqrt(x*x+y*y+z*z)(too many mult, casting, shifts,...) and less accurate (8% error!!!???).

##### Share on other sites
I wouldn't doubt that that code turns out to be slower than a simple sqrt. The reason is that you have 3 float to int conversions, 3 branches which can't be predicted, and another int to float conversion back. Meanwhile, floating multiplies take 1 clock, so the only slow part of the normal method is the actual sqrt.

Unless you've found that the distance function is the only thing slowing down your application, just use the normal method.

1. 1
Rutin
32
2. 2
3. 3
4. 4
5. 5

• 12
• 9
• 9
• 9
• 14
• ### Forum Statistics

• Total Topics
633314
• Total Posts
3011326
• ### Who's Online (See full list)

There are no registered users currently online

×