PERRY v1.0.0
P-E-R-R-Y/PERRY helps creating games with a bunch of tools.
Loading...
Searching...
No Matches
geometry.hpp
1#ifndef MATH_HPP_
2 #define MATH_HPP_
3
4 #include <iostream>
5 #include "../system/type.hpp"
6
7using namespace type;
8
16double cross_product(__v2f_t a, __v2f_t b) {
17 //cross product formula
18 return a.x * b.y - a.y * b.x;
19}
20
31bool is_inside_triangle(__v2f_t P, __v2f_t A, __v2f_t B, __v2f_t C) {
32 //To calculate the area of a triangle given three points (x, y), you can use the formula for the area of a triangle formed by three vertices (x1, y1), (x2, y2), and (x3, y3):
33 //Area = 0.5 * |(x1(y2 - y3) + x2(y3 - y1) + x3(y1 - y2))|
34
35 double abc = 0.5 * abs(A.x * (B.y - C.y) + B.x * (C.y - A.y) + C.x * (A.y - B.y));
36
37 double abp = 0.5 * abs(A.x * (B.y - P.y) + B.x * (P.y - A.y) + P.x * (A.y - B.y));
38 double bcp = 0.5 * abs(B.x * (C.y - P.y) + C.x * (P.y - B.y) + P.x * (B.y - C.y));
39 double cap = 0.5 * abs(C.x * (A.y - P.y) + A.x * (P.y - C.y) + P.x * (C.y - A.y));
40
41 //if sum of abp, bcp, cap is equal to abc, then the point is inside the triangle, otherwise it's outside.
42 return abc == abp + bcp + cap;
43}
44
55bool is_convex(__v2f_t A, __v2f_t B, __v2f_t C, bool clockwise = true) {
56 //calculate the vector from B to A and B to C
57 __v2f_t BA = {A.x - B.x, A.y - B.y};
58 __v2f_t BC = {C.x - B.x, C.y - B.y};
59 //calculate the cross product of BA and BC
60 double cross = BA.x * BC.y - BA.y * BC.x;
61
62 // 1. if it's a clockwise direction, then the cross product should be negative to be a convex angle
63 // 2. if it's a counter clockwise direction, then the cross product should be positive to be a convex angle
64 // 180 degree in this case is an exception, it's neither convex nor concave, but we can consider it as concave.
65 if (clockwise) {
66 return cross < 0;
67 } else {
68 return cross > 0;
69 }
70}
71
82bool is_concave(__v2f_t A, __v2f_t B, __v2f_t C, bool clockwise = true) {
83 //if it's not convex, then it's concave
84 //prefere to inverse clockwise rather than inverse the result of is_convex to handle the 180 degree case
85 return is_convex(A, B, C, !clockwise);
86}
87
88#endif /* !MATH_HPP_ */