random_dir.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
  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 <igl/PI.h>
  10. #include <cmath>
  11. IGL_INLINE Eigen::Vector3d igl::random_dir()
  12. {
  13. using namespace Eigen;
  14. using namespace igl;
  15. double z = (double)rand() / (double)RAND_MAX*2.0 - 1.0;
  16. double t = (double)rand() / (double)RAND_MAX*2.0*PI;
  17. // http://www.altdevblogaday.com/2012/05/03/generating-uniformly-distributed-points-on-sphere/
  18. double r = sqrt(1.0-z*z);
  19. double x = r * cos(t);
  20. double y = r * sin(t);
  21. return Vector3d(x,y,z);
  22. }
  23. IGL_INLINE Eigen::MatrixXd igl::random_dir_stratified(const int n)
  24. {
  25. using namespace Eigen;
  26. using namespace igl;
  27. using namespace std;
  28. const double m = floor(sqrt(double(n)));
  29. MatrixXd N(n,3);
  30. int row = 0;
  31. for(int i = 0;i<m;i++)
  32. {
  33. const double x = double(i)*1./m;
  34. for(int j = 0;j<m;j++)
  35. {
  36. const double y = double(j)*1./m;
  37. double z = (x+(1./m)*(double)rand() / (double)RAND_MAX)*2.0 - 1.0;
  38. double t = (y+(1./m)*(double)rand() / (double)RAND_MAX)*2.0*PI;
  39. double r = sqrt(1.0-z*z);
  40. N(row,0) = r * cos(t);
  41. N(row,1) = r * sin(t);
  42. N(row,2) = z;
  43. row++;
  44. }
  45. }
  46. // Finish off with uniform random directions
  47. for(;row<n;row++)
  48. {
  49. N.row(row) = random_dir();
  50. }
  51. return N;
  52. }