Smooth more patterns (#15205)

This commit is contained in:
Ian Bassi
2026-08-18 12:19:27 -03:00
committed by GitHub
parent 6a52ea1818
commit 322dc9b6a6
19 changed files with 996 additions and 157 deletions

View File

@@ -698,3 +698,290 @@ TEST_CASE("Solid infill direction offsets every layer when no template is set",
CHECK(delta == 30);
}
}
TEST_CASE("Honeycomb infill rounds its cell corners with the smooth factor", "[Fill]")
{
// A cell whose sides are several times the line width, so that the corners have room to be rounded.
const double spacing = 0.45;
const double density = 0.1;
auto fill = [spacing, density](double smooth_factor) {
std::unique_ptr<Slic3r::Fill> filler(Slic3r::Fill::new_from_type("honeycomb"));
filler->spacing = spacing;
FillParams params;
params.density = float(density);
params.dont_adjust = true;
// Keep the fragments apart, so that only the turns of the pattern itself are measured.
params.anchor_length_max = 0.f;
params.smooth_factor = smooth_factor;
Slic3r::ExPolygon square{ Slic3r::Points{
Point::new_scale(0., 0.), Point::new_scale(50., 0.), Point::new_scale(50., 50.), Point::new_scale(0., 50.) } };
Slic3r::Surface surface(stInternal, square);
return filler->fill_surface(&surface, params);
};
// Cosine of the sharpest turn of any of the paths, 1 meaning none of them turns at all.
auto sharpest_turn_cosine = [](const Slic3r::Polylines &polylines) {
double sharpest = 1.;
for (const Polyline &polyline : polylines)
for (size_t i = 1; i + 1 < polyline.size(); ++i) {
const Vec2d incoming = (polyline[i] - polyline[i - 1]).cast<double>().normalized();
const Vec2d outgoing = (polyline[i + 1] - polyline[i]).cast<double>().normalized();
sharpest = std::min(sharpest, incoming.dot(outgoing));
}
return sharpest;
};
auto point_count = [](const Slic3r::Polylines &polylines) {
return std::accumulate(polylines.begin(), polylines.end(), size_t(0),
[](size_t count, const Polyline &polyline) { return count + polyline.size(); });
};
const Slic3r::Polylines sharp = fill(0.);
const Slic3r::Polylines smooth = fill(1.);
REQUIRE(!sharp.empty());
REQUIRE(smooth.size() == sharp.size());
REQUIRE(point_count(smooth) > point_count(sharp));
// The cell corners turn by 60 degrees; smoothing replaces them by gentle curves.
REQUIRE(sharpest_turn_cosine(sharp) < 0.6);
REQUIRE(sharpest_turn_cosine(smooth) > 0.9);
}
// Point count, number of turns sharper than 25 degrees and length of the sparse infill of a print.
// A rounded corner is a run of much gentler turns, so smoothing shows up as fewer sharp ones.
struct SparseInfillShape {
size_t point_count { 0 };
size_t sharp_turns { 0 };
size_t path_count { 0 };
double length { 0. };
};
static SparseInfillShape sparse_infill_shape(const Print &print)
{
SparseInfillShape shape;
auto account = [&shape](const ExtrusionPath &path) {
if (!sparse_role(path.role()))
return;
const Points3 &pts = path.polyline.points;
++shape.path_count;
shape.point_count += pts.size();
for (size_t i = 1; i < pts.size(); ++i)
shape.length += (pts[i] - pts[i - 1]).head<2>().cast<double>().norm();
for (size_t i = 1; i + 1 < pts.size(); ++i) {
const Vec2d incoming = (pts[i] - pts[i - 1]).head<2>().cast<double>();
const Vec2d outgoing = (pts[i + 1] - pts[i]).head<2>().cast<double>();
if (incoming.squaredNorm() > 0. && outgoing.squaredNorm() > 0. &&
incoming.normalized().dot(outgoing.normalized()) < 0.9)
++shape.sharp_turns;
}
};
for (const Layer *layer : print.objects().front()->layers())
for (const LayerRegion *region : layer->regions())
for (const ExtrusionEntity *entity : region->fills.flatten().entities) {
if (auto *path = dynamic_cast<const ExtrusionPath *>(entity))
account(*path);
else if (auto *multi = dynamic_cast<const ExtrusionMultiPath *>(entity))
for (const ExtrusionPath &p : multi->paths)
account(p);
else if (auto *loop = dynamic_cast<const ExtrusionLoop *>(entity))
for (const ExtrusionPath &p : loop->paths)
account(p);
}
return shape;
}
TEST_CASE("Lightning infill rounds the turns of its branches with the smooth factor", "[Fill]")
{
auto shape_for = [](const std::string &smooth_factor) {
Print print;
Slic3r::Test::init_and_process_print({Slic3r::Test::cube(20)}, print,
{{"sparse_infill_pattern", "lightning"},
{"sparse_infill_density", "15%"},
{"sparse_infill_smooth_factor", smooth_factor},
{"layer_height", 0.2}});
return sparse_infill_shape(print);
};
const SparseInfillShape sharp = shape_for("0%");
const SparseInfillShape smooth = shape_for("100%");
REQUIRE(sharp.point_count > 0);
// The branch turns are replaced by curves, which cut the corners off and take more points to
// describe. The turns where two branches are joined into one path stay sharp.
REQUIRE(smooth.point_count > sharp.point_count);
REQUIRE(smooth.sharp_turns < sharp.sharp_turns);
REQUIRE(smooth.length < sharp.length);
}
TEST_CASE("Concentric infill rounds its loops with the smooth factor", "[Fill]")
{
auto shape_for = [](const std::string &smooth_factor) {
Print print;
Slic3r::Test::init_and_process_print({Slic3r::Test::cube(20)}, print,
{{"sparse_infill_pattern", "concentric"},
{"sparse_infill_density", "20%"},
{"sparse_infill_smooth_factor", smooth_factor},
{"layer_height", 0.2}});
return sparse_infill_shape(print);
};
const SparseInfillShape sharp = shape_for("0%");
const SparseInfillShape smooth = shape_for("100%");
REQUIRE(sharp.point_count > 0);
REQUIRE(smooth.point_count > sharp.point_count);
REQUIRE(smooth.sharp_turns < sharp.sharp_turns);
REQUIRE(smooth.length < sharp.length);
}
TEST_CASE("Cross hatch infill rounds its transition layers with the smooth factor", "[Fill]")
{
auto shape_for = [](const std::string &smooth_factor) {
Print print;
Slic3r::Test::init_and_process_print({Slic3r::Test::cube(20)}, print,
{{"sparse_infill_pattern", "crosshatch"},
{"sparse_infill_density", "20%"},
{"sparse_infill_smooth_factor", smooth_factor},
{"layer_height", 0.2}});
return sparse_infill_shape(print);
};
const SparseInfillShape sharp = shape_for("0%");
const SparseInfillShape smooth = shape_for("100%");
REQUIRE(sharp.point_count > 0);
REQUIRE(smooth.point_count > sharp.point_count);
REQUIRE(smooth.sharp_turns < sharp.sharp_turns);
REQUIRE(smooth.length < sharp.length);
}
TEST_CASE("Trapezoidal grid infill rounds its corners only with more than one line", "[Fill]")
{
auto shape_for = [](int multiline, const std::string &smooth_factor) {
Print print;
Slic3r::Test::init_and_process_print({Slic3r::Test::cube(20)}, print,
{{"sparse_infill_pattern", "grid"},
{"sparse_infill_density", "20%"},
{"fill_multiline", multiline},
{"sparse_infill_smooth_factor", smooth_factor},
{"layer_height", 0.2}});
return sparse_infill_shape(print);
};
const SparseInfillShape sharp = shape_for(2, "0%");
const SparseInfillShape smooth = shape_for(2, "100%");
REQUIRE(sharp.point_count > 0);
REQUIRE(smooth.point_count > sharp.point_count);
REQUIRE(smooth.sharp_turns < sharp.sharp_turns);
REQUIRE(smooth.length < sharp.length);
// A single line per infill wall is the plain crossing line grid, which has no corner of its own.
const SparseInfillShape single_sharp = shape_for(1, "0%");
const SparseInfillShape single_smooth = shape_for(1, "100%");
REQUIRE(single_sharp.point_count > 0);
REQUIRE(single_smooth.point_count == single_sharp.point_count);
REQUIRE(single_smooth.length == single_sharp.length);
}
TEST_CASE("3D honeycomb infill rounds its octahedral waves with the smooth factor", "[Fill]")
{
auto shape_for = [](const std::string &smooth_factor) {
Print print;
Slic3r::Test::init_and_process_print({Slic3r::Test::cube(20)}, print,
{{"sparse_infill_pattern", "3dhoneycomb"},
{"sparse_infill_density", "20%"},
{"sparse_infill_smooth_factor", smooth_factor},
{"layer_height", 0.2}});
return sparse_infill_shape(print);
};
const SparseInfillShape sharp = shape_for("0%");
const SparseInfillShape smooth = shape_for("100%");
REQUIRE(sharp.point_count > 0);
REQUIRE(smooth.point_count > sharp.point_count);
REQUIRE(smooth.sharp_turns < sharp.sharp_turns);
REQUIRE(smooth.length < sharp.length);
}
TEST_CASE("Smoothed concentric infill stays inside the fill region", "[Fill][Regression]")
{
// The concentric loops are offsets of the fill region and are never clipped to it, so a corner
// rounded across its boundary ends up in a hole or over a wall. Rounding cuts toward the inside of
// the turn, which leaves the region at every corner of a hole, and in a region thinner than the
// curve even at a corner turning inwards.
const bool thin_region = GENERATE(false, true);
ExPolygon region;
if (thin_region) {
// An L of two 1.2mm wide arms: cutting the corner they meet at crosses both of them.
region = ExPolygon{ Slic3r::Points{
Point::new_scale(0., 0.), Point::new_scale(20., 0.), Point::new_scale(20., 1.2),
Point::new_scale(1.2, 1.2), Point::new_scale(1.2, 20.), Point::new_scale(0., 20.) } };
} else {
region = ExPolygon{ Slic3r::Points{ Point::new_scale(0., 0.), Point::new_scale(50., 0.),
Point::new_scale(50., 50.), Point::new_scale(0., 50.) },
Slic3r::Points{ Point::new_scale(30., 20.), Point::new_scale(30., 30.),
Point::new_scale(20., 30.), Point::new_scale(20., 20.) } };
}
CAPTURE(thin_region);
auto fill = [&region](double smooth_factor) {
std::unique_ptr<Slic3r::Fill> filler(Slic3r::Fill::new_from_type("concentric"));
filler->spacing = 0.45;
FillParams params;
params.density = 0.1f;
params.dont_adjust = true;
params.smooth_factor = smooth_factor;
Slic3r::Surface surface(stInternal, region);
return filler->fill_surface(&surface, params);
};
auto point_count = [](const Slic3r::Polylines &polylines) {
return std::accumulate(polylines.begin(), polylines.end(), size_t(0),
[](size_t count, const Polyline &polyline) { return count + polyline.size(); });
};
const Slic3r::Polylines sharp = fill(0.);
const Slic3r::Polylines smooth = fill(1.);
REQUIRE(!sharp.empty());
// Nothing leaves the fill region, which the unrounded loops already touch from the inside.
const ExPolygons bounds = offset_ex(region, float(SCALED_EPSILON));
REQUIRE(diff_pl(sharp, bounds).empty());
REQUIRE(diff_pl(smooth, bounds).empty());
// The corners that the region has room for are still rounded.
if (!thin_region)
REQUIRE(point_count(smooth) > point_count(sharp));
}
TEST_CASE("Smoothing multiline lightning infill keeps its outlines connected", "[Fill][Regression]")
{
// With more than one line per infill wall, the branches are printed as outlines drawn around them,
// and the outlines of branches that run close to each other merge into one. Rounding the branches
// before those outlines are built moves them apart, which breaks the merged outlines up into
// separate loops - many more of them, each needing its own travel move.
auto shape_for = [](const std::string &smooth_factor) {
Print print;
Slic3r::Test::init_and_process_print({Slic3r::Test::cube(20)}, print,
{{"sparse_infill_pattern", "lightning"},
{"sparse_infill_density", "50%"},
{"fill_multiline", 2},
{"sparse_infill_smooth_factor", smooth_factor},
{"layer_height", 0.2}});
return sparse_infill_shape(print);
};
const SparseInfillShape sharp = shape_for("0%");
const SparseInfillShape smooth = shape_for("100%");
REQUIRE(sharp.path_count > 0);
REQUIRE(smooth.path_count <= sharp.path_count);
// The outlines are still rounded.
REQUIRE(smooth.point_count > sharp.point_count);
REQUIRE(smooth.sharp_turns < sharp.sharp_turns);
}

