shape.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //
  2. // shape.cpp
  3. // math
  4. //
  5. // Created by Sam Jaffe on 7/5/16.
  6. //
  7. #include "game/math/shape.hpp"
  8. #include <vector>
  9. #include "game/math/compare.hpp"
  10. namespace math { namespace dim2 {
  11. float line::length() const { return (second - first).magnitude(); }
  12. float line::slope() const {
  13. return safe_div(second[1] - first[1], second[0] - first[0]);
  14. }
  15. rectangle::operator quad() const {
  16. return {origin, origin + vec2{{size.x(), 0.0}}, origin + size,
  17. origin + vec2{{0.0, size.y()}}};
  18. }
  19. square::operator rectangle() const { return {origin, vec2{{size, size}}}; }
  20. square::operator quad() const {
  21. return {origin, origin + vec2{{size, 0.0}}, origin + vec2{{size, size}},
  22. origin + vec2{{0.0, size}}};
  23. }
  24. }}
  25. namespace math { namespace shapes {
  26. std::vector<dim2::line> segments(dim2::quad const & shape) {
  27. return {{shape.ll, shape.lr},
  28. {shape.lr, shape.ur},
  29. {shape.ur, shape.ul},
  30. {shape.ul, shape.ll}};
  31. }
  32. }}
  33. namespace math { namespace lines {
  34. bool parallel(dim2::line const & lhs, dim2::line const & rhs) {
  35. return lhs.slope() == rhs.slope();
  36. }
  37. inline dim2::point intersection(float b1, float s1, float b2, float s2) {
  38. float const x = safe_div(b1 - b2, s2 - s1);
  39. return {{x, b1 + x * s1}};
  40. }
  41. inline dim2::point intersection(dim2::point const & p1, float s1,
  42. dim2::point const & p2, float s2) {
  43. // Solve for Inf * NaN
  44. float y1 = p1[0] == 0 ? 0 : s1 * p1[0];
  45. float y2 = p2[0] == 0 ? 0 : s2 * p2[0];
  46. return intersection(p1[1] - y1, s1, p2[1] - y2, s2);
  47. }
  48. dim2::point intersection(dim2::line const & lhs, dim2::line const & rhs) {
  49. return intersection(lhs.first, lhs.slope(), rhs.first, rhs.slope());
  50. }
  51. dim2::line orthogonal(dim2::line const & from, dim2::point const & to) {
  52. float const slope = from.slope();
  53. if (slope == 0 || isinf(slope)) { return {to, {{to[0], from.first[1]}}}; }
  54. return {to, intersection(from.first, slope, to, -1 / slope)};
  55. }
  56. }}