Uses Graham scan on projected coordinates.
533{
534 if (vertices.size() < 3) {
535 return vertices;
536 }
537
538 glm::vec3 n = glm::normalize(projection_normal);
539 glm::vec3 u;
540
541 if (std::abs(n.z) < 0.9F) {
542 u = glm::normalize(glm::cross(n, glm::vec3(0, 0, 1)));
543 } else {
544 u = glm::normalize(glm::cross(n, glm::vec3(1, 0, 0)));
545 }
546
547 glm::vec3 v = glm::cross(n, u);
548
549 struct Point2D {
550 glm::vec2 pos;
552 };
553
554 std::vector<Point2D>
points;
555 points.reserve(vertices.size());
556
557 for (size_t i = 0; i < vertices.size(); ++i) {
558 glm::vec3
offset = vertices[i];
559 float x = glm::dot(
offset, u);
560 float y = glm::dot(
offset, v);
561 points.push_back({ .pos = glm::vec2(x, y), .index = i });
562 }
563
564 auto pivot_it = std::ranges::min_element(
points,
565 [](
const Point2D&
a,
const Point2D&
b) {
566 if (std::abs(
a.pos.y -
b.pos.y) < 1e-6F) {
567 return a.pos.x < b.pos.x;
568 }
569 return a.pos.y <
b.pos.y;
570 });
571
572 std::swap(
points[0], *pivot_it);
573 Point2D pivot =
points[0];
574
576 [&pivot](
const Point2D&
a,
const Point2D&
b) {
577 glm::vec2 va = a.pos - pivot.pos;
578 glm::vec2 vb = b.pos - pivot.pos;
579
580 float cross = va.x * vb.y - va.y * vb.x;
581 if (std::abs(cross) < 1e-6F) {
582 return glm::length(va) < glm::length(vb);
583 }
584 return cross > 0.0F;
585 });
586
587
588 std::vector<size_t> hull;
591
592 auto ccw = [](
const glm::vec2&
a,
const glm::vec2&
b,
const glm::vec2& c) {
593 return (
b.x -
a.x) * (c.y -
a.y) - (
b.y -
a.y) * (c.x -
a.x) > 0.0F;
594 };
595
596 for (
size_t i = 2; i <
points.size(); ++i) {
597 while (hull.size() >= 2) {
598 size_t top = hull.back();
599 size_t second = hull[hull.size() - 2];
600
601 glm::vec2 p1 =
points[second].pos;
602 glm::vec2 p2 =
points[top].pos;
603 glm::vec2 p3 =
points[i].pos;
604
605 if (ccw(p1, p2, p3)) {
606 break;
607 }
608 hull.pop_back();
609 }
611 }
612
613 std::vector<glm::vec3> result;
614 result.reserve(hull.size() + 1);
615
616 for (size_t idx : hull) {
617 result.push_back(vertices[idx]);
618 }
619
620 result.push_back(vertices[hull[0]]);
621
622 return result;
623}
std::vector< glm::vec2 > * points