shape.cpp 2.1 KB

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