Parker Schuh | 6691f19 | 2017-01-14 17:01:02 -0800 | [diff] [blame^] | 1 | #ifndef AOS_VISION_COMP_GEO_SEGMENT_H_ |
| 2 | #define AOS_VISION_COMP_GEO_SEGMENT_H_ |
| 3 | |
| 4 | #include <cmath> |
| 5 | |
| 6 | #include "aos/vision/math/vector.h" |
| 7 | |
| 8 | namespace aos { |
| 9 | namespace vision { |
| 10 | |
| 11 | template <int Size> |
| 12 | class Segment { |
| 13 | public: |
| 14 | Segment() : A_(), B_() {} |
| 15 | |
| 16 | Segment(Vector<Size> A, Vector<Size> B) : A_(A), B_(B) {} |
| 17 | |
| 18 | Segment(double ax, double ay, double az, double bx, double by, double bz) |
| 19 | : A_(ax, ay, az), B_(bx, by, bz) {} |
| 20 | |
| 21 | ~Segment() {} |
| 22 | |
| 23 | void Set(Vector<Size> a, Vector<Size> b) { |
| 24 | A_ = a; |
| 25 | B_ = b; |
| 26 | } |
| 27 | |
| 28 | Vector<Size> A() const { return A_; } |
| 29 | Vector<Size> B() const { return B_; } |
| 30 | |
| 31 | Vector<Size> AsVector() const { return B_ - A_; } |
| 32 | Vector<Size> AsNormed() const { return AsVector().normed(); } |
| 33 | |
| 34 | Vector<Size> Center() const { return (A_ + B_) * (0.5); } |
| 35 | |
| 36 | // Fast part of length. |
| 37 | double MagSqr() { return (AsVector()).MagSqr(); } |
| 38 | |
| 39 | // Length of the vector. |
| 40 | double Mag() { return std::sqrt(MagSqr()); } |
| 41 | |
| 42 | Segment<Size> Scale(const double &other) { |
| 43 | return Segment<Size>(A_ * (other), B_ * (other)); |
| 44 | } |
| 45 | |
| 46 | // Intersect two lines in a plane. |
| 47 | Vector<2> Intersect(const Segment<2> &other) { |
| 48 | static_assert(Size == 2, "Only works for size == 2"); |
| 49 | double x1 = A_.x(); |
| 50 | double y1 = A_.y(); |
| 51 | double x2 = B_.x(); |
| 52 | double y2 = B_.y(); |
| 53 | |
| 54 | double x3 = other.A().x(); |
| 55 | double y3 = other.A().y(); |
| 56 | double x4 = other.B().x(); |
| 57 | double y4 = other.B().y(); |
| 58 | |
| 59 | // check wikipedia on how to intersect two lines. |
| 60 | double xn = |
| 61 | (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4); |
| 62 | double xd = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); |
| 63 | |
| 64 | double yn = |
| 65 | (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4); |
| 66 | double yd = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); |
| 67 | |
| 68 | return Vector<2>(xn / xd, yn / yd); |
| 69 | } |
| 70 | |
| 71 | private: |
| 72 | // Begining point. |
| 73 | Vector<Size> A_; |
| 74 | |
| 75 | // Ending point. |
| 76 | Vector<Size> B_; |
| 77 | }; |
| 78 | |
| 79 | } // namespace vision |
| 80 | } // namespace aos |
| 81 | |
| 82 | #endif // AOS_VISION_COMP_GEO_VECTOR_H_ |