diff --git a/.github/workflows/build_orca.yml b/.github/workflows/build_orca.yml index e9c4603bc8..8880009c19 100644 --- a/.github/workflows/build_orca.yml +++ b/.github/workflows/build_orca.yml @@ -264,8 +264,9 @@ jobs: KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} CERTIFICATE_ID: ${{ secrets.MACOS_CERTIFICATE_ID }} run: | - # Load the `retry` helper (retries flaky commands such as `hdiutil create`). + # Load the `retry` and `create_dmg` helpers. source ${{ github.workspace }}/scripts/retry.sh + source ${{ github.workspace }}/scripts/create_dmg.sh CERTIFICATE_PATH=$RUNNER_TEMP/build_certificate.p12 KEYCHAIN_PATH=$RUNNER_TEMP/app-signing.keychain-db echo -n "$BUILD_CERTIFICATE_BASE64" | base64 --decode --output $CERTIFICATE_PATH @@ -319,7 +320,7 @@ jobs: rm -rf ${{ github.workspace }}/build/universal/OrcaSlicer_dmg/* cp -R ${{ github.workspace }}/build/universal/OrcaSlicer/OrcaSlicer.app ${{ github.workspace }}/build/universal/OrcaSlicer_dmg/ ln -sfn /Applications ${{ github.workspace }}/build/universal/OrcaSlicer_dmg/Applications - retry hdiutil create -volname "OrcaSlicer" -srcfolder ${{ github.workspace }}/build/universal/OrcaSlicer_dmg -ov -format UDZO OrcaSlicer_Mac_universal_${{ env.ver }}.dmg + create_dmg "OrcaSlicer" ${{ github.workspace }}/build/universal/OrcaSlicer_dmg OrcaSlicer_Mac_universal_${{ env.ver }}.dmg codesign --deep --force --verbose --options runtime --timestamp --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE_ID" OrcaSlicer_Mac_universal_${{ env.ver }}.dmg # Create separate OrcaSlicer_profile_validator DMG if the app exists @@ -328,7 +329,7 @@ jobs: rm -rf ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg/* cp -R ${{ github.workspace }}/build/universal/OrcaSlicer/OrcaSlicer_profile_validator.app ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg/ ln -sfn /Applications ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg/Applications - retry hdiutil create -volname "OrcaSlicer Profile Validator" -srcfolder ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg -ov -format UDZO OrcaSlicer_profile_validator_Mac_universal_${{ env.ver }}.dmg + create_dmg "OrcaSlicer Profile Validator" ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg OrcaSlicer_profile_validator_Mac_universal_${{ env.ver }}.dmg codesign --deep --force --verbose --options runtime --timestamp --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE_ID" OrcaSlicer_profile_validator_Mac_universal_${{ env.ver }}.dmg fi @@ -346,13 +347,14 @@ jobs: if: github.ref != 'refs/heads/main' && runner.os == 'macOS' && inputs.macos-combine-only working-directory: ${{ github.workspace }} run: | - # Load the `retry` helper (retries flaky commands such as `hdiutil create`). + # Load the `retry` and `create_dmg` helpers. source ${{ github.workspace }}/scripts/retry.sh + source ${{ github.workspace }}/scripts/create_dmg.sh mkdir -p ${{ github.workspace }}/build/universal/OrcaSlicer_dmg rm -rf ${{ github.workspace }}/build/universal/OrcaSlicer_dmg/* cp -R ${{ github.workspace }}/build/universal/OrcaSlicer/OrcaSlicer.app ${{ github.workspace }}/build/universal/OrcaSlicer_dmg/ ln -sfn /Applications ${{ github.workspace }}/build/universal/OrcaSlicer_dmg/Applications - retry hdiutil create -volname "OrcaSlicer" -srcfolder ${{ github.workspace }}/build/universal/OrcaSlicer_dmg -ov -format UDZO OrcaSlicer_Mac_universal_${{ env.ver }}.dmg + create_dmg "OrcaSlicer" ${{ github.workspace }}/build/universal/OrcaSlicer_dmg OrcaSlicer_Mac_universal_${{ env.ver }}.dmg # Create separate OrcaSlicer_profile_validator DMG if the app exists if [ -f "${{ github.workspace }}/build/universal/OrcaSlicer/OrcaSlicer_profile_validator.app/Contents/MacOS/OrcaSlicer_profile_validator" ]; then @@ -360,7 +362,7 @@ jobs: rm -rf ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg/* cp -R ${{ github.workspace }}/build/universal/OrcaSlicer/OrcaSlicer_profile_validator.app ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg/ ln -sfn /Applications ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg/Applications - retry hdiutil create -volname "OrcaSlicer Profile Validator" -srcfolder ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg -ov -format UDZO OrcaSlicer_profile_validator_Mac_universal_${{ env.ver }}.dmg + create_dmg "OrcaSlicer Profile Validator" ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg OrcaSlicer_profile_validator_Mac_universal_${{ env.ver }}.dmg fi # Delete the per-arch bundles only after signing/DMG creation succeeded, so a diff --git a/docs/HLSD/infill-corner-smoothing.md b/docs/HLSD/infill-corner-smoothing.md new file mode 100644 index 0000000000..d7a7f05d2e --- /dev/null +++ b/docs/HLSD/infill-corner-smoothing.md @@ -0,0 +1,68 @@ +# Infill corner smoothing — High Level Design + +## Purpose and scope + +`sparse_infill_smooth_factor` rounds the corners of the sparse infill paths of +the patterns `is_smoothable_infill_pattern()` lists, so the toolhead does not +slow to near a stop in every corner. `FillCornerSmoothing` does the rounding for +every pattern; the fills only call it on their paths before clipping and before +`multiline_fill()` copies them. + +The design is shaped by how firmware plans speed. Klipper, Marlin 2 with +junction deviation and OrcaSlicer's estimator limit the speed at the junction of +two moves by how much the path turns there, and by the length of the moves for +the centripetal part. A curve is printed as straight moves, so its speed depends +on how it is cut into moves as much as on its shape, and the cut decides the size +of the G-code. + +## The curve + +Each corner is replaced by a curve that runs from `reach` before it along the +incoming leg to `reach` after it along the outgoing one, `reach` being the factor +times half of the shorter leg, so the curves of two corners never overlap. + +The curve is a quintic Bézier curve whose first three control points on each leg +are equally spaced, 0.3 of the reach apart, which makes its curvature zero at the +legs: the toolhead eases into the turn. A circular arc takes fewer vertices within +the resolution and prints slower, and a septic curve, whose rate of curvature is +also zero at the legs, prints no faster than the quintic one and takes longer to +slice. Tuning the spacing to the turn angle lowers the peak curvature of sharp +turns but made no measurable difference to print time. + +## The vertices + +A corner is printed as the polygon of the curve's tangents taken at equal steps +of direction: every vertex turns by the same angle, which spends each vertex +where the planner needs it. Uniform steps of the curve parameter put vertices +where the curve is nearly straight and leave the sharpest turn in the middle. + +The number of vertices follows the G-code resolution (`resolution`), as the rest +of the G-code does: it is the fewest that keep the polygon within the resolution +of its curve. The arc of the curve's peak curvature gives the first count, which +the flatter parts of the curve may raise. The count is never so high that a +vertex stands out of the chord of its neighbours by less than the resolution, as +`LayerRegion::simplify_*` simplifies the infill to it afterwards and would drop +that vertex again. + +The vertices depend on the geometry and the resolution only, not on the printer. +A finer resolution splits a corner into more and gentler turns, which a planner +takes faster, for a larger G-code file. + +A corner of a given turn and vertex count is the same shape at any reach and +resolution, scaled. Each thread builds a shape once at unit reach and all its +`CornerSmoother`s share it, as some fills start a smoother for every path, every +layer starts its own, some patterns (Octagram Spiral) change the reach at every +corner, and searching the tangents of the curve is what slicing spends its time +on. + +## Constraints + +- At 100% every corner gets the largest curve its legs allow: the factor sets + the shape of the corners, not their speed. A large curve split into few + vertices can print slower than the sharp corner, as every vertex is a slowdown + and the short moves between them leave no room to accelerate. +- With the factor at 0 the paths are unchanged, and the fills keep their order of + operations, so that rounding to the integer grid does not move a point. +- The plane-path fills (Hilbert Curve, Octagram Spiral) produce their path point + by point in units of the line distance, so `CornerSmoother` takes points one + at a time, with the resolution in the same units. diff --git a/docs/HLSD/travel-optimization.md b/docs/HLSD/travel-optimization.md index 119133cee2..79774f7ff9 100644 --- a/docs/HLSD/travel-optimization.md +++ b/docs/HLSD/travel-optimization.md @@ -10,7 +10,9 @@ things shorten the travel between infill paths: - the fill generators join their lines into as few paths as they can, since every separate path needs a travel to it; - the G-code export refines the greedy chain with a local search that shortens - the straight-line travel between the paths. + the straight-line travel between the paths; +- a fill that keeps its order prints each piece of its gap fill where it passes + by, since the G-code export cannot reorder it. The refinement covers every chain that `chain_and_reorder_extrusion_entities()` builds from a start point: the infill and ironing of `GCode::extrude_infill()` @@ -97,6 +99,22 @@ joined at different walls and the travel between them crossed the island. Lines that cannot reverse, such as Grid's, only join the end of one to the start of the next, and fills that keep their order are left alone. +## Gap fill in a fill that keeps its order + +`Fill::_create_gap_fill()` adds the gap fill of a solid surface, where +`gap_fill_target` asks for it, after the lines of the fill. The chain mixes it +in with the lines of a sortable fill like any other path. A fill that keeps its +order, such as monotonic, would print all of its lines and then come back for +every piece of gap fill, most of which lies at the walls where the lines end. + +So each piece, in turn, goes between the two extrusions of the fill where it +adds the least travel, flipped when that is shorter. A closed piece counts from +its point nearest the nozzle, where `GCode::extrude_loop()` starts it. The two +ends of the fill cost nothing, since the travel to and from them depends on what +is printed before and after. The fill's own extrusions keep their order and +direction, so a monotonic fill stays monotonic. When the result travels no less +than the gap fill printed after the lines in its own order, that order is kept. + ## The search A chain of up to eight paths is found exactly, by dynamic programming over the diff --git a/scripts/create_dmg.sh b/scripts/create_dmg.sh new file mode 100644 index 0000000000..81804b7542 --- /dev/null +++ b/scripts/create_dmg.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# Sourceable helper: `create_dmg ` builds a +# compressed DMG, retrying via `retry` (source retry.sh first). +# hdiutil sizes the image from -srcfolder itself and sometimes leaves too +# little room, failing with "No space left on device" on every attempt. An +# explicit -size of the source plus 20% and 50 MB avoids that; the free space +# compresses away in UDZO. +create_dmg() { + local volname="$1" srcfolder="$2" output="$3" + local src_mb + src_mb=$(( $(du -sk "$srcfolder" | cut -f1) / 1024 )) + retry hdiutil create -volname "$volname" -srcfolder "$srcfolder" \ + -size "$(( src_mb + src_mb / 5 + 50 ))m" -ov -format UDZO "$output" +} diff --git a/src/OrcaSlicer.cpp b/src/OrcaSlicer.cpp index 48ddd16a3b..d125699932 100644 --- a/src/OrcaSlicer.cpp +++ b/src/OrcaSlicer.cpp @@ -6403,10 +6403,16 @@ int CLI::run(int argc, char **argv) continue; // An empty estimate is a plate that prints no tower (one filament and // neither smooth timelapse, wrapping detection nor a raft). - Vec3d wt_pos, wt_size; - plate->estimate_wipe_tower_polygon(m_print_config, index, wt_pos, wt_size); + Vec3d wt_pos, wt_size; + Slic3r::GUI::WipeTowerRelocation relocation; + plate->estimate_wipe_tower_polygon(m_print_config, index, wt_pos, wt_size, 0, false, &relocation); if (wt_size(0) < EPSILON || wt_size(1) < EPSILON) continue; + if (relocation.moved) + BOOST_LOG_TRIVIAL(warning) << boost::format("plate %1%: the wipe tower no longer fits at its saved position {%2%, %3%} and was moved %4%") + % (index + 1) % m_print_config.option("wipe_tower_x", true)->get_at(index) + % m_print_config.option("wipe_tower_y", true)->get_at(index) + % (relocation.overlaps_objects ? "onto an object, as no free space is left" : "to free space"); ConfigOptionFloat wt_x_opt((float) wt_pos(0)); ConfigOptionFloat wt_y_opt((float) wt_pos(1)); m_print_config.option("wipe_tower_x", true)->set_at(&wt_x_opt, index, 0); diff --git a/src/libslic3r/ClipperUtils.cpp b/src/libslic3r/ClipperUtils.cpp index 0b4033ce8f..a3a38ad2cf 100644 --- a/src/libslic3r/ClipperUtils.cpp +++ b/src/libslic3r/ClipperUtils.cpp @@ -415,14 +415,15 @@ Polylines c2_clip_open(C2::ClipType type, const C2::Paths64 &subject, const C2:: } // Clipper1 semantics: miter limit at least 2, arc tolerance (also for round caps) at most a quarter of the offset. -void c2_offset_setup(C2::ClipperOffset &co, float delta, JoinType joinType, double miterLimit) +// Without a round join, a positive capTolerance replaces Clipper1's 0.25 for the round caps. +void c2_offset_setup(C2::ClipperOffset &co, float delta, JoinType joinType, double miterLimit, double capTolerance = 0.) { const double max_arc_tolerance = std::abs(delta) * 0.25; if (joinType == jtRound) co.ArcTolerance(miterLimit > 0. ? std::min(miterLimit, max_arc_tolerance) : 0.25); else { co.MiterLimit(std::max(miterLimit, 2.)); - co.ArcTolerance(std::min(0.25, max_arc_tolerance)); + co.ArcTolerance(std::min(capTolerance > 0. ? capTolerance : 0.25, max_arc_tolerance)); } } @@ -546,7 +547,7 @@ ExPolygons c2_expolygons_offset_ex(const ExPolygonRange &src, float delta, JoinT } template -Polygons c2_offset_lines(PathsProvider &&src, float delta, JoinType joinType, double miterLimit, EndType endType) +Polygons c2_offset_lines(PathsProvider &&src, float delta, JoinType joinType, double miterLimit, EndType endType, double capTolerance = 0.) { C2::Paths64 out; if (endType == etClosedPolygon) { @@ -560,7 +561,7 @@ Polygons c2_offset_lines(PathsProvider &&src, float delta, JoinType joinType, do for (const Points &path : src) append_offset_path(paths, path, shortest, end); C2::ClipperOffset co; - c2_offset_setup(co, delta, joinType, miterLimit); + c2_offset_setup(co, delta, joinType, miterLimit, capTolerance); co.AddPaths(paths, to_c2(joinType), end); co.Execute(delta, out); return c2_to_polygons(out); @@ -616,8 +617,8 @@ Slic3r::Polygons offset(const Slic3r::Polyline3 &polyline, const float delta, Jo assert(delta > 0); return c2_offset_lines(ClipperUtils::SinglePathProvider(polyline.to_polyline().points), delta, joinType, miterLimit, end_type); } -Slic3r::Polygons offset(const Slic3r::Polylines &polylines, const float delta, JoinType joinType, double miterLimit, EndType end_type) - { assert(delta > 0); return c2_offset_lines(ClipperUtils::PolylinesProvider(polylines), delta, joinType, miterLimit, end_type); } +Slic3r::Polygons offset(const Slic3r::Polylines &polylines, const float delta, JoinType joinType, double miterLimit, EndType end_type, double cap_tolerance) + { assert(delta > 0); return c2_offset_lines(ClipperUtils::PolylinesProvider(polylines), delta, joinType, miterLimit, end_type, cap_tolerance); } Polygons contour_to_polygons(const Polygon &polygon, const float line_width, JoinType join_type, double miter_limit) { assert(line_width > 1.f); return c2_offset_lines(ClipperUtils::SinglePathProvider(polygon.points), line_width / 2, join_type, miter_limit, etClosedLine); } diff --git a/src/libslic3r/ClipperUtils.hpp b/src/libslic3r/ClipperUtils.hpp index 43904ff4b4..4e09eaaf58 100644 --- a/src/libslic3r/ClipperUtils.hpp +++ b/src/libslic3r/ClipperUtils.hpp @@ -358,7 +358,8 @@ Slic3r::Polygons offset(const Slic3r::Polygon &polygon, const float delta, JoinT // Input polygons for negative offset shall be "normalized": There must be no overlap / intersections between the input polygons. Slic3r::Polygons offset(const Slic3r::Polyline &polyline, const float delta, JoinType joinType = DefaultLineJoinType, double miterLimit = DefaultLineMiterLimit, EndType end_type = DefaultEndType); Slic3r::Polygons offset(const Slic3r::Polyline3 &polyline, const float delta, JoinType joinType = DefaultLineJoinType, double miterLimit = DefaultLineMiterLimit, EndType end_type = DefaultEndType); -Slic3r::Polygons offset(const Slic3r::Polylines &polylines, const float delta, JoinType joinType = DefaultLineJoinType, double miterLimit = DefaultLineMiterLimit, EndType end_type = DefaultEndType); +// cap_tolerance: the arc tolerance of round end caps when joinType is not jtRound, 0 for the default. +Slic3r::Polygons offset(const Slic3r::Polylines &polylines, const float delta, JoinType joinType = DefaultLineJoinType, double miterLimit = DefaultLineMiterLimit, EndType end_type = DefaultEndType, double cap_tolerance = 0.); Slic3r::Polygons offset(const Slic3r::Polygons &polygons, const float delta, JoinType joinType = DefaultJoinType, double miterLimit = DefaultMiterLimit); Slic3r::Polygons offset(const Slic3r::ExPolygon &expolygon, const float delta, JoinType joinType = DefaultJoinType, double miterLimit = DefaultMiterLimit); Slic3r::Polygons offset(const Slic3r::ExPolygons &expolygons, const float delta, JoinType joinType = DefaultJoinType, double miterLimit = DefaultMiterLimit); diff --git a/src/libslic3r/Fill/Fill3DHoneycomb.cpp b/src/libslic3r/Fill/Fill3DHoneycomb.cpp index 3612608301..d810bb671e 100644 --- a/src/libslic3r/Fill/Fill3DHoneycomb.cpp +++ b/src/libslic3r/Fill/Fill3DHoneycomb.cpp @@ -400,10 +400,9 @@ void Fill3DHoneycomb::_fill_surface_single( // move pattern in place for (Polyline &pl : polylines){ pl.translate(bb.min); - pl.simplify(5 * spacing); // simplify to 5x line width // Orca: round the corners of the octahedral wave. The layers where the wave degenerates to a // straight line have no corner to round. - smooth_polyline_corners(pl, params.smooth_factor, scaled(params.resolution)); + smooth_polyline_corners(pl, params.corner_smoothing()); } // Note: multiline fill adjustment is carried out in this code, diff --git a/src/libslic3r/Fill/FillBase.cpp b/src/libslic3r/Fill/FillBase.cpp index 7a2aee3f7f..6338bc3208 100644 --- a/src/libslic3r/Fill/FillBase.cpp +++ b/src/libslic3r/Fill/FillBase.cpp @@ -228,6 +228,79 @@ void Fill::fill_surface_extrusion(const Surface* surface, const FillParams& para } } +// Orca: port of Bambu Studio's gap fill interleaving for fills printed in a fixed order, see docs/HLSD/travel-optimization.md. +static void insert_gap_fill(const ThickPolylines &gaps, const Flow &flow, ExtrusionEntitiesPtr &entities) +{ + if (entities.empty()) { + variable_width(gaps, erGapFill, flow, entities); + return; + } + static constexpr size_t npos = size_t(-1); + // An extrusion of the fill, or gaps[gap], with the points where the nozzle enters and leaves it. + struct Item { Point in, out; size_t gap; bool reversed; }; + auto distance = [](const Point &a, const Point &b) { return (b - a).cast().norm(); }; + auto closed = [&gaps](size_t gap) { return gaps[gap].first_point() == gaps[gap].last_point(); }; + // GCode::extrude_loop starts a loop at its point nearest the nozzle. + auto travel = [&](const std::vector &seq) { + double sum = 0.; + Point at = seq.front().out; + for (auto it = seq.begin() + 1; it != seq.end(); ++ it) { + const Point in = it->gap != npos && closed(it->gap) ? *gaps[it->gap].closest_point(at) : it->in; + sum += distance(at, in); + at = it->gap != npos && closed(it->gap) ? in : it->out; + } + return sum; + }; + + std::vector items, appended; + items.reserve(entities.size() + gaps.size()); + for (const ExtrusionEntity *ee : entities) + items.push_back({ ee->first_point(), ee->last_point(), npos, false }); + appended = items; + for (size_t gap = 0; gap < gaps.size(); ++ gap) { + appended.push_back({ gaps[gap].first_point(), gaps[gap].last_point(), gap, false }); + double best = std::numeric_limits::max(); + size_t best_slot = 0; + Item best_item{}; + for (size_t slot = 0; slot <= items.size(); ++ slot) { + const Point *prev = slot > 0 ? &items[slot - 1].out : nullptr; + const Point *next = slot < items.size() ? &items[slot].in : nullptr; + auto consider = [&](const Point &in, const Point &out, bool reversed) { + const double added = (prev ? distance(*prev, in) : 0.) + (next ? distance(out, *next) : 0.) - (prev && next ? distance(*prev, *next) : 0.); + if (added < best) { + best = added; + best_slot = slot; + best_item = { in, out, gap, reversed }; + } + }; + if (closed(gap)) { + const Point &entry = *gaps[gap].closest_point(prev ? *prev : *next); + consider(entry, entry, false); + } else { + consider(gaps[gap].first_point(), gaps[gap].last_point(), false); + consider(gaps[gap].last_point(), gaps[gap].first_point(), true); + } + } + items.insert(items.begin() + best_slot, best_item); + } + if (travel(appended) <= travel(items)) + items = std::move(appended); + + ExtrusionEntitiesPtr out; + out.reserve(entities.size() + gaps.size()); + size_t next_entity = 0; + for (const Item &item : items) + if (item.gap == npos) + out.push_back(entities[next_entity ++]); + else { + ThickPolylines gap { gaps[item.gap] }; + if (item.reversed) + gap.front().reverse(); + variable_width(gap, erGapFill, flow, out); + } + entities = std::move(out); +} + // Orca: Dedicated function to calculate gap fill lines for the provided surface, according to the print object parameters // and append them to the out ExtrusionEntityCollection. void Fill::_create_gap_fill(const Surface* surface, const FillParams& params, ExtrusionEntityCollection* out){ @@ -277,7 +350,10 @@ void Fill::_create_gap_fill(const Surface* surface, const FillParams& params, Ex return p.length() < scale_(params.config->filter_out_gap_fill.value); }), polylines.end()); - variable_width(polylines, erGapFill, params.flow, out->entities); + if (out->no_sort) + insert_gap_fill(polylines, params.flow, out->entities); + else + variable_width(polylines, erGapFill, params.flow, out->entities); } } } @@ -2913,8 +2989,8 @@ void multiline_fill(Polylines& polylines, const FillParams& params, float spacin } const float delta = float(scale_(t)); - // Arc tolerance of 1/500 of the offset, Clipper2's default. - for (const Polygon &ring : offset(polylines, delta, jtMiter, 0.002 * delta, etOpenRound)) + // Mitered corners keep the lines parallel; the round end caps take 1/500 of the offset, Clipper2's default. + for (const Polygon &ring : offset(polylines, delta, jtMiter, DefaultMiterLimit, etOpenRound, 0.002 * delta)) if (ring.size() >= 3) all_polylines.emplace_back(ring.split_at_first_point()); } diff --git a/src/libslic3r/Fill/FillBase.hpp b/src/libslic3r/Fill/FillBase.hpp index f60fde6d1d..4711192999 100644 --- a/src/libslic3r/Fill/FillBase.hpp +++ b/src/libslic3r/Fill/FillBase.hpp @@ -24,6 +24,7 @@ #include "../PrintConfig.hpp" #include "../Flow.hpp" #include "../ExtrusionEntity.hpp" +#include "FillCornerSmoothing.hpp" #include "libslic3r/Polyline.hpp" #include "libslic3r/Polygon.hpp" #include "libslic3r/Point.hpp" @@ -99,6 +100,8 @@ struct FillParams // Orca: corner smoothing factor in the range [0, 1]. double smooth_factor { 0. }; + // The corner smoothing in scaled coordinates. + CornerSmoothing corner_smoothing() const { return CornerSmoothing{smooth_factor, scaled(resolution)}; } // For Lateral lattice coordf_t lateral_lattice_angle_1 { 0.f }; diff --git a/src/libslic3r/Fill/FillConcentric.cpp b/src/libslic3r/Fill/FillConcentric.cpp index f112d6243a..dff2e654e5 100644 --- a/src/libslic3r/Fill/FillConcentric.cpp +++ b/src/libslic3r/Fill/FillConcentric.cpp @@ -73,8 +73,7 @@ void FillConcentric::_fill_surface_single( } return true; }; - smooth_polygons_corners(loops, params.smooth_factor, scaled(params.resolution), 0.5 * distance, - corner_stays_inside); + smooth_polygons_corners(loops, params.corner_smoothing(), 0.5 * distance, corner_stays_inside); // generate paths from the outermost to the innermost, to avoid // adhesion problems of the first central tiny loops diff --git a/src/libslic3r/Fill/FillCornerSmoothing.cpp b/src/libslic3r/Fill/FillCornerSmoothing.cpp index f87de98293..f8af0a59d6 100644 --- a/src/libslic3r/Fill/FillCornerSmoothing.cpp +++ b/src/libslic3r/Fill/FillCornerSmoothing.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -18,104 +19,176 @@ namespace Slic3r { // coincide, so the corner would be rounded into a degenerate loop instead of a hairpin. static constexpr const double min_smoothed_turn_cosine = -0.9; -// The control points are expressed in the (incoming, outgoing) basis of the corner, which is not -// orthonormal for turns other than a right angle. -using QuinticBezier = std::array; +// Spacing of the control points of the corner curve along each leg, as a fraction of the reach. +static constexpr const double control_spacing = 0.3; -static bool is_bezier_flat(const QuinticBezier &curve, const Vec2d &incoming, const Vec2d &outgoing, const double deviation) +// Bounds the vertices of a corner whatever the tolerance. +static constexpr const size_t max_corner_vertices = 256; +// Bounds the corners a smoother keeps, for paths turning by ever new angles. +static constexpr const size_t max_cached_corners = 4096; + +// The control points of the quintic Bezier corner curve. +using ControlPoints = std::array; + +// The control points of the corner curve in a frame where the incoming leg runs along +x into the corner at +// the origin and the outgoing leg leaves it turning left. At each end, the first three control points are +// collinear and equally spaced: the tangent follows the adjoining leg and the second derivative is zero, +// so the curvature starts from zero and the toolhead eases into the turn. +static ControlPoints bezier_control_points(const double reach, const Vec2d &outgoing) { - // A Bezier curve stays inside the convex hull of its control points. Therefore, keeping every - // control point within a deviation-wide strip around the endpoint chord conservatively bounds the - // flattening error. The cross product is the perpendicular distance scaled by the chord length; - // comparing squared values avoids a square root. - auto in_plane = [&incoming, &outgoing](const Vec2d &c) { return c.x() * incoming + c.y() * outgoing; }; - const Vec2d chord = in_plane(curve.back() - curve.front()); - const double chord_length_sq = chord.squaredNorm(); - const double max_cross_sq = deviation * deviation * chord_length_sq; - - for (size_t i = 1; i + 1 < curve.size(); ++i) { - const Vec2d offset = in_plane(curve[i] - curve.front()); - const double cross = chord.x() * offset.y() - chord.y() * offset.x(); - if (cross * cross > max_cross_sq) - return false; - } - return true; + const double spacing = control_spacing * reach; + return { Vec2d(-reach, 0.), Vec2d(-(reach - spacing), 0.), Vec2d(-(reach - 2. * spacing), 0.), + (reach - 2. * spacing) * outgoing, (reach - spacing) * outgoing, reach * outgoing }; } -static void subdivide_bezier(const QuinticBezier &curve, QuinticBezier &left, QuinticBezier &right) +// The first and second derivatives of the curve, by de Casteljau down to its last three points. +static std::pair bezier_derivatives(const ControlPoints &control, const double t) { - // Split the curve at t = 0.5 using de Casteljau's algorithm. Each averaging level contributes one - // control point to the left half and one to the right half; the latter is filled backwards to keep - // both resulting control polygons in their original parameter direction. - QuinticBezier subdivision = curve; - left.front() = subdivision.front(); - right.back() = subdivision.back(); - for (size_t level = 1; level < curve.size(); ++level) { - for (size_t i = 0; i + level < curve.size(); ++i) - subdivision[i] = 0.5 * (subdivision[i] + subdivision[i + 1]); - left[level] = subdivision.front(); - right[curve.size() - level - 1] = subdivision[curve.size() - level - 1]; - } + ControlPoints work = control; + for (size_t count = work.size(); count > 3; --count) + for (size_t i = 0; i + 1 < count; ++i) + work[i] = (1. - t) * work[i] + t * work[i + 1]; + const double degree = double(work.size() - 1); + return { degree * ((1. - t) * (work[1] - work[0]) + t * (work[2] - work[1])), + degree * (degree - 1.) * (work[2] - 2. * work[1] + work[0]) }; } -static void flatten_bezier( - const QuinticBezier &curve, const Vec2d &incoming, const Vec2d &outgoing, const double deviation, std::vector &output) +static Vec2d bezier_point(const ControlPoints &control, const double t) { - // Subdivide to at least depth 1 so a rounded corner cannot collapse to a single diagonal chord. - // A uniform subdivision depth keeps samples at equal parameter intervals t = k / 2^depth, - // avoiding abrupt segment-length jumps at adaptive-depth boundaries. - static constexpr size_t max_depth = 16; + ControlPoints work = control; + for (size_t count = work.size(); count > 1; --count) + for (size_t i = 0; i + 1 < count; ++i) + work[i] = (1. - t) * work[i] + t * work[i + 1]; + return work.front(); +} - std::vector subcurves(2); - subdivide_bezier(curve, subcurves[0], subcurves[1]); +// A rounded corner of unit reach: its vertices in the (incoming, outgoing) basis of the corner, relative to it, +// and how far they stray from the curve. +struct UnitCorner +{ + std::vector vertices; + double deviation { 0. }; +}; - for (size_t depth = 1; depth < max_depth; ++depth) { - bool all_flat = true; - for (const QuinticBezier &c : subcurves) - if (!is_bezier_flat(c, incoming, outgoing, deviation)) { - all_flat = false; +// The corner shapes built on a thread. They depend on the turn and the vertex count only, so all the smoothers of +// the thread share them: some fills start a smoother for every path, and every layer starts its own. +struct CornerShapes +{ + std::map, UnitCorner> corners; + std::map peak_curvatures; +}; +static thread_local CornerShapes corner_shapes; + +// The peak curvature of the corner curve times its reach, which depends on the turn only. +static double peak_curvature_by_reach(const double cosine) +{ + std::map &cache = corner_shapes.peak_curvatures; + if (const auto it = cache.find(cosine); it != cache.end()) + return it->second; + + const double turn = std::acos(std::clamp(cosine, -1., 1.)); + const ControlPoints control = bezier_control_points(1., Vec2d(cosine, std::sin(turn))); + static constexpr const size_t samples = 256; + double peak = 0.; + for (size_t i = 0; i <= samples; ++i) { + const auto [first, second] = bezier_derivatives(control, double(i) / double(samples)); + const double speed = first.norm(); + if (speed > EPSILON) + peak = std::max(peak, std::abs(cross2(first, second)) / (speed * speed * speed)); + } + if (cache.size() >= max_cached_corners) + cache.clear(); + cache.emplace(cosine, peak); + return peak; +} + +// The polygon of `count` vertices of the corner of unit reach, and how far it strays from the curve. +static double tangent_polygon(const double cosine, const size_t count, std::vector &vertices) +{ + const double turn = std::acos(std::clamp(cosine, -1., 1.)); + const double sine = std::sin(turn); + const Vec2d outgoing(cosine, sine); + + // The lines tangent to the curve at equal steps of direction, both legs included, and halfway between them. + // Each vertex of the rounded corner is where two consecutive steps cross, so each turns by the same step. + std::vector> tangents; + tangents.reserve(2 * count + 1); + tangents.emplace_back(Vec2d(-1., 0.), Vec2d(1., 0.)); + const ControlPoints control = bezier_control_points(1., outgoing); + double from = 0.; + for (size_t i = 1; i < 2 * count; ++i) { + // The direction of the tangent grows monotonically along the curve, so Newton steps on it converge + // within the bracket of the parameter; a step leaving the bracket is replaced by a bisection. + const double angle = 0.5 * turn * double(i) / double(count); + double low = from, high = 1., t = 0.5 * (low + high); + for (int iteration = 0; iteration < 64 && high - low > 1e-15; ++iteration) { + const auto [first, second] = bezier_derivatives(control, t); + const double error = std::atan2(first.y(), first.x()) - angle; + if (std::abs(error) < 1e-14) break; - } - if (all_flat) - break; - std::vector finer(subcurves.size() * 2); - for (size_t i = 0; i < subcurves.size(); ++i) - subdivide_bezier(subcurves[i], finer[i * 2], finer[i * 2 + 1]); - subcurves = std::move(finer); + if (error < 0.) + low = t; + else + high = t; + const double rate = cross2(first, second) / first.squaredNorm(); + const double next = rate > 0. ? t - error / rate : low; + t = next > low && next < high ? next : 0.5 * (low + high); + } + from = low; + tangents.emplace_back(bezier_point(control, t), bezier_derivatives(control, t).first.normalized()); } + tangents.emplace_back(outgoing, outgoing); - // The curve start is deliberately omitted so it can be shared with the straight leg feeding into it. - output.clear(); - output.reserve(subcurves.size()); - for (const QuinticBezier &c : subcurves) - output.emplace_back(c.back()); + vertices.clear(); + vertices.reserve(count); + double deviation = 0.; + for (size_t i = 0; i < count; ++i) { + const auto &[point, direction] = tangents[2 * i]; + const auto &[next_point, next_direction] = tangents[2 * i + 2]; + const Vec2d vertex = point + (cross2(next_point - point, next_direction) / cross2(direction, next_direction)) * direction; + // The curve passes closest to the vertex about where it heads halfway between the two tangents. + deviation = std::max(deviation, (vertex - tangents[2 * i + 1].first).norm()); + // In the (incoming, outgoing) basis, which is not orthonormal for turns other than a right angle. + const double along_outgoing = vertex.y() / sine; + vertices.emplace_back(vertex.x() - along_outgoing * cosine, along_outgoing); + } + return deviation; } -const std::vector& CornerSmoother::curve_coefficients( - const double corner_distance, const Vec2d &incoming, const Vec2d &outgoing) +// Valid until the next corner of the thread is built. +static const UnitCorner &unit_corner(const double cosine, const size_t count) { - const double cosine = incoming.dot(outgoing); - // Corners of the same size and turn angle are congruent, so they flatten identically. An infill - // path walks over the very same corner over and over again, the Hilbert curve over a single one. - if (m_has_cached_coefficients && corner_distance == m_cached_distance && cosine == m_cached_cosine) - return m_cached_coefficients; + std::map, UnitCorner> &cache = corner_shapes.corners; + const std::pair key(cosine, count); + if (const auto it = cache.find(key); it != cache.end()) + return it->second; + if (cache.size() >= max_cached_corners) + cache.clear(); + UnitCorner corner; + corner.deviation = tangent_polygon(cosine, count, corner.vertices); + return cache.emplace(key, std::move(corner)).first->second; +} - // One canonical corner running from -corner_distance along the incoming leg to corner_distance - // along the outgoing one. At each end, the first three control points are collinear and equally - // spaced: the tangent follows the adjoining straight leg and the second derivative is zero. The - // endpoint curvature is therefore zero, giving G2 joins to both legs. - const double d = corner_distance; - const QuinticBezier corner_curve {{ - {-d, 0.}, {-0.7 * d, 0.}, {-0.4 * d, 0.}, {0., 0.4 * d}, {0., 0.7 * d}, {0., d} - }}; - // Retain a finite positive tolerance if the smoother was set up with an invalid one. - const double deviation = m_tolerance > 0. && std::isfinite(m_tolerance) ? m_tolerance : EPSILON; - flatten_bezier(corner_curve, incoming, outgoing, deviation, m_cached_coefficients); - - m_cached_distance = corner_distance; - m_cached_cosine = cosine; - m_has_cached_coefficients = true; - return m_cached_coefficients; +const std::vector *CornerSmoother::corner_vertices(const double reach, const double cosine) const +{ + const double tolerance = m_smoothing.tolerance > 0. && std::isfinite(m_smoothing.tolerance) ? m_smoothing.tolerance : EPSILON; + const double turn = std::acos(std::clamp(cosine, -1., 1.)); + const double curvature = peak_curvature_by_reach(cosine) / reach; + // Simplifying the path to the tolerance drops a vertex standing out of the chord of its neighbours by less, + // which the sharpest vertex of the curve does at finer steps than this. + const size_t most = size_t(std::min(double(max_corner_vertices), turn / std::sqrt(2. * curvature * tolerance))); + // The count an arc of the peak curvature takes; the flatter parts of the curve may need more. + size_t count = std::min(most, size_t(std::ceil(turn / std::sqrt(8. * curvature * tolerance) - EPSILON))); + if (count < 2) + return nullptr; + for (;;) { + const double deviation = reach * unit_corner(cosine, count).deviation; + if (deviation <= tolerance || count >= most) + break; + // The deviation falls about with the square of the count. + count = std::min(most, std::max(count + 1, size_t(std::ceil(double(count) * std::sqrt(deviation / tolerance))))); + } + return &unit_corner(cosine, count).vertices; } bool CornerSmoother::is_on_straight_run(const Vec2d &previous, const Vec2d &vertex, const Vec2d &next) @@ -150,29 +223,28 @@ void CornerSmoother::round_corner(const Vec2d &previous, const Vec2d &corner, co const Vec2d incoming = incoming_leg / incoming_length; const Vec2d outgoing = outgoing_leg / outgoing_length; const double cross = incoming.x() * outgoing.y() - incoming.y() * outgoing.x(); + // Snapped, so that the corners of one turn share the cached shapes whatever rounding their legs carry. + const double cosine = std::round(incoming.dot(outgoing) * 1e12) * 1e-12; // A collinear vertex is no corner at all, and a hairpin cannot be rounded, see above. - if (std::abs(cross) < EPSILON || incoming.dot(outgoing) < min_smoothed_turn_cosine) { + if (std::abs(cross) < EPSILON || cosine < min_smoothed_turn_cosine) { m_corner_points.emplace_back(corner); return; } // Consuming at most half of the shorter leg keeps the curves of two adjacent corners apart. - double corner_distance = m_corner_distance_ratio * std::min(incoming_length, outgoing_length); + double reach = m_corner_distance_ratio * std::min(incoming_length, outgoing_length); if (m_max_corner_distance > 0.) - corner_distance = std::min(corner_distance, m_max_corner_distance); + reach = std::min(reach, m_max_corner_distance); - const Vec2d curve_start = corner - corner_distance * incoming; - const Vec2d curve_end = corner + corner_distance * outgoing; - if (m_corner_filter && !m_corner_filter(curve_start, curve_end)) { + const std::vector *vertices = corner_vertices(reach, cosine); + if (vertices == nullptr || (m_corner_filter && !m_corner_filter(corner - reach * incoming, corner + reach * outgoing))) { m_corner_points.emplace_back(corner); return; } - const std::vector &coefficients = curve_coefficients(corner_distance, incoming, outgoing); - m_corner_points.reserve(coefficients.size() + 1); - m_corner_points.emplace_back(curve_start); - for (const Vec2d &coefficient : coefficients) - m_corner_points.emplace_back(corner + coefficient.x() * incoming + coefficient.y() * outgoing); + m_corner_points.reserve(vertices->size()); + for (const Vec2d &vertex : *vertices) + m_corner_points.emplace_back(corner + reach * (vertex.x() * incoming + vertex.y() * outgoing)); } // Rounds the corners of a scaled point sequence. A polygon closes implicitly, so all of its vertices @@ -209,31 +281,31 @@ static Points smooth_corners(const Points &points, const bool polygon, CornerSmo return smoothed; } -void smooth_polyline_corners(Polyline &polyline, const double smooth_factor, const double tolerance, - const double max_corner_distance, const CornerFilter &corner_filter) +void smooth_polyline_corners(Polyline &polyline, const CornerSmoothing &smoothing, const double max_corner_distance, + const CornerFilter &corner_filter) { - CornerSmoother smoother(smooth_factor, tolerance, max_corner_distance, corner_filter); + CornerSmoother smoother(smoothing, max_corner_distance, corner_filter); if (!smoother.enabled() || polyline.size() < 3) return; polyline.points = smooth_corners(polyline.points, false, smoother); - // Rounding back to the integer grid may collapse neighbouring samples of a curve. + // Rounding back to the integer grid may collapse neighbouring vertices of a corner. polyline.remove_duplicate_points(); } -void smooth_polylines_corners(Polylines &polylines, const double smooth_factor, const double tolerance, - const double max_corner_distance, const CornerFilter &corner_filter) +void smooth_polylines_corners(Polylines &polylines, const CornerSmoothing &smoothing, const double max_corner_distance, + const CornerFilter &corner_filter) { - if (sanitize_smooth_factor(smooth_factor) == 0.) + if (sanitize_smooth_factor(smoothing.factor) == 0.) return; for (Polyline &polyline : polylines) - smooth_polyline_corners(polyline, smooth_factor, tolerance, max_corner_distance, corner_filter); + smooth_polyline_corners(polyline, smoothing, max_corner_distance, corner_filter); } -void smooth_polygons_corners(Polygons &polygons, const double smooth_factor, const double tolerance, - const double max_corner_distance, const CornerFilter &corner_filter) +void smooth_polygons_corners(Polygons &polygons, const CornerSmoothing &smoothing, const double max_corner_distance, + const CornerFilter &corner_filter) { - CornerSmoother smoother(smooth_factor, tolerance, max_corner_distance, corner_filter); + CornerSmoother smoother(smoothing, max_corner_distance, corner_filter); if (!smoother.enabled()) return; @@ -242,8 +314,8 @@ void smooth_polygons_corners(Polygons &polygons, const double smooth_factor, con continue; polygon.points = smooth_corners(polygon.points, true, smoother); polygon.remove_duplicate_points(); - // The curves of the first and of the last corner may have met on the segment they share. A - // polygon closes implicitly, so it must not repeat its first vertex at the end. + // The vertices of the first and of the last corner may meet on the leg they share. A polygon closes + // implicitly, so it must not repeat its first vertex at the end. if (polygon.points.size() > 1 && polygon.points.front() == polygon.points.back()) polygon.points.pop_back(); } diff --git a/src/libslic3r/Fill/FillCornerSmoothing.hpp b/src/libslic3r/Fill/FillCornerSmoothing.hpp index b6acf20049..195283e641 100644 --- a/src/libslic3r/Fill/FillCornerSmoothing.hpp +++ b/src/libslic3r/Fill/FillCornerSmoothing.hpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -19,29 +20,39 @@ inline double sanitize_smooth_factor(double smooth_factor) return std::isfinite(smooth_factor) ? std::clamp(smooth_factor, 0., 1.) : 0.; } +// Orca: How the corners of an infill path are rounded. The tolerance is in the units of the points the smoother is fed. +struct CornerSmoothing +{ + // Fraction of the shorter adjoining leg a curve may reach along it, relative to half of that leg. + double factor { 0. }; + // The G-code resolution: a rounded corner keeps within it of its curve, and its vertices stand out of the + // path by at least it, so that simplifying the path to it keeps them. + double tolerance { 0. }; +}; + // Decides whether a corner may be replaced by the curve that leaves the path at `from` and rejoins it // at `to`, both in the coordinate system of the pushed points. Rounding cuts toward the inside of the // turn, so a path that is not clipped to the fill region afterwards needs this to stay inside it. using CornerFilter = std::function; -// Orca: Replaces the sharp vertices of an infill path with curves that join the adjoining straight -// legs with a continuous curvature, so the toolhead does not have to stop in every corner. -// Points are pushed one by one, because the plane path fills produce their path on the fly, and -// every point of the smoothed path is handed over to the caller supplied emit callback. -// Fully smoothed adjacent corners meet at the midpoint of the segment they share, so the emitted -// points may collapse onto each other once rounded to the integer grid of the caller. Dropping such -// duplicates is left to the caller, which is the only one knowing that grid. +// Orca: Replaces the sharp vertices of an infill path with curves joining the adjoining straight legs, so the +// toolhead does not have to slow down to a stop in every corner. A curve is printed as the polygon of its +// tangents taken at equal steps of direction, so every vertex of a rounded corner turns by the same angle: +// a planner limits the speed at a vertex by how much it turns, and equal turns make the most of each vertex. +// Points are pushed one by one, because the plane path fills produce their path on the fly, and every point +// of the smoothed path is handed over to the caller supplied emit callback. Points that collapse onto each +// other once rounded to the integer grid of the caller are left to the caller to drop. class CornerSmoother { public: - // tolerance is the maximum chordal deviation of the flattened curves, in the units of the pushed - // points. max_corner_distance caps how far a curve may reach along a leg, in the same units; it - // bounds how far a rounded corner moves away from the original path, which matters where the legs - // are much longer than the spacing of the pattern. Zero leaves the reach uncapped. - CornerSmoother(double smooth_factor, double tolerance, double max_corner_distance = 0., - CornerFilter corner_filter = {}) - : m_corner_distance_ratio(0.5 * sanitize_smooth_factor(smooth_factor)), m_tolerance(tolerance), - m_max_corner_distance(max_corner_distance), m_corner_filter(std::move(corner_filter)) + // max_corner_distance caps how far a curve may reach along a leg, in the units of the pushed points; it + // bounds how far a rounded corner moves away from the original path, which matters where the legs are + // much longer than the spacing of the pattern. Zero leaves the reach uncapped. + CornerSmoother(const CornerSmoothing &smoothing, double max_corner_distance = 0., CornerFilter corner_filter = {}) + : m_smoothing(smoothing) + , m_corner_distance_ratio(0.5 * sanitize_smooth_factor(smoothing.factor)) + , m_max_corner_distance(max_corner_distance) + , m_corner_filter(std::move(corner_filter)) {} bool enabled() const { return m_corner_distance_ratio > 0.; } @@ -93,22 +104,17 @@ private: static bool is_on_straight_run(const Vec2d &previous, const Vec2d &vertex, const Vec2d &next); // Fills m_corner_points with the points replacing the corner vertex. void round_corner(const Vec2d &previous, const Vec2d &corner, const Vec2d &next); - // Flattens the canonical corner curve of the given size and turn into coordinates of the - // (incoming, outgoing) basis of the corner. Cached, as an infill path repeats the same corner. - const std::vector& curve_coefficients(double corner_distance, const Vec2d &incoming, const Vec2d &outgoing); + // The vertices of the rounded corner of unit reach in the (incoming, outgoing) basis of the corner, relative to it, + // or none if the sharp corner keeps within the tolerance. A corner of another reach is this one scaled. + const std::vector *corner_vertices(double reach, double cosine) const; + const CornerSmoothing m_smoothing; // Fraction of the shorter adjoining leg consumed on each side of a corner. Half of a leg is the // maximum, otherwise the curves of two adjacent corners would overlap. const double m_corner_distance_ratio; - const double m_tolerance; const double m_max_corner_distance; const CornerFilter m_corner_filter; std::vector m_corner_points; - // Cached flattening of the last corner, valid for corners of the same size and turn angle. - std::vector m_cached_coefficients; - double m_cached_distance { 0. }; - double m_cached_cosine { 0. }; - bool m_has_cached_coefficients { false }; // The corners seen last, kept free of vertices that merely split a straight leg. The middle one // is rounded once the third arrives, which is what makes its outgoing leg final. @@ -120,12 +126,12 @@ private: // Rounds the corners of already scaled paths in place. Paths of less than three points are left alone. // Both ends of a polyline are kept where they are, even when they coincide: such a path retraces its // way back and joining its ends would turn it into a loop. See CornerSmoother for max_corner_distance. -void smooth_polyline_corners(Polyline &polyline, double smooth_factor, double tolerance, - double max_corner_distance = 0., const CornerFilter &corner_filter = {}); -void smooth_polylines_corners(Polylines &polylines, double smooth_factor, double tolerance, - double max_corner_distance = 0., const CornerFilter &corner_filter = {}); +void smooth_polyline_corners(Polyline &polyline, const CornerSmoothing &smoothing, double max_corner_distance = 0., + const CornerFilter &corner_filter = {}); +void smooth_polylines_corners(Polylines &polylines, const CornerSmoothing &smoothing, double max_corner_distance = 0., + const CornerFilter &corner_filter = {}); // Polygons close implicitly, so every one of their vertices is a corner. -void smooth_polygons_corners(Polygons &polygons, double smooth_factor, double tolerance, - double max_corner_distance = 0., const CornerFilter &corner_filter = {}); +void smooth_polygons_corners(Polygons &polygons, const CornerSmoothing &smoothing, double max_corner_distance = 0., + const CornerFilter &corner_filter = {}); } // namespace Slic3r diff --git a/src/libslic3r/Fill/FillCrossHatch.cpp b/src/libslic3r/Fill/FillCrossHatch.cpp index 79ca4743d9..a77bbaf021 100644 --- a/src/libslic3r/Fill/FillCrossHatch.cpp +++ b/src/libslic3r/Fill/FillCrossHatch.cpp @@ -214,7 +214,7 @@ void FillCrossHatch ::_fill_surface_single( for (Polyline &pl : polylines) { pl.translate(bb.min); } // Orca: round the corners of the transition layers. The repeat layers are straight lines and stay as they are. - smooth_polylines_corners(polylines, params.smooth_factor, scaled(params.resolution)); + smooth_polylines_corners(polylines, params.corner_smoothing()); // Apply multiline offset if needed multiline_fill(polylines, params, spacing); diff --git a/src/libslic3r/Fill/FillHoneycomb.cpp b/src/libslic3r/Fill/FillHoneycomb.cpp index c9337074f7..3d2c4ae62c 100644 --- a/src/libslic3r/Fill/FillHoneycomb.cpp +++ b/src/libslic3r/Fill/FillHoneycomb.cpp @@ -79,10 +79,9 @@ void FillHoneycomb::_fill_surface_single( x += m.distance; } p.rotate(-direction.first, m.hex_center); - p.simplify(5 * spacing); // simplify to 5x line width // Orca: round the corners of the honeycomb cells. Done before the clipping, so that the // curves are cut by the region boundary just like the sharp path would be. - smooth_polyline_corners(p, params.smooth_factor, scaled(params.resolution)); + smooth_polyline_corners(p, params.corner_smoothing()); all_polylines.push_back(p); } } diff --git a/src/libslic3r/Fill/FillLightning.cpp b/src/libslic3r/Fill/FillLightning.cpp index a81ef31586..6bd5172db8 100644 --- a/src/libslic3r/Fill/FillLightning.cpp +++ b/src/libslic3r/Fill/FillLightning.cpp @@ -36,7 +36,7 @@ void Filler::_fill_surface_single( const double branch_width = scaled(this->spacing) * params.multiline; const double branch_spacing = branch_width / std::max(double(params.density), EPSILON); const double max_reach = 0.5 * (params.multiline > 1 ? branch_width : branch_spacing); - smooth_polylines_corners(fill_lines, params.smooth_factor, scaled(params.resolution), max_reach); + smooth_polylines_corners(fill_lines, params.corner_smoothing(), max_reach); // Apply multiline offset if needed multiline_fill(fill_lines, params, spacing); diff --git a/src/libslic3r/Fill/FillPlanePath.cpp b/src/libslic3r/Fill/FillPlanePath.cpp index 4e967affa4..5ae254f8e6 100644 --- a/src/libslic3r/Fill/FillPlanePath.cpp +++ b/src/libslic3r/Fill/FillPlanePath.cpp @@ -308,8 +308,8 @@ template class SmoothingPolylineOutput { public: - SmoothingPolylineOutput(Output &output, const double smooth_factor, const double tolerance) - : m_output(output), m_smoother(smooth_factor, tolerance) {} + SmoothingPolylineOutput(Output &output, const CornerSmoothing &smoothing) + : m_output(output), m_smoother(smoothing) {} void reserve(size_t n) { m_output.reserve(n); } void add_point(const Vec2d &pt) { auto emit = emitter(); m_smoother.push(pt, emit); } @@ -317,8 +317,8 @@ public: void finish() { auto emit = emitter(); m_smoother.flush(emit); } private: - // The curves of two adjacent corners meet at the midpoint of the segment they share, where they - // may round to the very same output point. Drop those, they would be zero length extrusions. + // Close vertices of a rounded corner may round to the very same output point. Drop those, they + // would be zero length extrusions. auto emitter() { return [this](const Vec2d &pt) { @@ -342,14 +342,15 @@ private: template static void generate_path(InfillPolylineOutput &output, const FillParams ¶ms, const double resolution, GenerateFn generate) { - const double smooth_factor = sanitize_smooth_factor(params.smooth_factor); - auto run = [smooth_factor, resolution, &generate](auto &out) { - if (smooth_factor == 0.) { + // The path runs in units of the line spacing, as the resolution passed in does. + const CornerSmoothing smoothing{ params.smooth_factor, resolution }; + auto run = [&smoothing, &generate](auto &out) { + if (sanitize_smooth_factor(smoothing.factor) == 0.) { generate(out); } else { - SmoothingPolylineOutput> smoothing(out, smooth_factor, resolution); - generate(smoothing); - smoothing.finish(); + SmoothingPolylineOutput> smoothing_output(out, smoothing); + generate(smoothing_output); + smoothing_output.finish(); } }; diff --git a/src/libslic3r/Fill/FillRectilinear.cpp b/src/libslic3r/Fill/FillRectilinear.cpp index f7954ef7fc..142afbae1a 100644 --- a/src/libslic3r/Fill/FillRectilinear.cpp +++ b/src/libslic3r/Fill/FillRectilinear.cpp @@ -3428,7 +3428,7 @@ bool FillRectilinear::fill_surface_trapezoidal( // Orca: round the corners of the trapezoids. The straight base lines of the triangular family // have no corner to round. - smooth_polylines_corners(polylines, params.smooth_factor, scaled(params.resolution)); + smooth_polylines_corners(polylines, params.corner_smoothing()); // Only the centerlines within d1 / 2 of the surface have outlines reaching it. polylines = intersection_pl(std::move(polylines), offset(expolygon, float(d1 / 2))); diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index 6508c8453f..d1436184e1 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -1135,12 +1135,14 @@ static std::vector get_path_of_change_filament(const Print& print) const std::string& filament_end_gcode = gcodegen.config().filament_end_gcode.get_at(old_filament_id); if (gcodegen.writer().filament() != nullptr && !filament_end_gcode.empty()) { DynamicConfig config; + config.set_key_value("filament_extruder_id", new ConfigOptionInt((int) old_filament_id)); config.set_key_value("current_filament_id", new ConfigOptionInt((int) old_filament_id)); config.set_key_value("current_nozzle_id", new ConfigOptionInt(nozzle_id_for_gcode_placeholder(group_result, (int) old_filament_id, (int) gcodegen.writer().filament()->extruder_id(), m_layer_idx))); config.set_key_value("nozzle_diameter_at_nozzle_id", new ConfigOptionFloats(get_nozzle_diameters_by_nozzle_id(group_result.get()))); config.set_key_value("nozzle_volume_types", new ConfigOptionStrings(get_nozzle_volume_types_by_nozzle_id(group_result.get()))); config.set_key_value("layer_num", new ConfigOptionInt(gcodegen.m_layer_index)); config.set_key_value("layer_z", new ConfigOptionFloat(tcr.print_z)); + config.set_key_value("max_layer_z", new ConfigOptionFloat(gcodegen.m_max_layer_z)); if (!gcodegen.m_filament_instances_code.empty()) { end_filament_gcode_str += ("M624 " + gcodegen.m_filament_instances_code + "\n"); gcodegen.m_filament_instances_code = ""; @@ -1524,6 +1526,9 @@ static std::vector get_path_of_change_filament(const Print& print) config.set_key_value("current_nozzle_id", new ConfigOptionInt(nozzle_id_for_gcode_placeholder(group_result, new_filament_id, new_extruder_id, m_layer_idx))); config.set_key_value("nozzle_diameter_at_nozzle_id", new ConfigOptionFloats(get_nozzle_diameters_by_nozzle_id(group_result.get()))); config.set_key_value("nozzle_volume_types", new ConfigOptionStrings(get_nozzle_volume_types_by_nozzle_id(group_result.get()))); + config.set_key_value("layer_num", new ConfigOptionInt(gcodegen.m_layer_index)); + config.set_key_value("layer_z", new ConfigOptionFloat(tcr.print_z)); + config.set_key_value("max_layer_z", new ConfigOptionFloat(gcodegen.m_max_layer_z)); start_filament_gcode_str = gcodegen.placeholder_parser_process("filament_start_gcode", filament_start_gcode, new_filament_id, &config); if (add_change_filament_624) { start_filament_gcode_str += "M625\n"; @@ -3294,6 +3299,13 @@ void GCode::_do_export(Print& print, GCodeOutputStream &file, ThumbnailsGenerato m_print = &print; m_timelapse_pos_picker.init(&print,m_writer.get_xy_offset().cast()); + { + // Runs the costly per-layer snapshot picker only for a template that names its results. + const std::string &templ = print.config().time_lapse_gcode.value; + m_timelapse_uses_pos = templ.find("timelapse_pos") != std::string::npos || + templ.find("has_timelapse_safe_pos") != std::string::npos; + m_timelapse_uses_clear_to_x0 = templ.find("clear_to_x0") != std::string::npos; + } // init as filament map update_layer_related_config(0); @@ -4297,6 +4309,8 @@ void GCode::_do_export(Print& print, GCodeOutputStream &file, ThumbnailsGenerato config.set_key_value("nozzle_diameter_at_nozzle_id", new ConfigOptionFloats(get_nozzle_diameters_by_nozzle_id(group_result.get()))); config.set_key_value("nozzle_volume_types", new ConfigOptionStrings(get_nozzle_volume_types_by_nozzle_id(group_result.get()))); config.set_key_value("layer_num", new ConfigOptionInt(m_layer_index)); + config.set_key_value("layer_z", new ConfigOptionFloat(m_writer.get_position().z() - m_config.z_offset.value)); + config.set_key_value("max_layer_z", new ConfigOptionFloat(m_max_layer_z)); std::string filament_start_gcode = this->placeholder_parser_process("filament_start_gcode", print.config().filament_start_gcode.get_at(initial_non_support_extruder_id), initial_non_support_extruder_id,&config); file.writeln(filament_start_gcode); // Mark the first filament used in print. Multi-nozzle printers (H2C) get ";VT%d H%d" where @@ -5942,6 +5956,42 @@ std::string GCode::generate_object_brim(const Print &print, const PrintObject &o return {}; } +std::string GCode::process_layer_change_gcode(const Print &print, coordf_t print_z, int most_used_extruder, bool has_wipe_tower) +{ + DynamicConfig config; + config.set_key_value("most_used_physical_extruder_id", new ConfigOptionInt(m_config.physical_extruder_map.get_at(most_used_extruder))); + config.set_key_value("layer_num", new ConfigOptionInt(m_layer_index)); + config.set_key_value("layer_z", new ConfigOptionFloat(print_z)); + config.set_key_value("max_layer_z", new ConfigOptionFloat(m_max_layer_z)); + { + const int cur_filament_id = (int) m_writer.filament()->id(); + const auto group_result = m_print->get_layered_nozzle_group_result(); + config.set_key_value("current_filament_id", new ConfigOptionInt(cur_filament_id)); + config.set_key_value("current_nozzle_id", new ConfigOptionInt( + nozzle_id_for_gcode_placeholder(group_result, cur_filament_id, (int) m_writer.filament()->extruder_id(), m_layer_index))); + } + + PrintStatistics curr_print_statistics; + for (const Extruder &extruder : m_writer.extruders()) { + double extruded_volume = extruder.extruded_volume() + (has_wipe_tower ? print.wipe_tower_data().used_filament[extruder.id()] * 2.4052f : 0.f); // assumes 1.75mm filament diameter + double filament_weight = extruded_volume * extruder.filament_density() * 0.001; + if (filament_weight > 0.) + curr_print_statistics.total_weight += filament_weight; + } + double curr_y_acceleration_limit = -1, curr_accumulated_mass = -1; + mass_load_limited_machine_acceleration(curr_print_statistics, print, curr_y_acceleration_limit, curr_accumulated_mass); + double curr_layer_mass = curr_print_statistics.total_weight - m_last_layer_accumulated_mass; + if (curr_layer_mass <= EPSILON) curr_layer_mass = 0.0; + m_last_layer_accumulated_mass = curr_print_statistics.total_weight; + config.set_key_value("curr_y_acceleration_limit", new ConfigOptionFloat(curr_y_acceleration_limit)); + config.set_key_value("curr_accumulated_mass", new ConfigOptionFloat(curr_accumulated_mass)); + config.set_key_value("curr_layer_mass", new ConfigOptionFloat(curr_layer_mass)); + + return this->placeholder_parser_process("layer_change_gcode", + print.config().layer_change_gcode.value, m_writer.filament()->id(), &config) + + "\n"; +} + // Belt printers: emit one brim-only apron layer. On a tilted belt the brim ahead // of the part lands at slicing Z below the object's first layer, because the // object's layer 0 IS its leading contact with the belt. Those layers carry brim @@ -5957,7 +6007,8 @@ LayerResult GCode::process_belt_brim_layer( const std::vector &layers, const LayerTools &layer_tools, const bool last_layer, - const size_t single_object_instance_idx) + const size_t single_object_instance_idx, + const int most_used_extruder) { // layer_id 0 is deliberate, not a placeholder. CoolingBuffer reads it for the // initial_layer_fan_speed override and the close_fan_the_first_x_layers gate @@ -6029,14 +6080,8 @@ LayerResult GCode::process_belt_brim_layer( gcode += this->change_layer(print_z); - if (! m_config.layer_change_gcode.value.empty()) { - DynamicConfig config; - config.set_key_value("layer_num", new ConfigOptionInt(m_layer_index)); - config.set_key_value("layer_z", new ConfigOptionFloat(print_z)); - config.set_key_value("max_layer_z", new ConfigOptionFloat(m_max_layer_z)); - gcode += this->placeholder_parser_process("layer_change_gcode", - print.config().layer_change_gcode.value, m_writer.filament()->id(), &config) + "\n"; - } + if (! m_config.layer_change_gcode.value.empty()) + gcode += this->process_layer_change_gcode(print, print_z, most_used_extruder, layer_tools.has_wipe_tower && m_wipe_tower); // Objects sharing this apron Z may use different brim filaments; print each in its own tool. for (const unsigned int brim_extruder : layer_tools.extruders) { @@ -6304,41 +6349,10 @@ std::string GCode::generate_timelapse_gcode(const Print &print, coordf_t print_z if (!m_writer.filament()) return {}; - PosPickCtx ctx; - ctx.curr_pos = { (coord_t)(scale_(m_writer.get_position().x())),(coord_t)(scale_(m_writer.get_position().y())) }; - ctx.curr_layer = this->layer(); - ctx.curr_extruder_id = m_writer.filament()->extruder_id(); - ctx.picture_extruder_id = most_used_extruder; - if (m_farthest_point_timelapse.enabled) { - // farthest_point is stored in the global print frame (includes plate origin); the picker works in - // the plate-relative frame, so subtract the plate origin here. - Vec3d po = print.get_plate_origin(); - ctx.farthest_point = m_farthest_point_timelapse.farthest_point - Point(scale_(po.x()), scale_(po.y())); - } - if (m_config.print_sequence == PrintSequence::ByObject && printed_objects) - ctx.printed_objects = *printed_objects; - - auto timelapse_pos = skip_pos_pick ? DefaultTimelapsePos : m_timelapse_pos_picker.pick_pos(ctx); - std::string timelapse_gcode; if (!print.config().time_lapse_gcode.value.empty()) { - DynamicConfig config; - config.set_key_value("layer_num", new ConfigOptionInt(m_layer_index)); - config.set_key_value("layer_z", new ConfigOptionFloat(print_z)); - config.set_key_value("max_layer_z", new ConfigOptionFloat(m_max_layer_z)); - config.set_key_value("most_used_physical_extruder_id", new ConfigOptionInt(m_config.physical_extruder_map.get_at(most_used_extruder))); - config.set_key_value("curr_physical_extruder_id", new ConfigOptionInt(m_config.physical_extruder_map.get_at(ctx.curr_extruder_id))); - config.set_key_value("timelapse_pos_x", new ConfigOptionInt((int)timelapse_pos.x())); - config.set_key_value("timelapse_pos_y", new ConfigOptionInt((int)timelapse_pos.y())); - config.set_key_value("has_timelapse_safe_pos", new ConfigOptionBool(timelapse_pos != DefaultTimelapsePos)); - // Timelapse-context vars. - config.set_key_value("timelapse_inline_photo", new ConfigOptionBool(skip_pos_pick)); - // Drive the template ternary Z{layer_z + (farthest_point_timelapse_enabled ? 0.0 : 0.4)} from the - // effective (per-layer, config+traditional+non-i3-folded) enabled state. False for every printer - // that leaves the toggle off, so their template evaluates to the pre-existing +0.4 lift byte-for-byte. - config.set_key_value("farthest_point_timelapse_enabled", new ConfigOptionBool(m_farthest_point_timelapse.enabled)); - config.set_key_value("clear_to_x0", new ConfigOptionBool(m_timelapse_pos_picker.get_is_clear_to_x0(ctx))); - timelapse_gcode = this->placeholder_parser_process("timelapse_gcode", print.config().time_lapse_gcode.value, m_writer.filament()->id(), &config) + "\n"; + const DynamicConfig config = timelapse_gcode_config(print, print_z, most_used_extruder, printed_objects, skip_pos_pick); + timelapse_gcode = this->placeholder_parser_process("time_lapse_gcode", print.config().time_lapse_gcode.value, m_writer.filament()->id(), &config) + "\n"; } if (!timelapse_gcode.empty()) { @@ -6377,6 +6391,42 @@ std::string GCode::generate_timelapse_gcode(const Print &print, coordf_t print_z return timelapse_gcode; } +DynamicConfig GCode::timelapse_gcode_config(const Print &print, coordf_t print_z, int most_used_extruder, + const std::vector *printed_objects, + bool skip_pos_pick) +{ + assert(m_writer.filament()); + PosPickCtx ctx; + ctx.curr_pos = { (coord_t)(scale_(m_writer.get_position().x())),(coord_t)(scale_(m_writer.get_position().y())) }; + ctx.curr_layer = this->layer(); + ctx.curr_extruder_id = m_writer.filament()->extruder_id(); + ctx.picture_extruder_id = most_used_extruder; + if (m_farthest_point_timelapse.enabled) { + // farthest_point is stored in the global print frame (includes plate origin); the picker works in + // the plate-relative frame, so subtract the plate origin here. + Vec3d po = print.get_plate_origin(); + ctx.farthest_point = m_farthest_point_timelapse.farthest_point - Point(scale_(po.x()), scale_(po.y())); + } + if (m_config.print_sequence == PrintSequence::ByObject && printed_objects) + ctx.printed_objects = *printed_objects; + + auto timelapse_pos = (skip_pos_pick || !m_timelapse_uses_pos) ? DefaultTimelapsePos : m_timelapse_pos_picker.pick_pos(ctx); + + DynamicConfig config; + config.set_key_value("layer_num", new ConfigOptionInt(m_layer_index)); + config.set_key_value("layer_z", new ConfigOptionFloat(print_z)); + config.set_key_value("max_layer_z", new ConfigOptionFloat(m_max_layer_z)); + config.set_key_value("most_used_physical_extruder_id", new ConfigOptionInt(m_config.physical_extruder_map.get_at(most_used_extruder))); + config.set_key_value("curr_physical_extruder_id", new ConfigOptionInt(m_config.physical_extruder_map.get_at(ctx.curr_extruder_id))); + config.set_key_value("timelapse_pos_x", new ConfigOptionInt((int)timelapse_pos.x())); + config.set_key_value("timelapse_pos_y", new ConfigOptionInt((int)timelapse_pos.y())); + config.set_key_value("has_timelapse_safe_pos", new ConfigOptionBool(timelapse_pos != DefaultTimelapsePos)); + config.set_key_value("timelapse_inline_photo", new ConfigOptionBool(skip_pos_pick)); + config.set_key_value("farthest_point_timelapse_enabled", new ConfigOptionBool(m_farthest_point_timelapse.enabled)); + config.set_key_value("clear_to_x0", new ConfigOptionBool(m_timelapse_uses_clear_to_x0 && m_timelapse_pos_picker.get_is_clear_to_x0(ctx))); + return config; +} + // In sequential mode, process_layer is called once per each object and its copy, // therefore layers will contain a single entry and single_object_instance_idx will point to the copy of the object. // In non-sequential mode, process_layer is called per each print_z height with all object and support layers accumulated. @@ -6422,7 +6472,7 @@ LayerResult GCode::process_layer( if (object_layer == nullptr && support_layer == nullptr && std::any_of(layers.begin(), layers.end(), [](const LayerToPrint &l) { return l.belt_brim_band != nullptr; })) - return this->process_belt_brim_layer(print, layers, layer_tools, last_layer, single_object_instance_idx); + return this->process_belt_brim_layer(print, layers, layer_tools, last_layer, single_object_instance_idx, most_used_extruder); const Layer* layer_ptr = nullptr; if (object_layer != nullptr) @@ -6536,55 +6586,15 @@ LayerResult GCode::process_layer( m_object_layer_over_raft = false; if (!need_insert_timelapse_gcode_for_traditional && !m_config.time_lapse_gcode.value.empty() && !is_BBL_Printer()) { - DynamicConfig config; - config.set_key_value("layer_num", new ConfigOptionInt(m_layer_index)); - config.set_key_value("layer_z", new ConfigOptionFloat(print_z)); - config.set_key_value("max_layer_z", new ConfigOptionFloat(m_max_layer_z)); - gcode += this->placeholder_parser_process("timelapse_gcode", + const DynamicConfig config = timelapse_gcode_config(print, print_z, most_used_extruder, &m_printed_objects, false); + gcode += this->placeholder_parser_process("time_lapse_gcode", print.config().time_lapse_gcode.value, m_writer.filament()->id(), &config) + "\n"; } - if (!m_config.layer_change_gcode.value.empty()) { - DynamicConfig config; - config.set_key_value("most_used_physical_extruder_id", new ConfigOptionInt(m_config.physical_extruder_map.get_at(most_used_extruder))); - config.set_key_value("layer_num", new ConfigOptionInt(m_layer_index)); - config.set_key_value("layer_z", new ConfigOptionFloat(print_z)); - { - const int cur_filament_id = (int) m_writer.filament()->id(); - const auto group_result = m_print->get_layered_nozzle_group_result(); - config.set_key_value("current_filament_id", new ConfigOptionInt(cur_filament_id)); - config.set_key_value("current_nozzle_id", new ConfigOptionInt( - nozzle_id_for_gcode_placeholder(group_result, cur_filament_id, (int) m_writer.filament()->extruder_id(), m_layer_index))); - } + if (!m_config.layer_change_gcode.value.empty()) + gcode += this->process_layer_change_gcode(print, print_z, most_used_extruder, has_wipe_tower); - // Bedslinger mass model. Compute the running printed mass at this layer (same weight calc as - // DoExport::update_print_stats_and_format_filament_stats) and the Y acceleration limit it implies. - // These are new placeholder vars no existing template reads, and mass_load_limited_machine_acceleration - // returns the plain min Y accel unless the A2L force/bed-mass keys are set, so this is inert for every - // existing printer. - PrintStatistics curr_print_statistics; - for (const Extruder &extruder : m_writer.extruders()) { - double extruded_volume = extruder.extruded_volume() + (has_wipe_tower ? print.wipe_tower_data().used_filament[extruder.id()] * 2.4052f : 0.f); // assumes 1.75mm filament diameter - double filament_weight = extruded_volume * extruder.filament_density() * 0.001; - if (filament_weight > 0.) - curr_print_statistics.total_weight += filament_weight; - } - double curr_y_acceleration_limit = -1, curr_accumulated_mass = -1; - mass_load_limited_machine_acceleration(curr_print_statistics, print, curr_y_acceleration_limit, curr_accumulated_mass); - double curr_layer_mass = curr_print_statistics.total_weight - m_last_layer_accumulated_mass; - if (curr_layer_mass <= EPSILON) curr_layer_mass = 0.0; - m_last_layer_accumulated_mass = curr_print_statistics.total_weight; - config.set_key_value("curr_y_acceleration_limit", new ConfigOptionFloat(curr_y_acceleration_limit)); - config.set_key_value("curr_accumulated_mass", new ConfigOptionFloat(curr_accumulated_mass)); - config.set_key_value("curr_layer_mass", new ConfigOptionFloat(curr_layer_mass)); - - gcode += this->placeholder_parser_process("layer_change_gcode", - print.config().layer_change_gcode.value, m_writer.filament()->id(), &config) - + "\n"; - config.set_key_value("max_layer_z", new ConfigOptionFloat(m_max_layer_z)); - } - //BBS: set layer time fan speed after layer change gcode gcode += ";_SET_FAN_SPEED_CHANGING_LAYER\n"; diff --git a/src/libslic3r/GCode.hpp b/src/libslic3r/GCode.hpp index b5898b2305..38740abd7e 100644 --- a/src/libslic3r/GCode.hpp +++ b/src/libslic3r/GCode.hpp @@ -476,13 +476,18 @@ protected: // object's first layer, so there is no object or support layer for the normal // process_layer() machinery to work from. Kept to the minimum a layer needs - // tool, Z move, extrusions - so that nothing here can perturb the - // Layer::id()-based logic the ordinary path relies on. + // Layer::id()-based logic the ordinary path relies on. Its layer change G-code + // uses process_layer_change_gcode(), so an apron band counts in the running + // printed mass like an object layer. LayerResult process_belt_brim_layer( const Print &print, const std::vector &layers, const LayerTools &layer_tools, const bool last_layer, - const size_t single_object_instance_idx); + const size_t single_object_instance_idx, + const int most_used_extruder); + + std::string process_layer_change_gcode(const Print &print, coordf_t print_z, int most_used_extruder, bool has_wipe_tower); // Emit the apron bands carried by these layers whose brim filament is extruder_id // (0-based). Called from both the brim-only branch and the ordinary path, since a @@ -649,6 +654,10 @@ protected: // Farthest-point timelapse: find the extrusion point farthest from camera (0,0) void compute_farthest_point(const std::vector &layers, int most_used_extruder, const std::map, unsigned int> &support_filaments); + // Requires an active filament. + DynamicConfig timelapse_gcode_config(const Print &print, coordf_t print_z, int most_used_extruder, + const std::vector *printed_objects, + bool skip_pos_pick); // Build the per-layer timelapse snapshot g-code (safe-position or, when skip_pos_pick, // an inline photo at the current head position). Extracted from the former process_layer lambda so the // per-extrusion farthest-point hook (_extrude) can call it too. Identical to the old lambda when the @@ -759,6 +768,8 @@ protected: AvoidCrossingPerimeters m_avoid_crossing_perimeters; RetractWhenCrossingPerimeters m_retract_when_crossing_perimeters; TimelapsePosPicker m_timelapse_pos_picker; + bool m_timelapse_uses_pos{ false }; + bool m_timelapse_uses_clear_to_x0{ false }; // Farthest-point timelapse context. Corexy-only refinement layered on top of the existing // timelapse_type. All fields default to the inert state; `enabled` is (re)computed each layer in diff --git a/src/libslic3r/GCode/WipeTower.cpp b/src/libslic3r/GCode/WipeTower.cpp index e081717ecf..b72e924da4 100644 --- a/src/libslic3r/GCode/WipeTower.cpp +++ b/src/libslic3r/GCode/WipeTower.cpp @@ -3349,7 +3349,7 @@ WipeTower::ToolChangeResult WipeTower::merge_tcr(ToolChangeResult &first, ToolCh WipeTower::ToolChangeResult out = first; if ((first.end_pos - second.start_pos).norm() > (float)EPSILON) { std::string travel_gcode = "G1 X" + Slic3r::float_to_string_decimal_point(second.start_pos.x(), 3) + " Y" + - Slic3r::float_to_string_decimal_point(second.start_pos.y(), 3) + " F" + std::to_string(m_max_speed) + "\n"; + Slic3r::float_to_string_decimal_point(second.start_pos.y(), 3) + " F" + Slic3r::float_to_string_decimal_point(m_max_speed, 6) + "\n"; bool need_insert_travel = true; if (second.is_tool_change && is_approx(second.start_pos.x(), second.tool_change_start_pos.x()) diff --git a/src/libslic3r/GCode/WipeTowerEstimate.cpp b/src/libslic3r/GCode/WipeTowerEstimate.cpp index e974f9351f..0be6a4acaa 100644 --- a/src/libslic3r/GCode/WipeTowerEstimate.cpp +++ b/src/libslic3r/GCode/WipeTowerEstimate.cpp @@ -3,15 +3,23 @@ #include "libslic3r/Polygon.hpp" #include "WipeTower.hpp" #include "WipeTower2.hpp" +#include "../ClipperUtils.hpp" #include "../Config.hpp" +#include "../ExPolygon.hpp" +#include "../Geometry/ConvexHull.hpp" +#include "../Line.hpp" #include "../FilamentMixer.hpp" +#include "../Point.hpp" #include "../PrintConfig.hpp" #include "../libslic3r.h" #include #include #include +#include +#include #include +#include #include #include "libslic3r/clonable_ptr.hpp" @@ -236,4 +244,44 @@ WipeTowerFootprint estimate_wipe_tower_footprint(const ConfigBase &config, WipeT return footprint; } +std::optional nearest_clear_wipe_tower_anchor(const BoundingBox &anchor_bounds, const Polygon &footprint, + const Polygons &obstacles, const Point &target) +{ + // The anchors that put the footprint on a convex obstacle form the obstacle grown by the + // reflected footprint. For two convex shapes that Minkowski sum is the hull of the + // differences of their vertices. + const Polygon tower = Geometry::convex_hull(footprint.points); + Polygons blocked; + blocked.reserve(obstacles.size()); + for (const Polygon &obstacle : obstacles) { + Points differences; + differences.reserve(obstacle.size() * tower.size()); + for (const Point &o : obstacle.points) + for (const Point &f : tower.points) + differences.emplace_back(o - f); + blocked.emplace_back(Geometry::convex_hull(std::move(differences))); + } + + // Grown by a hair so bounds pinned to one coordinate on a cramped plate still have an area. + BoundingBox bounds = anchor_bounds; + bounds.offset(SCALED_EPSILON); + const ExPolygons clear = diff_ex(Polygons{ bounds.polygon() }, blocked); + + std::optional nearest; + double nearest_distance = std::numeric_limits::max(); + for (const ExPolygon ®ion : clear) { + if (region.contains(target)) + return target; + for (const Line &edge : to_lines(region)) { + Point closest; + const double distance = edge.distance_to_squared(target, &closest); + if (distance < nearest_distance) { + nearest_distance = distance; + nearest = closest; + } + } + } + return nearest; +} + } // namespace Slic3r diff --git a/src/libslic3r/GCode/WipeTowerEstimate.hpp b/src/libslic3r/GCode/WipeTowerEstimate.hpp index 9dad82f51f..ff20c3a44d 100644 --- a/src/libslic3r/GCode/WipeTowerEstimate.hpp +++ b/src/libslic3r/GCode/WipeTowerEstimate.hpp @@ -1,7 +1,10 @@ #pragma once +#include #include +#include "../BoundingBox.hpp" +#include "../Point.hpp" #include "../Polygon.hpp" namespace Slic3r { @@ -59,4 +62,11 @@ WipeTowerFootprint estimate_wipe_tower_footprint(const ConfigBase // `config` only has to carry the print preset's own keys. bool prime_tower_is_printed(const ConfigBase &config, int used_filaments, int num_objects, bool has_mixed_filament); +// Where to put a tower whose saved position no longer fits: of the anchors (the tower's +// position) inside `anchor_bounds`, the one nearest `target` whose `footprint` touches none of +// the `obstacles`. `footprint` is relative to the anchor, brim included; an obstacle is taken +// as its convex hull. Empty when every anchor in bounds meets an obstacle. All coordinates scaled. +std::optional nearest_clear_wipe_tower_anchor(const BoundingBox &anchor_bounds, const Polygon &footprint, + const Polygons &obstacles, const Point &target); + } // namespace Slic3r diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index e9f741b890..78e6ad4277 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -4289,9 +4289,11 @@ Points Print::first_layer_wipe_tower_corners(bool check_wipe_tower_existance) co Vec2d(pt0.x(),pt0.y()+depth) }; - // Now the stabilization cone. + // Now the stabilization cone, which only a Type2 tower with a cone wall prints. Vec2d center = (pts[0] + pts[2])/2.; - const auto [cone_R, cone_x_scale] = WipeTower2::get_wipe_tower_cone_base(m_config.prime_tower_width, m_wipe_tower_data.height, m_wipe_tower_data.depth, m_config.wipe_tower_cone_angle); + const bool has_cone = wipe_tower_type() == WipeTowerType::Type2 && m_config.wipe_tower_wall_type.value == WipeTowerWallType::wtwCone; + const double cone_angle = has_cone ? m_config.wipe_tower_cone_angle.value : 0.; + const auto [cone_R, cone_x_scale] = WipeTower2::get_wipe_tower_cone_base(m_config.prime_tower_width, m_wipe_tower_data.height, m_wipe_tower_data.depth, cone_angle); double r = cone_R + m_wipe_tower_data.brim_width; for (double alpha = 0.; alpha<2*M_PI; alpha += M_PI/20.) pts.emplace_back(center + r*Vec2d(std::cos(alpha)/cone_x_scale, std::sin(alpha))); @@ -5406,13 +5408,14 @@ void Print::_make_wipe_tower() m_wipe_tower_data.used_filament = wipe_tower.get_used_filament(); m_wipe_tower_data.number_of_toolchanges = wipe_tower.get_number_of_toolchanges(); + // Only a cone wall prints the stabilization cone, whatever cone angle the config holds. + const float cone_angle = config().wipe_tower_wall_type.value == WipeTowerWallType::wtwCone ? + static_cast(config().wipe_tower_cone_angle.value) : 0.f; m_wipe_tower_data.construct_mesh(wipe_tower.width(), wipe_tower.get_depth(), wipe_tower.get_wipe_tower_height(), wipe_tower.get_brim_width(), config().wipe_tower_wall_type.value == WipeTowerWallType::wtwRib, wipe_tower.get_rib_width(), wipe_tower.get_rib_length(), - config().wipe_tower_fillet_wall.value, - config().wipe_tower_wall_type.value == WipeTowerWallType::wtwCone ? - (float) config().wipe_tower_cone_angle.value : 0.f); + config().wipe_tower_fillet_wall.value, cone_angle); const Vec3d origin = Vec3d::Zero(); // FakeWipeTower::pos is a bed-frame translation applied after rotation // (getFakeExtrusionPathsFromWipeTower2 rotates about the local origin), so the @@ -5422,7 +5425,7 @@ void Print::_make_wipe_tower() m_fake_wipe_tower.set_fake_extrusion_data(wipe_tower.position() + m_fake_wipe_tower.rib_offset, wipe_tower.width(), wipe_tower.get_wipe_tower_height(), config().initial_layer_print_height, m_wipe_tower_data.depth, m_wipe_tower_data.z_and_depth_pairs, m_wipe_tower_data.brim_width, - config().wipe_tower_rotation_angle, config().wipe_tower_cone_angle, + config().wipe_tower_rotation_angle, cone_angle, {scale_(origin.x()), scale_(origin.y())}); } diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 0876d7ebb8..91261690fd 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -13333,8 +13333,8 @@ PrintStatisticsConfigDef::PrintStatisticsConfigDef() def->tooltip = L("Total cost of the material wasted on the wipe tower. Calculated from filament_cost value in Filament Settings."); def = this->add("total_wipe_tower_filament", coFloat); - def->label = L("Wipe tower volume"); - def->tooltip = L("Total filament volume extruded on the wipe tower."); + def->label = L("Total wipe tower filament"); + def->tooltip = L("Total length of filament used on the wipe tower, in mm."); def = this->add("used_filament", coFloat); def->label = L("Used filament"); @@ -13507,7 +13507,7 @@ static std::map s_CustomGcodeSpecificP {"layer_change_gcode", {"layer_num", "layer_z", "max_layer_z", "most_used_physical_extruder_id", "current_filament_id", "current_nozzle_id", "curr_y_acceleration_limit", "curr_accumulated_mass", "curr_layer_mass"}}, - {"timelapse_gcode", {"layer_num", "layer_z", "max_layer_z", "most_used_physical_extruder_id", + {"time_lapse_gcode", {"layer_num", "layer_z", "max_layer_z", "most_used_physical_extruder_id", "curr_physical_extruder_id", "timelapse_pos_x", "timelapse_pos_y", "has_timelapse_safe_pos", "timelapse_inline_photo", "farthest_point_timelapse_enabled", "clear_to_x0"}}, @@ -13562,7 +13562,8 @@ CustomGcodeSpecificConfigDef::CustomGcodeSpecificConfigDef() // Common Defs def = this->add("layer_num", coInt); def->label = L("Layer number"); - def->tooltip = L("Index of the current layer. Zero-based (i.e. first layer is number 0), except in extrusion role change G-code, where it is one-based."); + def->tooltip = L("Index of the current layer. The index is zero-based (first layer has index 0). Before the first " + "layer starts, it is -1. In extrusion role change G-code, the index is one-based (first layer has index 1)."); def = this->add("layer_z", coFloat); def->label = L("Layer Z"); @@ -13574,7 +13575,11 @@ CustomGcodeSpecificConfigDef::CustomGcodeSpecificConfigDef() def = this->add("filament_extruder_id", coInt); def->label = L("Filament extruder ID"); - def->tooltip = L("The current extruder ID. The same as current_extruder."); + def->tooltip = L("In filament start G-code, the index of the filament that is being loaded. In filament end G-code, " + "the index of the filament that is being unloaded. The index is zero-based (first filament has " + "index 0). At a tool change, filament end G-code gets the extruder index instead, unless the Type 1 " + "wipe tower does the tool change. Machine end G-code gets the value from the last filament end " + "G-code at the end of the print."); new_def("current_filament_id", coInt, L("Current filament ID"), L("Index of the currently active filament. The index is zero-based (first filament has index 0).")); new_def("current_extruder_id", coInt, L("Current extruder ID"), L("Index of the currently active physical extruder. The index is zero-based (first extruder has index 0).")); @@ -13590,7 +13595,7 @@ CustomGcodeSpecificConfigDef::CustomGcodeSpecificConfigDef() new_def("curr_accumulated_mass", coFloat, L("Current accumulated mass"), L("Accumulated printed mass at the current layer.")); new_def("curr_layer_mass", coFloat, L("Current layer mass"), L("Printed mass of the previous layer.")); -// timelapse_gcode +// time_lapse_gcode new_def("curr_physical_extruder_id", coInt, L("Current physical extruder ID"), L("Index of the physical extruder active for the current layer. The index is zero-based (first extruder has index 0).")); new_def("timelapse_pos_x", coInt, L("Timelapse position X"), L("Selected X position for timelapse capture.")); new_def("timelapse_pos_y", coInt, L("Timelapse position Y"), L("Selected Y position for timelapse capture.")); @@ -13600,8 +13605,8 @@ CustomGcodeSpecificConfigDef::CustomGcodeSpecificConfigDef() new_def("clear_to_x0", coBool, L("Clear to X0"), L("Whether the timelapse move is clear to X0.")); // change_filament_gcode - new_def("previous_extruder", coInt, L("Previous extruder"), L("Index of the extruder that is being unloaded. The index is zero based (first extruder has index 0).")); - new_def("next_extruder", coInt, L("Next extruder"), L("Index of the extruder that is being loaded. The index is zero based (first extruder has index 0).")); + new_def("previous_extruder", coInt, L("Previous extruder"), L("Index of the filament that is being unloaded. The index is zero-based (first filament has index 0). At the start of the print, when no filament is loaded yet, it is -1.")); + new_def("next_extruder", coInt, L("Next extruder"), L("Index of the filament that is being loaded. The index is zero-based (first filament has index 0).")); new_def("current_hotend", coInt, L("Current hotend"), L("Zero-based extruder index of the outgoing filament. On Bambu printers it is -1, or the nozzle ID when a filament moves between nozzles across layers.")); new_def("next_hotend", coInt, L("Next hotend"), L("Zero-based extruder index of the incoming filament. On Bambu printers it is -1, or the nozzle ID when a filament moves between nozzles across layers.")); new_def("next_nozzle_id", coInt, L("Next nozzle ID"), L("Index of the nozzle associated with the incoming filament. The index is zero-based (first nozzle has index 0).")); diff --git a/src/libslic3r/PrintObjectSlice.cpp b/src/libslic3r/PrintObjectSlice.cpp index c4b250bac4..e2f2c1af8a 100644 --- a/src/libslic3r/PrintObjectSlice.cpp +++ b/src/libslic3r/PrintObjectSlice.cpp @@ -551,7 +551,11 @@ static std::vector> slices_to_regions( } //BBS: justify whether a volume is connected to another one -bool doesVolumeIntersect(VolumeSlices& vs1, VolumeSlices& vs2) +// bboxes1 and bboxes2 hold the extents of each layer's slices. Slices whose boxes are disjoint cannot overlap, so +// the Clipper test runs only for slices that are close. The layers are scanned serially because this is called +// for every pair of volumes: a parallel_for per call costs far more in thread wake-ups than the scan itself. +static bool doesVolumeIntersect(const VolumeSlices& vs1, const std::vector& bboxes1, + const VolumeSlices& vs2, const std::vector& bboxes2) { if (vs1.volume_id == vs2.volume_id) return true; // two volumes in the same object should have same number of layers, otherwise the slicing is incorrect. @@ -559,28 +563,17 @@ bool doesVolumeIntersect(VolumeSlices& vs1, VolumeSlices& vs2) auto& vs1s = vs1.slices; auto& vs2s = vs2.slices; - bool is_intersect = false; + auto layers_overlap = [&](size_t i, size_t j) { + return bboxes1[i].defined && bboxes2[j].defined && bboxes1[i].overlap(bboxes2[j]) && overlaps(vs1s[i], vs2s[j]); + }; - tbb::parallel_for(tbb::blocked_range(0, vs1s.size()), - [&vs1s, &vs2s, &is_intersect](const tbb::blocked_range& range) { - for (auto i = range.begin(); i != range.end(); ++i) { - if (vs1s[i].empty()) continue; - - if (overlaps(vs1s[i], vs2s[i])) { - is_intersect = true; - break; - } - if (i + 1 != vs2s.size() && overlaps(vs1s[i], vs2s[i + 1])) { - is_intersect = true; - break; - } - if (i - 1 >= 0 && overlaps(vs1s[i], vs2s[i - 1])) { - is_intersect = true; - break; - } - } - }); - return is_intersect; + for (size_t i = 0; i < vs1s.size(); ++i) { + if (layers_overlap(i, i) || + (i + 1 < vs2s.size() && layers_overlap(i, i + 1)) || + (i > 0 && layers_overlap(i, i - 1))) + return true; + } + return false; } //BBS: grouping the volumes of an object according to their connection relationship @@ -590,7 +583,10 @@ bool groupingVolumes(std::vector objSliceByVolume, std::vector> osvIndex; + // Extents of each volume's offset slices per layer, for the prefilter in doesVolumeIntersect(). + std::vector> bboxes(objSliceByVolume.size()); for (int i = 0; i != objSliceByVolume.size(); ++i) { + bboxes[i].resize(objSliceByVolume[i].slices.size()); for (int j = 0; j != objSliceByVolume[i].slices.size(); ++j) { osvIndex.push_back({ i,j }); } @@ -605,9 +601,10 @@ bool groupingVolumes(std::vector objSliceByVolume, std::vector(0, osvIndex.size()), - [&osvIndex, &objSliceByVolume,&offsetValue](const tbb::blocked_range& range) { + [&osvIndex, &objSliceByVolume,&offsetValue, &bboxes](const tbb::blocked_range& range) { for (auto k = range.begin(); k != range.end(); ++k) { objSliceByVolume[osvIndex[k][0]].slices[osvIndex[k][1]] = offset_ex(objSliceByVolume[osvIndex[k][0]].slices[osvIndex[k][1]], offsetValue); + bboxes[osvIndex[k][0]][osvIndex[k][1]] = get_extents(objSliceByVolume[osvIndex[k][0]].slices[osvIndex[k][1]]); } }); @@ -616,7 +613,7 @@ bool groupingVolumes(std::vector objSliceByVolume, std::vectorget_model_mall_rating_result(curr_instance_id, rating_result, http_code, http_error); + res = m_agent->get_model_mall_rating_result(curr_instance_id, rating_result, http_code, http_error, Slic3r::GUI::wxGetApp().get_printer_cloud_provider()); request_model_result++; BOOST_LOG_TRIVIAL(info) << "request times: " << request_model_result << " http code: " << http_code; auto rating_info = new DevPrintTaskRatingInfo(); @@ -5064,7 +5064,7 @@ void MachineObject::get_firmware_info() unsigned int http_code; std::string http_body; if (!m_agent) return; - result = m_agent->get_printer_firmware(get_dev_id(), &http_code, &http_body); + result = m_agent->get_printer_firmware(get_dev_id(), &http_code, &http_body, Slic3r::GUI::wxGetApp().get_printer_cloud_provider()); if (result < 0) { // get upgrade list failed return; diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index c6a7f8f6a6..50ba576736 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -103,6 +103,7 @@ #include "GUI_Colors.hpp" #include "Mouse3DController.hpp" #include "I18N.hpp" +#include "format.hpp" #include "NotificationManager.hpp" #include "DailyTips.hpp" #include "FilamentMapDialog.hpp" @@ -3591,13 +3592,25 @@ void GLCanvas3D::reload_scene(bool refresh_immediately, bool force_full_scene_re // psWipeTower, so gating on it would skip the clamp exactly when it is needed. { Vec3d clamped_pos, clamped_size; - part_plate->estimate_wipe_tower_polygon(full_config, plate_id, clamped_pos, clamped_size); + WipeTowerRelocation relocation; + part_plate->estimate_wipe_tower_polygon(full_config, plate_id, clamped_pos, clamped_size, 0, false, &relocation); if (std::abs(x - (float) clamped_pos(0)) > EPSILON || std::abs(y - (float) clamped_pos(1)) > EPSILON) { x = (float) clamped_pos(0); y = (float) clamped_pos(1); ConfigOptionFloat wt_x_opt(x), wt_y_opt(y); dynamic_cast(proj_cfg.option("wipe_tower_x"))->set_at(&wt_x_opt, plate_id, 0); dynamic_cast(proj_cfg.option("wipe_tower_y"))->set_at(&wt_y_opt, plate_id, 0); + // The stored position changes once, so this is shown once per move. + if (NotificationManager *notifications = wxGetApp().notification_manager(); notifications != nullptr && relocation.moved) { + if (relocation.overlaps_objects) + notifications->push_notification(NotificationType::CustomNotification, NotificationManager::NotificationLevel::WarningNotificationLevel, + // TRN %1% is the plate number. + format(_u8L("The prime tower on plate %1% no longer fits where it was placed. There is no free space left on the plate for it, so it was moved onto an object."), plate_id + 1)); + else + notifications->push_notification(NotificationType::CustomNotification, NotificationManager::NotificationLevel::RegularNotificationLevel, + // TRN %1% is the plate number. + format(_u8L("The prime tower on plate %1% no longer fits where it was placed, so it was moved to free space on the plate."), plate_id + 1)); + } } } diff --git a/src/slic3r/GUI/MainFrame.cpp b/src/slic3r/GUI/MainFrame.cpp index b1ae832abc..c36a895a17 100644 --- a/src/slic3r/GUI/MainFrame.cpp +++ b/src/slic3r/GUI/MainFrame.cpp @@ -801,7 +801,6 @@ DPIFrame(NULL, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, BORDERLESS_FRAME_ this->Iconize(); return; } - if (evt.CmdDown() && evt.GetKeyCode() == 'Q') { wxPostEvent(this, wxCloseEvent(wxEVT_CLOSE_WINDOW)); return;} if (evt.CmdDown() && evt.RawControlDown() && evt.GetKeyCode() == 'F') { EnableFullScreenView(true); if (IsFullScreen()) { @@ -901,6 +900,9 @@ bool MainFrame::handle_global_shortcut(const KeyChord& chord) if (can_export_model()) publish_project(); break; + case Shortcut::Quit: + Close(false); + break; case Shortcut::ShowLabels: if (m_plater && m_plater->is_view3D_shown()) { m_plater->show_view3D_labels(!m_plater->are_view3D_labels_shown()); @@ -3116,7 +3118,7 @@ void MainFrame::init_menubar_as_editor() fileMenu->AppendSeparator(); #ifndef __APPLE__ - append_menu_item(fileMenu, wxID_EXIT, _L("Quit"), wxString::Format(_L("Quit")), + append_shortcut_item(fileMenu, Shortcut::Quit, false, _L("Quit"), wxString::Format(_L("Quit")), [this](wxCommandEvent&) { Close(false); }, "menu_exit", nullptr); #else append_menu_item(fileMenu, wxID_EXIT, _L("Quit"), wxString::Format(_L("Quit")), diff --git a/src/slic3r/GUI/PartPlate.cpp b/src/slic3r/GUI/PartPlate.cpp index ae0c0c46db..984323daff 100644 --- a/src/slic3r/GUI/PartPlate.cpp +++ b/src/slic3r/GUI/PartPlate.cpp @@ -3372,7 +3372,37 @@ WipeTowerFootprint PartPlate::estimate_wipe_tower_footprint(const DynamicPrintCo return Slic3r::estimate_wipe_tower_footprint(config, resolve_wipe_tower_type(config), filament_ids, layer_height, max_height); } -arrangement::ArrangePolygon PartPlate::estimate_wipe_tower_polygon(const DynamicPrintConfig& config, int plate_index, Vec3d& wt_pos, Vec3d& wt_size, int plate_extruder_size, bool use_global_objects) const +Polygons PartPlate::wipe_tower_obstacles(const DynamicPrintConfig &config) const +{ + Polygons obstacles; + for (const auto &[obj_id, instance_id] : obj_to_instance_set) { + if (!valid_instance(obj_id, instance_id)) + continue; + const ModelObject *object = m_model->objects[obj_id]; + const ModelInstance *instance = object->instances[instance_id]; + if (!instance->printable) + continue; + // A sinking object counts its whole outline, the part below the bed included. + Polygon hull = object->convex_hull_2d(instance->get_matrix()); + if (hull.size() < 3) + continue; + hull.translate(-scaled(m_origin.x()), -scaled(m_origin.y())); + // An object's own setting wins over the print preset's. + auto option_of = [&object, &config](const char *key) { + const ConfigOption *opt = object->config.option(key); + return opt != nullptr ? opt : config.option(key); + }; + // An auto brim is only sized while slicing, so it is taken at the brim width option too. + const ConfigOption *brim_type = option_of("brim_type"); + const ConfigOption *brim_width = option_of("brim_width"); + const double brim = brim_type != nullptr && brim_width != nullptr && brim_type->getInt() != static_cast(btNoBrim) ? brim_width->getFloat() : 0.; + append(obstacles, offset(hull, static_cast(scaled(brim + WIPE_TOWER_MARGIN)))); + } + return obstacles; +} + +arrangement::ArrangePolygon PartPlate::estimate_wipe_tower_polygon(const DynamicPrintConfig& config, int plate_index, Vec3d& wt_pos, Vec3d& wt_size, int plate_extruder_size, bool use_global_objects, + WipeTowerRelocation *relocation) const { float x = dynamic_cast(config.option("wipe_tower_x"))->get_at(plate_index); float y = dynamic_cast(config.option("wipe_tower_y"))->get_at(plate_index); @@ -3405,10 +3435,40 @@ arrangement::ArrangePolygon PartPlate::estimate_wipe_tower_polygon(const Dynamic // mesh, a couple of mm inside this reserved estimate), so a drop can land slightly out // of bounds — snap it onto the bound; only far-out positions get the comfort re-place. const float tol = 5.f; - if (x < margin - tol || x > x_hi + tol) x = std::clamp(x, x_lo_c, x_hi_c); - else x = std::clamp(x, margin, x_hi); - if (y < margin - tol || y > y_hi + tol) y = std::clamp(y, y_lo_c, y_hi_c); - else y = std::clamp(y, margin, y_hi); + const float saved_x = x, saved_y = y; + const bool replace_x = x < margin - tol || x > x_hi + tol; + const bool replace_y = y < margin - tol || y > y_hi + tol; + x = replace_x ? std::clamp(x, x_lo_c, x_hi_c) : std::clamp(x, margin, x_hi); + y = replace_y ? std::clamp(y, y_lo_c, y_hi_c) : std::clamp(y, margin, y_hi); + if (relocation != nullptr && (replace_x || replace_y)) { + relocation->moved = true; + // The footprint keeps clear of every object and its brim, and turns about its anchor + // as the tower does. + Polygon tower({ {scaled(-wp_brim_width), scaled(-wp_brim_width)}, + {scaled(w + wp_brim_width), scaled(-wp_brim_width)}, + {scaled(w + wp_brim_width), scaled(depth + wp_brim_width)}, + {scaled(-wp_brim_width), scaled(depth + wp_brim_width)} }); + if (const auto *rotation = config.option("wipe_tower_rotation_angle"); rotation != nullptr && rotation->value != 0.) + tower.rotate(Geometry::deg2rad(rotation->value)); + const Polygons objects = wipe_tower_obstacles(config); + const Point placed(scaled(x), scaled(y)); + // The re-placed spot stands when it is clear. Otherwise take the clear spot nearest the + // saved position, keeping the comfort margin where the plate leaves room for it. + if (!nearest_clear_wipe_tower_anchor(BoundingBox(placed, placed), tower, objects, placed)) { + const Point saved(scaled(saved_x), scaled(saved_y)); + std::optional clear = nearest_clear_wipe_tower_anchor( + BoundingBox(Point(scaled(x_lo_c), scaled(y_lo_c)), Point(scaled(x_hi_c), scaled(y_hi_c))), tower, objects, saved); + if (!clear) + clear = nearest_clear_wipe_tower_anchor(BoundingBox(Point(scaled(margin), scaled(margin)), Point(scaled(x_hi), scaled(y_hi))), + tower, objects, saved); + if (clear) { + x = static_cast(unscaled(clear->x())); + y = static_cast(unscaled(clear->y())); + } else { + relocation->overlaps_objects = true; + } + } + } wt_pos(0) = x; wt_pos(1) = y; wt_pos(2) = 0.f; diff --git a/src/slic3r/GUI/PartPlate.hpp b/src/slic3r/GUI/PartPlate.hpp index ac7a9db0b6..043fc3ee82 100644 --- a/src/slic3r/GUI/PartPlate.hpp +++ b/src/slic3r/GUI/PartPlate.hpp @@ -94,6 +94,13 @@ class PartPlateList; using GCodeResult = GCodeProcessorResult; +// What estimate_wipe_tower_polygon did to a saved tower position that no longer fits the plate. +struct WipeTowerRelocation +{ + bool moved = false; // re-placed, not just snapped onto the bound it was dropped past + bool overlaps_objects = false; // no spot on the plate was clear of the objects, so it sits on one +}; + class PartPlate : public ObjectBase { public: @@ -254,6 +261,9 @@ private: int picking_id_component(int idx) const; void on_filament_map_mode_change(); + // What a re-placed tower keeps clear of: each printable instance's convex hull, grown by its + // brim and the tower margin, in plate coordinates. + Polygons wipe_tower_obstacles(const DynamicPrintConfig &config) const; public: static constexpr unsigned int PLATE_NAME_HOVER_ID = 6; @@ -457,7 +467,10 @@ public: // use_global_objects skips the containment test, which the CLI needs before objects are // assigned to plates - the layer height is then the project's thinnest, which over-reserves. WipeTowerFootprint estimate_wipe_tower_footprint(const DynamicPrintConfig & config, int plate_extruder_size = 0, bool use_global_objects = false) const; - arrangement::ArrangePolygon estimate_wipe_tower_polygon(const DynamicPrintConfig & config, int plate_index, Vec3d& wt_pos, Vec3d& wt_size, int plate_extruder_size = 0, bool use_global_objects = false) const; + // relocation: callers that store the returned position pass it, so a re-placed tower is + // moved clear of the plate's objects where there is room, and they are told it moved. + arrangement::ArrangePolygon estimate_wipe_tower_polygon(const DynamicPrintConfig & config, int plate_index, Vec3d& wt_pos, Vec3d& wt_size, int plate_extruder_size = 0, bool use_global_objects = false, + WipeTowerRelocation *relocation = nullptr) const; bool check_objects_empty_and_gcode3mf(std::vector &result) const; // get used filaments from config, 1 based idx // expand_mixed_slots = false keeps mixed filament slots as slots instead of their components. diff --git a/src/slic3r/GUI/PartSkipDialog.cpp b/src/slic3r/GUI/PartSkipDialog.cpp index af90584549..f68590976e 100644 --- a/src/slic3r/GUI/PartSkipDialog.cpp +++ b/src/slic3r/GUI/PartSkipDialog.cpp @@ -511,7 +511,7 @@ void PartSkipDialog::fetchUrl(boost::weak_ptr wfs) fs->SetUrl("3"); } }); - }); + }, wxGetApp().get_printer_cloud_provider()); break; } default: break; diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 99cc0de21b..dd20492ce3 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -17176,8 +17176,10 @@ void adjust_settings_for_flowrate_calib(ModelObjectPtrs& objects, bool linear, i canvas->do_scale(""); auto cur_flowrate = filament_config->option("filament_flow_ratio")->get_at(0); // TODO: per-filament param - std::vector internal_solid_speeds = generate_max_speed_parameter_value("internal_solid_infill_speed", linear, pass); - std::vector top_surface_speeds = generate_max_speed_parameter_value("top_surface_speed", linear, pass); + // Cap the speeds for the extrusion the test prints, not the profile's line width and layer height + const float infill_line_width = nozzle_diameter * 1.2f; + std::vector internal_solid_speeds = generate_max_speed_parameter_value("internal_solid_infill_speed", infill_line_width, layer_height, linear, pass); + std::vector top_surface_speeds = generate_max_speed_parameter_value("top_surface_speed", infill_line_width, layer_height, linear, pass); // adjust parameters for (auto _obj : objects) { @@ -17196,8 +17198,8 @@ void adjust_settings_for_flowrate_calib(ModelObjectPtrs& objects, bool linear, i _obj->config.set_key_value("detect_thin_wall", new ConfigOptionBool(true)); _obj->config.set_key_value("filter_out_gap_fill", new ConfigOptionFloat(0)); _obj->config.set_key_value("sparse_infill_pattern", new ConfigOptionEnum(ipRectilinear)); - _obj->config.set_key_value("top_surface_line_width", new ConfigOptionFloatOrPercent(nozzle_diameter * 1.2f, false)); - _obj->config.set_key_value("internal_solid_infill_line_width", new ConfigOptionFloatOrPercent(nozzle_diameter * 1.2f, false)); + _obj->config.set_key_value("top_surface_line_width", new ConfigOptionFloatOrPercent(infill_line_width, false)); + _obj->config.set_key_value("internal_solid_infill_line_width", new ConfigOptionFloatOrPercent(infill_line_width, false)); // ORCA: use the pattern parameter _obj->config.set_key_value("top_surface_pattern", new ConfigOptionEnum(pattern)); const auto *top_solid_flow = dynamic_cast(_obj->config.option("top_solid_infill_flow_ratio")); diff --git a/src/slic3r/GUI/SendToPrinter.cpp b/src/slic3r/GUI/SendToPrinter.cpp index 031c5847f4..cd45264a7a 100644 --- a/src/slic3r/GUI/SendToPrinter.cpp +++ b/src/slic3r/GUI/SendToPrinter.cpp @@ -1831,7 +1831,7 @@ what(); } BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << " : Tutk url error: ress = " << res; } - }); + }, wxGetApp().get_printer_cloud_provider()); } } } diff --git a/src/slic3r/GUI/Shortcuts.cpp b/src/slic3r/GUI/Shortcuts.cpp index df8d7c00ca..b3809ade38 100644 --- a/src/slic3r/GUI/Shortcuts.cpp +++ b/src/slic3r/GUI/Shortcuts.cpp @@ -159,6 +159,7 @@ constexpr std::array shortcut_table = {{ SHORTCUT(CollapseSidebar, "collapse_sidebar", L("Collapse/Expand the sidebar"), CANVAS, { WXK_TAB, SHIFT }), SHORTCUT(ReloadDevicePage, "reload_device_page", L("Reload the device page"), CANVAS, { WXK_F5 }), SHORTCUT(KeyboardShortcuts, "keyboard_shortcuts", L("Show keyboard shortcuts list"), CANVAS, { '?' }), + SHORTCUT(Quit, "quit", L("Quit"), GLOBAL, { 'Q', CTRL }), // Speed Dial SHORTCUT(SpeedDial, "speed_dial", L("Open the Speed Dial"), GLOBAL, { WXK_SPACE }), diff --git a/src/slic3r/GUI/Shortcuts.hpp b/src/slic3r/GUI/Shortcuts.hpp index aba315d521..50652af000 100644 --- a/src/slic3r/GUI/Shortcuts.hpp +++ b/src/slic3r/GUI/Shortcuts.hpp @@ -48,7 +48,7 @@ enum class Shortcut : uint8_t { // Display ShowLabels, ShowWireframe, ToggleGcodeWindow, ToggleOneLayerMode, ToggleBeltRawGcode, // Application - Preferences, Search, SwitchView, CollapseSidebar, ReloadDevicePage, KeyboardShortcuts, + Preferences, Search, SwitchView, CollapseSidebar, ReloadDevicePage, KeyboardShortcuts, Quit, // Speed Dial SpeedDial, Count diff --git a/src/slic3r/GUI/StatusPanel.cpp b/src/slic3r/GUI/StatusPanel.cpp index 654d8db56c..d68c9f1635 100644 --- a/src/slic3r/GUI/StatusPanel.cpp +++ b/src/slic3r/GUI/StatusPanel.cpp @@ -196,8 +196,8 @@ static void market_model_scoring_page(int design_id) std::string url; std::string country_code = GUI::wxGetApp().app_config->get_country_code(); std::string model_http_url = GUI::wxGetApp().get_model_http_url(country_code); - if (GUI::wxGetApp().getAgent()->get_model_mall_detail_url(&url, std::to_string(design_id)) == 0) { - std::string user_id = GUI::wxGetApp().getAgent()->get_user_id(); + if (GUI::wxGetApp().getAgent()->get_model_mall_detail_url(&url, std::to_string(design_id), GUI::wxGetApp().get_printer_cloud_provider()) == 0) { + std::string user_id = GUI::wxGetApp().getAgent()->get_user_id(GUI::wxGetApp().get_printer_cloud_provider()); boost::algorithm::replace_first(url, "models", "u/" + user_id + "/rating"); // Prevent user_id from containing design_id size_t sign_in = url.find("/rating"); @@ -3783,7 +3783,7 @@ void StatusPanel::update_model_info() curr_model_task->task_id = curr_task->task_id; request_model_info_flag = true; if (!curr_model_task->task_id.empty() && curr_model_task->task_id.compare("0") != 0) { - wxGetApp().getAgent()->get_subtask(curr_model_task, get_subtask_fn); + wxGetApp().getAgent()->get_subtask(curr_model_task, get_subtask_fn, wxGetApp().get_printer_cloud_provider()); } } } @@ -6032,7 +6032,7 @@ wxBoxSizer *ScoreDialog::get_button_sizer() if (!need_upload_images.empty()) { std::string config; - int ret = wxGetApp().getAgent()->get_oss_config(config, wxGetApp().app_config->get_country_code(), http_code, http_error); + int ret = wxGetApp().getAgent()->get_oss_config(config, wxGetApp().app_config->get_country_code(), http_code, http_error, wxGetApp().get_printer_cloud_provider()); if (ret == -1) { error_info += into_u8(_L("Get oss config failed.")) + "\n\thttp code: " + std::to_string(http_code) + "\n\thttp error: " + http_error; BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": get oss config filed and http_error: " << http_error; @@ -6047,7 +6047,7 @@ wxBoxSizer *ScoreDialog::get_button_sizer() std::pair need_upload = *it; std::string need_upload_uf8 = into_u8(need_upload.second); //Local path when incoming, cloud path when outgoing - ret = wxGetApp().getAgent()->put_rating_picture_oss(config, need_upload_uf8, m_model_id, m_profile_id, http_code, http_error); + ret = wxGetApp().getAgent()->put_rating_picture_oss(config, need_upload_uf8, m_model_id, m_profile_id, http_code, http_error, wxGetApp().get_printer_cloud_provider()); std::unordered_map::iterator iter; switch (ret) { case 0: @@ -6107,7 +6107,7 @@ wxBoxSizer *ScoreDialog::get_button_sizer() } if (m_upload_status_code == StatusCode::UPLOAD_PROGRESS) { - int ret = wxGetApp().getAgent()->put_model_mall_rating(m_rating_id, m_star_count, comment, m_image_url_paths, http_code, http_error); + int ret = wxGetApp().getAgent()->put_model_mall_rating(m_rating_id, m_star_count, comment, m_image_url_paths, http_code, http_error, wxGetApp().get_printer_cloud_provider()); MessageDialog *dlg_info; switch (ret) { case 0: EndModal(wxID_OK); break; diff --git a/src/slic3r/GUI/TaskManager.cpp b/src/slic3r/GUI/TaskManager.cpp index 54efafe8ae..287ef2b5cf 100644 --- a/src/slic3r/GUI/TaskManager.cpp +++ b/src/slic3r/GUI/TaskManager.cpp @@ -375,7 +375,7 @@ std::map TaskManager::get_task_list(int curr_page, i task_query_params.limit = page_count; task_query_params.offset = curr_page * page_count; std::string task_info; - int result = agent->get_user_tasks(task_query_params, &task_info); + int result = agent->get_user_tasks(task_query_params, &task_info, GUI::wxGetApp().get_printer_cloud_provider()); BOOST_LOG_TRIVIAL(trace) << "task_manager: get_task_list task_info=" << task_info; if (result == 0) { try { diff --git a/src/slic3r/GUI/WebViewDialog.cpp b/src/slic3r/GUI/WebViewDialog.cpp index d6fc4a7170..578d33ffd0 100644 --- a/src/slic3r/GUI/WebViewDialog.cpp +++ b/src/slic3r/GUI/WebViewDialog.cpp @@ -832,7 +832,7 @@ void WebViewPanel::SendDesignStaffpick(bool on) void WebViewPanel::OpenModelDetail(std::string id, NetworkAgent *agent) { std::string url; - if ((agent ? agent->get_model_mall_detail_url(&url, id) : get_model_mall_detail_url(&url, id)) == 0) + if ((agent ? agent->get_model_mall_detail_url(&url, id, wxGetApp().get_printer_cloud_provider()) : get_model_mall_detail_url(&url, id)) == 0) { if (url.find("?") != std::string::npos) { diff --git a/src/slic3r/Utils/CalibUtils.cpp b/src/slic3r/Utils/CalibUtils.cpp index a15dffa76a..e23e7645c9 100644 --- a/src/slic3r/Utils/CalibUtils.cpp +++ b/src/slic3r/Utils/CalibUtils.cpp @@ -181,7 +181,7 @@ void update_speed_parameter( const std::string& key) } } -std::vector generate_max_speed_parameter_value(const std::string &key, const bool linear, const int pass) +std::vector generate_max_speed_parameter_value(const std::string &key, const float line_width, const float layer_height, const bool linear, const int pass) { auto preset_bundle = wxGetApp().preset_bundle; auto &printer_config = preset_bundle->printers.get_edited_preset().config; @@ -193,8 +193,6 @@ std::vector generate_max_speed_parameter_value(const std::string &key, c std::vector nozzle_volume_types = preset_bundle->project_config.option("nozzle_volume_type")->values; float nozzle_diameter = printer_config.option("nozzle_diameter")->values[0]; - float layer_height = print_config.option("layer_height")->value; - float line_width = print_config.get_abs_value("line_width", nozzle_diameter); Flow flow = Flow(line_width, layer_height, nozzle_diameter); diff --git a/src/slic3r/Utils/CalibUtils.hpp b/src/slic3r/Utils/CalibUtils.hpp index 00b9e0020c..5bd4a0a04a 100644 --- a/src/slic3r/Utils/CalibUtils.hpp +++ b/src/slic3r/Utils/CalibUtils.hpp @@ -101,7 +101,7 @@ extern void get_default_k_n_value(const std::string &filament_id, float &k, floa extern wxString get_nozzle_volume_type_name(NozzleVolumeType type); extern void update_speed_parameter(const std::string &key); -extern std::vector generate_max_speed_parameter_value(const std::string &key, bool linear, int pass); +extern std::vector generate_max_speed_parameter_value(const std::string &key, float line_width, float layer_height, bool linear, int pass); } } \ No newline at end of file diff --git a/src/slic3r/Utils/MoonrakerPrinterAgent.cpp b/src/slic3r/Utils/MoonrakerPrinterAgent.cpp index 025f0ba918..731d0c007e 100644 --- a/src/slic3r/Utils/MoonrakerPrinterAgent.cpp +++ b/src/slic3r/Utils/MoonrakerPrinterAgent.cpp @@ -146,6 +146,14 @@ beast::error_code run_until_done(net::io_context& ioc, const std::atomic& return done ? result : beast::error_code{net::error::operation_aborted}; } +Slic3r::Http::ProgressFn cancel_when(std::function cancelled) +{ + if (!cancelled) { + return {}; + } + return [cancelled = std::move(cancelled)](Slic3r::Http::Progress, bool& cancel) { cancel = cancelled(); }; +} + uint64_t steady_now_ms() { return static_cast( @@ -214,9 +222,6 @@ int MoonrakerPrinterAgent::connect_printer(const PrinterConnectionParams& params gen = ++connect_generation; base_url = device_info.base_url; api_key = device_info.api_key; - if (connect_thread.joinable()) { - connect_thread.detach(); - } } // Stop existing status stream and clear state @@ -232,7 +237,20 @@ int MoonrakerPrinterAgent::connect_printer(const PrinterConnectionParams& params // Launch connection in background thread (capture by value to avoid data races) { std::lock_guard lock(connect_mutex); - connect_thread = std::thread([this, dev_id = params.dev_id, base_url, api_key, gen]() { perform_connection_async(dev_id, base_url, api_key, gen); }); + // Each connection thread joins the one it supersedes, so the destructor's join waits for all of them + // Shared, so a failed thread start does not destroy the superseded thread while it is still joinable + auto superseded = std::make_shared(std::move(connect_thread)); + try { + connect_thread = std::thread([this, dev_id = params.dev_id, base_url, api_key, gen, superseded]() { + perform_connection_async(dev_id, base_url, api_key, gen); + if (superseded->joinable()) { + superseded->join(); + } + }); + } catch (...) { + connect_thread = std::move(*superseded); + throw; + } } return BAMBU_NETWORK_SUCCESS; @@ -244,9 +262,6 @@ int MoonrakerPrinterAgent::disconnect_printer() std::lock_guard lock(connect_mutex); device_info = MoonrakerDeviceInfo{}; ++connect_generation; // Invalidate any in-flight connection - if (connect_thread.joinable()) { - connect_thread.detach(); - } } stop_status_stream(); @@ -1123,10 +1138,11 @@ bool MoonrakerPrinterAgent::init_device_info(const std::string& dev_id, const st return true; } -bool MoonrakerPrinterAgent::fetch_device_info(const std::string& base_url, - const std::string& api_key, - MoonrakerDeviceInfo& info, - std::string& error) const +bool MoonrakerPrinterAgent::fetch_device_info(const std::string& base_url, + const std::string& api_key, + MoonrakerDeviceInfo& info, + std::string& error, + const std::function& cancelled) const { auto fetch_json = [&](const std::string& url, nlohmann::json& out) { std::string response_body; @@ -1139,6 +1155,7 @@ bool MoonrakerPrinterAgent::fetch_device_info(const std::string& base_url, } http.timeout_connect(5) .timeout_max(10) + .on_progress(cancel_when(cancelled)) .on_complete([&](std::string body, unsigned status) { if (status == 200) { response_body = body; @@ -1182,10 +1199,11 @@ bool MoonrakerPrinterAgent::fetch_device_info(const std::string& base_url, return true; } -bool MoonrakerPrinterAgent::query_printer_status(const std::string& base_url, - const std::string& api_key, - nlohmann::json& status, - std::string& error) const +bool MoonrakerPrinterAgent::query_printer_status(const std::string& base_url, + const std::string& api_key, + nlohmann::json& status, + std::string& error, + const std::function& cancelled) const { std::string url = join_url(base_url, "/printer/objects/query?print_stats&virtual_sdcard&extruder&heater_bed&fan"); @@ -1199,6 +1217,7 @@ bool MoonrakerPrinterAgent::query_printer_status(const std::string& base_url, } http.timeout_connect(5) .timeout_max(10) + .on_progress(cancel_when(cancelled)) .on_complete([&](std::string body, unsigned status_code) { if (status_code == 200) { response_body = body; @@ -1331,7 +1350,7 @@ bool MoonrakerPrinterAgent::fetch_object_list(const std::string& base_url, http.timeout_connect(5) .timeout_max(10) // Gives up once the status stream, the only caller, stops - .on_progress([this](Http::Progress, bool& cancel) { cancel = ws_stop.load(); }) + .on_progress(cancel_when([this] { return ws_stop.load(); })) .on_complete([&](std::string body, unsigned status) { if (status == 200) { response_body = body; @@ -2253,8 +2272,10 @@ void MoonrakerPrinterAgent::perform_connection_async(const std::string& dev_id, try { MoonrakerDeviceInfo fetched_info; - if (!fetch_device_info(base_url, api_key, fetched_info, error_msg)) { - BOOST_LOG_TRIVIAL(error) << "MoonrakerPrinterAgent: Failed to fetch server info: " << error_msg; + if (!fetch_device_info(base_url, api_key, fetched_info, error_msg, is_stale)) { + if (!is_stale()) { + BOOST_LOG_TRIVIAL(error) << "MoonrakerPrinterAgent: Failed to fetch server info: " << error_msg; + } // Orca todo: revist here, for now don't send error, this is set current MachineObject to null // dispatch_local_connect(ConnectStatusFailed, dev_id, "server_info_failed"); return; @@ -2275,12 +2296,15 @@ void MoonrakerPrinterAgent::perform_connection_async(const std::string& dev_id, #if 1 // Query initial status nlohmann::json initial_status; - if (query_printer_status(base_url, api_key, initial_status, error_msg)) { - { - update_status_cache(initial_status); + if (query_printer_status(base_url, api_key, initial_status, error_msg, is_stale)) { + // Under connect_mutex, so a superseded connection never writes into the next connection's cache + std::lock_guard lock(connect_mutex); + if (is_stale()) { + return; } + update_status_cache(initial_status); BOOST_LOG_TRIVIAL(info) << "MoonrakerPrinterAgent: Initial status queried successfully"; - } else { + } else if (!is_stale()) { BOOST_LOG_TRIVIAL(warning) << "MoonrakerPrinterAgent: Initial status query failed: " << error_msg; } @@ -2304,12 +2328,15 @@ void MoonrakerPrinterAgent::perform_connection_async(const std::string& dev_id, result = BAMBU_NETWORK_ERR_CONNECTION_TO_PRINTER_FAILED; } - // Only dispatch if this connection is still the current one - if (result == BAMBU_NETWORK_SUCCESS && !is_stale()) { - dispatch_local_connect(ConnectStatusOk, dev_id, "0"); - dispatch_printer_connected(dev_id); - BOOST_LOG_TRIVIAL(info) << "MoonrakerPrinterAgent: connect_printer completed - dev_id=" << dev_id; - } else if (result != BAMBU_NETWORK_SUCCESS && result != BAMBU_NETWORK_ERR_CANCELED) { + if (result == BAMBU_NETWORK_SUCCESS) { + // Under connect_mutex, so a superseded connection never reports itself connected + std::lock_guard lock(connect_mutex); + if (!is_stale()) { + dispatch_local_connect(ConnectStatusOk, dev_id, "0"); + dispatch_printer_connected(dev_id); + BOOST_LOG_TRIVIAL(info) << "MoonrakerPrinterAgent: connect_printer completed - dev_id=" << dev_id; + } + } else if (result != BAMBU_NETWORK_ERR_CANCELED) { // Orca todo: revist here, for now don't send error, this is set current MachineObject to null // dispatch_local_connect(ConnectStatusFailed, dev_id, error_msg); } diff --git a/src/slic3r/Utils/MoonrakerPrinterAgent.hpp b/src/slic3r/Utils/MoonrakerPrinterAgent.hpp index a7edc476e8..cf487bcf6b 100644 --- a/src/slic3r/Utils/MoonrakerPrinterAgent.hpp +++ b/src/slic3r/Utils/MoonrakerPrinterAgent.hpp @@ -112,7 +112,12 @@ protected: // Methods that derived classes may need to override or access virtual bool init_device_info(const std::string& dev_id, const std::string& dev_ip, const std::string& username, const std::string& password, bool use_ssl, const std::string& port); - virtual bool fetch_device_info(const std::string& base_url, const std::string& api_key, MoonrakerDeviceInfo& info, std::string& error) const; + // An override must give up its request once `cancelled` returns true, or the destructor waits out its timeout + virtual bool fetch_device_info(const std::string& base_url, + const std::string& api_key, + MoonrakerDeviceInfo& info, + std::string& error, + const std::function& cancelled) const; void start_status_stream(const std::string& dev_id, const std::string& base_url, const std::string& api_key); void stop_status_stream(); @@ -137,7 +142,11 @@ private: int send_access_code(const std::string& dev_id); bool fetch_object_list(const std::string& base_url, const std::string& api_key, std::set& objects, std::string& error) const; - bool query_printer_status(const std::string& base_url, const std::string& api_key, nlohmann::json& status, std::string& error) const; + bool query_printer_status(const std::string& base_url, + const std::string& api_key, + nlohmann::json& status, + std::string& error, + const std::function& cancelled) const; bool send_gcode_sync(const std::string& dev_id, const std::string& gcode) const; void send_gcode_async(const std::string& dev_id, const std::string& gcode, std::function on_result = {}) const; diff --git a/src/slic3r/Utils/NetworkAgentFactory.cpp b/src/slic3r/Utils/NetworkAgentFactory.cpp index 82a6e469ae..7f59dc7573 100644 --- a/src/slic3r/Utils/NetworkAgentFactory.cpp +++ b/src/slic3r/Utils/NetworkAgentFactory.cpp @@ -166,8 +166,12 @@ std::shared_ptr NetworkAgentFactory::create_printer_agent_by_id(c void NetworkAgentFactory::clear_printer_agent_cache() { - std::lock_guard lock(s_registry_mutex); - auto& cache = get_printer_agent_cache(); + // Disconnects and destroys the agents outside the lock, since a destructor waits for its agent's threads + std::map> cache; + { + std::lock_guard lock(s_registry_mutex); + cache.swap(get_printer_agent_cache()); + } for (auto& pair : cache) { if (pair.second) pair.second->disconnect_printer(); diff --git a/src/slic3r/Utils/OrcaCloudServiceAgent.cpp b/src/slic3r/Utils/OrcaCloudServiceAgent.cpp index f759d15a2b..69686d470e 100644 --- a/src/slic3r/Utils/OrcaCloudServiceAgent.cpp +++ b/src/slic3r/Utils/OrcaCloudServiceAgent.cpp @@ -71,6 +71,7 @@ #if !defined(_WIN32) #include #include +#include #include #endif @@ -145,10 +146,9 @@ public: #else m_fd = ::open(path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600); if (m_fd == -1) { m_locked = true; return; } // can't open -> don't block - struct flock fl{}; - fl.l_type = F_WRLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; int rc; - do { rc = ::fcntl(m_fd, F_SETLKW, &fl); } while (rc == -1 && errno == EINTR); // blocks in kernel + // An fcntl lock would not block other threads in this process, and any close() of this file would release it. + do { rc = ::flock(m_fd, LOCK_EX); } while (rc == -1 && errno == EINTR); // blocks in kernel m_locked = (rc != -1); #endif } diff --git a/src/slic3r/Utils/QidiPrinterAgent.cpp b/src/slic3r/Utils/QidiPrinterAgent.cpp index 063f7721f0..9b3c8a7cb7 100644 --- a/src/slic3r/Utils/QidiPrinterAgent.cpp +++ b/src/slic3r/Utils/QidiPrinterAgent.cpp @@ -55,7 +55,7 @@ bool QidiPrinterAgent::fetch_filament_info(std::string dev_id, FilamentSyncMode std::string series_id; { MoonrakerDeviceInfo info; - if (fetch_device_info(device_info.base_url, device_info.api_key, info, error)) { + if (fetch_device_info(device_info.base_url, device_info.api_key, info, error, {})) { series_id = infer_series_id(info.model_id, info.dev_name); } } diff --git a/src/slic3r/plugin/PluginAuditManager.cpp b/src/slic3r/plugin/PluginAuditManager.cpp index d3e4ffeb53..1f464cc3ff 100644 --- a/src/slic3r/plugin/PluginAuditManager.cpp +++ b/src/slic3r/plugin/PluginAuditManager.cpp @@ -360,47 +360,52 @@ static const char* category_name(AuditEventCategory category) // Path safety // --------------------------------------------------------------------------- -bool is_inside_allowed_root(const boost::filesystem::path& candidate, const boost::filesystem::path& allowed_root) +namespace { + +// Canonicalize a path for containment comparison. weakly_canonical resolves symlinks but does +// NOT require the path to exist — it canonicalizes the prefix that exists and appends the +// non-existing tail lexically. +boost::filesystem::path canonical_for_comparison(const boost::filesystem::path& path) { namespace fs = boost::filesystem; boost::system::error_code ec; - - // Canonicalize both paths. weakly_canonical resolves symlinks but does - // NOT require the path to exist — it canonicalizes the prefix that exists - // and appends the non-existing tail lexically. - fs::path canon_candidate = fs::weakly_canonical(candidate, ec); + fs::path canon = fs::weakly_canonical(path, ec); if (ec) { // Fall back to lexically_normal + absolute - canon_candidate = fs::absolute(candidate, ec).lexically_normal(); + canon = fs::absolute(path, ec).lexically_normal(); if (ec) - canon_candidate = candidate; + canon = path; } + return canon; +} - fs::path canon_root = fs::weakly_canonical(allowed_root, ec); - if (ec) { - canon_root = fs::absolute(allowed_root, ec).lexically_normal(); - if (ec) - canon_root = allowed_root; - } - - // Component-wise comparison: the root must be a prefix of candidate, - // and the next component must not be ".." or missing. - auto cand_it = canon_candidate.begin(); - auto cand_end = canon_candidate.end(); - auto root_it = canon_root.begin(); - auto root_end = canon_root.end(); - - const auto same_component = [](const fs::path& lhs, const fs::path& rhs) { +bool same_path_component(const boost::filesystem::path& lhs, const boost::filesystem::path& rhs) +{ #ifdef _WIN32 - return boost::algorithm::iequals(lhs.native(), rhs.native()); + return boost::algorithm::iequals(lhs.native(), rhs.native()); #else - return lhs == rhs; + return lhs == rhs; #endif - }; +} + +// Component-wise containment: the whole of canonical_root must be a prefix of +// canonical_candidate, and the remaining components must not traverse upward. Both arguments are +// expected to come from canonical_for_comparison(). On a match, suffix receives the candidate's +// components below the root (empty when the two paths are equal). +bool suffix_inside_root(const boost::filesystem::path& canonical_candidate, + const boost::filesystem::path& canonical_root, + boost::filesystem::path& suffix) +{ + suffix.clear(); + + auto cand_it = canonical_candidate.begin(); + auto cand_end = canonical_candidate.end(); + auto root_it = canonical_root.begin(); + auto root_end = canonical_root.end(); // Consume matching components - while (root_it != root_end && cand_it != cand_end && same_component(*root_it, *cand_it)) { + while (root_it != root_end && cand_it != cand_end && same_path_component(*root_it, *cand_it)) { ++root_it; ++cand_it; } @@ -415,9 +420,19 @@ bool is_inside_allowed_root(const boost::filesystem::path& candidate, const boos return false; } + for (; cand_it != cand_end; ++cand_it) + suffix /= *cand_it; return true; } +} // namespace + +bool is_inside_allowed_root(const boost::filesystem::path& candidate, const boost::filesystem::path& allowed_root) +{ + boost::filesystem::path suffix; + return suffix_inside_root(canonical_for_comparison(candidate), canonical_for_comparison(allowed_root), suffix); +} + // --------------------------------------------------------------------------- // ScopedPluginAuditContext // --------------------------------------------------------------------------- @@ -589,7 +604,8 @@ std::vector PluginAuditManager::default_denied_path_keywords() // it happens to live inside an otherwise-allowed root (e.g. the bundled TLS client cert at // resources_dir()/cert/..., which would become reachable the moment resources_dir() is // granted as a read-only allowed root). Match as whole path components, not substrings, so - // imports such as numpy/__config__.py and stdlib configparser.py remain usable. + // imports such as numpy/__config__.py and stdlib configparser.py remain usable. Inside + // data_dir() they match below that root only; see is_denied_path_keyword(). return {"secret", "secrets", "cert", "certs", "certificate", "certificates", "conf", "config"}; } @@ -608,19 +624,29 @@ bool PluginAuditManager::is_denied_path_keyword(const boost::filesystem::path& c { namespace fs = boost::filesystem; - boost::system::error_code ec; - fs::path canon = fs::weakly_canonical(candidate, ec); - if (ec) { - canon = fs::absolute(candidate, ec).lexically_normal(); - if (ec) - canon = candidate; - } + const fs::path canon = canonical_for_comparison(candidate); + + // The app's data folder can itself sit below a component named like one of the keywords + // without being one: Flatpak keeps it under /.var/app//config/OrcaSlicer, and + // the sandbox's home layout is not ours to change. A keyword above data_dir() therefore says + // nothing about what a plugin may reach inside it, so inside data_dir() the keywords apply to + // the suffix below data_dir() only. Everywhere else -- resources_dir() with the bundled + // certificates, a plugin's own folders, arbitrary files -- the whole path is still checked, + // and so is a keyword under data_dir() itself. + fs::path canonical_data_dir; + if (!data_dir().empty()) + canonical_data_dir = canonical_for_comparison(data_dir()); + + fs::path scope = canon; + fs::path suffix; + if (!canonical_data_dir.empty() && suffix_inside_root(canon, canonical_data_dir, suffix)) + scope = suffix; std::lock_guard lock(m_mutex); if (m_denied_path_keywords.empty()) return false; - for (const auto& component : canon) { + for (const auto& component : scope) { std::string name = component.string(); if (name.empty()) continue; @@ -715,130 +741,38 @@ AuditDecision PluginAuditManager::check_open(const std::string& path_str, const namespace { -// Builds and shows the modal confirmation. Must run on the GUI thread. +// Builds and shows the modal confirmation. Must run on the GUI thread. The prompt helpers in +// PluginAuditDetail below share it so every permission prompt is styled the same way. bool show_permission_dialog(const wxString& message, const wxString& title) { wxMessageDialog dialog(nullptr, message, title, wxYES_NO | wxICON_WARNING); return dialog.ShowModal() == wxID_YES; } -// Shows a permission prompt on the GUI thread and waits for the answer. The caller may be the -// plugin-load worker, so off the main thread the dialog is marshaled with CallAfter. -bool ask_permission(const wxString& message) -{ - if (wxTheApp == nullptr || GUI::wxGetApp().is_closing()) - return false; - - if (wxIsMainThread()) - return show_permission_dialog(message, _L("Plugin permissions")); - - auto result = std::make_shared>(); - auto future = result->get_future(); - GUI::wxGetApp().CallAfter([result, message]() { - if (wxTheApp == nullptr || GUI::wxGetApp().is_closing()) { - result->set_value(false); - return; - } - result->set_value(show_permission_dialog(message, _L("Plugin permissions"))); - }); - return future.get(); -} - } // namespace -bool PluginAuditManager::request_filesystem_read_permissions(const std::string& plugin_key, - const std::vector& paths) -{ - if (plugin_key.empty() || paths.empty()) - return true; - - PluginDescriptor descriptor; - if (!PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty()) - return false; - - PluginInstallState state; - read_install_state(boost::filesystem::path(descriptor.plugin_root), state); - - std::vector missing; - for (const std::string& path : paths) { - if (std::find(state.permissions.fs_read.begin(), state.permissions.fs_read.end(), path) == state.permissions.fs_read.end()) - missing.push_back(path); - } - if (missing.empty()) - return true; - - wxString requested_paths; - for (const std::string& path : missing) - requested_paths += wxString::FromUTF8(path.c_str()) + "\n"; - - if (!ask_permission(wxString::Format(_L("Plugin \"%s\" requests filesystem read access to:\n%s"), - wxString::FromUTF8(descriptor.name.c_str()), requested_paths))) - return false; - - seed_install_metadata(state, descriptor); - - state.permissions.fs_read.insert(state.permissions.fs_read.end(), missing.begin(), missing.end()); - return write_install_state(boost::filesystem::path(descriptor.plugin_root), state); -} - bool PluginAuditManager::request_network_permissions(const std::string& plugin_key, const std::vector& urls) { if (plugin_key.empty() || urls.empty()) return true; - PluginDescriptor descriptor; - if (!PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty()) - return false; - // Reduce every request to scheme://host before comparing or persisting it, so a URL with a // path or query cannot create a second grant for the same host. - std::vector requested; + PluginPermissions requested; for (const std::string& url : urls) { const std::string normalized = normalize_network_url(url); if (normalized.empty()) { BOOST_LOG_TRIVIAL(warning) << "[AUDIT] Invalid network permission request for plugin " << plugin_key << ": " << url; return false; } - if (std::find(requested.begin(), requested.end(), normalized) == requested.end()) - requested.push_back(normalized); + if (std::find(requested.network_http.begin(), requested.network_http.end(), normalized) == requested.network_http.end()) + requested.network_http.push_back(normalized); } - PluginInstallState state; - read_install_state(boost::filesystem::path(descriptor.plugin_root), state); - - std::vector missing; - for (const std::string& entry : requested) { - if (!network_permission_matches(state.permissions.network_http, entry) && - !network_permission_matches(state.permissions.network_socket, entry)) - missing.push_back(entry); - } - if (missing.empty()) - return true; - - wxString requested_hosts; - for (const std::string& entry : missing) - requested_hosts += wxString::FromUTF8(entry.c_str()) + "\n"; - - if (!ask_permission(wxString::Format(_L("Plugin \"%s\" requests network access to:\n%s"), - wxString::FromUTF8(descriptor.name.c_str()), requested_hosts))) - return false; - - seed_install_metadata(state, descriptor); - - // A declared host is reachable through both HTTP and raw socket events. Recording the grant in - // both existing lists keeps the sidecar self-describing and means either event layer matches - // it without relying on the other list. - for (const std::string& entry : missing) { - if (std::find(state.permissions.network_http.begin(), state.permissions.network_http.end(), entry) == - state.permissions.network_http.end()) - state.permissions.network_http.push_back(entry); - if (std::find(state.permissions.network_socket.begin(), state.permissions.network_socket.end(), entry) == - state.permissions.network_socket.end()) - state.permissions.network_socket.push_back(entry); - } - - return write_install_state(boost::filesystem::path(descriptor.plugin_root), state); + // network_permission_matches() also applies the recorded host grant to raw socket events, so + // one HTTP grant covers both event layers without prompting for each list separately. + return request_permissions(plugin_key, requested); } void PluginAuditManager::report_violation(const AuditViolation& violation) @@ -1095,7 +1029,7 @@ std::vector audit_targets(const std::string& event_name, AuditEvent // Thread creation exposes no user-supplied target. Use a fixed sentinel so the grant // persists per plugin: the permission list matches targets by exact string, and the // started function's repr embeds an address that changes every run. - targets.emplace_back("thread"); + targets.emplace_back(kThreadPermissionTarget); return targets; default: break; @@ -1160,6 +1094,20 @@ bool has_network_permission(const PluginPermissions& permissions, const std::str PluginAuditManager::network_permission_matches(permissions.network_socket, target); } +// A sandbox plugin may not have a sidecar yet. Seed the small amount of install metadata the +// writer needs so clicking Yes still creates the JSON file. +void seed_install_metadata(const PluginDescriptor& descriptor, PluginInstallState& state) +{ + if (!state.plugin_name.empty()) + return; + + state.installed_from = descriptor.is_cloud_plugin() ? "cloud" : "local"; + state.installed_version = !descriptor.installed_version.empty() ? descriptor.installed_version : descriptor.version; + state.plugin_name = descriptor.name; + state.cloud_uuid = descriptor.cloud_uuid(); + state.enabled = true; +} + bool persist_permission(const std::string& plugin_key, PluginInstallState& state, std::vector& permission_list, @@ -1169,7 +1117,7 @@ bool persist_permission(const std::string& plugin_key, if (!PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty()) return false; - seed_install_metadata(state, descriptor); + seed_install_metadata(descriptor, state); if (!has_permission(permission_list, target)) permission_list.push_back(target); @@ -1254,6 +1202,13 @@ bool prompt_for_targets(AuditEventCategory category, const std::string& plugin_n _L("Plugin permission request")); } +// Shows a prompt whose body may cover several permission buckets. Must run on the GUI thread. +bool prompt_for_permission_message(const wxString& message) +{ + wxMessageDialog dialog(nullptr, message, _L("Plugin permissions"), wxYES_NO | wxICON_WARNING); + return dialog.ShowModal() == wxID_YES; +} + // Records a grant in the plugin's sidecar so it is not asked again. Reads the install state // freshly because the async prompt outlives the caller's stack copy of it. void persist_grant(const std::string& plugin_key, AuditEventCategory category, bool by_event, const std::vector& keys) @@ -1296,7 +1251,7 @@ static const char* audit_category_name(AuditEventCategory category) // SlicingPipeline hook runs on the slicing worker thread (see PluginHooks.cpp), and // BackgroundSlicingProcess::stop()/stop_internal() park the UI thread until that worker stops. // Blocking the worker on a marshaled modal -- which is safe for the plugin-load worker that -// request_filesystem_read_permissions runs on -- would therefore deadlock the application (the +// request_permissions runs on -- would therefore deadlock the application (the // invariant PluginHostUi.cpp documents for slicing-hook UI calls). Off the main thread the prompt // is therefore posted asynchronously and the current event denied (fail closed, like an unanswered // prompt); the grant is persisted once the user accepts, so a later attempt succeeds without @@ -1434,6 +1389,113 @@ int audit_plugin_event(PluginAuditManager& mgr, const std::string& event_name, A } // namespace PluginAuditDetail +bool PluginAuditManager::request_permissions(const std::string& plugin_key, const PluginPermissions& requested) +{ + if (plugin_key.empty()) + return true; + + PluginDescriptor descriptor; + if (!PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty()) + return false; + + PluginInstallState state; + read_install_state(boost::filesystem::path(descriptor.plugin_root), state); + + // Per bucket, keep only the targets that no earlier grant already covers. Dropping these + // before prompting keeps a repeated declaration from asking again for what is on disk. + struct MissingBucket { + AuditEventCategory category; + std::vector targets; + }; + std::vector missing_buckets; + + // A network target counts as granted when either network list covers it, matched the same + // way the audit hook matches it (canonical scheme://host, bare host, legacy address tuple), + // so a declaration that is already reachable is not asked for again. + const auto collect_missing = [&missing_buckets, &state](AuditEventCategory category, + const std::vector& requested_targets, + const std::vector& granted_targets) { + MissingBucket bucket{category, {}}; + for (const std::string& target : requested_targets) { + if (target.empty()) + continue; + + const bool already_granted = + is_network_category(category) + ? PluginAuditDetail::has_network_permission(state.permissions, target) + : std::find(granted_targets.begin(), granted_targets.end(), target) != granted_targets.end(); + + if (!already_granted && std::find(bucket.targets.begin(), bucket.targets.end(), target) == bucket.targets.end()) + bucket.targets.push_back(target); + } + if (!bucket.targets.empty()) + missing_buckets.push_back(std::move(bucket)); + }; + + collect_missing(AuditEventCategory::FsRead, requested.fs_read, state.permissions.fs_read); + collect_missing(AuditEventCategory::FsReadWrite, requested.fs_readwrite, state.permissions.fs_readwrite); + collect_missing(AuditEventCategory::Http, requested.network_http, state.permissions.network_http); + collect_missing(AuditEventCategory::Socket, requested.network_socket, state.permissions.network_socket); + collect_missing(AuditEventCategory::ProcessCreate, requested.process, state.permissions.process); + collect_missing(AuditEventCategory::Threading, requested.threading, state.permissions.threading); + + if (missing_buckets.empty()) + return true; + + if (wxTheApp == nullptr || GUI::wxGetApp().is_closing()) + return false; + + const auto build_message = [](const std::string& plugin_name, const std::vector& buckets) { + wxString message; + for (const MissingBucket& bucket : buckets) { + wxString targets; + for (const std::string& target : bucket.targets) + targets += wxString::FromUTF8(target.c_str()) + "\n"; + + if (!message.IsEmpty()) + message += "\n\n"; + message += PluginAuditDetail::audit_message(bucket.category, wxString::FromUTF8(plugin_name.c_str()), + wxEmptyString, targets, bucket.targets.size()); + } + return message; + }; + + bool granted = false; + if (wxIsMainThread()) { + granted = PluginAuditDetail::prompt_for_permission_message(build_message(descriptor.name, missing_buckets)); + } else { + auto result = std::make_shared>(); + auto future = result->get_future(); + GUI::wxGetApp().CallAfter([result, plugin_name = descriptor.name, missing_buckets, build_message]() { + result->set_value(PluginAuditDetail::prompt_for_permission_message(build_message(plugin_name, missing_buckets))); + }); + granted = future.get(); + } + + if (!granted) + return false; + + // The dialog can stay open while another grant is persisted; re-read before saving so this + // request adds to the current state instead of replacing it. + PluginInstallState latest_state; + if (read_install_state(boost::filesystem::path(descriptor.plugin_root), latest_state)) + state = std::move(latest_state); + + PluginAuditDetail::seed_install_metadata(descriptor, state); + + for (const MissingBucket& bucket : missing_buckets) { + std::vector* permission_list = + PluginAuditDetail::permission_list_for(bucket.category, /*by_event=*/false, state.permissions); + if (!permission_list) + continue; + for (const std::string& target : bucket.targets) + if (std::find(permission_list->begin(), permission_list->end(), target) == permission_list->end()) + permission_list->push_back(target); + } + + return write_install_state(boost::filesystem::path(descriptor.plugin_root), state); +} + void PluginAuditManager::record_root_frame() { PyObject* frame = reinterpret_cast(PyEval_GetFrame()); // borrowed reference @@ -1595,10 +1657,12 @@ void PluginAuditManager::install_hook() for (const auto& name : default_denied_filenames()) add_denied_filename(name); - // Categorical denies on top of the exact-name list above: no path a plugin can reach may - // contain a "secret", "cert"(ificate), or "conf"(ig) path component, regardless of which - // allowed root it happens to sit inside. default_denied_path_keywords() is the single - // source of this list; the tests seed from it too. + // Categorical denies on top of the exact-name list above: a path a plugin reaches must not + // have a "secret", "cert"(ificate), or "conf"(ig) component below data_dir() -- or anywhere + // in the path outside data_dir(), whose own location may legitimately contain one (Flatpak + // keeps it under .../config/OrcaSlicer). This holds regardless of which allowed root the + // path happens to sit inside. default_denied_path_keywords() is the single source of this + // list; the tests seed from it too. for (const auto& keyword : default_denied_path_keywords()) add_denied_path_keyword(keyword); diff --git a/src/slic3r/plugin/PluginAuditManager.hpp b/src/slic3r/plugin/PluginAuditManager.hpp index b3340ee4a6..c2f043286a 100644 --- a/src/slic3r/plugin/PluginAuditManager.hpp +++ b/src/slic3r/plugin/PluginAuditManager.hpp @@ -13,6 +13,12 @@ namespace Slic3r { +struct PluginPermissions; + +// Thread creation exposes no user-supplied target, so both the runtime audit event and a +// request_permissions(threading=True) declaration use this fixed target. +inline constexpr const char* kThreadPermissionTarget = "thread"; + struct AuditDecision { bool allowed = true; std::string reason; @@ -102,12 +108,13 @@ public: bool is_denied_filename(const boost::filesystem::path& candidate) const; // --- denied-path-keyword registry --- - // Keywords that categorically deny a path if ANY component matches one case-insensitively -- + // Keywords that categorically deny a path when a component matches one case-insensitively -- // e.g. a "secrets" subfolder, a "certificates" folder, a "conf"/"config" directory, or a // .conf/.ini file anywhere the plugin can otherwise reach, including inside an allowed root. - // This is broader than the exact-name is_denied_filename registry, but it is not a substring - // match: importable modules such as numpy/__config__.py, configparser.py, sysconfig.py, or - // user folders such as "Conference" and "Concert" are unrelated names and must stay promptable. + // The components above the app's data_dir() are not considered (see below). This is broader + // than the exact-name is_denied_filename registry, but it is not a substring match: + // importable modules such as numpy/__config__.py, configparser.py, sysconfig.py, or user + // folders such as "Conference" and "Concert" are unrelated names and must stay promptable. void add_denied_path_keyword(const std::string& keyword); // The list install_hook() seeds into the keyword registry. Exposed so tests seed the exact @@ -115,7 +122,10 @@ public: static std::vector default_denied_path_keywords(); // True when any component of candidate's (canonicalized) path matches a registered keyword, - // case-insensitively. A registered "conf" keyword also blocks .conf/.ini file components. + // case-insensitively. Inside data_dir(), only the components below data_dir() are checked: + // the app's own data folder may itself sit under a component named like a keyword (Flatpak + // keeps it under .../config/OrcaSlicer), which must not deny everything inside it. A + // registered "conf" keyword also blocks .conf/.ini file components. bool is_denied_path_keyword(const boost::filesystem::path& candidate) const; // is_denied_filename(candidate) || is_denied_path_keyword(candidate). Convenience for @@ -130,19 +140,19 @@ public: AuditDecision check_path_access(const boost::filesystem::path& candidate, bool is_write); AuditDecision check_open(const std::string& path, const std::string& mode); - // Ask the user to grant the requested filesystem-read paths. The request may originate on a - // plugin load worker, so the implementation marshals the modal dialog to the wx main thread. - // Returns true only when every missing path was granted and persisted; denial aborts the plugin - // load without adding a permission. - bool request_filesystem_read_permissions(const std::string& plugin_key, - const std::vector& paths); + // Ask the user to grant the requested permissions. The request may originate on a plugin + // load worker, so the implementation marshals the modal dialog to the wx main thread. + // Targets already persisted for the plugin are not shown or asked for again. Returns true + // only when every missing target was granted and persisted; denial aborts the plugin load + // without adding a permission. + bool request_permissions(const std::string& plugin_key, const PluginPermissions& requested); // Ask the user to grant network access to the given http(s) URLs. Each URL is reduced to its // scheme and host before prompting and persisting, so one approval covers every path, query - // and port on that host. The grant is written to both network_http and network_socket: the - // same declared host can surface through HTTP events (urllib/http.client) and raw socket - // events. Like request_filesystem_read_permissions, the request may originate on a plugin - // load worker; denial aborts the plugin load without adding a permission. + // and port on that host. The grant is recorded as an HTTP grant; network_permission_matches + // applies it to raw socket events for the same host too. Like request_permissions, the request + // may originate on a plugin load worker; denial aborts the plugin load without adding a + // permission. bool request_network_permissions(const std::string& plugin_key, const std::vector& urls); diff --git a/src/slic3r/plugin/PythonInterpreter.cpp b/src/slic3r/plugin/PythonInterpreter.cpp index 89dc91723c..ca0dfa16f4 100644 --- a/src/slic3r/plugin/PythonInterpreter.cpp +++ b/src/slic3r/plugin/PythonInterpreter.cpp @@ -2,6 +2,7 @@ #include "GeneratedConfig.hpp" #include "libslic3r/Utils.hpp" #include "PluginAuditManager.hpp" +#include "PythonPluginBridge.hpp" #include #include #include @@ -664,6 +665,11 @@ bool PythonInterpreter::initialize() // background-thread exceptions) to /log/python_*.log. install_python_stderr_redirect(); + // Attribute plugin-spawned Python threads to the plugin/capability that created them. + // Must run while the GIL is still held here, after the audit hook is in place and + // before the GIL is released below. + install_python_thread_audit_shim(); + // Release the GIL so other threads can acquire it via PyGILState_Ensure. // Without this, calls from background threads will block trying to acquire the GIL. m_main_thread_state = PyEval_SaveThread(); diff --git a/src/slic3r/plugin/PythonPluginBridge.cpp b/src/slic3r/plugin/PythonPluginBridge.cpp index e12192af7d..379ffd8741 100644 --- a/src/slic3r/plugin/PythonPluginBridge.cpp +++ b/src/slic3r/plugin/PythonPluginBridge.cpp @@ -49,8 +49,7 @@ thread_local std::string g_active_plugin_key; std::mutex g_registry_mutex; std::unordered_map> g_pending_capabilities; std::unordered_map g_pending_package; -std::unordered_map> g_pending_fs_read_permissions; -std::unordered_map> g_pending_network_permissions; +std::unordered_map g_pending_permissions; struct PluginInstanceHandle { // The C++ plugin interface points into a Python object. Keep both alive through one @@ -89,8 +88,7 @@ void discard_pending_capture_without_python(const std::string& plugin_key) g_pending_package.erase(package); } - g_pending_fs_read_permissions.erase(plugin_key); - g_pending_network_permissions.erase(plugin_key); + g_pending_permissions.erase(plugin_key); } } // namespace @@ -115,8 +113,7 @@ void PythonPluginBridge::begin_plugin_capture(const std::string& plugin_key) // for this same entry path. g_pending_capabilities.erase(plugin_key); g_pending_package.erase(plugin_key); - g_pending_fs_read_permissions.erase(plugin_key); - g_pending_network_permissions.erase(plugin_key); + g_pending_permissions.erase(plugin_key); } // From now until finalize/cancel, @orca.plugin and register_capability() calls made by // Python code on this thread are attributed to this plugin. @@ -147,8 +144,7 @@ std::vector PythonPluginBridge::finalize_plugin_capture(cons std::lock_guard lock(g_registry_mutex); g_pending_capabilities.erase(capture_key); g_pending_package.erase(capture_key); - g_pending_fs_read_permissions.erase(capture_key); - g_pending_network_permissions.erase(capture_key); + g_pending_permissions.erase(capture_key); }; try { @@ -181,47 +177,27 @@ std::vector PythonPluginBridge::finalize_plugin_capture(cons // Permission declarations are collected while register_capabilities() runs so the // plugin can describe its needs without touching wx from the Python load worker. Ask // only after registration returns, before capability instances are materialized. - std::vector fs_read_permissions; + PluginPermissions requested_permissions; { std::lock_guard lock(g_registry_mutex); - auto it = g_pending_fs_read_permissions.find(capture_key); - if (it != g_pending_fs_read_permissions.end()) { - fs_read_permissions = std::move(it->second); - g_pending_fs_read_permissions.erase(it); + auto it = g_pending_permissions.find(capture_key); + if (it != g_pending_permissions.end()) { + requested_permissions = std::move(it->second); + g_pending_permissions.erase(it); } } - if (!fs_read_permissions.empty()) { + const bool has_permission_request = + !requested_permissions.fs_read.empty() || !requested_permissions.fs_readwrite.empty() || + !requested_permissions.network_http.empty() || !requested_permissions.network_socket.empty() || + !requested_permissions.process.empty() || !requested_permissions.threading.empty(); + if (has_permission_request) { bool granted = false; { py::gil_scoped_release release; - granted = PluginAuditManager::instance().request_filesystem_read_permissions(plugin_key, fs_read_permissions); + granted = PluginAuditManager::instance().request_permissions(plugin_key, requested_permissions); } if (!granted) { - error = _u8L("Plugin filesystem read permission request denied"); - BOOST_LOG_TRIVIAL(warning) << error << " for key " << plugin_key; - discard_pending_for_key(); - clear_active_key(); - return {}; - } - } - - std::vector network_permissions; - { - std::lock_guard lock(g_registry_mutex); - auto it = g_pending_network_permissions.find(capture_key); - if (it != g_pending_network_permissions.end()) { - network_permissions = std::move(it->second); - g_pending_network_permissions.erase(it); - } - } - if (!network_permissions.empty()) { - bool granted = false; - { - py::gil_scoped_release release; - granted = PluginAuditManager::instance().request_network_permissions(plugin_key, network_permissions); - } - if (!granted) { - error = _u8L("Plugin network permission request denied"); + error = _u8L("Plugin permission request denied"); BOOST_LOG_TRIVIAL(warning) << error << " for key " << plugin_key; discard_pending_for_key(); clear_active_key(); @@ -350,8 +326,7 @@ void PythonPluginBridge::cancel_plugin_capture(const std::string& plugin_key) // may already have registered under this key. g_pending_capabilities.erase(plugin_key); g_pending_package.erase(plugin_key); - g_pending_fs_read_permissions.erase(plugin_key); - g_pending_network_permissions.erase(plugin_key); + g_pending_permissions.erase(plugin_key); } if (g_active_plugin_key == plugin_key) @@ -378,8 +353,7 @@ void PythonPluginBridge::clear_pending_captures() (void) pkg.release(); } g_pending_package.clear(); - g_pending_fs_read_permissions.clear(); - g_pending_network_permissions.clear(); + g_pending_permissions.clear(); g_active_plugin_key.clear(); return; } @@ -388,8 +362,7 @@ void PythonPluginBridge::clear_pending_captures() BOOST_LOG_TRIVIAL(info) << "Clearing " << g_pending_capabilities.size() << " pending Python plugin capture(s)"; g_pending_capabilities.clear(); g_pending_package.clear(); - g_pending_fs_read_permissions.clear(); - g_pending_network_permissions.clear(); + g_pending_permissions.clear(); g_active_plugin_key.clear(); } @@ -589,12 +562,33 @@ void bind_python_api(pybind11::module_& m) m.def( "request_permissions", - [](const std::vector& fs_read, const std::vector& network) { + [](const std::vector& fs_read, + const std::vector& fs_readwrite, + const std::vector& network_http, + const std::vector& network_socket, + const std::vector& process, + bool threading, + const std::vector& network) { if (g_active_plugin_key.empty()) throw py::value_error("request_permissions() called outside plugin discovery context"); // Validate and canonicalize everything before touching the pending registry, so a // partially invalid call cannot leave a half-recorded request behind. + const auto reject_empty = [](const char* name, const std::vector& targets) { + for (const std::string& target : targets) + if (target.empty()) + throw py::value_error(std::string("request_permissions(") + name + + "=...) does not accept empty values"); + }; + reject_empty("fs_read", fs_read); + reject_empty("fs_readwrite", fs_readwrite); + reject_empty("network_http", network_http); + reject_empty("network_socket", network_socket); + reject_empty("process", process); + + // A network URL is reduced to scheme://host, so one grant covers every path, query + // and port on that host. It is recorded as an HTTP grant; network_permission_matches + // applies that grant to raw socket events for the same host too. std::vector normalized_network; normalized_network.reserve(network.size()); for (const std::string& url : network) { @@ -602,37 +596,49 @@ void bind_python_api(pybind11::module_& m) if (normalized.empty()) throw py::value_error( "request_permissions(network=...) requires an http:// or https:// URL with a host"); - if (std::find(normalized_network.begin(), normalized_network.end(), normalized) == normalized_network.end()) + if (std::find(normalized_network.begin(), normalized_network.end(), normalized) == + normalized_network.end()) normalized_network.push_back(normalized); } - for (const std::string& path : fs_read) { - if (path.empty()) - throw py::value_error("request_permissions(fs_read=...) does not accept empty paths"); - } - std::lock_guard lock(g_registry_mutex); - auto& requested_fs = g_pending_fs_read_permissions[g_active_plugin_key]; - for (const std::string& path : fs_read) { - if (std::find(requested_fs.begin(), requested_fs.end(), path) == requested_fs.end()) - requested_fs.push_back(path); - } + PluginPermissions& requested = g_pending_permissions[g_active_plugin_key]; - if (!normalized_network.empty()) { - auto& requested_network = g_pending_network_permissions[g_active_plugin_key]; - for (const std::string& entry : normalized_network) { - if (std::find(requested_network.begin(), requested_network.end(), entry) == requested_network.end()) - requested_network.push_back(entry); - } - } + const auto add_targets = [](std::vector& bucket, const std::vector& targets) { + for (const std::string& target : targets) + if (std::find(bucket.begin(), bucket.end(), target) == bucket.end()) + bucket.push_back(target); + }; + + add_targets(requested.fs_read, fs_read); + add_targets(requested.fs_readwrite, fs_readwrite); + add_targets(requested.network_http, network_http); + add_targets(requested.network_http, normalized_network); + add_targets(requested.network_socket, network_socket); + add_targets(requested.process, process); + + if (threading && std::find(requested.threading.begin(), requested.threading.end(), + kThreadPermissionTarget) == requested.threading.end()) + requested.threading.emplace_back(kThreadPermissionTarget); }, - py::arg("fs_read") = std::vector{}, py::arg("network") = std::vector{}, + py::arg("fs_read") = std::vector{}, + py::arg("fs_readwrite") = std::vector{}, + py::arg("network_http") = std::vector{}, + py::arg("network_socket") = std::vector{}, + py::arg("process") = std::vector{}, + py::arg("threading") = false, + py::arg("network") = std::vector{}, R"pbdoc(Request permissions while OrcaSlicer loads your module. -`fs_read` lists filesystem paths to read. `network` lists http(s) URLs; each is reduced to its -scheme and host, so one grant covers every path, query and port on that host. The host presents -the requests to the user after register_capabilities() returns. Denying a request aborts the -plugin load.)pbdoc"); +Each bucket takes the target strings the plugin expects the corresponding audit event to +report: filesystem paths for fs_read and fs_readwrite, URLs for network_http, socket addresses +for network_socket, and commands for process. threading=True requests permission to start +threads. Targets already granted to the plugin are not asked for again. + +`network` also lists http(s) URLs, but each is reduced to its scheme and host, so one grant covers +every path, query and port on that host and also authorizes raw socket events for it. The host +presents one request to the user after register_capabilities() returns and before any capability +instance is created. Denying the request aborts the plugin load.)pbdoc"); m.def("plugin", [](py::object cls) { if (g_active_plugin_key.empty()) @@ -660,6 +666,93 @@ plugin load.)pbdoc"); } +void install_python_thread_audit_shim() +{ + // Runs with the GIL held from PythonInterpreter::initialize(). CPython's own thread bootstrap + // calls the target with no knowledge of the audit context that created it: the calling + // thread is the only place the plugin key and capability are still available. Capture them + // here, then re-establish the same ScopedPluginAuditContext inside the spawned thread before + // the plugin body runs. The identity lives only in this C++ closure -- no Python-visible + // setter is added. + try { + py::object thread_module = py::module_::import("_thread"); + + const int installed = PyObject_HasAttrString(thread_module.ptr(), "_orca_thread_audit_shim_installed"); + if (installed == 1) { + BOOST_LOG_TRIVIAL(debug) << "[AUDIT] Python thread attribution shim already installed"; + return; + } + if (installed < 0) + PyErr_Clear(); + + py::object original = py::reinterpret_steal( + PyObject_GetAttrString(thread_module.ptr(), "start_new_thread")); + if (!original || !PyCallable_Check(original.ptr())) { + PyErr_Clear(); + BOOST_LOG_TRIVIAL(error) << "[AUDIT] _thread.start_new_thread is missing or not callable; " + "plugin threads will run without audit attribution"; + return; + } + + py::object shim = py::cpp_function( + [original](py::object function, py::object args, py::object kwargs) -> py::object { + const std::string plugin_key = PluginAuditManager::instance().current_plugin(); + if (plugin_key.empty()) { + // Not called from a plugin: preserve the stock implementation untouched. + return kwargs.is_none() ? original(function, args) : original(function, args, kwargs); + } + const std::string capability = PluginAuditManager::instance().current_capability(); + + py::object guarded = py::cpp_function( + [function, plugin_key, capability](py::args call_args, py::kwargs call_kwargs) -> py::object { + ScopedPluginAuditContext audit_scope(plugin_key, capability); + PyObject* result = PyObject_Call(function.ptr(), call_args.ptr(), call_kwargs.ptr()); + if (result == nullptr) + throw py::error_already_set(); + return py::reinterpret_steal(result); + }); + return kwargs.is_none() ? original(guarded, args) : original(guarded, args, kwargs); + }, + py::arg("function"), py::arg("args"), py::arg("kwargs") = py::none()); + + if (PyObject_SetAttrString(thread_module.ptr(), "start_new_thread", shim.ptr()) < 0) { + PyErr_Clear(); + BOOST_LOG_TRIVIAL(error) + << "[AUDIT] Failed to install Python thread attribution shim on _thread.start_new_thread"; + return; + } + if (PyObject_SetAttrString(thread_module.ptr(), "_orca_thread_audit_shim_installed", Py_True) < 0) + PyErr_Clear(); + + // threading.py caches the function at import time (as `_start_new_thread` in 3.12, and as + // `start_new_thread` in older versions). Patch the cached reference too when the module is + // already loaded; otherwise its Thread.start() would keep calling the unwrapped original. + py::object sys_modules = py::module_::import("sys").attr("modules"); + PyObject* threading_module = PyDict_GetItemString(sys_modules.ptr(), "threading"); + if (threading_module && threading_module != Py_None) { + const char* cached_names[] = {"_start_new_thread", "start_new_thread"}; + for (const char* cached_name : cached_names) { + const int has_cached_name = PyObject_HasAttrString(threading_module, cached_name); + if (has_cached_name < 0) { + PyErr_Clear(); + continue; + } + if (has_cached_name != 1) + continue; + if (PyObject_SetAttrString(threading_module, cached_name, shim.ptr()) < 0) { + PyErr_Clear(); + BOOST_LOG_TRIVIAL(warning) << "[AUDIT] Failed to update threading." << cached_name + << " with the Python thread attribution shim"; + } + } + } + + BOOST_LOG_TRIVIAL(info) << "[AUDIT] Python thread attribution shim installed"; + } catch (const std::exception& ex) { + BOOST_LOG_TRIVIAL(error) << "[AUDIT] Failed to install Python thread attribution shim: " << ex.what(); + } +} + } // namespace Slic3r #ifdef ORCA_PYTHON_STUBGEN_MODULE diff --git a/src/slic3r/plugin/PythonPluginBridge.hpp b/src/slic3r/plugin/PythonPluginBridge.hpp index 5178c6f5db..39d6191702 100644 --- a/src/slic3r/plugin/PythonPluginBridge.hpp +++ b/src/slic3r/plugin/PythonPluginBridge.hpp @@ -13,6 +13,15 @@ namespace Slic3r { class PluginCapabilityInterface; } namespace Slic3r { +// Install the thread-attribution shim: wraps `_thread.start_new_thread` (and the reference +// cached by an already-imported `threading` module) so a thread spawned from inside a plugin +// call runs with that call's plugin key/capability audit scope. The captured identity is held +// in a private C++ wrapper; nothing is exposed to Python that could set it. +// +// Call with the GIL held, after PluginAuditManager::install_hook() and before the interpreter +// releases the GIL. Safe to call more than once per interpreter. +void install_python_thread_audit_shim(); + // One materialized capability returned from finalize_plugin_capture: the C++ instance // and its resolved get_name() (cached while the GIL was held). struct CapturedCapability diff --git a/tests/fff_print/test_fill.cpp b/tests/fff_print/test_fill.cpp index b2d0ef9abe..f6e7c55b4b 100644 --- a/tests/fff_print/test_fill.cpp +++ b/tests/fff_print/test_fill.cpp @@ -1392,6 +1392,27 @@ TEST_CASE("Gyroid infill of an object matches the infill of a larger object with } } +TEST_CASE("Multiline infill keeps its lines parallel around a corner", "[Fill]") +{ + // A left turn by 135 degrees, drawn as two lines half of the 0.4 mm spacing to each side of it. + const double turn = 0.75 * PI; + Polylines paths{ Polyline{ Point::new_scale(0., 0.), Point::new_scale(10., 0.), + Point::new_scale(10. + 10. * std::cos(turn), 10. * std::sin(turn)) } }; + FillParams params; + params.multiline = 2; + multiline_fill(paths, params, 0.4f); + REQUIRE(paths.size() == 1); + + // The outer line turns at the miter point, where the lines 0.2 mm out from both legs meet. + const Point miter = Point::new_scale(10. + 0.2 * std::tan(0.5 * turn), -0.2); + double nearest = std::numeric_limits::max(); + for (const Point &point : paths.front().points) + nearest = std::min(nearest, (point - miter).cast().norm()); + REQUIRE(nearest < scaled(0.001)); + // The round ends are flattened to a fraction of the offset rather than to the integer grid. + REQUIRE(paths.front().size() < 100); +} + TEST_CASE("Multiline cubic infill follows the cubic lines without crossing itself", "[Fill]") { const int multiline = GENERATE(2, 3); @@ -2417,3 +2438,70 @@ TEST_CASE("Infill lines that cannot reverse join only end to start", "[Fill]") CHECK(position(c) < position(d)); } } + +// Orca: the top surface fills of the topmost layer, which keep their order, each as its extrusions in print order. +static std::vector> top_surface_fills(const Print &print) +{ + std::vector> fills; + for (const LayerRegion *region : print.objects().front()->layers().back()->regions()) + for (const ExtrusionEntity *entity : region->fills.entities) + if (auto *fill = dynamic_cast(entity); fill && fill->no_sort) + if (std::any_of(fill->entities.begin(), fill->entities.end(), [](const ExtrusionEntity *ee) { return ee->role() == erTopSolidInfill; })) + fills.emplace_back(fill->entities.begin(), fill->entities.end()); + return fills; +} + +static double travel_between(const std::vector &extrusions) +{ + double travel = 0.; + for (size_t i = 1; i < extrusions.size(); ++ i) + travel += unscale((extrusions[i]->first_point() - extrusions[i - 1]->last_point()).cast().norm()); + return travel; +} + +TEST_CASE("Monotonic line top surfaces print their gap fill next to their lines and keep the lines in order", "[Fill]") +{ + // The slanted legs of the letter A leave gap fill along the walls where the lines end. + auto slice_letter = [](Print &print, Model &model, const char *gap_fill_target) { + auto config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({{"top_surface_pattern", "monotonicline"}, + {"gap_fill_target", gap_fill_target}, + {"filter_out_gap_fill", 0}, + {"top_shell_layers", 3}, + {"layer_height", 0.2}, + {"initial_layer_print_height", 0.2}}); + Slic3r::Test::init_print({Slic3r::Test::TestMesh::A}, print, model, config); + print.process(); + }; + Print print_without, print_with; + Model model_without, model_with; + slice_letter(print_without, model_without, "nowhere"); + slice_letter(print_with, model_with, "topbottom"); + const auto without = top_surface_fills(print_without); + const auto with = top_surface_fills(print_with); + REQUIRE(with.size() == without.size()); + + auto is_gap_fill = [](const ExtrusionEntity *ee) { return ee->role() == erGapFill; }; + size_t gap_fills = 0, gap_fills_before_a_line = 0; + for (size_t i = 0; i < with.size(); ++ i) { + std::vector lines, gaps; + std::partition_copy(with[i].begin(), with[i].end(), std::back_inserter(gaps), std::back_inserter(lines), is_gap_fill); + const auto last_line = std::find_if_not(with[i].rbegin(), with[i].rend(), is_gap_fill); + gap_fills += gaps.size(); + gap_fills_before_a_line += std::count_if(last_line, with[i].rend(), is_gap_fill); + // The lines are those of the surface without gap fill, in the same order and direction. + REQUIRE(lines.size() == without[i].size()); + for (size_t j = 0; j < lines.size(); ++ j) { + CHECK(lines[j]->first_point() == without[i][j]->first_point()); + CHECK(lines[j]->last_point() == without[i][j]->last_point()); + } + // Printed where they are, the gap fills travel less than printed after the last line. + if (! gaps.empty()) { + std::vector appended = lines; + appended.insert(appended.end(), gaps.begin(), gaps.end()); + CHECK(travel_between(with[i]) < travel_between(appended)); + } + } + REQUIRE(gap_fills > 0); + CHECK(gap_fills_before_a_line > 0); +} diff --git a/tests/fff_print/test_multifilament.cpp b/tests/fff_print/test_multifilament.cpp index b7fccf2890..1a5b9630c9 100644 --- a/tests/fff_print/test_multifilament.cpp +++ b/tests/fff_print/test_multifilament.cpp @@ -388,6 +388,50 @@ TEST_CASE("Toolchange gcode is bracketed against FanMover splitting its moves", CHECK(count_occurrences(gcode_str, ";_FAN_MOVER_SKIP_START") <= 1); } +TEST_CASE("Filament start and end G-code get the same placeholders on every toolchange path", "[MultiFilament]") +{ + const std::string path = GENERATE(as{}, "direct", "type1"); + CAPTURE(path); + + DynamicPrintConfig config = multifilament_config(2, { + { "skirt_loops", 0 }, + { "brim_type", "no_brim" }, + }); + std::vector> per_object_overrides; + if (path == "direct") { + config.set_deserialize_strict({ { "print_sequence", "by object" } }); + per_object_overrides = { {}, { { "outer_wall_filament_id", "2" }, { "inner_wall_filament_id", "2" } } }; + } else { + config.set_deserialize_strict({ + { "enable_prime_tower", true }, + { "wipe_tower_type", "type1" }, + { "prime_tower_width", 35 }, + { "wipe_tower_x", 120 }, + { "wipe_tower_y", 120 }, + { "printable_area", "0x0,200x0,200x200,0x200" }, + }); + per_object_overrides = { { { "extruder", "1" } }, { { "extruder", "2" } } }; + } + const std::string start = "; filament start [filament_extruder_id] [layer_num] [layer_z] [max_layer_z]"; + const std::string end = "; filament end [filament_extruder_id] [layer_num] [layer_z] [max_layer_z]"; + config.set_key_value("filament_start_gcode", new ConfigOptionStrings({ start, start })); + config.set_key_value("filament_end_gcode", new ConfigOptionStrings({ end, end })); + + std::string gcode; + REQUIRE_NOTHROW(gcode = slice_with_object_overrides({ cube(20), cube(20) }, config, per_object_overrides)); + CHECK(gcode.find("\n; filament start 1 ") != std::string::npos); + if (path == "direct") { + CHECK(gcode.find("\n; filament end 0 ") != std::string::npos); + } else { + // Most layers unload filament 1, which the extruder index (always 0 on this single nozzle) can't show, + // and the end of the print adds at most one such line. + size_t unloads_of_1 = 0; + for (size_t pos = gcode.find("\n; filament end 1 "); pos != std::string::npos; pos = gcode.find("\n; filament end 1 ", pos + 1)) + ++unloads_of_1; + CHECK(unloads_of_1 > 1); + } +} + // With wait_for_temp_on_wipe_tower the blocking M109 moves from right after the Tn command to // a stop point parked beside the wipe tower (heat-up drool falls next to the tower, not onto // its top): tagged with _WAIT_FOR_TEMP_ON_WIPE_TOWER, after the toolchange and before the diff --git a/tests/fff_print/test_print.cpp b/tests/fff_print/test_print.cpp index a9654809c6..29decadcdd 100644 --- a/tests/fff_print/test_print.cpp +++ b/tests/fff_print/test_print.cpp @@ -725,15 +725,49 @@ TEST_CASE("Custom G-code placeholders are substituted", "[Print]") }) .find("; between-object-gcode") != std::string::npos); - // [layer_num] keeps counting across sequentially printed objects (199 then 399). + // [layer_num] keeps counting across sequentially printed objects (199 then 399), and [max_layer_z] + // stays at the first object's 20mm top while the second object starts. const std::string per_layer = slice_two_cubes_arranged({ { "print_sequence", "by object" }, - { "layer_change_gcode", ";Layer:[layer_num] ([layer_z] mm)" }, + { "layer_change_gcode", ";Layer:[layer_num] ([layer_z] mm) max [max_layer_z]" }, { "layer_height", 0.1 }, { "initial_layer_print_height", 0.1 }, }); CHECK(per_layer.find(";Layer:199 ") != std::string::npos); CHECK(per_layer.find(";Layer:399 ") != std::string::npos); + CHECK(per_layer.find(";Layer:200 (0.1 mm) max 20\n") != std::string::npos); +} + +TEST_CASE("Timelapse G-code gets the snapshot placeholders on bed slingers and other printers", "[Print]") +{ + const std::string structure = GENERATE(as{}, "i3", "corexy"); + CAPTURE(structure); + std::string gcode; + REQUIRE_NOTHROW(gcode = slice({ cube(20) }, { + { "printer_structure", structure }, + { "printable_area", "0x0,200x0,200x200,0x200" }, + { "bed_exclude_area", "0x0" }, + { "extruder_clearance_radius", 40 }, + { "timelapse_type", "0" }, + { "time_lapse_gcode", "; Timelapse {if has_timelapse_safe_pos}safe{else}none{endif} [timelapse_pos_x] " + "[clear_to_x0] [curr_physical_extruder_id]" }, + })); + CHECK(gcode.find("\n; Timelapse safe ") != std::string::npos); +} + +TEST_CASE("The first filament start G-code on Bambu Lab printers gets the layer placeholders", "[Print]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_key_value("filament_start_gcode", new ConfigOptionStrings({ "; Start [layer_num] [layer_z] [max_layer_z]" })); + Print print; + Model model; + init_print({ cube(20) }, print, model, config); + print.is_BBL_printer() = true; + + std::string gcode; + REQUIRE_NOTHROW(gcode = Slic3r::Test::gcode(print)); + // The first filament start G-code runs before the first layer. + CHECK(gcode.find("\n; Start -1 ") != std::string::npos); } // The final print statistics are known only after the whole G-code is generated, yet every custom G-code, diff --git a/tests/fff_print/test_skirt_brim.cpp b/tests/fff_print/test_skirt_brim.cpp index c51dd5ebc6..c732c54793 100644 --- a/tests/fff_print/test_skirt_brim.cpp +++ b/tests/fff_print/test_skirt_brim.cpp @@ -212,6 +212,36 @@ TEST_CASE("Object brims are generated per instance", "[SkirtBrim]") } } +TEST_CASE("Brim groups the parts of an object by contact", "[SkirtBrim]") +{ + // 10 mm cubes along X as the parts of one object: A and B overlap, C and D touch, and E stands 0.5 mm clear of D. + const std::vector part_x{ 0., 8., 30., 40., 50.5 }; + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ { "skirt_loops", 0 }, { "brim_type", "outer_only" }, { "brim_width", 3 }, { "layer_height", 0.2 } }); + Print print; + Model model; + init_print({ cube(10) }, print, model, config, nullptr, false); + for (size_t i = 1; i < part_x.size(); ++ i) { + TriangleMesh part = cube(10); + part.translate(float(part_x[i]), 0.f, 0.f); + model.objects.front()->add_volume(std::move(part), ModelVolumeType::MODEL_PART, false); + } + print.apply(model, config); + print.process(); + + const PrintObject &object = *print.objects().front(); + std::set> groups; + for (const groupedVolumeSlices &group : object.firstLayerObjGroups()) { + std::set parts; + for (const ObjectID &volume_id : group.volume_ids) + for (size_t i = 0; i < object.model_object()->volumes.size(); ++ i) + if (object.model_object()->volumes[i]->id() == volume_id) + parts.insert(i); + groups.insert(parts); + } + CHECK(groups == std::set>{ { 0, 1 }, { 2, 3 }, { 4 } }); +} + TEST_CASE("Uncombined neighboring brims precede their respective objects", "[SkirtBrim]") { Print print; @@ -1091,6 +1121,32 @@ TEST_CASE("Belt brim is absent when both widths are zero", "[SkirtBrim][belt]") } } +TEST_CASE("Belt brim layers give layer change G-code every layer change placeholder", "[SkirtBrim][belt]") +{ + DynamicPrintConfig config = belt_brim_config(); + config.set_deserialize_strict({ + { "brim_type", "outer_only" }, + { "brim_width", 10 }, + { "leading_brim_length", 30 }, + { "brim_object_gap", 0 }, + { "layer_change_gcode", "G92 E0\n; LC [layer_num] [most_used_physical_extruder_id] [curr_y_acceleration_limit] " + "[curr_accumulated_mass] [curr_layer_mass]\n" }, + }); + Print print; + Model model; + init_print({ cube(20) }, print, model, config); + print.process(); + const int bands = belt_brim_apron_bands(*print.objects().front()); + REQUIRE(bands > 0); + std::string gc; + REQUIRE_NOTHROW(gc = gcode(print)); + // The apron bands print first, so they are layers 0 to bands - 1. + for (int layer = 0; layer < bands; ++ layer) { + INFO(layer); + CHECK(gc.find("\n; LC " + std::to_string(layer) + " 0 ") != std::string::npos); + } +} + TEST_CASE("Leading brim length alone produces a belt brim", "[SkirtBrim][belt]") { // Exercises the leading_brim_length-only enablement path and the downhill sweep. diff --git a/tests/fff_print/test_wipe_tower.cpp b/tests/fff_print/test_wipe_tower.cpp index 78adb000be..fd6aa7c5cf 100644 --- a/tests/fff_print/test_wipe_tower.cpp +++ b/tests/fff_print/test_wipe_tower.cpp @@ -8,7 +8,9 @@ #include #include "libslic3r/Model.hpp" #include "libslic3r/Print.hpp" +#include #include +#include #include #include @@ -22,9 +24,11 @@ #include "libslic3r/ClipperUtils.hpp" #include "libslic3r/GCode/GCodeProcessor.hpp" #include "libslic3r/GCode/WipeTower.hpp" +#include "libslic3r/LocalesUtils.hpp" #include "libslic3r/PrintConfig.hpp" #include "test_helpers.hpp" +#include "test_utils.hpp" #include "libslic3r/PrintBase.hpp" #include "libslic3r/TriangleMesh.hpp" @@ -219,6 +223,24 @@ TEST_CASE("The wipe tower sets Klipper's acceleration and accel_to_decel on one !Catch::Matchers::ContainsSubstring("M204")); } +TEST_CASE("The wipe tower's G-code moves keep a decimal point in a comma-decimal locale", "[WipeTower]") +{ + // The GUI slices on a thread that keeps the user's numeric locale. + CommaNumericLocale comma; + CNumericLocalesSetter restore; + if (! comma.apply()) + SKIP("no locale with a comma decimal separator is installed"); + DynamicPrintConfig config = wipe_tower_toolchange_config("klipper"); + // Type 1 towers join their toolchange blocks with a travel move of their own. + config.set_deserialize_strict({ { "wipe_tower_type", "type1" } }); + const std::string gcode = slice_with_prime_tower(config); + REQUIRE_FALSE(wipe_tower_regions(gcode).empty()); + std::istringstream lines(gcode); + for (std::string line; std::getline(lines, line);) + if (! line.empty() && line.front() == 'G' && line.find(',') != std::string::npos) + FAIL_CHECK(line); +} + // What Print feeds the shared estimate. The libslic3r WipeTowerEstimate cases cannot see this: // they call the estimator directly. The estimate counts the filaments the print really uses, // so the two-filament shape gives the outer wall the second one. @@ -476,3 +498,41 @@ TEST_CASE("A tower printed without a tool change is still validated against the CHECK(print.wipe_tower_data(1).depth > 0.f); CHECK_THAT(print.validate().string, Catch::Matchers::ContainsSubstring("printable area")); } + +TEST_CASE("Only a cone wall gives the tower a stabilization cone", "[WipeTower]") +{ + // The cone angle stays in the config for every wall type, but only a cone wall prints the + // cone. A 120 mm object makes the tower tall enough that a 30 degree cone would reach the + // thin plate in front of the tower, which the real rectangle or rib tower stays clear of. + const std::string wall_type = GENERATE("rectangle", "rib", "cone"); + DynamicPrintConfig config = tower_estimate_config(wall_type.c_str()); + config.set_deserialize_strict({ { "wipe_tower_type", "type2" }, + { "wipe_tower_cone_angle", "30" }, + { "wipe_tower_x", "30" }, + { "wipe_tower_y", "80" }, + { "layer_height", "0.3" } }); + + TriangleMesh tall = make_cube(20., 20., 120.); + tall.translate(150.f, 150.f, 0.f); + TriangleMesh plate = make_cube(30., 32., 2.); + plate.translate(40.f, 30.f, 0.f); + const double plate_max_y = 30. + 32.; + + Print print; + Model model; + init_print({ std::move(tall), std::move(plate) }, print, model, config, nullptr, false); + print.apply(model, config); + print.process(); + REQUIRE(print.has_wipe_tower()); + + const BoundingBox footprint(print.first_layer_wipe_tower_corners()); + INFO("wall type " << wall_type << ", tower depth " << print.wipe_tower_data().depth << ", footprint min y " + << unscaled(footprint.min.y())); + if (wall_type == "cone") { + CHECK(unscaled(footprint.min.y()) < plate_max_y); + CHECK(print.get_conflict_result().has_value()); + } else { + CHECK(unscaled(footprint.min.y()) > plate_max_y); + CHECK_FALSE(print.get_conflict_result().has_value()); + } +} diff --git a/tests/libslic3r/test_config.cpp b/tests/libslic3r/test_config.cpp index dcf808ab92..b1add2b3c5 100644 --- a/tests/libslic3r/test_config.cpp +++ b/tests/libslic3r/test_config.cpp @@ -28,6 +28,7 @@ #include #include +#include #include #include #include @@ -1728,6 +1729,29 @@ TEST_CASE("Default options of enum lists get their definition's keys map", "[Con CHECK(enum_lists > 0); } +TEST_CASE("Custom G-code placeholder lists are keyed by option keys", "[Config]") +{ + const auto &placeholders = custom_gcode_specific_placeholders(); + REQUIRE_FALSE(placeholders.empty()); + for (const auto &[gcode_key, keys] : placeholders) { + INFO(gcode_key); + CHECK(print_config_def.has(gcode_key)); + } + + // Multiline text options that aren't custom G-code; add any new one that isn't G-code here. + const std::set not_gcode = { "notes", "filament_notes", "printer_notes", "post_process", + "adaptive_pressure_advance_model", "small_area_infill_flow_compensation_model" }; + size_t gcode_options = 0; + for (const auto &[key, def] : print_config_def.options) { + if (!def.multiline || not_gcode.count(key) > 0) + continue; + INFO(key); + CHECK(placeholders.count(key) == 1); + ++gcode_options; + } + CHECK(gcode_options == placeholders.size()); +} + TEST_CASE("A disabled filament override survives the merge with a parent that sets it", "[Config][Variant]") { std::set no_keys; diff --git a/tests/libslic3r/test_fill_corner_smoothing.cpp b/tests/libslic3r/test_fill_corner_smoothing.cpp index 6991917655..35296809b1 100644 --- a/tests/libslic3r/test_fill_corner_smoothing.cpp +++ b/tests/libslic3r/test_fill_corner_smoothing.cpp @@ -8,8 +8,12 @@ #include #include +#include +#include #include "libslic3r/Fill/FillCornerSmoothing.hpp" +#include "libslic3r/Line.hpp" #include "libslic3r/Polyline.hpp" +#include "libslic3r/libslic3r.h" using namespace Slic3r; @@ -32,20 +36,40 @@ double max_turn_cosine(const Polyline &polyline) return sharpest; } -bool contains(const Polyline &polyline, const Point &point) +// How far before the corner at (10, 0) the path leaves the straight leg along the x axis. +double departure_before_corner(const Polyline &polyline) { - return std::find(polyline.points.begin(), polyline.points.end(), point) != polyline.points.end(); + double departure = 0.; + for (const Point &point : polyline.points) + if (point.y() == 0) + departure = std::max(departure, unscale(point.x())); + return 10. - departure; +} + +// The distance from a point to the nearest edge of a path. +double distance_to(const Polyline &polyline, const Point &point) +{ + double distance = std::numeric_limits::max(); + for (size_t i = 1; i < polyline.size(); ++i) + distance = std::min(distance, Line(polyline[i - 1], polyline[i]).distance_to(point)); + return distance; } const double tolerance = scaled(0.0125); +// The smoothing at the given factor, flattened to the given resolution. +CornerSmoothing smoothing(double factor, double resolution = tolerance) +{ + return CornerSmoothing{ factor, resolution }; +} + } // 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); + smooth_polyline_corners(smooth, smoothing(1.)); REQUIRE(smooth.size() > sharp.size()); REQUIRE(smooth.front() == sharp.front()); @@ -61,11 +85,11 @@ TEST_CASE("Corner smoothing keeps the path untouched at a zero factor", "[FillCo const Polyline sharp = asymmetric_corner(); Polyline none = sharp; - smooth_polyline_corners(none, 0., tolerance); + smooth_polyline_corners(none, smoothing(0.)); REQUIRE(none.points == sharp.points); Polyline invalid = sharp; - smooth_polyline_corners(invalid, std::numeric_limits::quiet_NaN(), tolerance); + smooth_polyline_corners(invalid, smoothing(std::numeric_limits::quiet_NaN())); REQUIRE(invalid.points == sharp.points); } @@ -73,32 +97,33 @@ TEST_CASE("Corner smoothing consumes at most half of the shorter leg", "[FillCor { // 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. + // rounded within 5mm of it on both legs, even though the other leg is 100mm long. Polyline smooth = asymmetric_corner(); - smooth_polyline_corners(smooth, 1., tolerance); + smooth_polyline_corners(smooth, smoothing(1.)); - 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. + REQUIRE(departure_before_corner(smooth) > 0.); + REQUIRE(departure_before_corner(smooth) <= 5.); + // The rounded corner is the polygon of the curve's tangents, which stays inside the box spanned by the + // two legs, and every vertex of it is within 5mm of the corner along the outgoing leg. 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()); + if (point.x() == Point::new_scale(10., 0.).x() && point != smooth.back()) + REQUIRE(point.y() <= Point::new_scale(0., 5.).y()); } } TEST_CASE("Corner smoothing scales the curve with the factor", "[FillCornerSmoothing]") { Polyline half = asymmetric_corner(); - smooth_polyline_corners(half, 0.5, tolerance); + smooth_polyline_corners(half, smoothing(0.5)); Polyline full = asymmetric_corner(); - smooth_polyline_corners(full, 1., tolerance); + smooth_polyline_corners(full, smoothing(1.)); - // 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.))); + // Half of the factor leaves the 10mm leg closer to the corner. + REQUIRE(departure_before_corner(half) < departure_before_corner(full)); // A larger factor rounds a wider portion of the legs, cutting more of the corner off. REQUIRE(full.length() < half.length()); } @@ -109,16 +134,16 @@ TEST_CASE("Corner smoothing leaves hairpins sharp", "[FillCornerSmoothing]") // 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); + smooth_polyline_corners(hairpin, smoothing(1.)); REQUIRE(hairpin == sharp); } TEST_CASE("Corner smoothing follows the flattening tolerance", "[FillCornerSmoothing]") { Polyline coarse = asymmetric_corner(); - smooth_polyline_corners(coarse, 1., scaled(0.2)); + smooth_polyline_corners(coarse, smoothing(1., scaled(0.2))); Polyline fine = asymmetric_corner(); - smooth_polyline_corners(fine, 1., scaled(0.001)); + smooth_polyline_corners(fine, smoothing(1., scaled(0.001))); REQUIRE(fine.size() > coarse.size()); REQUIRE(fine.front() == coarse.front()); @@ -131,7 +156,7 @@ TEST_CASE("Corner smoothing emits no zero length segments", "[FillCornerSmoothin 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); + smooth_polyline_corners(zigzag, smoothing(1.)); for (size_t i = 1; i < zigzag.size(); ++i) REQUIRE((zigzag[i] - zigzag[i - 1]).cast().squaredNorm() > 0.); @@ -143,7 +168,7 @@ TEST_CASE("Corner smoothing rounds every vertex of a polygon", "[FillCornerSmoot 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); + smooth_polygons_corners(smooth, smoothing(1.)); const Polyline rounded = smooth.front().split_at_first_point(); REQUIRE(smooth.front().size() > square.size()); @@ -168,7 +193,7 @@ TEST_CASE("Corner smoothing keeps the ends of a path that returns to its start", 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); + smooth_polyline_corners(retrace, smoothing(1.)); REQUIRE(retrace.size() > sharp.size()); REQUIRE(retrace.front() == sharp.front()); @@ -187,11 +212,51 @@ TEST_CASE("Corner smoothing ignores vertices splitting a straight leg", "[FillCo split.points.insert(split.points.begin() + 2, Point::new_scale(15., 0.)); Polyline smooth_plain = plain; - smooth_polyline_corners(smooth_plain, 1., tolerance); + smooth_polyline_corners(smooth_plain, smoothing(1.)); Polyline smooth_split = split; - smooth_polyline_corners(smooth_split, 1., tolerance); + smooth_polyline_corners(smooth_split, smoothing(1.)); REQUIRE(smooth_split.points == smooth_plain.points); - // Both corners reach the middle of the 10mm run they share, which the extra vertex sat on. - REQUIRE(contains(smooth_plain, Point::new_scale(15., 0.))); + // Both corners reach equally far into the 10mm run they share. + double first = 20., last = 10.; + for (const Point &point : smooth_plain.points) + if (point.y() == 0) { + first = std::min(first, unscale(point.x())); + last = std::max(last, unscale(point.x())); + } + REQUIRE(first - 10. == Catch::Approx(20. - last).margin(1e-5)); +} + +TEST_CASE("Corner smoothing turns by the same angle at every vertex of a corner", "[FillCornerSmoothing]") +{ + Polyline smooth = asymmetric_corner(); + smooth_polyline_corners(smooth, smoothing(1.)); + REQUIRE(smooth.size() > 4); + double sharpest = 0., gentlest = PI; + for (size_t i = 1; i + 1 < smooth.size(); ++i) { + const Vec2d incoming = (smooth[i] - smooth[i - 1]).cast().normalized(); + const Vec2d outgoing = (smooth[i + 1] - smooth[i]).cast().normalized(); + const double turn = std::atan2(std::abs(cross2(incoming, outgoing)), incoming.dot(outgoing)); + sharpest = std::max(sharpest, turn); + gentlest = std::min(gentlest, turn); + } + // The vertices together make up the right angle of the corner. + REQUIRE_THAT(sharpest * double(smooth.size() - 2), Catch::Matchers::WithinRel(0.5 * PI, 0.02)); + REQUIRE_THAT(gentlest, Catch::Matchers::WithinRel(sharpest, 0.02)); +} + +TEST_CASE("Corner smoothing keeps within the resolution of its curve", "[FillCornerSmoothing]") +{ + // The curve itself, up to 0.2 microns. + Polyline fine = asymmetric_corner(); + smooth_polyline_corners(fine, smoothing(1., scaled(0.0002))); + auto vertices = [&fine](double resolution) { + Polyline smooth = asymmetric_corner(); + smooth_polyline_corners(smooth, smoothing(1., scaled(resolution))); + for (const Point &point : smooth.points) + REQUIRE(distance_to(fine, point) <= scaled(resolution + 0.0002)); + return smooth.size() - 2; + }; + // A coarser resolution takes fewer vertices. + REQUIRE(vertices(0.05) < vertices(0.0125)); } diff --git a/tests/libslic3r/test_fill_plane_path.cpp b/tests/libslic3r/test_fill_plane_path.cpp index e28d74b4fc..c12cabed72 100644 --- a/tests/libslic3r/test_fill_plane_path.cpp +++ b/tests/libslic3r/test_fill_plane_path.cpp @@ -6,10 +6,10 @@ #include "libslic3r/libslic3r.h" #include "libslic3r/Fill/FillBase.hpp" #include -#include #include "libslic3r/Config.hpp" #include #include +#include #include #include @@ -69,19 +69,18 @@ double path_length(const Points &points) return length; } -double discrete_curvature_at(const Points &points, const Point &point) +// The edges of the first rounded corner of the order 1 Hilbert curve, which leaves the leg x = 0 and joins the leg y = 1. +std::vector first_corner_edges(const Points &points) { - const auto point_it = std::find(points.begin(), points.end(), point); - REQUIRE(point_it != points.end()); - const size_t point_idx = size_t(std::distance(points.begin(), point_it)); - REQUIRE(point_idx > 0); - REQUIRE(point_idx + 1 < points.size()); - - const Vec2d incoming = (points[point_idx] - points[point_idx - 1]).cast() / output_scale; - const Vec2d outgoing = (points[point_idx + 1] - points[point_idx]).cast() / output_scale; - const Vec2d chord = incoming + outgoing; - const double cross = std::abs(incoming.x() * outgoing.y() - incoming.y() * outgoing.x()); - return 2. * cross / (incoming.norm() * outgoing.norm() * chord.norm()); + std::vector edges; + for (size_t i = 1; i < points.size(); ++i) { + if (points[i - 1].x() == 0 && points[i].x() == 0) + continue; + if (points[i - 1].y() == coord_t(output_scale) && points[i].y() == coord_t(output_scale)) + break; + edges.push_back((points[i] - points[i - 1]).cast().norm()); + } + return edges; } } // namespace @@ -140,44 +139,30 @@ TEST_CASE("Smoothed Hilbert curve honors path resolution", "[FillPlanePath]") REQUIRE(fine.back() == coarse.back()); } -TEST_CASE("Smoothed Hilbert corners use a uniform subdivision depth", "[FillPlanePath]") +TEST_CASE("Smoothed Hilbert corners turn by the same angle at every vertex", "[FillPlanePath]") { + // A planner slows down at a vertex by how much it turns, so a rounded corner spreads its turn evenly. const Points smooth = TestableHilbertCurve().generate_points(0.0035, 1., 1); - const Point curve_entry(0, coord_t(0.5 * output_scale)); - const Point curve_exit(coord_t(0.5 * output_scale), coord_t(output_scale)); - - const auto entry_it = std::find(smooth.begin(), smooth.end(), curve_entry); - REQUIRE(entry_it != smooth.end()); - const auto exit_it = std::find(entry_it, smooth.end(), curve_exit); - REQUIRE(exit_it != smooth.end()); - - const size_t segment_count = size_t(std::distance(entry_it, exit_it)); - REQUIRE(segment_count > 1); - REQUIRE((segment_count & (segment_count - 1)) == 0); - - double previous_length = (entry_it[1] - entry_it[0]).cast().norm(); - REQUIRE(previous_length > 0.); - double max_length_ratio = 1.; - for (size_t segment = 1; segment < segment_count; ++segment) { - const double current_length = (entry_it[segment + 1] - entry_it[segment]).cast().norm(); - REQUIRE(current_length > 0.); - max_length_ratio = std::max(max_length_ratio, - std::max(current_length / previous_length, previous_length / current_length)); - previous_length = current_length; + std::vector turns; + for (size_t i = 1; i + 1 < smooth.size(); ++i) { + const Vec2d incoming = (smooth[i] - smooth[i - 1]).cast().normalized(); + const Vec2d outgoing = (smooth[i + 1] - smooth[i]).cast().normalized(); + const double turn = std::atan2(std::abs(cross2(incoming, outgoing)), incoming.dot(outgoing)); + if (turn > 1e-6) + turns.push_back(turn); } - REQUIRE(max_length_ratio < 1.5); + REQUIRE(turns.size() > 2); + const auto [sharpest, gentlest] = std::minmax_element(turns.begin(), turns.end()); + REQUIRE_THAT(*gentlest, Catch::Matchers::WithinRel(*sharpest, 0.02)); } -TEST_CASE("Hilbert smoothing joins straight segments with continuous curvature", "[FillPlanePath]") +TEST_CASE("Hilbert smoothing eases into the turn", "[FillPlanePath]") { - const Points coarse = TestableHilbertCurve().generate_points(0.005, 0.5, 1); - const Points fine = TestableHilbertCurve().generate_points(0.0001, 0.5, 1); - const Point first_curve_entry(0, coord_t(0.75 * output_scale)); - - const double coarse_entry_curvature = discrete_curvature_at(coarse, first_curve_entry); - const double fine_entry_curvature = discrete_curvature_at(fine, first_curve_entry); - REQUIRE(coarse_entry_curvature > 0.); - REQUIRE(fine_entry_curvature < 0.25 * coarse_entry_curvature); + // Every vertex turns by the same angle, so the edges are as long as the curve is gentle. The curvature starts + // from zero at the legs, so the edges shorten away from them. + const std::vector edges = first_corner_edges(TestableHilbertCurve().generate_points(0.0002, 1., 1)); + REQUIRE(edges.size() >= 16); + REQUIRE(edges[0] / edges[1] > 1.1); } TEST_CASE("Octagram spiral smoothing rounds the turns of the spiral", "[FillPlanePath]") diff --git a/tests/libslic3r/test_locales_utils.cpp b/tests/libslic3r/test_locales_utils.cpp index fc17e26ad1..03300d6815 100644 --- a/tests/libslic3r/test_locales_utils.cpp +++ b/tests/libslic3r/test_locales_utils.cpp @@ -1,55 +1,17 @@ #include -#include -#include - #include #include #include #include #include #include "libslic3r/LocalesUtils.hpp" +#include "test_utils.hpp" #include using namespace Slic3r; -namespace { - -// Switches this thread's numeric locale to one whose decimal separator is a comma, -// when the system has one installed. -struct CommaNumericLocale -{ -#ifdef _WIN32 - bool apply() - { - for (const char* name : { "de-DE", "German_Germany.1252" }) - if (std::setlocale(LC_NUMERIC, name) != nullptr) - return true; - return false; - } -#else - locale_t locale { (locale_t) 0 }; - bool apply() - { - for (const char* name : { "de_DE.UTF-8", "de_DE.utf8", "de_DE" }) - if ((locale = newlocale(LC_NUMERIC_MASK, name, (locale_t) 0)) != (locale_t) 0) { - uselocale(locale); - return true; - } - return false; - } - // Freed once the setters around apply() have put the thread's own locale back. - ~CommaNumericLocale() - { - if (locale != (locale_t) 0) - freelocale(locale); - } -#endif -}; - -} // namespace - TEST_CASE("Floats print as printf prints them in the C locale", "[LocalesUtils]") { const auto [value, precision, text] = GENERATE(table({ diff --git a/tests/libslic3r/test_wipe_tower_estimate.cpp b/tests/libslic3r/test_wipe_tower_estimate.cpp index 22117e686d..220358bd5e 100644 --- a/tests/libslic3r/test_wipe_tower_estimate.cpp +++ b/tests/libslic3r/test_wipe_tower_estimate.cpp @@ -20,6 +20,7 @@ #include "libslic3r/Point.hpp" #include "libslic3r/libslic3r.h" #include +#include #include #include #include "libslic3r/clonable_ptr.hpp" @@ -426,3 +427,107 @@ TEST_CASE("prime_tower_is_printed follows the option the user set", "[WipeTowerE config.set_key_value("enable_prime_tower", new ConfigOptionBool(true)); CHECK(prime_tower_is_printed(config, 0, 1, false)); } + +// A size x size mm footprint anchored at its lower-left corner, on a plate whose anchors may +// lie anywhere in [0, 90] x [0, 90]. +static Polygon square_footprint(double size) { return Polygon({ {0, 0}, {scaled(size), 0}, {scaled(size), scaled(size)}, {0, scaled(size)} }); } +static Polygon box(double x0, double y0, double x1, double y1) +{ + return Polygon({ {scaled(x0), scaled(y0)}, {scaled(x1), scaled(y0)}, {scaled(x1), scaled(y1)}, {scaled(x0), scaled(y1)} }); +} +static const BoundingBox plate_anchors(Point(0, 0), Point(scaled(90.), scaled(90.))); + +// The footprint placed at `anchor` overlaps no obstacle: at most it touches one. +static bool clear_of(Polygon footprint, const Point &anchor, const Polygons &obstacles) +{ + footprint.translate(anchor); + double overlap = 0.; + for (const Polygon &shared : intersection(Polygons{ footprint }, obstacles)) + overlap += std::abs(shared.area()); + return overlap < scaled(0.01) * scaled(0.01); +} + +TEST_CASE("A tower already clear of every object stays where it is", "[WipeTowerEstimate]") { + const Point target(scaled(10.), scaled(70.)); + const std::optional anchor = nearest_clear_wipe_tower_anchor(plate_anchors, square_footprint(10.), { box(40., 0., 60., 100.) }, target); + REQUIRE(anchor.has_value()); + CHECK(*anchor == target); +} + +TEST_CASE("A tower that lands on an object moves to the nearest side of it", "[WipeTowerEstimate]") { + // A strip from x 40 to 60 covers the plate's full depth. Anchored at x 42 the footprint + // spans 42-52, so it clears the strip at x 30 (12 mm left) or x 60 (18 mm right). + const Polygons obstacles = { box(40., 0., 60., 100.) }; + const std::optional anchor = nearest_clear_wipe_tower_anchor(plate_anchors, square_footprint(10.), obstacles, + Point(scaled(42.), scaled(50.))); + REQUIRE(anchor.has_value()); + CHECK(clear_of(square_footprint(10.), *anchor, obstacles)); + CHECK_THAT(unscaled(anchor->x()), WithinAbs(30., 1e-3)); + CHECK_THAT(unscaled(anchor->y()), WithinAbs(50., 1e-3)); +} + +TEST_CASE("A tower is placed nearest its saved position even when that is off the plate", "[WipeTowerEstimate]") { + // Saved at y 120, past the plate. An object covers the top-left corner, so the nearest + // anchor on the plate is the top edge right of the object (x 30), not straight below. + const Polygons obstacles = { box(0., 60., 30., 100.) }; + const std::optional anchor = nearest_clear_wipe_tower_anchor(plate_anchors, square_footprint(10.), obstacles, + Point(scaled(20.), scaled(120.))); + REQUIRE(anchor.has_value()); + CHECK(clear_of(square_footprint(10.), *anchor, obstacles)); + CHECK_THAT(unscaled(anchor->x()), WithinAbs(30., 1e-3)); + CHECK_THAT(unscaled(anchor->y()), WithinAbs(90., 1e-3)); +} + +TEST_CASE("A rotated tower keeps its turned footprint off the objects", "[WipeTowerEstimate]") { + // Turned 90 degrees about its anchor, the footprint spans x - 10 to x. Saved at x 65 it + // would reach back to 55, so it moves right until it starts at the strip's edge. + Polygon footprint = square_footprint(10.); + footprint.rotate(PI / 2.); + const Polygons obstacles = { box(40., 0., 60., 100.) }; + const std::optional anchor = nearest_clear_wipe_tower_anchor(plate_anchors, footprint, obstacles, + Point(scaled(65.), scaled(50.))); + REQUIRE(anchor.has_value()); + CHECK(clear_of(footprint, *anchor, obstacles)); + CHECK_THAT(unscaled(anchor->x()), WithinAbs(70., 1e-3)); +} + +TEST_CASE("A plate with no room for the tower reports that no anchor is clear", "[WipeTowerEstimate]") { + CHECK_FALSE(nearest_clear_wipe_tower_anchor(plate_anchors, square_footprint(10.), { box(-5., -5., 105., 105.) }, + Point(scaled(50.), scaled(50.))) + .has_value()); +} + +TEST_CASE("A tower pinned to one coordinate by a cramped plate can still move along the other", "[WipeTowerEstimate]") { + // The plate is only as wide as the tower: every anchor has x 0. + const BoundingBox column(Point(0, 0), Point(0, scaled(90.))); + const Polygons obstacles = { box(-5., 42., 15., 62.) }; + const std::optional anchor = nearest_clear_wipe_tower_anchor(column, square_footprint(10.), obstacles, + Point(0, scaled(45.))); + // Blocked from y 32 to 62: down 13 mm beats up 17 mm. + REQUIRE(anchor.has_value()); + CHECK(clear_of(square_footprint(10.), *anchor, obstacles)); + CHECK_THAT(unscaled(anchor->x()), WithinAbs(0., 1e-3)); + CHECK_THAT(unscaled(anchor->y()), WithinAbs(32., 1e-3)); +} + +TEST_CASE("A single anchor is kept when clear and refused when taken", "[WipeTowerEstimate]") { + // Bounds that are one point ask whether that exact spot is clear. + const Point spot(scaled(10.), scaled(10.)); + const BoundingBox only_spot(spot, spot); + const std::optional clear = nearest_clear_wipe_tower_anchor(only_spot, square_footprint(10.), { box(40., 0., 60., 100.) }, spot); + REQUIRE(clear.has_value()); + CHECK(*clear == spot); + CHECK_FALSE(nearest_clear_wipe_tower_anchor(only_spot, square_footprint(10.), { box(15., 0., 60., 100.) }, spot).has_value()); +} + +TEST_CASE("A tower slides off a slanted side of an object", "[WipeTowerEstimate]") { + // The triangle's left side runs from (40, 0) to (50, 40), x = 40 + y / 4. The footprint's + // lower-right corner leads into it, so the clear anchors stop at x = 30 + y / 4, a line + // 13.75 / sqrt(1 + 1/16) mm from the saved anchor (45, 5): shorter than moving straight left. + const Polygons obstacles = { Polygon({ {scaled(40.), 0}, {scaled(60.), 0}, {scaled(50.), scaled(40.)} }) }; + const Point target(scaled(45.), scaled(5.)); + const std::optional anchor = nearest_clear_wipe_tower_anchor(plate_anchors, square_footprint(10.), obstacles, target); + REQUIRE(anchor.has_value()); + CHECK(clear_of(square_footprint(10.), *anchor, obstacles)); + CHECK_THAT(unscaled((*anchor - target).cast().norm()), WithinAbs(13.75 / std::sqrt(1. + 1. / 16.), 1e-3)); +} diff --git a/tests/slic3rutils/python_test_support.hpp b/tests/slic3rutils/python_test_support.hpp index e9b0aaac8d..347812f0aa 100644 --- a/tests/slic3rutils/python_test_support.hpp +++ b/tests/slic3rutils/python_test_support.hpp @@ -2,6 +2,15 @@ // Shared embedded-interpreter bootstrap for slic3rutils tests that need a live Python // interpreter (test_plugin_host_api.cpp, test_slicing_pipeline_bindings.cpp, ...). +// +// The runtime is process-wide: once initialized it stays up for the rest of the test process. +// CPython cannot be reinitialized after Py_Finalize (a second init aborts inside _datetime), and +// the app likewise finalizes it only at exit, so nothing here tears it down. +// slic3rutils_tests_main.cpp finalizes the production interpreter once, after the last test case. +// +// This bootstrap is separate from PythonInterpreter's runtime: whichever of the two brings Python +// up first in a process owns it, and the other cannot initialize it again. ctest runs one case per +// process, so that only matters if the binary is run directly. #include #include #include diff --git a/tests/slic3rutils/slic3rutils_tests_main.cpp b/tests/slic3rutils/slic3rutils_tests_main.cpp index f8d2b4fac5..b23e6731cd 100644 --- a/tests/slic3rutils/slic3rutils_tests_main.cpp +++ b/tests/slic3rutils/slic3rutils_tests_main.cpp @@ -1,8 +1,40 @@ #include #include +#include +#include + +#include +#include + +#include "catch2/interfaces/catch_interfaces_reporter.hpp" #include "slic3r/Utils/Http.hpp" +namespace { + +// Finalizes the embedded interpreter once, after the last test case, and never between cases. +// CPython cannot be reinitialized after Py_Finalize (a second init aborts inside _datetime), and +// the app likewise finalizes it only at exit, so the per-test fixtures tear down only the +// PluginManager. Running at the end of the run, rather than from a static destructor, also keeps +// shutdown()'s logging ahead of boost::log's teardown. +class PythonInterpreterRunEnd final : public Catch::EventListenerBase +{ +public: + using Catch::EventListenerBase::EventListenerBase; + + void testRunEnded(const Catch::TestRunStats&) override + { + if (!Slic3r::PythonInterpreter::instance().is_initialized()) + return; + Slic3r::PluginManager::instance().shutdown(); + Slic3r::PythonInterpreter::instance().shutdown(); + } +}; + +} // namespace + +CATCH_REGISTER_LISTENER(PythonInterpreterRunEnd) + TEST_CASE("Check SSL certificates paths", "[Http][NotWorking]") { Slic3r::Http g = Slic3r::Http::get("https://github.com/"); @@ -58,4 +90,3 @@ TEST_CASE("Http basic authentication", "[Http][NotWorking]") { REQUIRE(status == 200); } - diff --git a/tests/slic3rutils/test_moonraker_printer_agent.cpp b/tests/slic3rutils/test_moonraker_printer_agent.cpp index d3d61903fb..4d1d61a8c6 100644 --- a/tests/slic3rutils/test_moonraker_printer_agent.cpp +++ b/tests/slic3rutils/test_moonraker_printer_agent.cpp @@ -53,7 +53,8 @@ public: mutable unsigned fetch_count = 0; protected: - bool fetch_device_info(const std::string&, const std::string&, MoonrakerDeviceInfo& info, std::string&) const override + bool fetch_device_info( + const std::string&, const std::string&, MoonrakerDeviceInfo& info, std::string&, const std::function&) const override { ++fetch_count; info.dev_name = "Test printer"; @@ -61,13 +62,12 @@ protected: } }; -class StreamAgent : public MoonrakerPrinterAgent +// Connects without the app's printer preset, and counts the device info queries that have returned. +class ConnectAgent : public MoonrakerPrinterAgent { public: using MoonrakerPrinterAgent::MoonrakerPrinterAgent; - using MoonrakerPrinterAgent::start_status_stream; - using MoonrakerPrinterAgent::stop_status_stream; - using MoonrakerPrinterAgent::ws_timings; + std::shared_ptr> fetches_returned; protected: bool init_device_info( @@ -79,7 +79,32 @@ protected: return true; } - bool fetch_device_info(const std::string&, const std::string&, MoonrakerDeviceInfo& info, std::string&) const override + bool fetch_device_info(const std::string& base_url, + const std::string& api_key, + MoonrakerDeviceInfo& info, + std::string& error, + const std::function& cancelled) const override + { + // Copied first, since the base destructor that waits for this query runs after this class's members are gone + const std::shared_ptr> counter = fetches_returned; + const bool fetched = MoonrakerPrinterAgent::fetch_device_info(base_url, api_key, info, error, cancelled); + if (counter) + ++*counter; + return fetched; + } +}; + +class StreamAgent : public ConnectAgent +{ +public: + using ConnectAgent::ConnectAgent; + using MoonrakerPrinterAgent::start_status_stream; + using MoonrakerPrinterAgent::stop_status_stream; + using MoonrakerPrinterAgent::ws_timings; + +protected: + bool fetch_device_info( + const std::string&, const std::string&, MoonrakerDeviceInfo& info, std::string&, const std::function&) const override { info.dev_name = "Test printer"; return true; @@ -96,7 +121,7 @@ enum class Behavior { HangsUpWithoutAnswer, // Closes the websocket without sending anything IgnoresClose, // Reports Klippy disconnected, then never answers the close StallsObjectList, // Never answers the stream's object list request - StallsStatusQuery, // Never answers HTTP requests until released, then hangs up on them + StallsHttp, // Never answers HTTP requests until released, then hangs up on them }; class FakePrinter @@ -253,7 +278,7 @@ private: wait_for_release(); return; } - if (m_behavior == Behavior::StallsStatusQuery) { + if (m_behavior == Behavior::StallsHttp) { wait_for_release(); beast::error_code ec; socket.close(ec); @@ -401,6 +426,22 @@ struct StreamFixture StreamAgent agent{""}; }; +PrinterConnectionParams connection_to(const FakePrinter& printer) +{ + PrinterConnectionParams params; + params.dev_id = "printer"; + params.host = printer.host(); + params.port = printer.port(); + return params; +} + +// Destroys the agent, giving it `limit` to return. +template bool destroys_within(std::unique_ptr& agent, std::chrono::milliseconds limit) +{ + auto destroyed = std::async(std::launch::async, [&] { agent.reset(); }); + return destroyed.wait_for(limit) == std::future_status::ready; +} + } // namespace TEST_CASE("Moonraker discovery waits for a complete device identity", "[MoonrakerPrinterAgent][Discovery]") @@ -574,12 +615,8 @@ TEST_CASE("The status stream sends no heartbeat while the printer has nothing ne TEST_CASE("A disconnect during the connection queries keeps the status stream from starting", "[MoonrakerPrinterAgent][StatusStream]") { - StreamFixture f(Behavior::StallsStatusQuery); - PrinterConnectionParams params; - params.dev_id = "printer"; - params.host = f.printer.host(); - params.port = f.printer.port(); - f.agent.connect_printer(params); + StreamFixture f(Behavior::StallsHttp); + f.agent.connect_printer(connection_to(f.printer)); REQUIRE(f.printer.wait_for_http_requests(1)); f.agent.disconnect_printer(); @@ -588,3 +625,32 @@ TEST_CASE("A disconnect during the connection queries keeps the status stream fr REQUIRE(f.printer.wait_for_http_hang_ups(1)); CHECK_FALSE(f.printer.wait_for_ready_connections(1, 500ms)); } + +TEST_CASE("Destroying the agent waits for the connection threads it superseded", "[MoonrakerPrinterAgent][Connect]") +{ + FakePrinter printer(Behavior::StallsHttp); + const auto fetches_returned = std::make_shared>(0); + auto agent = std::make_unique(""); + agent->fetches_returned = fetches_returned; + + agent->connect_printer(connection_to(printer)); + REQUIRE(printer.wait_for_http_requests(1)); + agent->connect_printer(connection_to(printer)); + REQUIRE(printer.wait_for_http_requests(2)); + agent->disconnect_printer(); + + // The stalled queries see the change within 1 s of curl progress. + CHECK(destroys_within(agent, 2s)); + CHECK(*fetches_returned == 2); +} + +TEST_CASE("Destroying the agent stops a stalled status query", "[MoonrakerPrinterAgent][Connect]") +{ + FakePrinter printer(Behavior::StallsHttp); + auto agent = std::make_unique(""); + agent->connect_printer(connection_to(printer)); + REQUIRE(printer.wait_for_http_requests(1)); + + // The stalled query sees the change within 1 s of curl progress. + CHECK(destroys_within(agent, 2s)); +} diff --git a/tests/slic3rutils/test_plugin_audit.cpp b/tests/slic3rutils/test_plugin_audit.cpp index 5eb0aac357..6ab83db963 100644 --- a/tests/slic3rutils/test_plugin_audit.cpp +++ b/tests/slic3rutils/test_plugin_audit.cpp @@ -301,6 +301,67 @@ TEST_CASE("Plugin audit denies secret/certificate/config-like paths by keyword", } } +TEST_CASE("Plugin audit checks denied keywords below data_dir, not in the directories above it", "[PluginAudit]") +{ + // Flatpak keeps the app's data folder under /.var/app//config/OrcaSlicer, so + // data_dir() itself has a "config" component. That ancestor describes the sandbox's layout, + // not what the folder holds, and must not hard-deny every path inside it. + ScopedDataDir data_dir_guard("plugin-audit-data-dir-keyword"); + const fs::path flatpak_data_dir = data_dir_guard.dir / "config" / "OrcaSlicer"; + set_data_dir(flatpak_data_dir.string()); + + seed_denied_names(); + seed_denied_keywords(); + + PluginAuditManager& mgr = PluginAuditManager::instance(); + // Reproduce install_hook()'s grant: data_dir() is a global allowed root. + mgr.add_global_allowed_root(data_dir()); + + ScopedPluginAuditContext ctx("test_plugin", ""); + + SECTION("the root and the paths below it that carry no keyword are allowed") + { + CHECK_FALSE(mgr.is_denied_path_keyword(flatpak_data_dir / "orca_plugins" / "state.json")); + CHECK(mgr.check_open(data_dir(), "r").allowed); + CHECK(mgr.check_open((flatpak_data_dir / "orca_plugins" / "test_plugin" / "state.json").string(), "r").allowed); + CHECK(mgr.check_open((flatpak_data_dir / "orca_plugins" / "test_plugin" / "state.json").string(), "w").allowed); + CHECK(mgr.check_open((flatpak_data_dir / "system" / "profiles" / "vendor.json").string(), "r").allowed); + } + + SECTION("a 'secrets' component below data_dir() is still denied") + { + AuditDecision decision = mgr.check_open((flatpak_data_dir / "secrets" / "token.json").string(), "r"); + CHECK_FALSE(decision.allowed); + CHECK(decision.reason == "denied path keyword"); + } + + SECTION("a 'config' component below data_dir() is still denied") + { + AuditDecision decision = mgr.check_open((flatpak_data_dir / "config" / "settings.json").string(), "r"); + CHECK_FALSE(decision.allowed); + CHECK(decision.reason == "denied path keyword"); + } + + SECTION("the app config below data_dir() is still denied by name") + { + AuditDecision decision = mgr.check_open((flatpak_data_dir / (SLIC3R_APP_KEY ".conf")).string(), "r"); + CHECK_FALSE(decision.allowed); + CHECK(decision.reason == "denied filename"); + } + + SECTION("an unrelated resources root keeps the full-path keyword check") + { + ScopedResourcesDir resources_dir_guard("plugin-audit-data-dir-keyword-resources"); + mgr.add_global_allowed_root(resources_dir(), /*allow_write=*/false); + + CHECK(mgr.check_open((fs::path(resources_dir()) / "profiles" / "vendor.json").string(), "r").allowed); + + AuditDecision decision = mgr.check_open((fs::path(resources_dir()) / "cert" / "slicer_base64.cer").string(), "r"); + CHECK_FALSE(decision.allowed); + CHECK(decision.reason == "denied path keyword"); + } +} + TEST_CASE("Plugin audit is_denied_path combines the filename and keyword registries", "[audit]") { seed_denied_names(); @@ -583,7 +644,8 @@ class Handler(http.server.BaseHTTPRequestHandler): pass server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) -threading.Thread(target=server.serve_forever, daemon=True).start() +server_thread = threading.Thread(target=server.serve_forever, daemon=True) +server_thread.start() PORT = server.server_address[1] BASE = "http://127.0.0.1:%d" % PORT URL_A, URL_B, URL_REDIRECT = BASE + "/a", BASE + "/b", BASE + "/redirect" @@ -639,10 +701,14 @@ std::string describe(const std::vector& prompts) // The plugin system with the audit hook installed, and the permission dialog replaced by a // recorder that answers with `approve`. Declare it first in a test, so it is destroyed last. +// +// Only the manager is torn down here; the interpreter is finalized once per test process by +// PythonInterpreterRunEnd in slic3rutils_tests_main.cpp. struct AuditHarness { // Before initialize(): the interpreter creates {data_dir}/python/packages and {data_dir}/log. - // data_dir() is a global allowed root from then on, so the test files live in `outside`. + // data_dir() is a global allowed root from then on -- the first test to initialize Python in + // this process (under ctest, this one) -- so the test files live in `outside`. ScopedDataDir data{"plugin-audit-hook"}; bool initialized = PluginManager::instance().initialize(); ScopedTemporaryDir outside{"orca-plugin-audit-outside"}; @@ -651,6 +717,11 @@ struct AuditHarness AuditHarness() { + PluginAuditManager& audit = PluginAuditManager::instance(); + audit.clear_current_plugin(); + audit.clear_current_capability(); + audit.clear_audit_denial(); + audit.clear_last_violation(); PluginAuditManager::set_permission_prompt_for_testing( [this](const std::string& event, const std::vector& targets) { prompts.push_back({PluginAuditManager::instance().current_plugin(), event, targets}); @@ -662,7 +733,6 @@ struct AuditHarness { PluginAuditManager::set_permission_prompt_for_testing(nullptr); PluginManager::instance().shutdown(); - PythonInterpreter::instance().shutdown(); } // Call before taking the GIL: discovery is not Python work. @@ -695,7 +765,7 @@ struct AuditHarness }; // The test-side Python globals. Construct and destroy it with the GIL held; it stops the HTTP -// server before the interpreter shuts down. +// server before the test case ends, so nothing keeps serving once the test's temp dirs are gone. struct PythonSide { py::dict globals; @@ -708,7 +778,7 @@ struct PythonSide } // A Python error fails the test here, as text: an error_already_set left to propagate would - // outlive the interpreter the harness shuts down. + // outlive the test case and keep a traceback with references into the interpreter. void exec(const char* code) { std::string error; @@ -724,8 +794,11 @@ struct PythonSide ~PythonSide() { try { + // Stop the server thread while Python is still up: the interpreter now outlives the + // test case, so a daemon thread must not keep serving (and touching test temp dirs). globals["server"].attr("shutdown")(); globals["server"].attr("server_close")(); + globals["server_thread"].attr("join")(); } catch (...) { } } diff --git a/tests/slic3rutils/test_plugin_capability_config.cpp b/tests/slic3rutils/test_plugin_capability_config.cpp index bbd0368d26..bd8a91e356 100644 --- a/tests/slic3rutils/test_plugin_capability_config.cpp +++ b/tests/slic3rutils/test_plugin_capability_config.cpp @@ -27,10 +27,10 @@ using json = nlohmann::json; namespace { -// Brings the plugin system up for the duration of one test and tears it down at the end — same -// idiom as ScopedPluginManager in test_plugin_lifecycle.cpp, and for the same reason: shutdown() -// logs via boost::log, so it must run before boost::log tears down its thread-local storage, not be -// left to a static destructor at process exit. +// Brings the plugin system up for the duration of one test and tears the manager down at the end — +// same idiom as ScopedPluginManager in test_plugin_lifecycle.cpp. The interpreter itself is +// process-wide and finalized once by PythonInterpreterRunEnd in slic3rutils_tests_main.cpp: +// CPython cannot be reinitialized after Py_Finalize. // // Needed here (unlike a bare pybind11::scoped_interpreter): has_config_ui()/get_config_ui()/ // get_name()/etc. all cross PyPluginCommonTrampoline's ORCA_PY_OVERRIDE_AUDITED, which refuses to @@ -40,7 +40,7 @@ namespace { // // initialize() leaves the GIL released (production code re-acquires it per call via PythonGILState); // every TEST_CASE below pairs this with a py::gil_scoped_acquire, declared second so it releases -// before this destructor's shutdown() runs. +// before this destructor runs. struct ScopedPluginManager { // Before initialize(): the interpreter creates {data_dir}/python/packages and {data_dir}/log, @@ -48,11 +48,7 @@ struct ScopedPluginManager ScopedDataDir python_data_dir{"plugin-python"}; bool initialized = PluginManager::instance().initialize(); - ~ScopedPluginManager() - { - PluginManager::instance().shutdown(); - PythonInterpreter::instance().shutdown(); - } + ~ScopedPluginManager() { PluginManager::instance().shutdown(); } }; py::module_ import_orca_module() diff --git a/tests/slic3rutils/test_plugin_cloud_metadata.cpp b/tests/slic3rutils/test_plugin_cloud_metadata.cpp index 95ae6fcd43..3e3735a6ca 100644 --- a/tests/slic3rutils/test_plugin_cloud_metadata.cpp +++ b/tests/slic3rutils/test_plugin_cloud_metadata.cpp @@ -27,12 +27,11 @@ using json = nlohmann::json; namespace { -// Brings the plugin manager up and shuts both singletons down while boost::log is still alive; -// left to their static destructors, shutdown()'s logging runs after boost::log tears down its -// thread-local storage and crashes the process on exit (same reason ScopedPluginManager exists in -// test_plugin_lifecycle.cpp). initialize() IS needed here: the plugin under test is a -// slicing-pipeline script, so discover_plugins() brings up the Python interpreter to parse it, -// same as any other plugin. +// Brings the plugin manager up for the duration of one test and tears the manager down at the end. +// The interpreter itself is process-wide: PythonInterpreterRunEnd in slic3rutils_tests_main.cpp +// finalizes it once, after the last test case, because CPython cannot be reinitialized after +// Py_Finalize. initialize() IS needed here: the plugin under test is a slicing-pipeline script, so +// discover_plugins() brings up the Python interpreter to parse it, same as any other plugin. struct ScopedManagerShutdown { // Before initialize(): the interpreter creates {data_dir}/python/packages and {data_dir}/log, @@ -40,11 +39,7 @@ struct ScopedManagerShutdown ScopedDataDir python_data_dir{"plugin-python"}; bool initialized = PluginManager::instance().initialize(); - ~ScopedManagerShutdown() - { - PluginManager::instance().shutdown(); - PythonInterpreter::instance().shutdown(); - } + ~ScopedManagerShutdown() { PluginManager::instance().shutdown(); } }; const char* const CLOUD_PLUGIN_SOURCE = R"PY(# /// script diff --git a/tests/slic3rutils/test_plugin_json_depth.cpp b/tests/slic3rutils/test_plugin_json_depth.cpp index ad3c834b93..85f84d40e8 100644 --- a/tests/slic3rutils/test_plugin_json_depth.cpp +++ b/tests/slic3rutils/test_plugin_json_depth.cpp @@ -3,7 +3,6 @@ #include #include -#include #include "plugin_test_utils.hpp" @@ -19,17 +18,14 @@ using namespace Slic3r; namespace { -// Brings the embedded interpreter up for one test and tears it down before boost::log does, -// mirroring the ScopedPluginManager idiom in the other plugin tests. +// Brings the embedded interpreter up for one test and tears the manager down afterwards; the +// interpreter itself is process-wide and finalized once by PythonInterpreterRunEnd in +// slic3rutils_tests_main.cpp (CPython cannot be reinitialized after Py_Finalize). struct ScopedPluginManager { ScopedDataDir python_data_dir{"plugin-json-depth"}; bool initialized = PluginManager::instance().initialize(); - ~ScopedPluginManager() - { - PluginManager::instance().shutdown(); - PythonInterpreter::instance().shutdown(); - } + ~ScopedPluginManager() { PluginManager::instance().shutdown(); } }; } // namespace diff --git a/tests/slic3rutils/test_plugin_lifecycle.cpp b/tests/slic3rutils/test_plugin_lifecycle.cpp index 0a1a94dcef..fc32511336 100644 --- a/tests/slic3rutils/test_plugin_lifecycle.cpp +++ b/tests/slic3rutils/test_plugin_lifecycle.cpp @@ -41,16 +41,19 @@ namespace fs = boost::filesystem; // -> unload. // // Each Catch2 test case runs in its own process (catch_discover_tests), so the PluginManager and -// interpreter singletons are brought up at most once per test. +// interpreter singletons are brought up at most once per test. Running the binary directly runs +// every case in one process: the interpreter is then initialized once and finalized after the +// last case (see PythonInterpreterRunEnd in slic3rutils_tests_main.cpp). namespace { -// Brings the plugin system up, and tears it down explicitly at the end of the test. +// Brings the plugin system up, and tears the manager down at the end of the test. // -// Shutting the interpreter down here, rather than leaving it to PythonInterpreter's static -// destructor, mirrors what the app does (GUI_App finalizes it before exit). Left to static -// destruction, shutdown()'s logging runs after boost::log has torn down its thread-local storage -// and throws, aborting the process after the tests have already passed. +// The interpreter itself is not finalized here: it is process-wide. CPython cannot be +// reinitialized after Py_Finalize (a second init aborts inside _datetime), and the app likewise +// finalizes it only at exit (GUI_App). slic3rutils_tests_main.cpp finalizes it once, after the +// last test case and before static destruction, where shutdown()'s logging is still ahead of +// boost::log's teardown. // // Declare this FIRST in a test so it is destroyed last. struct ScopedPluginManager @@ -61,11 +64,7 @@ struct ScopedPluginManager bool initialized = false; ScopedPluginManager() { initialized = PluginManager::instance().initialize(); } - ~ScopedPluginManager() - { - PluginManager::instance().shutdown(); - PythonInterpreter::instance().shutdown(); - } + ~ScopedPluginManager() { PluginManager::instance().shutdown(); } }; // A minimal script plugin exposing exactly one capability, "Echo". diff --git a/tests/slic3rutils/test_plugin_printer_agent.cpp b/tests/slic3rutils/test_plugin_printer_agent.cpp index fc504c806a..7b5c2ca9f9 100644 --- a/tests/slic3rutils/test_plugin_printer_agent.cpp +++ b/tests/slic3rutils/test_plugin_printer_agent.cpp @@ -26,7 +26,9 @@ using namespace Slic3r; namespace { // Same idiom as ScopedPluginManager in test_plugin_lifecycle.cpp: the trampolines refuse to call -// into Python unless PythonInterpreter::instance() reports initialized. +// into Python unless PythonInterpreter::instance() reports initialized. Only the manager is torn +// down here; the interpreter is finalized once per test process by PythonInterpreterRunEnd in +// slic3rutils_tests_main.cpp. struct ScopedPluginManager { // Before initialize(): the interpreter creates {data_dir}/python/packages and {data_dir}/log, @@ -34,11 +36,7 @@ struct ScopedPluginManager ScopedDataDir python_data_dir{"plugin-python"}; bool initialized = PluginManager::instance().initialize(); - ~ScopedPluginManager() - { - PluginManager::instance().shutdown(); - PythonInterpreter::instance().shutdown(); - } + ~ScopedPluginManager() { PluginManager::instance().shutdown(); } }; // The host reaches a printer agent plugin through IPrinterAgent, so the tests do too. The Python diff --git a/tests/slic3rutils/test_plugin_resource_texture.cpp b/tests/slic3rutils/test_plugin_resource_texture.cpp index c57a39b5e1..c4c9feab9e 100644 --- a/tests/slic3rutils/test_plugin_resource_texture.cpp +++ b/tests/slic3rutils/test_plugin_resource_texture.cpp @@ -69,8 +69,10 @@ namespace fs = boost::filesystem; namespace { -// Brings the plugin system up, and tears it down explicitly at the end of the test, as -// test_plugin_lifecycle.cpp does. Declare this FIRST in a test so it is destroyed last. +// Brings the plugin system up for the duration of one test and tears the manager down at the end, +// as test_plugin_lifecycle.cpp does. The interpreter is process-wide and finalized once by +// PythonInterpreterRunEnd in slic3rutils_tests_main.cpp; CPython cannot be reinitialized after +// Py_Finalize. Declare this FIRST in a test so it is destroyed last. struct ScopedPluginManager { // Before initialize(): the interpreter creates {data_dir}/python/packages and {data_dir}/log. @@ -78,11 +80,7 @@ struct ScopedPluginManager bool initialized = false; ScopedPluginManager() { initialized = PluginManager::instance().initialize(); } - ~ScopedPluginManager() - { - PluginManager::instance().shutdown(); - PythonInterpreter::instance().shutdown(); - } + ~ScopedPluginManager() { PluginManager::instance().shutdown(); } }; // The app installs these in GUI_App::init_plugin_gui_wiring. Without an app the callbacks run inline diff --git a/tests/slic3rutils/test_shortcuts.cpp b/tests/slic3rutils/test_shortcuts.cpp index d36c1d3b39..171d3257b0 100644 --- a/tests/slic3rutils/test_shortcuts.cpp +++ b/tests/slic3rutils/test_shortcuts.cpp @@ -222,6 +222,7 @@ TEST_CASE("Every shortcut is listed under the section of its table row", "[Short CHECK(shortcut_section(Shortcut::MovesSliderEnd) == ShortcutSection::Sliders); CHECK(shortcut_section(Shortcut::ViewDefault) == ShortcutSection::Camera); CHECK(shortcut_section(Shortcut::KeyboardShortcuts) == ShortcutSection::Application); + CHECK(shortcut_section(Shortcut::Quit) == ShortcutSection::Application); CHECK(std::string(section_name(ShortcutSection::SlicingAndPrinting)) == "Slicing and printing"); } diff --git a/tests/slic3rutils/test_slicing_pipeline_config.cpp b/tests/slic3rutils/test_slicing_pipeline_config.cpp index 0dc12639a0..73a3840577 100644 --- a/tests/slic3rutils/test_slicing_pipeline_config.cpp +++ b/tests/slic3rutils/test_slicing_pipeline_config.cpp @@ -53,11 +53,9 @@ struct ScopedPluginManager bool initialized = false; ScopedPluginManager() { initialized = PluginManager::instance().initialize(); } - ~ScopedPluginManager() - { - PluginManager::instance().shutdown(); - PythonInterpreter::instance().shutdown(); - } + // The interpreter is process-wide; PythonInterpreterRunEnd in slic3rutils_tests_main.cpp + // finalizes it once, after the last test case. + ~ScopedPluginManager() { PluginManager::instance().shutdown(); } }; const char* const CONFIG_PROBE_SOURCE = R"PY(# /// script diff --git a/tests/test_utils.hpp b/tests/test_utils.hpp index cffa05cb15..f677b2de0b 100644 --- a/tests/test_utils.hpp +++ b/tests/test_utils.hpp @@ -12,12 +12,16 @@ #include #include +#include #include #include +#include #include #include #include +#include + #if defined(WIN32) || defined(_WIN32) #define PATH_SEPARATOR R"(\)" #else @@ -223,4 +227,36 @@ private: std::optional m_previous; }; +// Switches this thread's numeric locale to one whose decimal separator is a comma, +// when the system has one installed. +struct CommaNumericLocale +{ +#ifdef _WIN32 + bool apply() + { + for (const char* name : { "de-DE", "German_Germany.1252" }) + if (std::setlocale(LC_NUMERIC, name) != nullptr) + return true; + return false; + } +#else + locale_t locale { (locale_t) 0 }; + bool apply() + { + for (const char* name : { "de_DE.UTF-8", "de_DE.utf8", "de_DE" }) + if ((locale = newlocale(LC_NUMERIC_MASK, name, (locale_t) 0)) != (locale_t) 0) { + uselocale(locale); + return true; + } + return false; + } + // Freed once the setters around apply() have put the thread's own locale back. + ~CommaNumericLocale() + { + if (locale != (locale_t) 0) + freelocale(locale); + } +#endif +}; + #endif // SLIC3R_TEST_UTILS