Add polygon area & inertia computation functions

This commit is contained in:
Nikita Lisitsa 2021-05-07 17:38:06 +03:00
parent b8ac384770
commit 4439218141

View file

@ -0,0 +1,43 @@
#pragma once
#include <psemek/geom/point.hpp>
#include <psemek/geom/vector.hpp>
namespace psemek::cg
{
template <typename Iterator>
auto polygon_area(Iterator begin, Iterator end)
{
using scalar_type = std::remove_cvref_t<decltype((*begin)[0])>;
scalar_type result{};
using point_type = std::remove_cvref_t<decltype(*begin)>;
auto origin = point_type::zero();
for (auto it = begin, prev = std::prev(end); it != end; prev = it++)
{
result += geom::volume(origin, *prev, *it);
}
return result / scalar_type{2};
}
template <typename Iterator, typename Point>
auto polygon_inertia(Iterator begin, Iterator end, Point const & origin)
{
using scalar_type = std::remove_cvref_t<decltype((*begin)[0])>;
scalar_type result{};
for (auto it = begin, prev = std::prev(end); it != end; prev = it++)
{
auto const v0 = *prev - origin;
auto const v1 = *it - origin;
result += (v1[1] - v0[1]) * (v0[0] * v0[0] * v0[0] + v0[0] * v0[0] * v1[0] + v0[0] * v1[0] * v1[0] + v1[0] * v1[0] * v1[0]);
result -= (v1[0] - v0[0]) * (v0[1] * v0[1] * v0[1] + v0[1] * v0[1] * v1[1] + v0[1] * v1[1] * v1[1] + v1[1] * v1[1] * v1[1]);
}
return result / scalar_type{12};
}
}