math_helper.hpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #ifndef DEPTHGUIDE_MATH_HELPER_HPP
  2. #define DEPTHGUIDE_MATH_HELPER_HPP
  3. #include <glm/glm.hpp>
  4. #include <glm/gtc/quaternion.hpp>
  5. #include <glm/gtx/transform.hpp>
  6. #include <Eigen/Geometry>
  7. // r in radius
  8. inline glm::mat4 to_transform_mat(glm::vec3 t, glm::vec3 r) {
  9. static constexpr auto unit_x = glm::vec3(1.0f, 0.0f, 0.0f);
  10. static constexpr auto unit_y = glm::vec3(0.0f, 1.0f, 0.0f);
  11. static constexpr auto unit_z = glm::vec3(0.0f, 0.0f, 1.0f);
  12. auto rot = glm::angleAxis(r.x, unit_x)
  13. * glm::angleAxis(r.y, unit_y)
  14. * glm::angleAxis(r.z, unit_z);
  15. auto offset = glm::translate(t);
  16. return offset * glm::mat4_cast(rot);
  17. }
  18. template<typename Scalar, int Mode>
  19. inline glm::mat4 to_mat4(const Eigen::Transform<Scalar, 3, Mode> &m) {
  20. auto ret = glm::mat4();
  21. auto &mat = m.matrix();
  22. for (auto j = 0; j < 4; ++j)
  23. for (auto i = 0; i < 4; ++i) {
  24. ret[j][i] = mat(i, j);
  25. }
  26. return ret;
  27. }
  28. template<typename T>
  29. concept Vec2Type = requires(T t) {
  30. { t.x } -> std::convertible_to<float>;
  31. { t.y } -> std::convertible_to<float>;
  32. };
  33. template<Vec2Type T>
  34. inline auto to_vec2(const T &v) {
  35. return glm::vec2(v.x, v.y);
  36. }
  37. template<typename T>
  38. concept Vec3Type = requires(T t) {
  39. { t.x } -> std::convertible_to<float>;
  40. { t.y } -> std::convertible_to<float>;
  41. { t.z } -> std::convertible_to<float>;
  42. };
  43. template<Vec3Type T>
  44. inline auto to_vec3(const T &v) {
  45. return glm::vec3(v.x, v.y, v.z);
  46. }
  47. inline auto to_homo(const glm::vec3 &v) {
  48. return glm::vec4(v, 1.f);
  49. }
  50. inline auto from_homo(const glm::vec4 &v) {
  51. return glm::vec3(v) / v.w;
  52. }
  53. // transform point
  54. inline glm::vec3 transform_p(const glm::mat4 &mat, const glm::vec3 &point) {
  55. return from_homo(mat * to_homo(point));
  56. }
  57. // transform vector
  58. inline glm::vec3 transform_v(const glm::mat4 &mat, const glm::vec3 &vec) {
  59. return glm::mat3(mat) * vec;
  60. }
  61. #endif //DEPTHGUIDE_MATH_HELPER_HPP