💿🐜 Antkeeper source code https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.4 KiB

  1. /*
  2. * Copyright (C) 2021 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper source code.
  5. *
  6. * Antkeeper source code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper source code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper source code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "celestial-mechanics.hpp"
  20. #include "math/angles.hpp"
  21. #include <cmath>
  22. namespace ast
  23. {
  24. double solve_kepler(double ec, double ma, double tolerance, std::size_t iterations)
  25. {
  26. // Approximate eccentric anomaly, E
  27. double e0 = ma + ec * std::sin(ma) * (1.0 + ec * std::cos(ma));
  28. // Iteratively converge E0 and E1
  29. for (std::size_t i = 0; i < iterations; ++i)
  30. {
  31. double e1 = e0 - (e0 - ec * std::sin(e0) - ma) / (1.0 - ec * std::cos(e0));
  32. double error = std::abs(e1 - e0);
  33. e0 = e1;
  34. if (error < tolerance)
  35. break;
  36. }
  37. return e0;
  38. }
  39. double3 orbital_elements_to_ecliptic(const orbital_elements& elements, double ke_tolerance, std::size_t ke_iterations)
  40. {
  41. // Calculate semi-minor axis, b
  42. double b = elements.a * std::sqrt(1.0 - elements.ec * elements.ec);
  43. // Solve Kepler's equation for eccentric anomaly, E
  44. double ea = solve_kepler(elements.ec, elements.ma, ke_tolerance, ke_iterations);
  45. // Calculate radial distance, r; and true anomaly, v
  46. double xv = elements.a * (std::cos(ea) - elements.ec);
  47. double yv = b * std::sin(ea);
  48. double r = std::sqrt(xv * xv + yv * yv);
  49. double v = std::atan2(yv, xv);
  50. // Calculate true longitude, l
  51. double l = elements.w + v;
  52. // Transform vector (r, 0, 0) from local coordinates to ecliptic coordinates
  53. // = Rz(-omega) * Rx(-i) * Rz(-l) * r
  54. double cos_om = std::cos(elements.om);
  55. double sin_om = std::sin(elements.om);
  56. double cos_i = std::cos(elements.i);
  57. double cos_l = std::cos(l);
  58. double sin_l = std::sin(l);
  59. return double3
  60. {
  61. r * (cos_om * cos_l - sin_om * sin_l * cos_i),
  62. r * (sin_om * cos_l + cos_om * sin_l * cos_i),
  63. r * sin_l * std::sin(elements.i)
  64. };
  65. }
  66. } // namespace ast