View File

@@ -18,6 +18,7 @@ add_executable(${_TEST_NAME}_tests
test_preset_setting_id.cpp
test_preset_diff.cpp
test_elephant_foot_compensation.cpp
test_fill_corner_smoothing.cpp
test_fill_plane_path.cpp
test_geometry.cpp
test_multimaterial_segmentation.cpp

View File

@@ -0,0 +1,173 @@
#include <catch2/catch_all.hpp>
#include <algorithm>
#include <cmath>
#include <limits>
#include "libslic3r/Fill/FillCornerSmoothing.hpp"
#include "libslic3r/Polyline.hpp"
#include "libslic3r/libslic3r.h"
using namespace Slic3r;
namespace {
// A right angle turn, with the outgoing leg ten times longer than the incoming one.
Polyline asymmetric_corner()
{
return Polyline{ Point::new_scale(0., 0.), Point::new_scale(10., 0.), Point::new_scale(10., 100.) };
}
double max_turn_cosine(const Polyline &polyline)
{
double sharpest = 1.;
for (size_t i = 1; i + 1 < polyline.size(); ++i) {
const Vec2d incoming = (polyline[i] - polyline[i - 1]).cast<double>().normalized();
const Vec2d outgoing = (polyline[i + 1] - polyline[i]).cast<double>().normalized();
sharpest = std::min(sharpest, incoming.dot(outgoing));
}
return sharpest;
}
bool contains(const Polyline &polyline, const Point &point)
{
return std::find(polyline.points.begin(), polyline.points.end(), point) != polyline.points.end();
}
const double tolerance = scaled<double>(0.0125);
} // namespace
TEST_CASE("Corner smoothing replaces a sharp vertex by a curve", "[FillCornerSmoothing]")
{
const Polyline sharp = asymmetric_corner();
Polyline smooth = sharp;
smooth_polyline_corners(smooth, 1., tolerance);
REQUIRE(smooth.size() > sharp.size());
REQUIRE(smooth.front() == sharp.front());
REQUIRE(smooth.back() == sharp.back());
// The right angle is gone, every remaining turn is a gentle one.
REQUIRE(max_turn_cosine(sharp) < 0.1);
REQUIRE(max_turn_cosine(smooth) > 0.9);
REQUIRE(smooth.length() < sharp.length());
}
TEST_CASE("Corner smoothing keeps the path untouched at a zero factor", "[FillCornerSmoothing]")
{
const Polyline sharp = asymmetric_corner();
Polyline none = sharp;
smooth_polyline_corners(none, 0., tolerance);
REQUIRE(none.points == sharp.points);
Polyline invalid = sharp;
smooth_polyline_corners(invalid, std::numeric_limits<double>::quiet_NaN(), tolerance);
REQUIRE(invalid.points == sharp.points);
}
TEST_CASE("Corner smoothing consumes at most half of the shorter leg", "[FillCornerSmoothing]")
{
// The curve must not reach beyond the middle of either adjoining segment, otherwise the curves of
// two adjacent corners would overlap. The shorter leg is 10mm long, so the corner at (10, 0) is
// left 5mm before it and rejoined 5mm past it, even though the other leg is 100mm long.
Polyline smooth = asymmetric_corner();
smooth_polyline_corners(smooth, 1., tolerance);
REQUIRE(contains(smooth, Point::new_scale(5., 0.)));
REQUIRE(contains(smooth, Point::new_scale(10., 5.)));
// A Bezier curve stays within the convex hull of its control points, so the rounded path stays
// inside the box spanned by the two legs.
for (const Point &point : smooth.points) {
REQUIRE(point.x() >= 0);
REQUIRE(point.y() >= 0);
REQUIRE(point.x() <= Point::new_scale(10., 0.).x());
REQUIRE(point.y() <= Point::new_scale(0., 100.).y());
}
}
TEST_CASE("Corner smoothing scales the curve with the factor", "[FillCornerSmoothing]")
{
Polyline half = asymmetric_corner();
smooth_polyline_corners(half, 0.5, tolerance);
Polyline full = asymmetric_corner();
smooth_polyline_corners(full, 1., tolerance);
// Half of the factor leaves the 10mm leg half as far from the corner.
REQUIRE(contains(half, Point::new_scale(7.5, 0.)));
REQUIRE(contains(full, Point::new_scale(5., 0.)));
// A larger factor rounds a wider portion of the legs, cutting more of the corner off.
REQUIRE(full.length() < half.length());
}
TEST_CASE("Corner smoothing leaves hairpins sharp", "[FillCornerSmoothing]")
{
// Both ends of a curve replacing a nearly reversing turn coincide, which would round the hairpin
// into a degenerate loop instead of a tip.
Polyline hairpin{ Point::new_scale(0., 0.), Point::new_scale(10., 0.), Point::new_scale(0., 0.5) };
const Polyline sharp = hairpin;
smooth_polyline_corners(hairpin, 1., tolerance);
REQUIRE(hairpin == sharp);
}
TEST_CASE("Corner smoothing follows the flattening tolerance", "[FillCornerSmoothing]")
{
Polyline coarse = asymmetric_corner();
smooth_polyline_corners(coarse, 1., scaled<double>(0.2));
Polyline fine = asymmetric_corner();
smooth_polyline_corners(fine, 1., scaled<double>(0.001));
REQUIRE(fine.size() > coarse.size());
REQUIRE(fine.front() == coarse.front());
REQUIRE(fine.back() == coarse.back());
}
TEST_CASE("Corner smoothing emits no zero length segments", "[FillCornerSmoothing]")
{
// Fully smoothed adjacent corners meet at the midpoint of the segment they share.
Polyline zigzag;
for (int i = 0; i < 8; ++i)
zigzag.points.emplace_back(Point::new_scale(i, i % 2 ? 1. : 0.));
smooth_polyline_corners(zigzag, 1., tolerance);
for (size_t i = 1; i < zigzag.size(); ++i)
REQUIRE((zigzag[i] - zigzag[i - 1]).cast<double>().squaredNorm() > 0.);
}
TEST_CASE("Corner smoothing rounds every vertex of a polygon", "[FillCornerSmoothing]")
{
// A polygon closes implicitly, so none of its corners may stay sharp, not even the first one.
const Polygon square{ Point::new_scale(0., 0.), Point::new_scale(10., 0.), Point::new_scale(10., 10.),
Point::new_scale(0., 10.) };
Polygons smooth{ square };
smooth_polygons_corners(smooth, 1., tolerance);
const Polyline rounded = smooth.front().split_at_first_point();
REQUIRE(smooth.front().size() > square.size());
REQUIRE(max_turn_cosine(rounded) > 0.9);
// The turn from the closing segment back into the first one must be gentle as well.
const Vec2d incoming = (rounded[rounded.size() - 1] - rounded[rounded.size() - 2]).cast<double>().normalized();
const Vec2d outgoing = (rounded[1] - rounded[0]).cast<double>().normalized();
REQUIRE(incoming.dot(outgoing) > 0.9);
// None of the corners is cut by more than half of a 10mm side.
for (const Point &point : smooth.front().points) {
REQUIRE(point.x() >= 0);
REQUIRE(point.y() >= 0);
REQUIRE(point.x() <= Point::new_scale(10., 0.).x());
REQUIRE(point.y() <= Point::new_scale(0., 10.).y());
}
}
TEST_CASE("Corner smoothing keeps the ends of a path that returns to its start", "[FillCornerSmoothing][Regression]")
{
// A branch of a lightning tree walks out and retraces its way back, ending where it started. Its
// ends are two free ends that happen to coincide, and joining them would close it into a loop.
Polyline retrace{ Point::new_scale(0., 0.), Point::new_scale(10., 0.), Point::new_scale(10., 10.),
Point::new_scale(5., 10.), Point::new_scale(0., 0.) };
const Polyline sharp = retrace;
smooth_polyline_corners(retrace, 1., tolerance);
REQUIRE(retrace.size() > sharp.size());
REQUIRE(retrace.front() == sharp.front());
REQUIRE(retrace.back() == sharp.back());
}

View File

@@ -27,6 +27,31 @@ public:
}
};
class TestableOctagramSpiral : public FillOctagramSpiral
{
public:
Points generate_points(double resolution, double smooth_factor = 0., coord_t max_coordinate = 7)
{
InfillPolylineOutput output(output_scale);
FillParams params;
params.smooth_factor = smooth_factor;
FillOctagramSpiral::generate(-max_coordinate, -max_coordinate, max_coordinate, max_coordinate, resolution, params, output);
return std::move(output.result());
}
};
// Cosine of the sharpest turn of a path, 1 meaning it has no turn at all.
double sharpest_turn_cosine(const Points &points)
{
double sharpest = 1.;
for (size_t i = 1; i + 1 < points.size(); ++i) {
const Vec2d incoming = (points[i] - points[i - 1]).cast<double>().normalized();
const Vec2d outgoing = (points[i + 1] - points[i]).cast<double>().normalized();
sharpest = std::min(sharpest, incoming.dot(outgoing));
}
return sharpest;
}
double path_length(const Points &points)
{
double length = 0.;
@@ -146,6 +171,35 @@ TEST_CASE("Hilbert smoothing joins straight segments with continuous curvature",
REQUIRE(fine_entry_curvature < 0.25 * coarse_entry_curvature);
}
TEST_CASE("Octagram spiral smoothing rounds the turns of the spiral", "[FillPlanePath]")
{
const Points sharp = TestableOctagramSpiral().generate_points(0.005);
const Points smooth = TestableOctagramSpiral().generate_points(0.005, 1.);
REQUIRE(smooth.size() > sharp.size());
REQUIRE(smooth.front() == sharp.front());
REQUIRE(smooth.back() == sharp.back());
// The spiral alternates between 90 and 135 degree turns; both are rounded into gentle ones.
REQUIRE(sharpest_turn_cosine(sharp) < -0.7);
REQUIRE(sharpest_turn_cosine(smooth) > 0.9);
for (size_t i = 1; i < smooth.size(); ++i)
REQUIRE((smooth[i] - smooth[i - 1]).cast<double>().squaredNorm() > 0.);
}
TEST_CASE("Octagram spiral smooth factor controls corner curvature", "[FillPlanePath]")
{
const Points sharp = TestableOctagramSpiral().generate_points(0.005);
const Points half_smooth = TestableOctagramSpiral().generate_points(0.005, 0.5);
const Points full_smooth = TestableOctagramSpiral().generate_points(0.005, 1.);
const Points invalid_factor = TestableOctagramSpiral().generate_points(
0.005, std::numeric_limits<double>::quiet_NaN());
REQUIRE(path_length(full_smooth) < path_length(half_smooth));
REQUIRE(path_length(half_smooth) < path_length(sharp));
REQUIRE(invalid_factor == sharp);
}
TEST_CASE("Hilbert curve smooth factor controls corner curvature", "[FillPlanePath]")
{
const Points sharp = TestableHilbertCurve().generate_points(0.005);