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