diff --git a/localization/i18n/OrcaSlicer.pot b/localization/i18n/OrcaSlicer.pot index e8ff50e250..960b645c84 100644 --- a/localization/i18n/OrcaSlicer.pot +++ b/localization/i18n/OrcaSlicer.pot @@ -14890,8 +14890,9 @@ msgid "Brim ear detection radius" msgstr "" msgid "" -"The geometry will be decimated before detecting sharp angles. This parameter indicates the minimum length of the deviation for the decimation.\n" -"0 to deactivate." +"The direction change at a corner is measured over a window of this length along the outline.\n" +"The window grows while the outline keeps curving, so a rounded corner counts as one corner once its whole turn is seen.\n" +"0 to measure the angle at every vertex without smoothing." msgstr "" msgid "Brim ears outer only" diff --git a/src/libslic3r/Brim.cpp b/src/libslic3r/Brim.cpp index 1ab8cecbce..db7946b914 100644 --- a/src/libslic3r/Brim.cpp +++ b/src/libslic3r/Brim.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -346,6 +347,172 @@ double configBrimWidthByVolumeGroups(double adhesion, double maxSpeed, const std return brim_width; } +namespace { + +// ORCA: position at arc length a along the closed contour, interpolated inside one segment. +Vec2d point_at_arc(const Points &pts, const std::vector &cum, double perimeter, double a) +{ + const size_t n = pts.size(); + a = std::fmod(a, perimeter); + if (a < 0.) + a += perimeter; + // cum[k] <= a < cum[k + 1]. Segment lengths are positive, duplicates were dropped. + size_t k = size_t(std::upper_bound(cum.begin(), cum.end(), a) - cum.begin()) - 1; + if (k >= n) + k = n - 1; + const double t = (a - cum[k]) / (cum[k + 1] - cum[k]); + return pts[k].cast() * (1. - t) + pts[(k + 1) % n].cast() * t; +} + +} // namespace + +// ORCA: Detect mouse ear positions on one closed contour. Coordinates and ear_detection_length are scaled. +// The turn at a vertex is measured over a window of ear_detection_length of arc length per side, doubled +// while the outline keeps curving, so a corner is accepted once its turn saturates. Outer contours take +// convex corners, inner contours concave ones; candidates on the same corner collapse to the sharpest. +Points make_brim_ear_points(const Polygon &contour, coord_t ear_detection_length, + coordf_t brim_ears_max_angle, bool is_outer_brim) +{ + Points ears; + if (contour.points.size() < 3 || contour.length() <= 0 || brim_ears_max_angle <= 0) + return ears; + + const coordf_t angle_threshold = (180 - brim_ears_max_angle) * PI / 180.0; + const double cos_threshold = cos(std::nextafter(angle_threshold, +INFINITY)); + const double L = double(ear_detection_length); + + // ORCA: drop points closer than 1 um to the previous kept one, so no segment has zero length. + const double min_dist2 = 1000. * 1000.; + Points pts; + std::vector index_map; + pts.reserve(contour.points.size()); + index_map.reserve(contour.points.size()); + for (size_t i = 0; i < contour.points.size(); ++i) { + if (!pts.empty() && (contour.points[i] - pts.back()).cast().squaredNorm() < min_dist2) + continue; + pts.push_back(contour.points[i]); + index_map.push_back(i); + } + const size_t n = pts.size(); + if (n < 3) + return ears; + + // Cumulative arc length of every vertex, used as the position of a candidate along the closed contour. + std::vector cum(n + 1, 0.0); + for (size_t i = 0; i < n; ++i) + cum[i + 1] = cum[i] + (pts[(i + 1) % n] - pts[i]).cast().norm(); + const double perimeter = cum[n]; + if (perimeter <= 0.) + return ears; + + struct Candidate { + size_t idx; + double dot; + double arc; + double scale; + }; + std::vector candidates; + + // ORCA: window ladder L, 2L, 4L..., capped at 16L and at perimeter/8 so a window cannot reach the far side. + std::vector scales; + if (L > 0.) { + const double s_max = std::min(16.0 * L, perimeter / 8.0); + for (double s = L;; s *= 2.) { + scales.push_back(std::min(s, s_max)); + if (s >= s_max) + break; + } + } + + for (size_t i = 0; i < n; ++i) { + const Vec2d pi = pts[i].cast(); + if (L == 0.) { + // ORCA: zero window, measure the turn at the vertex itself. + const Vec2d a = pi - pts[(i + n - 1) % n].cast(); + const Vec2d b = pts[(i + 1) % n].cast() - pi; + if (a.squaredNorm() == 0. || b.squaredNorm() == 0.) + continue; + if (is_outer_brim ? cross2(a, b) <= 0. : cross2(a, b) >= 0.) + continue; + const double dot = a.normalized().dot(b.normalized()); + if (dot < cos_threshold) + candidates.push_back({i, dot, cum[i], 0.}); + continue; + } + for (size_t m = 0; m < scales.size(); ++m) { + const double s = scales[m]; + const double s_next = std::min(2.0 * s, perimeter / 4.0); // lookahead window, kept off the far side + const Vec2d a = pi - point_at_arc(pts, cum, perimeter, cum[i] - s); + const Vec2d b = point_at_arc(pts, cum, perimeter, cum[i] + s) - pi; + if (a.squaredNorm() == 0. || b.squaredNorm() == 0.) + continue; + const Vec2d ua = a.normalized(); + const Vec2d ub = b.normalized(); + const double cross = cross2(ua, ub); + if (is_outer_brim ? cross <= 0. : cross >= 0.) + continue; + const double dot = ua.dot(ub); + if (dot >= cos_threshold) + continue; + const double turn = std::abs(std::atan2(cross, dot)); + if (turn == 0.) + continue; + // ORCA: a corner is saturated once twice the window sees no more turning; a straight leg or an + // arc keeps turning, so the 1.5 ratio rejects it. The last rung of the ladder cannot grow any + // further, so its turn is final: the lookahead from there reaches the neighbouring corner on a + // small part and would otherwise reject every corner on it. + if (m + 1 < scales.size()) { + double next_turn = turn; + const Vec2d a_next = pi - point_at_arc(pts, cum, perimeter, cum[i] - s_next); + const Vec2d b_next = point_at_arc(pts, cum, perimeter, cum[i] + s_next) - pi; + if (a_next.squaredNorm() > 0. && b_next.squaredNorm() > 0.) { + const Vec2d ua_next = a_next.normalized(); + const Vec2d ub_next = b_next.normalized(); + next_turn = std::abs(std::atan2(cross2(ua_next, ub_next), ua_next.dot(ub_next))); + } + if (next_turn > 1.5 * turn) + continue; + } + candidates.push_back({i, dot, cum[i], s}); + break; + } + } + + // ORCA: take the most local candidate first (smallest window, i.e. the corner centre), then the sharpest, + // drop everything on the same corner, repeat. Chaining neighbours would swallow a curved contour. + const double fallback_suppress = double(std::max(1, scale_(0.01))); // 0.01 mm when there is no window + while (!candidates.empty()) { + size_t best = 0; + for (size_t c = 1; c < candidates.size(); ++c) { + const Candidate &cc = candidates[c]; + const Candidate &cb = candidates[best]; + if (cc.scale < cb.scale || + (cc.scale == cb.scale && (cc.dot < cb.dot || + (cc.dot == cb.dot && cc.idx < cb.idx)))) + best = c; + } + const Candidate picked = candidates[best]; + ears.emplace_back(contour.points[index_map[picked.idx]]); + // ORCA: suppress within twice the window that detected the ear, taking the wider of the two windows: a + // candidate whose window already reaches the picked ear measured the same corner, which otherwise leaves + // a duplicate beside a corner that meets a curve. Capped at perimeter/8 so a small part keeps every ear. + std::vector remaining; + remaining.reserve(candidates.size() - 1); + for (size_t c = 0; c < candidates.size(); ++c) { + if (c == best) + continue; + const double ds = std::abs(candidates[c].arc - picked.arc); + const double suppress_distance = + L > 0. ? std::min(2.0 * std::max(picked.scale, candidates[c].scale), perimeter / 8.0) + : fallback_suppress; + if (std::min(ds, perimeter - ds) > suppress_distance) + remaining.push_back(candidates[c]); + } + candidates = std::move(remaining); + } + return ears; +} + // Generate ears // Ported from SuperSlicer: https://github.com/supermerill/SuperSlicer/blob/45d0532845b63cd5cefe7de7dc4ef0e0ed7e030a/src/libslic3r/Brim.cpp#L1116 static ExPolygons make_brim_ears_auto(const ExPolygons& obj_expoly, coord_t size_ear, coord_t ear_detection_length, @@ -355,24 +522,9 @@ static ExPolygons make_brim_ears_auto(const ExPolygons& obj_expoly, coord_t size return mouse_ears_ex; } // Detect places to put ears - const coordf_t angle_threshold = (180 - brim_ears_max_angle) * PI / 180.0; Points pt_ears; - for (const ExPolygon &poly : obj_expoly) { - Polygon decimated_polygon = poly.contour; - if (ear_detection_length > 0) { - // decimate polygon - Points points = poly.contour.points; - points.push_back(points.front()); - points = MultiPoint::_douglas_peucker(points, ear_detection_length); - if (points.size() > 4) { // don't decimate if it's going to be below 4 points, as it's surely enough to fill everything anyway - points.erase(points.end() - 1); - decimated_polygon.points = points; - } - } - - append(pt_ears, is_outer_brim ? decimated_polygon.convex_points(angle_threshold) - : decimated_polygon.concave_points(angle_threshold)); - } + for (const ExPolygon &poly : obj_expoly) + append(pt_ears, make_brim_ear_points(poly.contour, ear_detection_length, brim_ears_max_angle, is_outer_brim)); // Then add ears // create ear pattern diff --git a/src/libslic3r/Brim.hpp b/src/libslic3r/Brim.hpp index 9279b1e023..ad9726a331 100644 --- a/src/libslic3r/Brim.hpp +++ b/src/libslic3r/Brim.hpp @@ -5,6 +5,7 @@ #include "ObjectID.hpp" #include "Point.hpp" #include "Polygon.hpp" +#include "libslic3r.h" #include #include @@ -31,6 +32,13 @@ ExtrusionEntityCollection makeBrimInfillFromPlateCoordinates(const ExPolygons& s // BBS: automatically make brim ExtrusionEntityCollection make_brim_auto(const Print &print, PrintTryCancel try_cancel, Polygons &islands_area); +// ORCA: Detect mouse ear positions on one closed contour. Coordinates and ear_detection_length are scaled. +// The window starts at ear_detection_length and doubles while the outline keeps curving; a corner is accepted +// once its turn saturates. Outer contours take convex corners, inner contours concave ones; candidates on the +// same corner collapse to the sharpest. +Points make_brim_ear_points(const Polygon &contour, coord_t ear_detection_length, + coordf_t brim_ears_max_angle, bool is_outer_brim); + } // Slic3r #endif // slic3r_Brim_hpp_ diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index b5514c4352..ba03678d1b 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -2211,9 +2211,10 @@ void PrintConfigDef::init_fff_params() def = this->add("brim_ears_detection_length", coFloat); def->label = L("Brim ear detection radius"); def->category = L("Support"); - def->tooltip = L("The geometry will be decimated before detecting sharp angles. " - "This parameter indicates the minimum length of the deviation for the decimation.\n" - "0 to deactivate."); + def->tooltip = L("The direction change at a corner is measured over a window of this length along the outline.\n" + "The window grows while the outline keeps curving, so a rounded corner counts as one corner " + "once its whole turn is seen.\n" + "0 to measure the angle at every vertex without smoothing."); def->sidetext = L("mm"); // millimeters, CIS languages need translation def->min = 0; def->mode = comAdvanced; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp b/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp index 34f49dfc53..790fa3af24 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp @@ -20,6 +20,7 @@ #include "slic3r/GUI/Event.hpp" #include "libslic3r/Utils.hpp" #include "libslic3r/Point.hpp" +#include "libslic3r/Brim.hpp" #include "libslic3r/BrimEarsPoint.hpp" #include "libslic3r/Geometry.hpp" #include @@ -958,22 +959,9 @@ void GLGizmoBrimEars::reload_cache() find_single(); } -Points GLGizmoBrimEars::generate_points(Polygon &obj_polygon, float ear_detection_length, float brim_ears_max_angle, bool is_outer) +Points GLGizmoBrimEars::generate_points(const Polygon &obj_polygon, float ear_detection_length, float brim_ears_max_angle, bool is_outer) { - const coordf_t angle_threshold = (180 - brim_ears_max_angle) * PI / 180.0; - Points pt_ears; - if (ear_detection_length > 0) { - double detect_length = ear_detection_length / SCALING_FACTOR; - Points points = obj_polygon.points; - points.push_back(points.front()); - points = MultiPoint::_douglas_peucker(points, detect_length); - if (points.size() > 4) { - points.erase(points.end() - 1); - } - obj_polygon.points = points; - } - append(pt_ears, is_outer ? obj_polygon.convex_points(angle_threshold) : obj_polygon.concave_points(angle_threshold)); - return pt_ears; + return make_brim_ear_points(obj_polygon, scale_(ear_detection_length), brim_ears_max_angle, is_outer); } void GLGizmoBrimEars::first_layer_slicer() @@ -1053,6 +1041,7 @@ void GLGizmoBrimEars::get_detection_radius_max() min_points_num = MultiPoint::_douglas_peucker(out_points, 0).size(); int repeat = 0; int loop_protect = 0; + // ORCA: only a feature-size estimate for the slider's upper bound; the detector no longer decimates. for (;;) { loop_protect++; tolerance += 10; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.hpp b/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.hpp index 35177bfac6..7153b3e93b 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.hpp @@ -159,7 +159,7 @@ private: void select_point(int i); void unselect_point(int i); void reload_cache(); - Points generate_points(Polygon &obj_polygon, float ear_detection_length, float brim_ears_max_angle, bool is_outer); + Points generate_points(const Polygon &obj_polygon, float ear_detection_length, float brim_ears_max_angle, bool is_outer); void auto_generate(); void first_layer_slicer(); void get_detection_radius_max(); diff --git a/tests/fff_print/test_skirt_brim.cpp b/tests/fff_print/test_skirt_brim.cpp index c03daa74d0..e3f091d59a 100644 --- a/tests/fff_print/test_skirt_brim.cpp +++ b/tests/fff_print/test_skirt_brim.cpp @@ -472,6 +472,120 @@ TEST_CASE("Outer-only painted brim ears stay out of model holes", "[SkirtBrim]") CHECK_FALSE(brim_enters_first_layer_hole(print)); } +// A 40 mm wide, 3 mm tall prism whose 70 degree apex is rounded by a 1.5 mm fillet in six chords: the +// outline test_brim.cpp builds, as a mesh the pipeline can slice. +// Same outline as filleted_triangle_outline(1.5, 6) in the libslic3r test_brim.cpp fixture. +static TriangleMesh triangle_with_rounded_apex() +{ + const std::vector outline{ + Vec2d(0., 0.), Vec2d(40., 0.), Vec2d(17.6811, 26.5986), Vec2d(17.3195, 26.9111), + Vec2d(16.8780, 27.0940), Vec2d(16.4013, 27.1287), Vec2d(15.9380, 27.0117), Vec2d(15.5349, 26.7549), + Vec2d(15.2330, 26.3844), + }; + const float height = 3.f; + std::vector vertices; + std::vector faces; + const size_t n = outline.size(); + for (const Vec2d &p : outline) { + vertices.emplace_back(float(p.x()), float(p.y()), 0.f); + vertices.emplace_back(float(p.x()), float(p.y()), height); + } + // Fan from rim vertex 0, so the first triangle is i = 1; starting at 0 would emit a face with a + // repeated vertex on both caps. + for (size_t i = 1; i + 1 < n; ++ i) { + faces.emplace_back(0, int(2 * (i + 1)), int(2 * i)); // bottom cap, facing down + faces.emplace_back(1, int(2 * i + 1), int(2 * (i + 1) + 1)); // top cap, facing up + } + for (size_t i = 0; i < n; ++ i) { + const size_t j = (i + 1) % n; + faces.emplace_back(int(2 * i), int(2 * j), int(2 * j + 1)); + faces.emplace_back(int(2 * i), int(2 * j + 1), int(2 * i + 1)); + } + return TriangleMesh(vertices, faces); +} + +// One entry per ear. The slicer clips each ear disc against the object, so an ear is a half disc, not a +// ring; its axis-aligned bounding box centre still identifies it, and that centre stays valid under the +// turns used below. Coordinates are scaled, hence scaled() tolerances. +static std::vector brim_ear_centres(Print &print) +{ + std::vector centres; + for (const auto &kv : print.get_brimMap()) { + Polylines paths; + kv.second.collect_polylines(paths); + for (const Polyline &path : paths) { + if (path.points.empty()) + continue; + const BoundingBox box = path.bounding_box(); + const Vec2d centre = (box.min.cast() + box.max.cast()) * 0.5; + if (std::none_of(centres.begin(), centres.end(), [¢re](const Vec2d &e) { return (e - centre).norm() < scaled(1.); })) + centres.push_back(centre); + } + } + return centres; +} + +// Sorted distances between every pair of ear centres: independent of where the part ends up on the plate. +static std::vector ear_centre_distances(const std::vector ¢res) +{ + std::vector distances; + for (size_t i = 0; i < centres.size(); ++ i) + for (size_t j = i + 1; j < centres.size(); ++ j) + distances.push_back((centres[i] - centres[j]).norm()); + std::sort(distances.begin(), distances.end()); + return distances; +} + +// A rounded corner must keep its ear whatever the part's orientation: the corner used to be measured after +// a decimation anchored on the contour's start vertex, which moves when the object is rotated. +TEST_CASE("Mouse ears stay on the same corners when the object rotates", "[SkirtBrim]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ + { "skirt_loops", 0 }, + { "brim_type", "brim_ears" }, + { "brim_width", 3 }, + { "brim_ears_max_angle", 125 }, + { "brim_ears_detection_length", 1 }, + { "initial_layer_line_width", 0.5 }, + }); + + // Not auto-arranged, so the part is rotated about its own footprint centre and stays on the bed. + auto slice_rotated = [&config](double rotation) { + Print print; + Model model; + init_print({ triangle_with_rounded_apex() }, print, model, config, nullptr, false); + const Vec3d pivot = model.objects.front()->raw_mesh_bounding_box().center(); + const Transform3d about_pivot = Geometry::translation_transform(Vec3d(pivot.x(), pivot.y(), 0.)) * + Geometry::rotation_transform(Vec3d(0., 0., Geometry::deg2rad(rotation))) * + Geometry::translation_transform(Vec3d(-pivot.x(), -pivot.y(), 0.)); + model.objects.front()->instances.front()->set_transformation(Geometry::Transformation(about_pivot)); + print.apply(model, config); + print.process(); + return std::make_pair(brim_loop_count(print), brim_ear_centres(print)); + }; + + const std::pair> base = slice_rotated(0.); + REQUIRE(base.first > 0); + // Two sharp base corners plus the rounded apex, at every orientation. + REQUIRE(base.second.size() == 3); + const std::vector base_distances = ear_centre_distances(base.second); + + for (double rotation : { 37., 90., 180. }) { + DYNAMIC_SECTION("rotation " << rotation) { + const std::pair> rotated = slice_rotated(rotation); + REQUIRE(rotated.second.size() == base.second.size()); + CHECK(rotated.first == base.first); + // The ear positions are compared up to the rigid motion the rotation applies, so the plate + // placement the slicer chooses for the rotated footprint does not enter the comparison. + const std::vector distances = ear_centre_distances(rotated.second); + REQUIRE(distances.size() == base_distances.size()); + for (size_t i = 0; i < distances.size(); ++ i) + CHECK_THAT(distances[i], Catch::Matchers::WithinAbs(base_distances[i], scaled(0.5))); + } + } +} + SCENARIO("Skirt has the configured number of loops", "[SkirtBrim]") { GIVEN("20mm cube and default config") { WHEN("skirt_loops is set to 2") { diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index 41c0fb05df..e2f39a622f 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -23,6 +23,8 @@ add_executable(${_TEST_NAME}_tests test_assemble_list.cpp test_bambu_networking.cpp test_belt_brim.cpp + # Mouse ear detection is pure contour geometry; the slicing pipeline stays in fff_print. + test_brim.cpp test_buildvolume.cpp test_calib.cpp test_clipper_offset.cpp diff --git a/tests/libslic3r/test_brim.cpp b/tests/libslic3r/test_brim.cpp new file mode 100644 index 0000000000..f3a652f8a9 --- /dev/null +++ b/tests/libslic3r/test_brim.cpp @@ -0,0 +1,502 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "catch2/catch_test_macros.hpp" +#include "catch2/matchers/catch_matchers.hpp" +#include "catch2/matchers/catch_matchers_floating_point.hpp" +#include "libslic3r/Brim.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Polygon.hpp" +#include "libslic3r/libslic3r.h" + +using namespace Slic3r; + +namespace { + +// Ear points come back in no particular order, so compare them as a set. +bool same_point_set(const Points &a, const Points &b, coord_t tolerance) +{ + if (a.size() != b.size()) + return false; + std::vector matched(b.size(), false); + for (const Point &p : a) { + bool found = false; + for (size_t i = 0; i < b.size() && ! found; ++ i) { + if (! matched[i] && std::abs(p.x() - b[i].x()) <= tolerance && std::abs(p.y() - b[i].y()) <= tolerance) { + matched[i] = true; + found = true; + } + } + if (! found) + return false; + } + return true; +} + +bool contains_point(const Points &points, const Point &expected, coord_t tolerance) +{ + return std::any_of(points.begin(), points.end(), [&expected, tolerance](const Point &p) { + return std::abs(p.x() - expected.x()) <= tolerance && std::abs(p.y() - expected.y()) <= tolerance; + }); +} + +bool is_finite(const Point &p) +{ + return std::isfinite(unscale(p.x())) && std::isfinite(unscale(p.y())); +} + +// Arc that replaces `corner` between `prev` and `next`, as `segments` chords of the given radius, in mm. +std::vector fillet_arc(const Vec2d &prev, const Vec2d &corner, const Vec2d &next, double radius, int segments) +{ + const Vec2d to_prev = (prev - corner).normalized(); + const Vec2d to_next = (next - corner).normalized(); + const double half = std::acos(std::clamp(to_prev.dot(to_next), -1., 1.)) / 2.; + const double tangent = radius / std::tan(half); + const Vec2d start = corner + to_prev * tangent; + const Vec2d end = corner + to_next * tangent; + const Vec2d centre = corner + (to_prev + to_next).normalized() * (radius / std::sin(half)); + const double from = std::atan2(start.y() - centre.y(), start.x() - centre.x()); + const double to = std::atan2(end.y() - centre.y(), end.x() - centre.x()); + double sweep = to - from; + while (sweep > PI) + sweep -= 2. * PI; + while (sweep < -PI) + sweep += 2. * PI; + std::vector arc; + for (int i = 0; i <= segments; ++ i) { + const double angle = from + sweep * i / segments; + arc.emplace_back(centre.x() + radius * std::cos(angle), centre.y() + radius * std::sin(angle)); + } + return arc; +} + +// The arc that fillet_arc puts at a corner: its middle point in mm, and the angle it sweeps in radians. +struct Fillet { + Vec2d midpoint; + double sweep; +}; + +Fillet fillet_geometry(const Vec2d &prev, const Vec2d &corner, const Vec2d &next, double radius) +{ + const Vec2d to_prev = (prev - corner).normalized(); + const Vec2d to_next = (next - corner).normalized(); + const double half = std::acos(std::clamp(to_prev.dot(to_next), -1., 1.)) / 2.; + const Vec2d midpoint = corner + (to_prev + to_next).normalized() * (radius / std::sin(half) - radius); + return Fillet{ midpoint, PI - 2. * half }; +} + +// A closed outline plus the geometry of the arc that replaced each of its corners. +struct FilletedOutline { + std::vector outline; + std::vector corners; +}; + +// Replace every corner of the closed `corners` polygon with an arc of `radius` in `chords` chords. +FilletedOutline filleted_outline(const std::vector &corners, double radius, int chords) +{ + FilletedOutline filleted; + filleted.outline.reserve(corners.size() * size_t(chords + 1)); + filleted.corners.reserve(corners.size()); + for (size_t i = 0; i < corners.size(); ++ i) { + const Vec2d &prev = corners[(i + corners.size() - 1) % corners.size()]; + const Vec2d &next = corners[(i + 1) % corners.size()]; + const std::vector arc = fillet_arc(prev, corners[i], next, radius, chords); + filleted.outline.insert(filleted.outline.end(), arc.begin(), arc.end()); + filleted.corners.push_back(fillet_geometry(prev, corners[i], next, radius)); + } + return filleted; +} + +// 40 mm wide triangle with a 70 degree apex rounded by a fillet of `radius` in `chords` chords, counter-clockwise. +// The 60 / 50 degree base corners are deliberately unequal: a mirror symmetric outline ties the fillet's +// two sharpest vertices exactly, and the tie is then broken by vertex index. +struct FilletedTriangle { + std::vector outline; + Fillet apex; +}; + +FilletedTriangle filleted_triangle(double radius, int chords) +{ + const Vec2d a(0., 0.); + const Vec2d b(40., 0.); + const double to_apex = 40. * std::sin(50. * PI / 180.) / std::sin(70. * PI / 180.); + const Vec2d apex = a + Vec2d(std::cos(60. * PI / 180.), std::sin(60. * PI / 180.)) * to_apex; + const std::vector arc = fillet_arc(a, apex, b, radius, chords); + std::vector outline{ a, b }; + outline.insert(outline.end(), arc.rbegin(), arc.rend()); + return { outline, fillet_geometry(a, apex, b, radius) }; +} + +std::vector filleted_triangle_outline(double radius, int chords) +{ + return filleted_triangle(radius, chords).outline; +} + +// Axis-aligned CCW square (0, 0)..(side, side) with every corner filleted. +FilletedOutline filleted_square_outline(double side, double radius, int chords) +{ + return filleted_outline({ Vec2d(0., 0.), Vec2d(side, 0.), Vec2d(side, side), Vec2d(0., side) }, radius, chords); +} + +// Regular polygon with `sides` vertices on a circle of the given radius, counter-clockwise. +std::vector regular_polygon_outline(int sides, double radius) +{ + std::vector outline; + outline.reserve(size_t(sides)); + for (int i = 0; i < sides; ++ i) { + const double angle = 2. * PI * i / sides; + outline.emplace_back(radius * std::cos(angle), radius * std::sin(angle)); + } + return outline; +} + +// Regular `chords`-gon approximating a circle of the given radius. +std::vector circle_outline(double radius, int chords) +{ + return regular_polygon_outline(chords, radius); +} + +// Half disc of `radius`: a flat side and a `chords`-chord semicircular wall meeting it at two right angles. +std::vector half_disc_outline(double radius, int chords) +{ + std::vector outline; + outline.reserve(size_t(chords) + 1); + outline.emplace_back(-radius, 0.); + for (int i = 1; i <= chords; ++ i) { + const double angle = PI + PI * i / chords; + outline.emplace_back(radius * std::cos(angle), radius * std::sin(angle)); + } + return outline; +} + +// Ellipse with semi-axes `a` and `b` in `chords` chords. +std::vector ellipse_outline(double a, double b, int chords) +{ + std::vector outline; + outline.reserve(size_t(chords)); + for (int i = 0; i < chords; ++ i) { + const double angle = 2. * PI * i / chords; + outline.emplace_back(a * std::cos(angle), b * std::sin(angle)); + } + return outline; +} + +// Mean of the outline's vertices, in mm. +Vec2d outline_centroid(const std::vector &points) +{ + Vec2d sum = Vec2d::Zero(); + for (const Vec2d &p : points) + sum += p; + return sum / double(points.size()); +} + +std::vector to_mm(const Points &points) +{ + std::vector out; + out.reserve(points.size()); + for (const Point &p : points) + out.emplace_back(unscale(p.x()), unscale(p.y())); + return out; +} + +// Sorted distances between every pair of points, in mm: unchanged by a rigid motion of the whole set. +std::vector pairwise_distances(const std::vector &points) +{ + std::vector distances; + distances.reserve(points.size() * (points.size() - 1) / 2); + for (size_t i = 0; i < points.size(); ++ i) + for (size_t j = i + 1; j < points.size(); ++ j) + distances.push_back((points[i] - points[j]).norm()); + std::sort(distances.begin(), distances.end()); + return distances; +} + +// Ears sitting on one rounded corner: within half a chord of the arc's midpoint, which is the closest any +// point of the fillet gets to an ear placed on it. +size_t ears_on_corner(const Points &ears, const Fillet &corner, double radius, int chords) +{ + const Point midpoint = Point::new_scale(corner.midpoint); + const coord_t tolerance = coord_t(scale_(radius + 0.5 * radius * corner.sweep / chords)); + return size_t(std::count_if(ears.begin(), ears.end(), [&midpoint, tolerance](const Point &ear) { + return (ear - midpoint).cast().norm() <= double(tolerance); + })); +} + +// A quarter turn about the origin is exact in scaled integer coordinates. +Point rotated_quarter_turns(const Point &p, int quarter) +{ + Point rotated = p; + for (int i = 0; i < quarter; ++ i) + rotated = Point(-rotated.y(), rotated.x()); + return rotated; +} + +} // namespace + +// The detection must read the corner, not the contour's start vertex: a decimation anchored on the first +// vertex used to place an ear on a rounded corner for some vertex orders and not for others. +TEST_CASE("Brim ear detection is independent of the contour start vertex", "[Brim][Regression]") +{ + struct Case { double radius; int chords; }; + + const coord_t detection = coord_t(scale_(1.0)); + for (const Case &c : { Case{ 1.5, 6 }, Case{ 2.0, 12 }, Case{ 5.0, 12 } }) { + DYNAMIC_SECTION("fillet " << c.radius << " mm in " << c.chords << " chords") { + const Points contour = Polygon::new_scale(filleted_triangle_outline(c.radius, c.chords)).points; + const Points found = make_brim_ear_points(Polygon(contour), detection, 125., true); + // Two sharp base corners plus the rounded apex. + REQUIRE(found.size() == 3); + + for (size_t shift = 1; shift < contour.size(); ++ shift) { + Points shifted; + shifted.reserve(contour.size()); + std::rotate_copy(contour.begin(), contour.begin() + shift, contour.end(), std::back_inserter(shifted)); + const Points ears = make_brim_ear_points(Polygon(shifted), detection, 125., true); + CHECK(ears.size() == found.size()); + CHECK(same_point_set(ears, found, 2)); + } + } + } +} + +TEST_CASE("Brim ear detection rotates with the contour", "[Brim]") +{ + const std::vector outline = filleted_triangle_outline(1.5, 6); + const Points contour = Polygon::new_scale(outline).points; + const coord_t detection = coord_t(scale_(1.0)); + const Points base = make_brim_ear_points(Polygon(contour), detection, 125., true); + REQUIRE(base.size() == 3); + + for (int quarter : { 1, 2, 3 }) { + DYNAMIC_SECTION("quarter turns " << quarter) { + Points rotated_contour; + rotated_contour.reserve(contour.size()); + for (const Point &p : contour) + rotated_contour.push_back(rotated_quarter_turns(p, quarter)); + Points expected; + expected.reserve(base.size()); + for (const Point &p : base) + expected.push_back(rotated_quarter_turns(p, quarter)); + + const Points ears = make_brim_ear_points(Polygon(rotated_contour), detection, 125., true); + CHECK(ears.size() == base.size()); + CHECK(same_point_set(ears, expected, 2)); + } + } + + SECTION("37 degrees") { + // 37 degrees is not exact in scaled integer coordinates, so compare ear distances instead of positions. + const Vec2d centre = outline_centroid(outline); + const double angle = 37. * PI / 180.; + const auto rotate = [¢re, angle](const Vec2d &p) -> Vec2d { + const Vec2d d(p.x() - centre.x(), p.y() - centre.y()); + return Vec2d(centre.x() + d.x() * std::cos(angle) - d.y() * std::sin(angle), + centre.y() + d.x() * std::sin(angle) + d.y() * std::cos(angle)); + }; + + Points rotated_contour; + rotated_contour.reserve(outline.size()); + for (const Vec2d &p : outline) + rotated_contour.push_back(Point::new_scale(rotate(p))); + + std::vector expected = to_mm(base); + for (Vec2d &p : expected) + p = rotate(p); + + const Points ears = make_brim_ear_points(Polygon(rotated_contour), detection, 125., true); + const std::vector found_distances = pairwise_distances(to_mm(ears)); + const std::vector expected_distances = pairwise_distances(expected); + REQUIRE(found_distances.size() == expected_distances.size()); + for (size_t i = 0; i < found_distances.size(); ++ i) + CHECK_THAT(found_distances[i], Catch::Matchers::WithinAbs(expected_distances[i], 0.01)); + } +} + +TEST_CASE("A rounded apex carries a single brim ear", "[Brim]") +{ + const coord_t detection = coord_t(scale_(1.0)); + + for (double radius : { 0.5, 1.5, 3.0, 5.0 }) { + for (int chords : { 3, 6, 12, 24 }) { + DYNAMIC_SECTION("fillet " << radius << " mm in " << chords << " chords") { + const FilletedTriangle triangle = filleted_triangle(radius, chords); + const Points ears = make_brim_ear_points(Polygon::new_scale(triangle.outline), detection, 125., true); + // Two sharp base corners plus the rounded apex. + REQUIRE(ears.size() == 3); + + // A fillet is one corner, so exactly one ear sits on it, never a row along its chords. + CHECK(ears_on_corner(ears, triangle.apex, radius, chords) == 1); + } + } + } +} + +TEST_CASE("A square keeps one brim ear per rounded corner", "[Brim][Regression]") +{ + const coord_t detection = coord_t(scale_(1.0)); + const double radius = 5.; + const int chords = 12; + const FilletedOutline square = filleted_square_outline(40., radius, chords); + const Points ears = make_brim_ear_points(Polygon::new_scale(square.outline), detection, 125., true); + + // Four 90 degree corners, each rounded by one fillet: four ears, not one per chord. + REQUIRE(ears.size() == 4); + + for (const Fillet &corner : square.corners) + CHECK(ears_on_corner(ears, corner, radius, chords) == 1); +} + +// A part whose fillets take up most of the perimeter: the ladder stops at its cap of perimeter/8, so the +// saturation lookahead already reaches the neighbouring corner, and twice the window reaches the +// neighbouring ear. Detection used to return two ears at some orientations and none at others. +TEST_CASE("A small part keeps one brim ear per rounded corner", "[Brim][Regression]") +{ + const coord_t detection = coord_t(scale_(1.0)); + + SECTION("12 mm square with 4 mm fillets") { + const double radius = 4.; + const int chords = 12; + const FilletedOutline square = filleted_square_outline(12., radius, chords); + const Points ears = make_brim_ear_points(Polygon::new_scale(square.outline), detection, 125., true); + + REQUIRE(ears.size() == 4); + for (const Fillet &corner : square.corners) + CHECK(ears_on_corner(ears, corner, radius, chords) == 1); + } + + SECTION("10 mm hexagon with 2 mm fillets") { + const double radius = 2.; + const int chords = 6; + const FilletedOutline hexagon = filleted_outline(regular_polygon_outline(6, 10.), radius, chords); + const Points ears = make_brim_ear_points(Polygon::new_scale(hexagon.outline), detection, 125., true); + + REQUIRE(ears.size() == 6); + for (const Fillet &corner : hexagon.corners) + CHECK(ears_on_corner(ears, corner, radius, chords) == 1); + } +} + +TEST_CASE("A smooth contour has no brim ears", "[Brim]") +{ + const coord_t detection = coord_t(scale_(1.0)); + + // A circle's turn is spread evenly, so no vertex turns past the threshold at any measurement scale. + CHECK(make_brim_ear_points(Polygon::new_scale(circle_outline(5., 48)), detection, 125., true).empty()); + // A 24-gon is as smooth as the detector can tell at the default 1 mm detection length. + CHECK(make_brim_ear_points(Polygon::new_scale(regular_polygon_outline(24, 10.)), detection, 125., true).empty()); +} + +// A corner that meets a curved wall is one corner. A point on the curve accepts only once its window reaches +// that corner, so its candidate is the same corner seen from further away; keeping it puts a second ear 2 to +// 7 mm from the first. +TEST_CASE("A corner next to a curve carries one brim ear", "[Brim][Regression]") +{ + const coord_t detection = coord_t(scale_(1.0)); + + for (double radius : { 5., 10. }) { + DYNAMIC_SECTION("half disc of " << radius << " mm") { + const Points ears = make_brim_ear_points(Polygon::new_scale(half_disc_outline(radius, 64)), + detection, 125., true); + // Two right angles, one at each end of the flat side, and nothing on the semicircle between them. + REQUIRE(ears.size() == 2); + for (const Point &ear : ears) { + CHECK_THAT(std::abs(unscale(ear.x())), Catch::Matchers::WithinAbs(radius, 1.)); + CHECK_THAT(unscale(ear.y()), Catch::Matchers::WithinAbs(0., 1.)); + } + } + } + + for (int chords : { 64, 128 }) { + DYNAMIC_SECTION("60 x 10 mm ellipse in " << chords << " chords") { + const Points ears = make_brim_ear_points(Polygon::new_scale(ellipse_outline(30., 5., chords)), + detection, 125., true); + // One ear at each end of the long axis, none on the flanks. + REQUIRE(ears.size() == 2); + for (const Point &ear : ears) + CHECK(std::abs(unscale(ear.x())) > 25.); + } + } +} + +TEST_CASE("A pentagon keeps one brim ear per rounded corner", "[Brim][Regression]") +{ + // Side 20 mm: circumradius 20 / (2 sin 36 degrees), every corner rounded by 1 mm in six chords. + const std::vector corners = regular_polygon_outline(5, 20. / (2. * std::sin(PI / 5.))); + const FilletedOutline filleted = filleted_outline(corners, 1., 6); + const Points ears = make_brim_ear_points(Polygon::new_scale(filleted.outline), + coord_t(scale_(1.0)), 125., true); + + // Five 72 degree corners: a decimation that collapsed the outline to a triangle would report three. + REQUIRE(ears.size() == 5); +} + +TEST_CASE("Zero detection length still finds the sharp corners", "[Brim]") +{ + const std::vector outline = filleted_triangle_outline(1.5, 6); + const Points contour = Polygon::new_scale(outline).points; + const Points ears = make_brim_ear_points(Polygon(contour), 0, 125., true); + + // With immediate neighbours only, the two base corners turn far past the threshold and the fillet does not. + REQUIRE(ears.size() == 2); + CHECK(contains_point(ears, contour[0], 2)); + CHECK(contains_point(ears, contour[1], 2)); + for (const Point &ear : ears) + CHECK(is_finite(ear)); +} + +TEST_CASE("A concave notch takes brim ears on an inner contour", "[Brim]") +{ + // 40 x 40 mm plate with a 10 x 10 mm notch in its top edge, given in the winding a hole is stored in. + const std::vector stored_outline{ + Vec2d(0., 40.), Vec2d(20., 40.), Vec2d(20., 30.), Vec2d(30., 30.), + Vec2d(30., 40.), Vec2d(40., 40.), Vec2d(40., 0.), Vec2d(0., 0.), + }; + Polygons holes{ Polygon::new_scale(stored_outline) }; + // outer_inner_brim_area reverses hole contours before its concave pass, so the test does the same. + polygons_reverse(holes); + const Polygon &contour = holes.front(); + const coord_t detection = coord_t(scale_(1.0)); + + const auto on_notch_floor = [](const Point &ear) { + const double x = unscale(ear.x()); + const double y = unscale(ear.y()); + return std::abs(y - 30.) < 1. && x > 19. && x < 31.; + }; + + const Points concave_ears = make_brim_ear_points(contour, detection, 125., false); + REQUIRE(! concave_ears.empty()); + CHECK(std::all_of(concave_ears.begin(), concave_ears.end(), on_notch_floor)); + + const Points convex_ears = make_brim_ear_points(contour, detection, 125., true); + CHECK(! convex_ears.empty()); + CHECK(std::none_of(convex_ears.begin(), convex_ears.end(), on_notch_floor)); +} + +TEST_CASE("A clockwise contour keeps brim ear detection well defined", "[Brim]") +{ + Points contour = Polygon::new_scale(filleted_triangle_outline(1.5, 6)).points; + std::reverse(contour.begin(), contour.end()); + + Points ears; + REQUIRE_NOTHROW(ears = make_brim_ear_points(Polygon(contour), coord_t(scale_(1.0)), 125., true)); + // The convexity predicate is winding sensitive, so a reversed outer contour has no convex corner left. + CHECK(ears.empty()); +} + +TEST_CASE("Brim ear max angle excludes a corner at exactly the bound", "[Brim]") +{ + // A rectangle's corners turn by exactly 90 degrees. + const std::vector rectangle{ Vec2d(0., 0.), Vec2d(40., 0.), Vec2d(40., 20.), Vec2d(0., 20.) }; + const Polygon contour = Polygon::new_scale(rectangle); + const coord_t detection = coord_t(scale_(1.0)); + + CHECK(make_brim_ear_points(contour, detection, 91., true).size() == 4); + CHECK(make_brim_ear_points(contour, detection, 90., true).empty()); + CHECK(make_brim_ear_points(contour, detection, 89., true).empty()); +}