Friday, 20 February 2009

OPTIMIZATION - Eliminating SQRTs

I have recently been through the code looking at where it can be optimized. The first thing i looked for was square roots in the code.

Square roots are required to find the length of a vector, and crop up a number of times in my code:-
  • one per spring, per frame (to calculate spring forces)
  • one per spring, per constraint pass, per frame (in order to constrain spring)
  • one per particle, per sphere on screen, per frame (to check if the particle collides with a sphere)
I successfully managed to eliminate all these square roots and work with squared lengths instead of actual lengths. I believe the methods i have used are approximations (i use a ratio of the squared_length to the "supposed" length squared). As of yet these methods appear stable and do not seem to have changed the behaviour of the cloth noticably, which is great.

I only have only square root left in the program, which is a D3DX Normalise call on each of the triangle normals, which is actually just used for the lighting in rendering the cloth.

So what's the benefit?

I was quite limited in cloth resolution before - beyond 40 x 40 was enough to bring the best of machines to a crawl.

I am still limited of course, but i can manage approaximatley 3 times the resolution with a similar frame-rate now.

I did a test running a simulation of cloth with resolution 85 x 100, with no collision handling, with my new optimized code and the old un-optimized code. The non-optimized version ran at an average of about 4.8 FPS. The new optimized version ran at about 14.2 FPS. Again thats an increase factor of about 3!

From a realism standpoint, higher FPS means smoother animation and higher resolution allows for smaller wrinkles and folds to occur. Additionally, the optimized version allows more constrain passes to be ran each frame, which gives rise to stiffer cloth - and generally the stiffer the better when it comes to cloth realism.

So by optimizing i potentially have more realistic and better looking cloth.

No comments: