random_dir.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Alec Jacobson <[email protected]>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "random_dir.h"
  9. #include "PI.h"
  10. #include <cmath>
  11. IGL_INLINE Eigen::Vector3d igl::random_dir()
  12. {
  13. double z = (double)rand() / (double)RAND_MAX*2.0 - 1.0;
  14. double t = (double)rand() / (double)RAND_MAX*2.0*PI;
  15. // http://www.altdevblogaday.com/2012/05/03/generating-uniformly-distributed-points-on-sphere/
  16. double r = sqrt(1.0-z*z);
  17. double x = r * cos(t);
  18. double y = r * sin(t);
  19. return Eigen::Vector3d(x,y,z);
  20. }
  21. IGL_INLINE Eigen::MatrixXd igl::random_dir_stratified(const int n)
  22. {
  23. const double m = std::floor(sqrt(double(n)));
  24. Eigen::MatrixXd N(n,3);
  25. int row = 0;
  26. for(int i = 0;i<m;i++)
  27. {
  28. const double x = double(i)*1./m;
  29. for(int j = 0;j<m;j++)
  30. {
  31. const double y = double(j)*1./m;
  32. double z = (x+(1./m)*(double)rand() / (double)RAND_MAX)*2.0 - 1.0;
  33. double t = (y+(1./m)*(double)rand() / (double)RAND_MAX)*2.0*PI;
  34. double r = sqrt(1.0-z*z);
  35. N(row,0) = r * cos(t);
  36. N(row,1) = r * sin(t);
  37. N(row,2) = z;
  38. row++;
  39. }
  40. }
  41. // Finish off with uniform random directions
  42. for(;row<n;row++)
  43. {
  44. N.row(row) = random_dir();
  45. }
  46. return N;
  47. }