unproject.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 "unproject.h"
  9. #include <Eigen/Dense>
  10. #include <Eigen/LU>
  11. template <
  12. typename Derivedwin,
  13. typename Derivedmodel,
  14. typename Derivedproj,
  15. typename Derivedviewport,
  16. typename Derivedscene>
  17. IGL_INLINE void igl::unproject(
  18. const Eigen::PlainObjectBase<Derivedwin>& win,
  19. const Eigen::PlainObjectBase<Derivedmodel>& model,
  20. const Eigen::PlainObjectBase<Derivedproj>& proj,
  21. const Eigen::PlainObjectBase<Derivedviewport>& viewport,
  22. Eigen::PlainObjectBase<Derivedscene> & scene)
  23. {
  24. typedef typename Derivedscene::Scalar Scalar;
  25. Eigen::Matrix<Scalar,4,4> Inverse =
  26. (proj.template cast<Scalar>() * model.template cast<Scalar>()).inverse();
  27. Eigen::Matrix<Scalar,4,1> tmp;
  28. tmp << win, 1;
  29. tmp(0) = (tmp(0) - viewport(0)) / viewport(2);
  30. tmp(1) = (tmp(1) - viewport(1)) / viewport(3);
  31. tmp = tmp.array() * 2.0f - 1.0f;
  32. Eigen::Matrix<Scalar,4,1> obj = Inverse * tmp;
  33. obj /= obj(3);
  34. scene = obj.head(3);
  35. }
  36. template <typename Scalar>
  37. IGL_INLINE Eigen::Matrix<Scalar,3,1> igl::unproject(
  38. const Eigen::Matrix<Scalar,3,1>& win,
  39. const Eigen::Matrix<Scalar,4,4>& model,
  40. const Eigen::Matrix<Scalar,4,4>& proj,
  41. const Eigen::Matrix<Scalar,4,1>& viewport)
  42. {
  43. Eigen::Matrix<Scalar,3,1> scene;
  44. unproject(win,model,proj,viewport,scene);
  45. return scene;
  46. }
  47. #ifdef IGL_STATIC_LIBRARY
  48. template Eigen::Matrix<float, 3, 1, 0, 3, 1> igl::unproject<float>(Eigen::Matrix<float, 3, 1, 0, 3, 1> const&, Eigen::Matrix<float, 4, 4, 0, 4, 4> const&, Eigen::Matrix<float, 4, 4, 0, 4, 4> const&, Eigen::Matrix<float, 4, 1, 0, 4, 1> const&);
  49. template Eigen::Matrix<double, 3, 1, 0, 3, 1> igl::unproject<double>(Eigen::Matrix<double, 3, 1, 0, 3, 1> const&, Eigen::Matrix<double, 4, 4, 0, 4, 4> const&, Eigen::Matrix<double, 4, 4, 0, 4, 4> const&, Eigen::Matrix<double, 4, 1, 0, 4, 1> const&);
  50. #endif