Skip to content

Instantly share code, notes, and snippets.

@max-dark
Last active Jan 7, 2020
Embed
What would you like to do?
signed triangle area / rotation direction
#include <iostream>
#include <iomanip>
struct point_t
{
using coord_t = int;
coord_t x;
coord_t y;
};
constexpr auto null_coord = point_t::coord_t{};
auto operator-(const point_t& a, const point_t& b)
{
return point_t{a.x - b.x, a.y - b.y};
}
/*
* B(b.x, b.y)
* /
* (0, 0)--A(a.x, a.y)
*
* |a c|
* | | = a*d - b*c
* |b d|
*
* |a.x a.y|
* a ^ b = | | = a.x * b.y - b.x * a.y
* |b.x b.y|
*/
auto signed_area(const point_t& a, const point_t& b)
{
return a.x * b.y - b.x * a.y;
}
/*
* B(b.x, b.y)
* /
* (c.x, c.y)C--A(a.x, a.y)
*/
auto signed_area(const point_t& a, const point_t& b, const point_t& c)
{
return signed_area(a - c, b - c);
}
/* clockwise:
*
* A --> B
* \ /
* \ /
* C
*/
auto is_cw_rotation(const point_t& a, const point_t& b, const point_t& c)
{
return signed_area(a, b, c) < null_coord;
}
/* counter clockwise:
*
* B <-- A
* \ /
* \ /
* C
*/
auto is_ccw_rotation(const point_t& a, const point_t& b, const point_t& c)
{
return signed_area(a, b, c) > null_coord;
}
int main() {
point_t a = {1, 2};
point_t b = {2, 1};
point_t c = {3, 3};
std::cout << std::setw(5);
std::cout << "- :" << std::setw(5)
<< signed_area(a, b) << std::endl;
std::cout << "+ :" << std::setw(5)
<< signed_area(b, a) << std::endl;
std::cout << "ccw :" << std::setw(5) << std::boolalpha
<< is_ccw_rotation(a, b, c) << std::endl;
std::cout << "ccw :" << std::setw(5) << std::boolalpha
<< is_ccw_rotation(b, a, c) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment