IDRandomUtil.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <cmath>
  2. #include <cstdlib>
  3. #include <ctime>
  4. #include "BulletInverseDynamics/IDConfig.hpp"
  5. #include "BulletInverseDynamics/IDMath.hpp"
  6. #include "IDRandomUtil.hpp"
  7. namespace btInverseDynamics {
  8. // constants for random mass and inertia generation
  9. // these are arbitrary positive values.
  10. static const float mass_min = 0.001;
  11. static const float mass_max = 1.0;
  12. void randomInit() { srand(time(NULL)); }
  13. void randomInit(unsigned seed) { srand(seed); }
  14. int randomInt(int low, int high) { return rand() % (high + 1 - low) + low; }
  15. float randomFloat(float low, float high) {
  16. return low + static_cast<float>(rand()) / RAND_MAX * (high - low);
  17. }
  18. float randomMass() { return randomFloat(mass_min, mass_max); }
  19. vec3 randomInertiaPrincipal() {
  20. vec3 inertia;
  21. do {
  22. inertia(0) = randomFloat(mass_min, mass_max);
  23. inertia(1) = randomFloat(mass_min, mass_max);
  24. inertia(2) = randomFloat(mass_min, mass_max);
  25. } while (inertia(0) + inertia(1) < inertia(2) || inertia(0) + inertia(2) < inertia(1) ||
  26. inertia(1) + inertia(2) < inertia(0));
  27. return inertia;
  28. }
  29. mat33 randomInertiaMatrix() {
  30. // generate random valid inertia matrix by first getting valid components
  31. // along major axes and then rotating by random amount
  32. vec3 principal = randomInertiaPrincipal();
  33. mat33 rot(transformX(randomFloat(-BT_ID_PI, BT_ID_PI)) * transformY(randomFloat(-BT_ID_PI, BT_ID_PI)) *
  34. transformZ(randomFloat(-BT_ID_PI, BT_ID_PI)));
  35. mat33 inertia;
  36. inertia(0, 0) = principal(0);
  37. inertia(0, 1) = 0;
  38. inertia(0, 2) = 0;
  39. inertia(1, 0) = 0;
  40. inertia(1, 1) = principal(1);
  41. inertia(1, 2) = 0;
  42. inertia(2, 0) = 0;
  43. inertia(2, 1) = 0;
  44. inertia(2, 2) = principal(2);
  45. return rot * inertia * rot.transpose();
  46. }
  47. vec3 randomAxis() {
  48. vec3 axis;
  49. idScalar length;
  50. do {
  51. axis(0) = randomFloat(-1.0, 1.0);
  52. axis(1) = randomFloat(-1.0, 1.0);
  53. axis(2) = randomFloat(-1.0, 1.0);
  54. length = std::sqrt(std::pow(axis(0), 2) + std::pow(axis(1), 2) + std::pow(axis(2), 2));
  55. } while (length < 0.01);
  56. return axis / length;
  57. }
  58. }