diff --git a/src/clipper/clipper.hpp b/src/clipper/clipper.hpp index b1dae3c248..1b0c48bc67 100644 --- a/src/clipper/clipper.hpp +++ b/src/clipper/clipper.hpp @@ -556,9 +556,9 @@ class clipperException : public std::exception //------------------------------------------------------------------------------ template -inline Paths SimplifyPolygons(PathsProvider &&in_polys, PolyFillType fillType = pftEvenOdd) { +inline Paths SimplifyPolygons(PathsProvider &&in_polys, PolyFillType fillType = pftEvenOdd, bool strictly_simple = true) { Clipper c; - c.StrictlySimple(true); + c.StrictlySimple(strictly_simple); c.AddPaths(std::forward(in_polys), ptSubject, true); Paths out; c.Execute(ctUnion, out, fillType, fillType); diff --git a/src/libslic3r/CMakeLists.txt b/src/libslic3r/CMakeLists.txt index 99e964da6b..d8cf96c547 100644 --- a/src/libslic3r/CMakeLists.txt +++ b/src/libslic3r/CMakeLists.txt @@ -261,6 +261,23 @@ set(lisbslic3r_sources SlicesToTriangleMesh.cpp SlicingAdaptive.cpp SlicingAdaptive.hpp + Support/SupportCommon.cpp + Support/SupportCommon.hpp + Support/SupportDebug.cpp + Support/SupportDebug.hpp + Support/SupportLayer.hpp + # Support/SupportMaterial.cpp + # Support/SupportMaterial.hpp + Support/SupportParameters.cpp + Support/SupportParameters.hpp + Support/OrganicSupport.cpp + Support/OrganicSupport.hpp + Support/TreeSupport.cpp + Support/TreeSupport.hpp + Support/TreeSupportCommon.cpp + Support/TreeSupportCommon.hpp + Support/TreeModelVolumes.cpp + Support/TreeModelVolumes.hpp SupportMaterial.cpp SupportMaterial.hpp PrincipalComponents2D.cpp @@ -496,6 +513,7 @@ target_link_libraries(libslic3r qhull semver TBB::tbb + TBB::tbbmalloc libslic3r_cgal ${CMAKE_DL_LIBS} PNG::PNG diff --git a/src/libslic3r/ClipperUtils.cpp b/src/libslic3r/ClipperUtils.cpp index c39dcb3f35..1db307b5b5 100644 --- a/src/libslic3r/ClipperUtils.cpp +++ b/src/libslic3r/ClipperUtils.cpp @@ -655,6 +655,8 @@ Slic3r::Polygons diff(const Slic3r::Polygon &subject, const Slic3r::Polygon &cli { return _clipper(ClipperLib::ctDifference, ClipperUtils::SinglePathProvider(subject.points), ClipperUtils::SinglePathProvider(clip.points), do_safety_offset); } Slic3r::Polygons diff(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) { return _clipper(ClipperLib::ctDifference, ClipperUtils::PolygonsProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } +Slic3r::Polygons diff_clipped(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) + { return diff(subject, ClipperUtils::clip_clipper_polygons_with_subject_bbox(clip, get_extents(subject).inflated(SCALED_EPSILON)), do_safety_offset); } Slic3r::Polygons diff(const Slic3r::Polygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset) { return _clipper(ClipperLib::ctDifference, ClipperUtils::PolygonsProvider(subject), ClipperUtils::ExPolygonsProvider(clip), do_safety_offset); } Slic3r::Polygons diff(const Slic3r::ExPolygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) @@ -665,6 +667,8 @@ Slic3r::Polygons diff(const Slic3r::Surfaces &subject, const Slic3r::Polygons &c { return _clipper(ClipperLib::ctDifference, ClipperUtils::SurfacesProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } Slic3r::Polygons intersection(const Slic3r::Polygon &subject, const Slic3r::Polygon &clip, ApplySafetyOffset do_safety_offset) { return _clipper(ClipperLib::ctIntersection, ClipperUtils::SinglePathProvider(subject.points), ClipperUtils::SinglePathProvider(clip.points), do_safety_offset); } +Slic3r::Polygons intersection_clipped(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) + { return intersection(subject, ClipperUtils::clip_clipper_polygons_with_subject_bbox(clip, get_extents(subject).inflated(SCALED_EPSILON)), do_safety_offset); } Slic3r::Polygons intersection(const Slic3r::Polygons &subject, const Slic3r::ExPolygon &clip, ApplySafetyOffset do_safety_offset) { return _clipper(ClipperLib::ctIntersection, ClipperUtils::PolygonsProvider(subject), ClipperUtils::ExPolygonProvider(clip), do_safety_offset); } Slic3r::Polygons intersection(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) diff --git a/src/libslic3r/ClipperUtils.hpp b/src/libslic3r/ClipperUtils.hpp index 585a519107..5b18339c06 100644 --- a/src/libslic3r/ClipperUtils.hpp +++ b/src/libslic3r/ClipperUtils.hpp @@ -362,6 +362,8 @@ inline Slic3r::Polygons expand(const Slic3r::Polygon &polygon, const float del { assert(delta > 0); return offset(polygon, delta, joinType, miterLimit); } inline Slic3r::Polygons expand(const Slic3r::Polygons &polygons, const float delta, ClipperLib::JoinType joinType = DefaultJoinType, double miterLimit = DefaultMiterLimit) { assert(delta > 0); return offset(polygons, delta, joinType, miterLimit); } +inline Slic3r::Polygons expand(const Slic3r::ExPolygons &polygons, const float delta, ClipperLib::JoinType joinType = DefaultJoinType, double miterLimit = DefaultMiterLimit) + { assert(delta > 0); return offset(polygons, delta, joinType, miterLimit); } inline Slic3r::ExPolygons expand_ex(const Slic3r::Polygons &polygons, const float delta, ClipperLib::JoinType joinType = DefaultJoinType, double miterLimit = DefaultMiterLimit) { assert(delta > 0); return offset_ex(polygons, delta, joinType, miterLimit); } // Input polygons for shrinking shall be "normalized": There must be no overlap / intersections between the input polygons. @@ -415,6 +417,9 @@ Slic3r::Lines _clipper_ln(ClipperLib::ClipType clipType, const Slic3r::Lines &su Slic3r::Polygons diff(const Slic3r::Polygon &subject, const Slic3r::Polygon &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); Slic3r::Polygons diff(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); Slic3r::Polygons diff(const Slic3r::Polygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +// Optimized version clipping the "clipping" polygon using clip_clipper_polygon_with_subject_bbox(). +// To be used with complex clipping polygons, where majority of the clipping polygons are outside of the source polygon. +Slic3r::Polygons diff_clipped(const Slic3r::Polygons &src, const Slic3r::Polygons &clipping, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); Slic3r::Polygons diff(const Slic3r::ExPolygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); Slic3r::Polygons diff(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); Slic3r::Polygons diff(const Slic3r::Surfaces &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); @@ -475,6 +480,9 @@ Slic3r::Polygons intersection(const Slic3r::Polygon &subject, const Slic3r::Po Slic3r::Polygons intersection(const Slic3r::Polygons &subject, const Slic3r::ExPolygon &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); Slic3r::Polygons intersection(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); Slic3r::Polygons intersection(const Slic3r::ExPolygon &subject, const Slic3r::ExPolygon &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +// Optimized version clipping the "clipping" polygon using clip_clipper_polygon_with_subject_bbox(). +// To be used with complex clipping polygons, where majority of the clipping polygons are outside of the source polygon. +Slic3r::Polygons intersection_clipped(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); Slic3r::Polygons intersection(const Slic3r::ExPolygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); Slic3r::Polygons intersection(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); Slic3r::Polygons intersection(const Slic3r::Surfaces &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); diff --git a/src/libslic3r/ExtrusionEntity.hpp b/src/libslic3r/ExtrusionEntity.hpp index 159c08e7e5..786a99b95e 100644 --- a/src/libslic3r/ExtrusionEntity.hpp +++ b/src/libslic3r/ExtrusionEntity.hpp @@ -298,6 +298,16 @@ private: bool m_no_extrusion = false; }; +class ExtrusionPathOriented : public ExtrusionPath +{ +public: + ExtrusionPathOriented(ExtrusionRole role, double mm3_per_mm, float width, float height) : ExtrusionPath(role, mm3_per_mm, width, height) {} + ExtrusionEntity* clone() const override { return new ExtrusionPathOriented(*this); } + // Create a new object, initialize it with this object using the move semantics. + ExtrusionEntity* clone_move() override { return new ExtrusionPathOriented(std::move(*this)); } + virtual bool can_reverse() const override { return false; } +}; + typedef std::vector ExtrusionPaths; // Single continuous extrusion path, possibly with varying extrusion thickness, extrusion height or bridging / non bridging. @@ -488,23 +498,23 @@ inline void extrusion_paths_append(ExtrusionPaths &dst, Polylines &&polylines, i polylines.clear(); } -inline void extrusion_entities_append_paths(ExtrusionEntitiesPtr &dst, Polylines &polylines, ExtrusionRole role, double mm3_per_mm, float width, float height) +inline void extrusion_entities_append_paths(ExtrusionEntitiesPtr &dst, Polylines &polylines, ExtrusionRole role, double mm3_per_mm, float width, float height, bool can_reverse = true) { dst.reserve(dst.size() + polylines.size()); for (Polyline &polyline : polylines) if (polyline.is_valid()) { - ExtrusionPath *extrusion_path = new ExtrusionPath(role, mm3_per_mm, width, height); + ExtrusionPath *extrusion_path = can_reverse ? new ExtrusionPath(role, mm3_per_mm, width, height) : new ExtrusionPathOriented(role, mm3_per_mm, width, height); dst.push_back(extrusion_path); extrusion_path->polyline = polyline; } } -inline void extrusion_entities_append_paths(ExtrusionEntitiesPtr &dst, Polylines &&polylines, ExtrusionRole role, double mm3_per_mm, float width, float height) +inline void extrusion_entities_append_paths(ExtrusionEntitiesPtr &dst, Polylines &&polylines, ExtrusionRole role, double mm3_per_mm, float width, float height, bool can_reverse = true) { dst.reserve(dst.size() + polylines.size()); for (Polyline &polyline : polylines) if (polyline.is_valid()) { - ExtrusionPath *extrusion_path = new ExtrusionPath(role, mm3_per_mm, width, height); + ExtrusionPath *extrusion_path = can_reverse ? new ExtrusionPath(role, mm3_per_mm, width, height) : new ExtrusionPathOriented(role, mm3_per_mm, width, height); dst.push_back(extrusion_path); extrusion_path->polyline = std::move(polyline); } diff --git a/src/libslic3r/Point.hpp b/src/libslic3r/Point.hpp index 80644073ee..92a00df9e2 100644 --- a/src/libslic3r/Point.hpp +++ b/src/libslic3r/Point.hpp @@ -93,8 +93,13 @@ inline typename Derived::Scalar cross2(const Eigen::MatrixBase &v1, con return v1.x() * v2.y() - v1.y() * v2.x(); } -template -inline Eigen::Matrix perp(const Eigen::MatrixBase> &v) { return Eigen::Matrix(- v.y(), v.x()); } +// 2D vector perpendicular to the argument. +template +inline Eigen::Matrix perp(const Eigen::MatrixBase &v) +{ + static_assert(Derived::IsVectorAtCompileTime && int(Derived::SizeAtCompileTime) == 2, "perp(): parameter is not a 2D vector"); + return { - v.y(), v.x() }; +} // Angle from v1 to v2, returning double atan2(y, x) normalized to <-PI, PI>. template @@ -107,12 +112,17 @@ inline double angle(const Eigen::MatrixBase& v1, const Eigen::MatrixBas return atan2(cross2(v1d, v2d), v1d.dot(v2d)); } +template +Eigen::Matrix to_2d(const Eigen::MatrixBase &ptN) { + static_assert(Derived::IsVectorAtCompileTime && int(Derived::SizeAtCompileTime) >= 3, "to_2d(): first parameter is not a 3D or higher dimensional vector"); + return ptN.template head<2>(); +} -template -Eigen::Matrix to_2d(const Eigen::MatrixBase> &ptN) { return { ptN.x(), ptN.y() }; } - -template -Eigen::Matrix to_3d(const Eigen::MatrixBase> & pt, const T z) { return { pt.x(), pt.y(), z }; } +template +inline Eigen::Matrix to_3d(const Eigen::MatrixBase &pt, const typename Derived::Scalar z) { + static_assert(Derived::IsVectorAtCompileTime && int(Derived::SizeAtCompileTime) == 2, "to_3d(): first parameter is not a 2D vector"); + return { pt.x(), pt.y(), z }; +} inline Vec2d unscale(coord_t x, coord_t y) { return Vec2d(unscale(x), unscale(y)); } inline Vec2d unscale(const Vec2crd &pt) { return Vec2d(unscale(pt.x()), unscale(pt.y())); } diff --git a/src/libslic3r/Polygon.cpp b/src/libslic3r/Polygon.cpp index 6697af0af5..64d197c5ba 100644 --- a/src/libslic3r/Polygon.cpp +++ b/src/libslic3r/Polygon.cpp @@ -594,7 +594,7 @@ void remove_collinear(Polygons &polys) remove_collinear(poly); } -Polygons polygons_simplify(const Polygons &source_polygons, double tolerance) +Polygons polygons_simplify(const Polygons &source_polygons, double tolerance, bool strictly_simple /* = true */) { Polygons out; out.reserve(source_polygons.size()); @@ -605,7 +605,7 @@ Polygons polygons_simplify(const Polygons &source_polygons, double tolerance) simplified.pop_back(); // Simplify the decimated contour by ClipperLib. bool ccw = ClipperLib::Area(simplified) > 0.; - for (Points &path : ClipperLib::SimplifyPolygons(ClipperUtils::SinglePathProvider(simplified), ClipperLib::pftNonZero)) { + for (Points &path : ClipperLib::SimplifyPolygons(ClipperUtils::SinglePathProvider(simplified), ClipperLib::pftNonZero, strictly_simple)) { if (! ccw) // ClipperLib likely reoriented negative area contours to become positive. Reverse holes back to CW. std::reverse(path.begin(), path.end()); @@ -664,4 +664,24 @@ bool contains(const Polygons &polygons, const Point &p, bool border_result) } return (poly_count_inside % 2) == 1; } + +Polygon make_circle(double radius, double error) +{ + double angle = 2. * acos(1. - error / radius); + size_t num_segments = size_t(ceil(2. * M_PI / angle)); + return make_circle_num_segments(radius, num_segments); +} + +Polygon make_circle_num_segments(double radius, size_t num_segments) +{ + Polygon out; + out.points.reserve(num_segments); + double angle_inc = 2.0 * M_PI / num_segments; + for (size_t i = 0; i < num_segments; ++ i) { + const double angle = angle_inc * i; + out.points.emplace_back(coord_t(cos(angle) * radius), coord_t(sin(angle) * radius)); + } + return out; +} + } \ No newline at end of file diff --git a/src/libslic3r/Polygon.hpp b/src/libslic3r/Polygon.hpp index 7da63c2cc5..d09d7bae7c 100644 --- a/src/libslic3r/Polygon.hpp +++ b/src/libslic3r/Polygon.hpp @@ -152,7 +152,7 @@ inline void polygons_append(Polygons &dst, Polygons &&src) } } -Polygons polygons_simplify(const Polygons &polys, double tolerance); +Polygons polygons_simplify(const Polygons &polys, double tolerance, bool strictly_simple = true); inline void polygons_rotate(Polygons &polys, double angle) { @@ -267,6 +267,9 @@ inline Polygons to_polygons(std::vector &&paths) // however their contours may be rotated. bool polygons_match(const Polygon &l, const Polygon &r); +Polygon make_circle(double radius, double error); +Polygon make_circle_num_segments(double radius, size_t num_segments); + bool overlaps(const Polygons& polys1, const Polygons& polys2); } // Slic3r diff --git a/src/libslic3r/Preset.cpp b/src/libslic3r/Preset.cpp index b278d1529e..a0f890e6de 100644 --- a/src/libslic3r/Preset.cpp +++ b/src/libslic3r/Preset.cpp @@ -748,8 +748,8 @@ static std::vector s_Preset_print_options { "prime_tower_width", "prime_tower_brim_width", "prime_volume", "wipe_tower_no_sparse_layers", "compatible_printers", "compatible_printers_condition", "inherits", "flush_into_infill", "flush_into_objects", "flush_into_support", - "tree_support_branch_angle", "tree_support_wall_count", "tree_support_branch_distance", - "tree_support_branch_diameter", + "tree_support_branch_angle", "tree_support_angle_slow", "tree_support_wall_count", "tree_support_top_rate", "tree_support_branch_distance", "tree_support_tip_diameter", + "tree_support_branch_diameter", "tree_support_branch_diameter_angle", "tree_support_branch_diameter_double_wall", "detect_narrow_internal_solid_infill", "gcode_add_line_number", "enable_arc_fitting", "infill_combination", /*"adaptive_layer_height",*/ "support_bottom_interface_spacing", "enable_overhang_speed", "overhang_1_4_speed", "overhang_2_4_speed", "overhang_3_4_speed", "overhang_4_4_speed", diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 131706c9b7..2691856de2 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -1173,6 +1173,20 @@ StringObjectException Print::validate(StringObjectException *warning, Polygons* return {L("The prime tower requires that support has the same layer height with object."), object, "support_filament"}; } #endif + + // Prusa: Fixing crashes with invalid tip diameter or branch diameter + // https://github.com/prusa3d/PrusaSlicer/commit/96b3ae85013ac363cd1c3e98ec6b7938aeacf46d + if (object->config().support_style == smsOrganic) { + float extrusion_width = std::min( + support_material_flow(object).width(), + support_material_interface_flow(object).width()); + if (object->config().tree_support_tip_diameter < extrusion_width - EPSILON) + return { L("Organic support tree tip diameter must not be smaller than support material extrusion width."), object, "tree_support_tip_diameter" }; + if (object->config().tree_support_branch_diameter < 2. * extrusion_width - EPSILON) + return { L("Organic support branch diameter must not be smaller than 2x support material extrusion width."), object, "tree_support_branch_diameter" }; + if (object->config().tree_support_branch_diameter < object->config().tree_support_tip_diameter) + return { L("Organic support branch diameter must not be smaller than support tree tip diameter."), object, "tree_support_branch_diameter" }; + } } // Do we have custom support data that would not be used? diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index c8fa95add4..beb4328b7d 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -188,7 +188,8 @@ static t_config_enum_values s_keys_map_SupportMaterialStyle { { "snug", smsSnug }, { "tree_slim", smsTreeSlim }, { "tree_strong", smsTreeStrong }, - { "tree_hybrid", smsTreeHybrid } + { "tree_hybrid", smsTreeHybrid }, + { "organic", smsOrganic } }; CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(SupportMaterialStyle) @@ -3354,12 +3355,14 @@ void PrintConfigDef::init_fff_params() def->enum_values.push_back("tree_slim"); def->enum_values.push_back("tree_strong"); def->enum_values.push_back("tree_hybrid"); + def->enum_values.push_back("organic"); def->enum_labels.push_back(L("Default")); def->enum_labels.push_back(L("Grid")); def->enum_labels.push_back(L("Snug")); def->enum_labels.push_back(L("Tree Slim")); def->enum_labels.push_back(L("Tree Strong")); def->enum_labels.push_back(L("Tree Hybrid")); + def->enum_labels.push_back(L("Organic")); def->mode = comAdvanced; def->set_default_value(new ConfigOptionEnum(smsDefault)); @@ -3392,6 +3395,18 @@ void PrintConfigDef::init_fff_params() def->mode = comAdvanced; def->set_default_value(new ConfigOptionFloat(40.)); + def = this->add("tree_support_angle_slow", coFloat); + def->label = L("Preferred Branch Angle"); + def->category = L("Support"); + // TRN PrintSettings: "Organic supports" > "Preferred Branch Angle" + def->tooltip = L("The preferred angle of the branches, when they do not have to avoid the model. " + "Use a lower angle to make them more vertical and more stable. Use a higher angle for branches to merge faster."); + def->sidetext = L("°"); + def->min = 10; + def->max = 85; + def->mode = comAdvanced; + def->set_default_value(new ConfigOptionFloat(25)); + def = this->add("tree_support_branch_distance", coFloat); def->label = L("Tree support branch distance"); def->category = L("Support"); @@ -3402,6 +3417,20 @@ void PrintConfigDef::init_fff_params() def->mode = comAdvanced; def->set_default_value(new ConfigOptionFloat(5.)); + def = this->add("tree_support_top_rate", coPercent); + def->label = L("Branch Density"); + def->category = L("Support"); + // TRN PrintSettings: "Organic supports" > "Branch Density" + def->tooltip = L("Adjusts the density of the support structure used to generate the tips of the branches. " + "A higher value results in better overhangs but the supports are harder to remove, " + "thus it is recommended to enable top support interfaces instead of a high branch density value " + "if dense interfaces are needed."); + def->sidetext = L("%"); + def->min = 5; + def->max_literal = 35; + def->mode = comAdvanced; + def->set_default_value(new ConfigOptionPercent(15)); + def = this->add("tree_support_adaptive_layer_height", coBool); def->label = L("Adaptive layer height"); def->category = L("Quality"); @@ -3421,6 +3450,17 @@ void PrintConfigDef::init_fff_params() def->tooltip = L("Distance from tree branch to the outermost brim line"); def->set_default_value(new ConfigOptionFloat(3)); + def = this->add("tree_support_tip_diameter", coFloat); + def->label = L("Tip Diameter"); + def->category = L("Support"); + // TRN PrintSettings: "Organic supports" > "Tip Diameter" + def->tooltip = L("Branch tip diameter for organic supports."); + def->sidetext = L("mm"); + def->min = 0.1f; + def->max = 100.f; + def->mode = comAdvanced; + def->set_default_value(new ConfigOptionFloat(0.8)); + def = this->add("tree_support_branch_diameter", coFloat); def->label = L("Tree support branch diameter"); def->category = L("Support"); @@ -3431,6 +3471,32 @@ void PrintConfigDef::init_fff_params() def->mode = comAdvanced; def->set_default_value(new ConfigOptionFloat(5.)); + def = this->add("tree_support_branch_diameter_angle", coFloat); + // TRN PrintSettings: #lmFIXME + def->label = L("Branch Diameter Angle"); + def->category = L("Support"); + // TRN PrintSettings: "Organic supports" > "Branch Diameter Angle" + def->tooltip = L("The angle of the branches' diameter as they gradually become thicker towards the bottom. " + "An angle of 0 will cause the branches to have uniform thickness over their length. " + "A bit of an angle can increase stability of the organic support."); + def->sidetext = L("°"); + def->min = 0; + def->max = 15; + def->mode = comAdvanced; + def->set_default_value(new ConfigOptionFloat(5)); + + def = this->add("tree_support_branch_diameter_double_wall", coFloat); + def->label = L("Branch Diameter with double walls"); + def->category = L("Support"); + // TRN PrintSettings: "Organic supports" > "Branch Diameter" + def->tooltip = L("Branches with area larger than the area of a circle of this diameter will be printed with double walls for stability. " + "Set this value to zero for no double walls."); + def->sidetext = L("mm"); + def->min = 0; + def->max = 100.f; + def->mode = comAdvanced; + def->set_default_value(new ConfigOptionFloat(3.)); + def = this->add("tree_support_wall_count", coInt); def->label = L("Tree support wall loops"); def->category = L("Support"); @@ -4640,7 +4706,7 @@ void PrintConfigDef::handle_legacy(t_config_option_key &opt_key, std::string &va #endif /* HAS_PRESSURE_EQUALIZER */ // BBS , "support_sharp_tails","support_remove_small_overhangs", "support_with_sheath", - "tree_support_branch_diameter_angle", "tree_support_collision_resolution", "tree_support_with_infill", + "tree_support_collision_resolution", "tree_support_with_infill", "max_volumetric_speed", "max_print_speed", "support_closing_radius", "remove_freq_sweep", "remove_bed_leveling", "remove_extrusion_calibration", diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index 73324e81b0..e451f52432 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -101,7 +101,7 @@ enum SupportMaterialPattern { }; enum SupportMaterialStyle { - smsDefault, smsGrid, smsSnug, smsTreeSlim, smsTreeStrong, smsTreeHybrid + smsDefault, smsGrid, smsSnug, smsTreeSlim, smsTreeStrong, smsTreeHybrid, smsOrganic, }; enum SupportMaterialInterfacePattern { @@ -699,9 +699,14 @@ PRINT_CONFIG_CLASS_DEFINE( ((ConfigOptionBool, flush_into_infill)) ((ConfigOptionBool, flush_into_support)) // BBS + ((ConfigOptionPercent, tree_support_top_rate)) ((ConfigOptionFloat, tree_support_branch_distance)) + ((ConfigOptionFloat, tree_support_tip_diameter)) ((ConfigOptionFloat, tree_support_branch_diameter)) + ((ConfigOptionFloat, tree_support_branch_diameter_angle)) + ((ConfigOptionFloat, tree_support_branch_diameter_double_wall)) ((ConfigOptionFloat, tree_support_branch_angle)) + ((ConfigOptionFloat, tree_support_angle_slow)) ((ConfigOptionInt, tree_support_wall_count)) ((ConfigOptionBool, tree_support_adaptive_layer_height)) ((ConfigOptionBool, tree_support_auto_brim)) diff --git a/src/libslic3r/PrintObject.cpp b/src/libslic3r/PrintObject.cpp index a7714f1ecc..eb83c36209 100644 --- a/src/libslic3r/PrintObject.cpp +++ b/src/libslic3r/PrintObject.cpp @@ -8,6 +8,7 @@ #include "Layer.hpp" #include "MutablePolygon.hpp" #include "SupportMaterial.hpp" +#include "Support/TreeSupport.hpp" #include "Surface.hpp" #include "Slicing.hpp" #include "Tesselate.hpp" @@ -813,9 +814,14 @@ bool PrintObject::invalidate_state_by_config_options( || opt_key == "tree_support_adaptive_layer_height" || opt_key == "tree_support_auto_brim" || opt_key == "tree_support_brim_width" + || opt_key == "tree_support_top_rate" || opt_key == "tree_support_branch_distance" + || opt_key == "tree_support_tip_diameter" || opt_key == "tree_support_branch_diameter" + || opt_key == "tree_support_branch_diameter_angle" + || opt_key == "tree_support_branch_diameter_double_wall" || opt_key == "tree_support_branch_angle" + || opt_key == "tree_support_angle_slow" || opt_key == "tree_support_wall_count") { steps.emplace_back(posSupportMaterial); } else if ( @@ -2494,8 +2500,14 @@ void PrintObject::_generate_support_material() PrintObjectSupportMaterial support_material(this, m_slicing_params); support_material.generate(*this); - TreeSupport tree_support(*this, m_slicing_params); - tree_support.generate(); + if (this->config().enable_support.value && is_tree(this->config().support_type.value)) { + if (this->config().support_style.value == smsOrganic) { + fff_tree_support_generate(*this, std::function([this]() { this->throw_if_canceled(); })); + } else { + TreeSupport tree_support(*this, m_slicing_params); + tree_support.generate(); + } + } } // BBS diff --git a/src/libslic3r/Support/OrganicSupport.cpp b/src/libslic3r/Support/OrganicSupport.cpp new file mode 100644 index 0000000000..69cc0cf7e1 --- /dev/null +++ b/src/libslic3r/Support/OrganicSupport.cpp @@ -0,0 +1,1424 @@ +///|/ Copyright (c) Prusa Research 2023 Vojtěch Bubník @bubnikv +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +#include "OrganicSupport.hpp" +#include "SupportCommon.hpp" + +#include "../AABBTreeLines.hpp" +#include "../ClipperUtils.hpp" +#include "../Polygon.hpp" +#include "../Polyline.hpp" +#include "../MutablePolygon.hpp" +#include "../TriangleMeshSlicer.hpp" + +#include + +#include + +#define TREE_SUPPORT_ORGANIC_NUDGE_NEW 1 + +#ifndef TREE_SUPPORT_ORGANIC_NUDGE_NEW + // Old version using OpenVDB, works but it is extremely slow for complex meshes. + #include "../OpenVDBUtilsLegacy.hpp" + #include +#endif // TREE_SUPPORT_ORGANIC_NUDGE_NEW + +namespace Slic3r +{ + +namespace FFFTreeSupport +{ + +// Single slice through a single branch or trough a number of branches. +struct Slice +{ + // All polygons collected for this slice. + Polygons polygons; + // All bottom contacts collected for this slice. + Polygons bottom_contacts; + // How many branches were merged in this slice? Used to decide whether ClipperLib union is needed. + size_t num_branches{ 0 }; +}; + +struct Element +{ + // Current position of the centerline including the Z coordinate, unscaled. + Vec3f position; + float radius; + + // Index of this layer, including the raft layers. + LayerIndex layer_idx; + + // Limits where the centerline could be placed at the current layer Z. + Polygons influence_area; + + // Locked node should not be moved. Locked nodes are at the top of an object or at the tips of branches. + bool locked; + + // Previous position, for Laplacian smoothing, unscaled. + Vec3f prev_position; + + // For sphere tracing and other collision detection optimizations. + Vec3f last_collision; + double last_collision_depth; + + struct CollisionSphere { + // Minimum Z for which the sphere collision will be evaluated. + // Limited by the minimum sloping angle and by the bottom of the tree. + float min_z{ -std::numeric_limits::max() }; + // Maximum Z for which the sphere collision will be evaluated. + // Limited by the minimum sloping angle and by the tip of the current branch. + float max_z{ std::numeric_limits::max() }; + // Span of layers to test collision of this sphere against. + uint32_t layer_begin; + uint32_t layer_end; + }; + + CollisionSphere collision_sphere; +}; + +struct Branch; + +struct Bifurcation +{ + Branch *branch; + double area; +}; + +// Single branch of a tree. +struct Branch +{ + std::vector path; + + using Bifurcations = +#ifdef NDEBUG + // To reduce memory allocation in release mode. + boost::container::small_vector; +#else // NDEBUG + // To ease debugging. + std::vector; +#endif // NDEBUG + + Bifurcations up; + Bifurcation down; + + // How many of the thick up branches are considered continuation of the trunk? + // These will be smoothed out together. + size_t num_up_trunk; + + bool has_root() const { return this->down.branch == nullptr; } + bool has_tip() const { return this->up.empty(); } +}; + +struct Tree +{ + // Branches: Store of all branches. + // The first branch is the root of the tree. + Slic3r::deque branches; + + Branch& root() { return branches.front(); } + const Branch& root() const { return branches.front(); } + + // Result of slicing the branches. + std::vector slices; + // First layer index of the first slice in the vector above. + LayerIndex first_layer_id{ -1 }; +}; + +using Forest = std::vector; +using Trees = std::vector; + +Element to_tree_element(const TreeSupportSettings &config, const SlicingParameters &slicing_params, SupportElement &element, bool is_root) +{ + Element out; + out.position = to_3d(unscaled(element.state.result_on_layer), float(layer_z(slicing_params, config, element.state.layer_idx))); + out.radius = support_element_radius(config, element); + out.layer_idx = element.state.layer_idx; + out.influence_area = std::move(element.influence_area); + out.locked = (is_root && element.state.layer_idx > 0) || element.state.locked(); + return out; +} + +// Convert move bounds into a forest of trees, each tree made of a graph of branches and bifurcation points. +// Destroys move_bounds. +Forest make_forest(const TreeSupportSettings &config, const SlicingParameters &slicing_params, std::vector &&move_bounds) +{ + struct TreeVisitor { + void visit_recursive(std::vector &move_bounds, SupportElement &start_element, Branch *parent_branch, Tree &out) const { + assert(! start_element.state.marked && ! start_element.parents.empty()); + // Collect elements up to a bifurcation above. + start_element.state.marked = true; + // For each branch bifurcating from this point: +// SupportElements &layer = move_bounds[start_element.state.layer_idx]; + SupportElements &layer_above = move_bounds[start_element.state.layer_idx + 1]; + for (size_t parent_idx = 0; parent_idx < start_element.parents.size(); ++ parent_idx) { + Branch branch; + if (parent_branch) + // Duplicate the last element of the trunk below. + // If this branch has a smaller diameter than the trunk below, its centerline will not be aligned with the centerline of the trunk. + branch.path.emplace_back(parent_branch->path.back()); + branch.path.emplace_back(to_tree_element(config, slicing_params, start_element, parent_branch == nullptr)); + // Traverse each branch until it branches again. + SupportElement &first_parent = layer_above[start_element.parents[parent_idx]]; + assert(! first_parent.state.marked); + assert(branch.path.back().layer_idx + 1 == first_parent.state.layer_idx); + branch.path.emplace_back(to_tree_element(config, slicing_params, first_parent, false)); + if (first_parent.parents.size() < 2) + first_parent.state.marked = true; + SupportElement *next_branch = nullptr; + if (first_parent.parents.size() == 1) { + for (SupportElement *parent = &first_parent;;) { + assert(parent->state.marked); + SupportElement &next_parent = move_bounds[parent->state.layer_idx + 1][parent->parents.front()]; + assert(! next_parent.state.marked); + assert(branch.path.back().layer_idx + 1 == next_parent.state.layer_idx); + branch.path.emplace_back(to_tree_element(config, slicing_params, next_parent, false)); + if (next_parent.parents.size() > 1) { + // Branching point was reached. + next_branch = &next_parent; + break; + } + next_parent.state.marked = true; + if (next_parent.parents.size() == 0) + // Tip is reached. + break; + parent = &next_parent; + } + } else if (first_parent.parents.size() > 1) + // Branching point was reached. + next_branch = &first_parent; + assert(branch.path.size() >= 2); + assert(next_branch == nullptr || ! next_branch->state.marked); + out.branches.emplace_back(std::move(branch)); + Branch *pbranch = &out.branches.back(); + if (parent_branch) { + parent_branch->up.push_back({ pbranch }); + pbranch->down = { parent_branch }; + } + if (next_branch) + this->visit_recursive(move_bounds, *next_branch, pbranch, out); + } + + if (parent_branch) { + // Update initial radii of thin branches merging with a trunk. + auto it_up_max_r = std::max_element(parent_branch->up.begin(), parent_branch->up.end(), + [](const Bifurcation &l, const Bifurcation &r){ return l.branch->path[1].radius < r.branch->path[1].radius; }); + const float r1 = it_up_max_r->branch->path[1].radius; + const float radius_increment = unscaled(config.branch_radius_increase_per_layer); + for (auto it = parent_branch->up.begin(); it != parent_branch->up.end(); ++ it) + if (it != it_up_max_r) { + Element &el = it->branch->path.front(); + Element &el2 = it->branch->path[1]; + if (! is_approx(r1, el2.radius)) + el.radius = std::min(el.radius, el2.radius + radius_increment); + } + // Sort children of parent_branch by decreasing radius. + std::sort(parent_branch->up.begin(), parent_branch->up.end(), + [](const Bifurcation &l, const Bifurcation &r){ return l.branch->path.front().radius > r.branch->path.front().radius; }); + // Update number of branches to be considered a continuation of the trunk during smoothing. + { + const float r_trunk = 0.75 * it_up_max_r->branch->path.front().radius; + parent_branch->num_up_trunk = 0; + for (const Bifurcation& up : parent_branch->up) + if (up.branch->path.front().radius < r_trunk) + break; + else + ++ parent_branch->num_up_trunk; + } + } + } + + const TreeSupportSettings &config; + const SlicingParameters &slicing_params; + }; + + TreeVisitor visitor{ config, slicing_params }; + + for (SupportElements &elements : move_bounds) + for (SupportElement &el : elements) + el.state.marked = false; + + Trees trees; + for (LayerIndex layer_idx = 0; layer_idx + 1 < LayerIndex(move_bounds.size()); ++ layer_idx) { + for (SupportElement &start_element : move_bounds[layer_idx]) { + if (! start_element.state.marked && ! start_element.parents.empty()) { +#if 0 + { + // Verify that this node is a root, such that there is no element in the layer below + // that points to it. + int ielement = &start_element - move_bounds.data(); + int found = 0; + if (layer_idx > 0) { + for (auto &el : move_bounds[layer_idx - 1]) { + for (auto iparent : el.parents) + if (iparent == ielement) + ++ found; + } + if (found != 0) + printf("Found: %d\n", found); + } + } +#endif + trees.push_back({}); + visitor.visit_recursive(move_bounds, start_element, nullptr, trees.back()); + assert(! trees.back().branches.empty()); + assert(! trees.back().branches.front().path.empty()); +#if 0 + // Debugging: Only build trees with specific properties. + if (start_element.state.lost) { + } + else if (start_element.state.verylost) { + } + else + trees.pop_back(); +#endif + } + } + } + +#if 1 + move_bounds.clear(); +#else + for (SupportElements &elements : move_bounds) + for (SupportElement &el : elements) + el.state.marked = false; +#endif + + return trees; +} + +// Move bounds were propagated top to bottom. At each joint of branches the move bounds were reduced significantly. +// Now reflect the reduction of tree space by propagating the reduction of tree centerline space +// bottom-up starting with the bottom-most joint. +void trim_influence_areas_bottom_up(Forest &forest, const float dxy_dlayer) +{ + struct Trimmer { + static void trim_recursive(Branch &branch, const float delta_r, const float dxy_dlayer) { + assert(delta_r >= 0); + if (delta_r > 0) + branch.path.front().influence_area = offset(branch.path.front().influence_area, delta_r); + for (size_t i = 1; i < branch.path.size(); ++ i) + branch.path[i].influence_area = intersection(branch.path[i].influence_area, offset(branch.path[i - 1].influence_area, dxy_dlayer)); + const float r0 = branch.path.back().radius; + for (Bifurcation &up : branch.up) { + up.branch->path.front().influence_area = branch.path.back().influence_area; + trim_recursive(*up.branch, r0 - up.branch->path.front().radius, dxy_dlayer); + } + } + }; + + for (Tree &tree : forest) { + Branch &root = tree.root(); + const float r0 = root.path.back().radius; + for (Bifurcation &up : root.up) + Trimmer::trim_recursive(*up.branch, r0 - up.branch->path.front().radius, dxy_dlayer); + } +} + +// Straighten up and smooth centerlines inside their influence areas. +void smooth_trees_inside_influence_areas(Branch &root, bool is_root) +{ + // Smooth the subtree: + // + // Apply laplacian and bilaplacian smoothing inside a branch, + // apply laplacian smoothing only at a bifurcation point. + // + // Applying a bilaplacian smoothing inside a branch should ensure curvature of the brach to be lower + // than the radius at each particular point of the centerline, + // while omitting bilaplacian smoothing at bifurcation points will create sharp bifurcations. + // Sharp bifurcations have a smaller volume, but just a tiny bit larger surfaces than smooth bifurcations + // where each continuation of the trunk satifies the path radius > centerline element radius. + const size_t num_iterations = 100; + struct StackElement { + Branch &branch; + size_t idx_up; + }; + std::vector stack; + + auto adjust_position = [](Element &el, Vec2f new_pos) { + Point new_pos_scaled = scaled(new_pos); + if (! contains(el.influence_area, new_pos_scaled)) { + int64_t min_dist = std::numeric_limits::max(); + Point min_proj_scaled; + for (const Polygon& polygon : el.influence_area) { + Point proj_scaled = polygon.point_projection(new_pos_scaled); + if (int64_t dist = (proj_scaled - new_pos_scaled).cast().squaredNorm(); dist < min_dist) { + min_dist = dist; + min_proj_scaled = proj_scaled; + } + } + new_pos = unscaled(min_proj_scaled); + } + el.position.head<2>() = new_pos; + }; + + for (size_t iter = 0; iter < num_iterations; ++ iter) { + // 1) Back-up the current positions. + stack.push_back({ root, 0 }); + while (! stack.empty()) { + StackElement &state = stack.back(); + if (state.idx_up == state.branch.num_up_trunk) { + // Process this path. + for (auto &el : state.branch.path) + el.prev_position = el.position; + stack.pop_back(); + } else { + // Open another up node of this branch. + stack.push_back({ *state.branch.up[state.idx_up].branch, 0 }); + ++ state.idx_up; + } + } + // 2) Calculate new position. + stack.push_back({ root, 0 }); + while (! stack.empty()) { + StackElement &state = stack.back(); + if (state.idx_up == state.branch.num_up_trunk) { + // Process this path. + for (size_t i = 1; i + 1 < state.branch.path.size(); ++ i) + if (auto &el = state.branch.path[i]; ! el.locked) { + // Laplacian smoothing with 0.5 weight. + const Vec3f &p0 = state.branch.path[i - 1].prev_position; + const Vec3f &p1 = el.prev_position; + const Vec3f &p2 = state.branch.path[i + 1].prev_position; + adjust_position(el, 0.5 * p1.head<2>() + 0.25 * (p0.head<2>() + p2.head<2>())); +#if 0 + // Only apply bilaplacian smoothing if the current curvature is smaller than el.radius. + // Interpolate p0, p1, p2 with a circle. + // First project p0, p1, p2 into a common plane. + const Vec3f n = (p1 - p0).cross(p2 - p1); + const Vec3f y = Vec3f(n.y(), n.x(), 0).normalized(); + const Vec2f q0{ p0.z(), p0.dot(y) }; + const Vec2f q1{ p1.z(), p1.dot(y) }; + const Vec2f q2{ p2.z(), p2.dot(y) }; + // Interpolate q0, q1, q2 with a circle, calculate its radius. + Vec2f b = q1 - q0; + Vec2f c = q2 - q0; + float lb = b.squaredNorm(); + float lc = c.squaredNorm(); + if (float d = b.x() * c.y() - b.y() * c.x(); std::abs(d) > EPSILON) { + Vec2f v = lc * b - lb * c; + float r2 = 0.25f * v.squaredNorm() / sqr(d); + if (r2 ) + } +#endif + } + { + // Laplacian smoothing with 0.5 weight, branching point. + float weight = 0; + Vec2f new_pos = Vec2f::Zero(); + for (size_t i = 0; i < state.branch.num_up_trunk; ++i) { + const Element &el = state.branch.up[i].branch->path.front(); + new_pos += el.prev_position.head<2>(); + weight += el.radius; + } + { + const Element &el = state.branch.path[state.branch.path.size() - 2]; + new_pos += el.prev_position.head<2>(); + weight *= 2.f; + } + adjust_position(state.branch.path.back(), 0.5f * state.branch.path.back().prev_position.head<2>() + 0.5f * weight * new_pos); + } + stack.pop_back(); + } else { + // Open another up node of this branch. + stack.push_back({ *state.branch.up[state.idx_up].branch, 0 }); + ++ state.idx_up; + } + } + } + // Also smoothen start of the path. + if (Element &first = root.path.front(); ! first.locked) { + Element &second = root.path[1]; + Vec2f new_pos = 0.75f * first.prev_position.head<2>() + 0.25f * second.prev_position.head<2>(); + if (is_root) + // Let the root of the tree float inside its influence area. + adjust_position(first, new_pos); + else { + // Keep the start of a thin branch inside the trunk. + const Element &trunk = root.down.branch->path.back(); + const float rdif = trunk.radius - root.path.front().radius; + assert(rdif >= 0); + Vec2f vdif = new_pos - trunk.prev_position.head<2>(); + float ldif = vdif.squaredNorm(); + if (ldif > sqr(rdif)) + // Clamp new position. + new_pos = trunk.prev_position.head<2>() + vdif * rdif / sqrt(ldif); + first.position.head<2>() = new_pos; + } + } +} + +void smooth_trees_inside_influence_areas(Forest &forest) +{ + // Parallel for! + for (Tree &tree : forest) + smooth_trees_inside_influence_areas(tree.root(), true); +} + +#if 0 +// Test whether two circles, each on its own plane in 3D intersect. +// Circles are considered intersecting, if the lowest point on one circle is below the other circle's plane. +// Assumption: The two planes are oriented the same way. +static bool circles_intersect( + const Vec3d &p1, const Vec3d &n1, const double r1, + const Vec3d &p2, const Vec3d &n2, const double r2) +{ + assert(n1.dot(n2) >= 0); + + const Vec3d z = n1.cross(n2); + const Vec3d dir1 = z.cross(n1); + const Vec3d lowest_point1 = p1 + dir1 * (r1 / dir1.norm()); + assert(n2.dot(p1) >= n2.dot(lowest_point1)); + if (n2.dot(lowest_point1) <= 0) + return true; + const Vec3d dir2 = z.cross(n2); + const Vec3d lowest_point2 = p2 + dir2 * (r2 / dir2.norm()); + assert(n1.dot(p2) >= n1.dot(lowest_point2)); + return n1.dot(lowest_point2) <= 0; +} +#endif + +template +void triangulate_fan(indexed_triangle_set &its, int ifan, int ibegin, int iend) +{ + // at least 3 vertices, increasing order. + assert(ibegin + 3 <= iend); + assert(ibegin >= 0 && iend <= its.vertices.size()); + assert(ifan >= 0 && ifan < its.vertices.size()); + int num_faces = iend - ibegin; + its.indices.reserve(its.indices.size() + num_faces * 3); + for (int v = ibegin, u = iend - 1; v < iend; u = v ++) { + if (flip_normals) + its.indices.push_back({ ifan, u, v }); + else + its.indices.push_back({ ifan, v, u }); + } +} + +static void triangulate_strip(indexed_triangle_set &its, int ibegin1, int iend1, int ibegin2, int iend2) +{ + // at least 3 vertices, increasing order. + assert(ibegin1 + 3 <= iend1); + assert(ibegin1 >= 0 && iend1 <= its.vertices.size()); + assert(ibegin2 + 3 <= iend2); + assert(ibegin2 >= 0 && iend2 <= its.vertices.size()); + int n1 = iend1 - ibegin1; + int n2 = iend2 - ibegin2; + its.indices.reserve(its.indices.size() + (n1 + n2) * 3); + + // For the first vertex of 1st strip, find the closest vertex on the 2nd strip. + int istart2 = ibegin2; + { + const Vec3f &p1 = its.vertices[ibegin1]; + auto d2min = std::numeric_limits::max(); + for (int i = ibegin2; i < iend2; ++ i) { + const Vec3f &p2 = its.vertices[i]; + const float d2 = (p2 - p1).squaredNorm(); + if (d2 < d2min) { + d2min = d2; + istart2 = i; + } + } + } + + // Now triangulate the strip zig-zag fashion taking always the shortest connection if possible. + for (int u = ibegin1, v = istart2; n1 > 0 || n2 > 0;) { + bool take_first; + int u2, v2; + auto update_u2 = [&u2, u, ibegin1, iend1]() { + u2 = u; + if (++ u2 == iend1) + u2 = ibegin1; + }; + auto update_v2 = [&v2, v, ibegin2, iend2]() { + v2 = v; + if (++ v2 == iend2) + v2 = ibegin2; + }; + if (n1 == 0) { + take_first = false; + update_v2(); + } else if (n2 == 0) { + take_first = true; + update_u2(); + } else { + update_u2(); + update_v2(); + float l1 = (its.vertices[u2] - its.vertices[v]).squaredNorm(); + float l2 = (its.vertices[v2] - its.vertices[u]).squaredNorm(); + take_first = l1 < l2; + } + if (take_first) { + its.indices.push_back({ u, u2, v }); + -- n1; + u = u2; + } else { + its.indices.push_back({ u, v2, v }); + -- n2; + v = v2; + } + } +} + +// Discretize 3D circle, append to output vector, return ranges of indices of the points added. +static std::pair discretize_circle(const Vec3f ¢er, const Vec3f &normal, const float radius, const float eps, std::vector &pts) +{ + // Calculate discretization step and number of steps. + float angle_step = 2. * acos(1. - eps / radius); + auto nsteps = int(ceil(2 * M_PI / angle_step)); + angle_step = 2 * M_PI / nsteps; + + // Prepare coordinate system for the circle plane. + Vec3f x = normal.cross(Vec3f(0.f, -1.f, 0.f)).normalized(); + Vec3f y = normal.cross(x).normalized(); + assert(std::abs(x.cross(y).dot(normal) - 1.f) < EPSILON); + + // Discretize the circle. + int begin = int(pts.size()); + pts.reserve(pts.size() + nsteps); + float angle = 0; + x *= radius; + y *= radius; + for (int i = 0; i < nsteps; ++ i) { + pts.emplace_back(center + x * cos(angle) + y * sin(angle)); + angle += angle_step; + } + return { begin, int(pts.size()) }; +} + +// Returns Z span of the generated mesh. +static std::pair extrude_branch( + const std::vector &path, + const TreeSupportSettings &config, + const SlicingParameters &slicing_params, + const std::vector &move_bounds, + indexed_triangle_set &result) +{ + Vec3d p1, p2, p3; + Vec3d v1, v2; + Vec3d nprev; + Vec3d ncurrent; + assert(path.size() >= 2); + static constexpr const float eps = 0.015f; + std::pair prev_strip; + +// char fname[2048]; +// static int irun = 0; + + float zmin = 0; + float zmax = 0; + + for (size_t ipath = 1; ipath < path.size(); ++ ipath) { + const SupportElement &prev = *path[ipath - 1]; + const SupportElement ¤t = *path[ipath]; + assert(prev.state.layer_idx + 1 == current.state.layer_idx); + p1 = to_3d(unscaled(prev .state.result_on_layer), layer_z(slicing_params, config, prev .state.layer_idx)); + p2 = to_3d(unscaled(current.state.result_on_layer), layer_z(slicing_params, config, current.state.layer_idx)); + v1 = (p2 - p1).normalized(); + if (ipath == 1) { + nprev = v1; + // Extrude the bottom half sphere. + float radius = unscaled(support_element_radius(config, prev)); + float angle_step = 2. * acos(1. - eps / radius); + auto nsteps = int(ceil(M_PI / (2. * angle_step))); + angle_step = M_PI / (2. * nsteps); + int ifan = int(result.vertices.size()); + result.vertices.emplace_back((p1 - nprev * radius).cast()); + zmin = result.vertices.back().z(); + float angle = angle_step; + for (int i = 1; i < nsteps; ++ i, angle += angle_step) { + std::pair strip = discretize_circle((p1 - nprev * radius * cos(angle)).cast(), nprev.cast(), radius * sin(angle), eps, result.vertices); + if (i == 1) + triangulate_fan(result, ifan, strip.first, strip.second); + else + triangulate_strip(result, prev_strip.first, prev_strip.second, strip.first, strip.second); +// sprintf(fname, "d:\\temp\\meshes\\tree-partial-%d.obj", ++ irun); +// its_write_obj(result, fname); + prev_strip = strip; + } + } + if (ipath + 1 == path.size()) { + // End of the tube. + ncurrent = v1; + // Extrude the top half sphere. + float radius = unscaled(support_element_radius(config, current)); + float angle_step = 2. * acos(1. - eps / radius); + auto nsteps = int(ceil(M_PI / (2. * angle_step))); + angle_step = M_PI / (2. * nsteps); + auto angle = float(M_PI / 2.); + for (int i = 0; i < nsteps; ++ i, angle -= angle_step) { + std::pair strip = discretize_circle((p2 + ncurrent * radius * cos(angle)).cast(), ncurrent.cast(), radius * sin(angle), eps, result.vertices); + triangulate_strip(result, prev_strip.first, prev_strip.second, strip.first, strip.second); +// sprintf(fname, "d:\\temp\\meshes\\tree-partial-%d.obj", ++ irun); +// its_write_obj(result, fname); + prev_strip = strip; + } + int ifan = int(result.vertices.size()); + result.vertices.emplace_back((p2 + ncurrent * radius).cast()); + zmax = result.vertices.back().z(); + triangulate_fan(result, ifan, prev_strip.first, prev_strip.second); +// sprintf(fname, "d:\\temp\\meshes\\tree-partial-%d.obj", ++ irun); +// its_write_obj(result, fname); + } else { + const SupportElement &next = *path[ipath + 1]; + assert(current.state.layer_idx + 1 == next.state.layer_idx); + p3 = to_3d(unscaled(next.state.result_on_layer), layer_z(slicing_params, config, next.state.layer_idx)); + v2 = (p3 - p2).normalized(); + ncurrent = (v1 + v2).normalized(); + float radius = unscaled(support_element_radius(config, current)); + std::pair strip = discretize_circle(p2.cast(), ncurrent.cast(), radius, eps, result.vertices); + triangulate_strip(result, prev_strip.first, prev_strip.second, strip.first, strip.second); + prev_strip = strip; +// sprintf(fname, "d:\\temp\\meshes\\tree-partial-%d.obj", ++irun); +// its_write_obj(result, fname); + } +#if 0 + if (circles_intersect(p1, nprev, support_element_radius(settings, prev), p2, ncurrent, support_element_radius(settings, current))) { + // Cannot connect previous and current slice using a simple zig-zag triangulation, + // because the two circles intersect. + + } else { + // Continue with chaining. + + } +#endif + } + + return std::make_pair(zmin, zmax); +} + +#ifdef TREE_SUPPORT_ORGANIC_NUDGE_NEW + +// New version using per layer AABB trees of lines for nudging spheres away from an object. +static void organic_smooth_branches_avoid_collisions( + const PrintObject &print_object, + const TreeModelVolumes &volumes, + const TreeSupportSettings &config, + std::vector &move_bounds, + const std::vector> &elements_with_link_down, + const std::vector &linear_data_layers, + std::function throw_on_cancel) +{ + struct LayerCollisionCache { + coord_t min_element_radius{ std::numeric_limits::max() }; + bool min_element_radius_known() const { return this->min_element_radius != std::numeric_limits::max(); } + coord_t collision_radius{ 0 }; + std::vector lines; + AABBTreeIndirect::Tree<2, double> aabbtree_lines; + bool empty() const { return this->lines.empty(); } + }; + std::vector layer_collision_cache; + layer_collision_cache.reserve(1024); + const SlicingParameters &slicing_params = print_object.slicing_parameters(); + for (const std::pair& element : elements_with_link_down) { + LayerIndex layer_idx = element.first->state.layer_idx; + if (size_t num_layers = layer_idx + 1; num_layers > layer_collision_cache.size()) { + if (num_layers > layer_collision_cache.capacity()) + reserve_power_of_2(layer_collision_cache, num_layers); + layer_collision_cache.resize(num_layers, {}); + } + auto& l = layer_collision_cache[layer_idx]; + l.min_element_radius = std::min(l.min_element_radius, support_element_radius(config, *element.first)); + } + + throw_on_cancel(); + + for (LayerIndex layer_idx = 0; layer_idx < LayerIndex(layer_collision_cache.size()); ++layer_idx) + if (LayerCollisionCache& l = layer_collision_cache[layer_idx]; !l.min_element_radius_known()) + l.min_element_radius = 0; + else { + //FIXME + l.min_element_radius = 0; + std::optional>> res = volumes.get_collision_lower_bound_area(layer_idx, l.min_element_radius); + assert(res.has_value()); + l.collision_radius = res->first; + Lines alines = to_lines(res->second.get()); + l.lines.reserve(alines.size()); + for (const Line &line : alines) + l.lines.push_back({ unscaled(line.a), unscaled(line.b) }); + l.aabbtree_lines = AABBTreeLines::build_aabb_tree_over_indexed_lines(l.lines); + throw_on_cancel(); + } + + struct CollisionSphere { + const SupportElement& element; + int element_below_id; + const bool locked; + float radius; + // Current position, when nudged away from the collision. + Vec3f position; + // Previous position, for Laplacian smoothing. + Vec3f prev_position; + // + Vec3f last_collision; + double last_collision_depth; + // Minimum Z for which the sphere collision will be evaluated. + // Limited by the minimum sloping angle and by the bottom of the tree. + float min_z{ -std::numeric_limits::max() }; + // Maximum Z for which the sphere collision will be evaluated. + // Limited by the minimum sloping angle and by the tip of the current branch. + float max_z{ std::numeric_limits::max() }; + uint32_t layer_begin; + uint32_t layer_end; + }; + + std::vector collision_spheres; + collision_spheres.reserve(elements_with_link_down.size()); + for (const std::pair &element_with_link : elements_with_link_down) { + const SupportElement &element = *element_with_link.first; + const int link_down = element_with_link.second; + collision_spheres.push_back({ + element, + link_down, + // locked + element.parents.empty() || (link_down == -1 && element.state.layer_idx > 0), + unscaled(support_element_radius(config, element)), + // 3D position + to_3d(unscaled(element.state.result_on_layer), float(layer_z(slicing_params, config, element.state.layer_idx))) + }); + // Update min_z coordinate to min_z of the tree below. + CollisionSphere &collision_sphere = collision_spheres.back(); + if (link_down != -1) { + const size_t offset_below = linear_data_layers[element.state.layer_idx - 1]; + collision_sphere.min_z = collision_spheres[offset_below + link_down].min_z; + } else + collision_sphere.min_z = collision_sphere.position.z(); + } + // Update max_z by propagating max_z from the tips of the branches. + for (int collision_sphere_id = int(collision_spheres.size()) - 1; collision_sphere_id >= 0; -- collision_sphere_id) { + CollisionSphere &collision_sphere = collision_spheres[collision_sphere_id]; + if (collision_sphere.element.parents.empty()) + // Tip + collision_sphere.max_z = collision_sphere.position.z(); + else { + // Below tip + const size_t offset_above = linear_data_layers[collision_sphere.element.state.layer_idx + 1]; + for (auto iparent : collision_sphere.element.parents) { + float parent_z = collision_spheres[offset_above + iparent].max_z; +// collision_sphere.max_z = collision_sphere.max_z == std::numeric_limits::max() ? parent_z : std::max(collision_sphere.max_z, parent_z); + collision_sphere.max_z = std::min(collision_sphere.max_z, parent_z); + } + } + } + // Update min_z / max_z to limit the search Z span of a given sphere for collision detection. + for (CollisionSphere &collision_sphere : collision_spheres) { + //FIXME limit the collision span by the tree slope. + collision_sphere.min_z = std::max(collision_sphere.min_z, collision_sphere.position.z() - collision_sphere.radius); + collision_sphere.max_z = std::min(collision_sphere.max_z, collision_sphere.position.z() + collision_sphere.radius); + collision_sphere.layer_begin = std::min(collision_sphere.element.state.layer_idx, layer_idx_ceil(slicing_params, config, collision_sphere.min_z)); + assert(collision_sphere.layer_begin < layer_collision_cache.size()); + collision_sphere.layer_end = std::min(LayerIndex(layer_collision_cache.size()), std::max(collision_sphere.element.state.layer_idx, layer_idx_floor(slicing_params, config, collision_sphere.max_z)) + 1); + } + + throw_on_cancel(); + + static constexpr const double collision_extra_gap = 0.1; + static constexpr const double max_nudge_collision_avoidance = 0.5; + static constexpr const double max_nudge_smoothing = 0.2; + static constexpr const size_t num_iter = 100; // 1000; + for (size_t iter = 0; iter < num_iter; ++ iter) { + // Back up prev position before Laplacian smoothing. + for (CollisionSphere &collision_sphere : collision_spheres) + collision_sphere.prev_position = collision_sphere.position; + std::atomic num_moved{ 0 }; + tbb::parallel_for(tbb::blocked_range(0, collision_spheres.size()), + [&collision_spheres, &layer_collision_cache, &slicing_params, &config, &linear_data_layers, &num_moved, &throw_on_cancel](const tbb::blocked_range range) { + for (size_t collision_sphere_id = range.begin(); collision_sphere_id < range.end(); ++ collision_sphere_id) + if (CollisionSphere &collision_sphere = collision_spheres[collision_sphere_id]; ! collision_sphere.locked) { + // Calculate collision of multiple 2D layers against a collision sphere. + collision_sphere.last_collision_depth = - std::numeric_limits::max(); + for (uint32_t layer_id = collision_sphere.layer_begin; layer_id != collision_sphere.layer_end; ++ layer_id) { + double dz = (layer_id - collision_sphere.element.state.layer_idx) * slicing_params.layer_height; + if (double r2 = sqr(collision_sphere.radius) - sqr(dz); r2 > 0) { + if (const LayerCollisionCache &layer_collision_cache_item = layer_collision_cache[layer_id]; ! layer_collision_cache_item.empty()) { + size_t hit_idx_out; + Vec2d hit_point_out; + if (double dist = sqrt(AABBTreeLines::squared_distance_to_indexed_lines( + layer_collision_cache_item.lines, layer_collision_cache_item.aabbtree_lines, Vec2d(to_2d(collision_sphere.position).cast()), + hit_idx_out, hit_point_out, r2)); dist >= 0.) { + double collision_depth = sqrt(r2) - dist; + if (collision_depth > collision_sphere.last_collision_depth) { + collision_sphere.last_collision_depth = collision_depth; + collision_sphere.last_collision = to_3d(hit_point_out.cast(), float(layer_z(slicing_params, config, layer_id))); + } + } + } + } + } + if (collision_sphere.last_collision_depth > 0) { + // Collision detected to be removed. + // Nudge the circle center away from the collision. + if (collision_sphere.last_collision_depth > EPSILON) + // a little bit of hysteresis to detect end of + ++ num_moved; + // Shift by maximum 2mm. + double nudge_dist = std::min(std::max(0., collision_sphere.last_collision_depth + collision_extra_gap), max_nudge_collision_avoidance); + Vec2d nudge_vector = (to_2d(collision_sphere.position) - to_2d(collision_sphere.last_collision)).cast().normalized() * nudge_dist; + collision_sphere.position.head<2>() += (nudge_vector * nudge_dist).cast(); + } + // Laplacian smoothing + Vec2d avg{ 0, 0 }; + //const SupportElements &above = move_bounds[collision_sphere.element.state.layer_idx + 1]; + const size_t offset_above = linear_data_layers[collision_sphere.element.state.layer_idx + 1]; + double weight = 0.; + for (auto iparent : collision_sphere.element.parents) { + double w = collision_sphere.radius; + avg += w * to_2d(collision_spheres[offset_above + iparent].prev_position.cast()); + weight += w; + } + if (collision_sphere.element_below_id != -1) { + const size_t offset_below = linear_data_layers[collision_sphere.element.state.layer_idx - 1]; + const double w = weight; // support_element_radius(config, move_bounds[element.state.layer_idx - 1][below]); + avg += w * to_2d(collision_spheres[offset_below + collision_sphere.element_below_id].prev_position.cast()); + weight += w; + } + avg /= weight; + static constexpr const double smoothing_factor = 0.5; + Vec2d old_pos = to_2d(collision_sphere.position).cast(); + Vec2d new_pos = (1. - smoothing_factor) * old_pos + smoothing_factor * avg; + Vec2d shift = new_pos - old_pos; + double nudge_dist_max = shift.norm(); + // Shift by maximum 1mm, less than the collision avoidance factor. + double nudge_dist = std::min(std::max(0., nudge_dist_max), max_nudge_smoothing); + collision_sphere.position.head<2>() += (shift.normalized() * nudge_dist).cast(); + + throw_on_cancel(); + } + }); +#if 0 + std::vector stat; + for (CollisionSphere& collision_sphere : collision_spheres) + if (!collision_sphere.locked) + stat.emplace_back(collision_sphere.last_collision_depth); + std::sort(stat.begin(), stat.end()); + printf("iteration: %d, moved: %d, collision depth: min %lf, max %lf, median %lf\n", int(iter), int(num_moved), stat.front(), stat.back(), stat[stat.size() / 2]); +#endif + if (num_moved == 0) + break; + } + + for (size_t i = 0; i < collision_spheres.size(); ++ i) + elements_with_link_down[i].first->state.result_on_layer = scaled(to_2d(collision_spheres[i].position)); +} +#else // TREE_SUPPORT_ORGANIC_NUDGE_NEW +// Old version using OpenVDB, works but it is extremely slow for complex meshes. +static void organic_smooth_branches_avoid_collisions( + const PrintObject &print_object, + const TreeModelVolumes &volumes, + const TreeSupportSettings &config, + std::vector &move_bounds, + const std::vector> &elements_with_link_down, + const std::vector &linear_data_layers, + std::function throw_on_cancel) +{ + TriangleMesh mesh = print_object.model_object()->raw_mesh(); + mesh.transform(print_object.trafo_centered()); + double scale = 10.; + openvdb::FloatGrid::Ptr grid = mesh_to_grid(mesh.its, openvdb::math::Transform{}, scale, 0., 0.); + std::unique_ptr> closest_surface_point = openvdb::tools::ClosestSurfacePoint::create(*grid); + std::vector pts, prev, projections; + std::vector distances; + for (const std::pair& element : elements_with_link_down) { + Vec3d pt = to_3d(unscaled(element.first->state.result_on_layer), layer_z(print_object.slicing_parameters(), config, element.first->state.layer_idx)) * scale; + pts.push_back({ pt.x(), pt.y(), pt.z() }); + } + + const double collision_extra_gap = 1. * scale; + const double max_nudge_collision_avoidance = 2. * scale; + const double max_nudge_smoothing = 1. * scale; + + static constexpr const size_t num_iter = 100; // 1000; + for (size_t iter = 0; iter < num_iter; ++ iter) { + prev = pts; + projections = pts; + distances.assign(pts.size(), std::numeric_limits::max()); + closest_surface_point->searchAndReplace(projections, distances); + size_t num_moved = 0; + for (size_t i = 0; i < projections.size(); ++ i) { + const SupportElement &element = *elements_with_link_down[i].first; + const int below = elements_with_link_down[i].second; + const bool locked = (below == -1 && element.state.layer_idx > 0) || element.state.locked(); + if (! locked && pts[i] != projections[i]) { + // Nudge the circle center away from the collision. + Vec3d v{ projections[i].x() - pts[i].x(), projections[i].y() - pts[i].y(), projections[i].z() - pts[i].z() }; + double depth = v.norm(); + assert(std::abs(distances[i] - depth) < EPSILON); + double radius = unscaled(support_element_radius(config, element)) * scale; + if (depth < radius) { + // Collision detected to be removed. + ++ num_moved; + double dxy = sqrt(sqr(radius) - sqr(v.z())); + double nudge_dist_max = dxy - std::hypot(v.x(), v.y()) + //FIXME 1mm gap + + collision_extra_gap; + // Shift by maximum 2mm. + double nudge_dist = std::min(std::max(0., nudge_dist_max), max_nudge_collision_avoidance); + Vec2d nudge_v = to_2d(v).normalized() * (- nudge_dist); + pts[i].x() += nudge_v.x(); + pts[i].y() += nudge_v.y(); + } + } + // Laplacian smoothing + if (! locked && ! element.parents.empty()) { + Vec2d avg{ 0, 0 }; + const SupportElements &above = move_bounds[element.state.layer_idx + 1]; + const size_t offset_above = linear_data_layers[element.state.layer_idx + 1]; + double weight = 0.; + for (auto iparent : element.parents) { + double w = support_element_radius(config, above[iparent]); + avg.x() += w * prev[offset_above + iparent].x(); + avg.y() += w * prev[offset_above + iparent].y(); + weight += w; + } + size_t cnt = element.parents.size(); + if (below != -1) { + const size_t offset_below = linear_data_layers[element.state.layer_idx - 1]; + const double w = weight; // support_element_radius(config, move_bounds[element.state.layer_idx - 1][below]); + avg.x() += w * prev[offset_below + below].x(); + avg.y() += w * prev[offset_below + below].y(); + ++ cnt; + weight += w; + } + //avg /= double(cnt); + avg /= weight; + static constexpr const double smoothing_factor = 0.5; + Vec2d old_pos{ pts[i].x(), pts[i].y() }; + Vec2d new_pos = (1. - smoothing_factor) * old_pos + smoothing_factor * avg; + Vec2d shift = new_pos - old_pos; + double nudge_dist_max = shift.norm(); + // Shift by maximum 1mm, less than the collision avoidance factor. + double nudge_dist = std::min(std::max(0., nudge_dist_max), max_nudge_smoothing); + Vec2d nudge_v = shift.normalized() * nudge_dist; + pts[i].x() += nudge_v.x(); + pts[i].y() += nudge_v.y(); + } + } +// printf("iteration: %d, moved: %d\n", int(iter), int(num_moved)); + if (num_moved == 0) + break; + } + + for (size_t i = 0; i < projections.size(); ++ i) { + elements_with_link_down[i].first->state.result_on_layer.x() = scaled(pts[i].x()) / scale; + elements_with_link_down[i].first->state.result_on_layer.y() = scaled(pts[i].y()) / scale; + } +} +#endif // TREE_SUPPORT_ORGANIC_NUDGE_NEW + +// Organic specific: Smooth branches and produce one cummulative mesh to be sliced. +void organic_draw_branches( + PrintObject &print_object, + TreeModelVolumes &volumes, + const TreeSupportSettings &config, + std::vector &move_bounds, + + // I/O: + SupportGeneratorLayersPtr &bottom_contacts, + SupportGeneratorLayersPtr &top_contacts, + InterfacePlacer &interface_placer, + + // Output: + SupportGeneratorLayersPtr &intermediate_layers, + SupportGeneratorLayerStorage &layer_storage, + + std::function throw_on_cancel) +{ + // All SupportElements are put into a layer independent storage to improve parallelization. + std::vector> elements_with_link_down; + std::vector linear_data_layers; + { + std::vector> map_downwards_old; + std::vector> map_downwards_new; + linear_data_layers.emplace_back(0); + for (LayerIndex layer_idx = 0; layer_idx < LayerIndex(move_bounds.size()); ++ layer_idx) { + SupportElements *layer_above = layer_idx + 1 < LayerIndex(move_bounds.size()) ? &move_bounds[layer_idx + 1] : nullptr; + map_downwards_new.clear(); + std::sort(map_downwards_old.begin(), map_downwards_old.end(), [](auto& l, auto& r) { return l.first < r.first; }); + SupportElements &layer = move_bounds[layer_idx]; + for (size_t elem_idx = 0; elem_idx < layer.size(); ++ elem_idx) { + SupportElement &elem = layer[elem_idx]; + int child = -1; + if (layer_idx > 0) { + auto it = std::lower_bound(map_downwards_old.begin(), map_downwards_old.end(), &elem, [](auto& l, const SupportElement* r) { return l.first < r; }); + if (it != map_downwards_old.end() && it->first == &elem) { + child = it->second; + // Only one link points to a node above from below. + assert(!(++it != map_downwards_old.end() && it->first == &elem)); + } +#ifndef NDEBUG + { + const SupportElement *pchild = child == -1 ? nullptr : &move_bounds[layer_idx - 1][child]; + assert(pchild ? pchild->state.result_on_layer_is_set() : elem.state.target_height > layer_idx); + } +#endif // NDEBUG + } + for (int32_t parent_idx : elem.parents) { + SupportElement &parent = (*layer_above)[parent_idx]; + if (parent.state.result_on_layer_is_set()) + map_downwards_new.emplace_back(&parent, elem_idx); + } + + elements_with_link_down.push_back({ &elem, int(child) }); + } + std::swap(map_downwards_old, map_downwards_new); + linear_data_layers.emplace_back(elements_with_link_down.size()); + } + } + + throw_on_cancel(); + + organic_smooth_branches_avoid_collisions(print_object, volumes, config, move_bounds, elements_with_link_down, linear_data_layers, throw_on_cancel); + + // Reduce memory footprint. After this point only finalize_interface_and_support_areas() will use volumes and from that only collisions with zero radius will be used. + volumes.clear_all_but_object_collision(); + + // Unmark all nodes. + for (SupportElements &elements : move_bounds) + for (SupportElement &element : elements) + element.state.marked = false; + + // Traverse all nodes, generate tubes. + // Traversal stack with nodes and their current parent + + struct Branch { + std::vector path; + bool has_root{ false }; + bool has_tip { false }; + }; + + struct Slice { + Polygons polygons; + Polygons bottom_contacts; + size_t num_branches{ 0 }; + }; + + struct Tree { + std::vector branches; + + std::vector slices; + LayerIndex first_layer_id{ -1 }; + }; + + std::vector trees; + + struct TreeVisitor { + static void visit_recursive(std::vector &move_bounds, SupportElement &start_element, Tree &out) { + assert(! start_element.state.marked && ! start_element.parents.empty()); + // Collect elements up to a bifurcation above. + start_element.state.marked = true; + // For each branch bifurcating from this point: + //SupportElements &layer = move_bounds[start_element.state.layer_idx]; + SupportElements &layer_above = move_bounds[start_element.state.layer_idx + 1]; + bool root = out.branches.empty(); + for (size_t parent_idx = 0; parent_idx < start_element.parents.size(); ++ parent_idx) { + Branch branch; + branch.path.emplace_back(&start_element); + // Traverse each branch until it branches again. + SupportElement &first_parent = layer_above[start_element.parents[parent_idx]]; + assert(! first_parent.state.marked); + assert(branch.path.back()->state.layer_idx + 1 == first_parent.state.layer_idx); + branch.path.emplace_back(&first_parent); + if (first_parent.parents.size() < 2) + first_parent.state.marked = true; + SupportElement *next_branch = nullptr; + if (first_parent.parents.size() == 1) { + for (SupportElement *parent = &first_parent;;) { + assert(parent->state.marked); + SupportElement &next_parent = move_bounds[parent->state.layer_idx + 1][parent->parents.front()]; + assert(! next_parent.state.marked); + assert(branch.path.back()->state.layer_idx + 1 == next_parent.state.layer_idx); + branch.path.emplace_back(&next_parent); + if (next_parent.parents.size() > 1) { + // Branching point was reached. + next_branch = &next_parent; + break; + } + next_parent.state.marked = true; + if (next_parent.parents.size() == 0) + // Tip is reached. + break; + parent = &next_parent; + } + } else if (first_parent.parents.size() > 1) + // Branching point was reached. + next_branch = &first_parent; + assert(branch.path.size() >= 2); + assert(next_branch == nullptr || ! next_branch->state.marked); + branch.has_root = root; + branch.has_tip = ! next_branch; + out.branches.emplace_back(std::move(branch)); + if (next_branch) + visit_recursive(move_bounds, *next_branch, out); + } + } + }; + + for (LayerIndex layer_idx = 0; layer_idx + 1 < LayerIndex(move_bounds.size()); ++ layer_idx) { +// int ielement; + for (SupportElement& start_element : move_bounds[layer_idx]) { + if (!start_element.state.marked && !start_element.parents.empty()) { +#if 0 + int found = 0; + if (layer_idx > 0) { + for (auto& el : move_bounds[layer_idx - 1]) { + for (auto iparent : el.parents) + if (iparent == ielement) + ++found; + } + if (found != 0) + printf("Found: %d\n", found); + } +#endif + trees.push_back({}); + TreeVisitor::visit_recursive(move_bounds, start_element, trees.back()); + assert(!trees.back().branches.empty()); + //FIXME debugging +#if 0 + if (start_element.state.lost) { + } + else if (start_element.state.verylost) { + } else + trees.pop_back(); +#endif + } +// ++ ielement; + } + } + + const SlicingParameters &slicing_params = print_object.slicing_parameters(); + MeshSlicingParams mesh_slicing_params; + mesh_slicing_params.mode = MeshSlicingParams::SlicingMode::Positive; + + tbb::parallel_for(tbb::blocked_range(0, trees.size(), 1), + [&trees, &volumes, &config, &slicing_params, &move_bounds, &mesh_slicing_params, &throw_on_cancel](const tbb::blocked_range &range) { + indexed_triangle_set partial_mesh; + std::vector slice_z; + std::vector bottom_contacts; + for (size_t tree_id = range.begin(); tree_id < range.end(); ++ tree_id) { + Tree &tree = trees[tree_id]; + for (const Branch &branch : tree.branches) { + // Triangulate the tube. + partial_mesh.clear(); + std::pair zspan = extrude_branch(branch.path, config, slicing_params, move_bounds, partial_mesh); + LayerIndex layer_begin = branch.has_root ? + branch.path.front()->state.layer_idx : + std::min(branch.path.front()->state.layer_idx, layer_idx_ceil(slicing_params, config, zspan.first)); + LayerIndex layer_end = (branch.has_tip ? + branch.path.back()->state.layer_idx : + std::max(branch.path.back()->state.layer_idx, layer_idx_floor(slicing_params, config, zspan.second))) + 1; + slice_z.clear(); + for (LayerIndex layer_idx = layer_begin; layer_idx < layer_end; ++ layer_idx) { + const double print_z = layer_z(slicing_params, config, layer_idx); + const double bottom_z = layer_idx > 0 ? layer_z(slicing_params, config, layer_idx - 1) : 0.; + slice_z.emplace_back(float(0.5 * (bottom_z + print_z))); + } + std::vector slices = slice_mesh(partial_mesh, slice_z, mesh_slicing_params, throw_on_cancel); + bottom_contacts.clear(); + //FIXME parallelize? + for (LayerIndex i = 0; i < LayerIndex(slices.size()); ++ i) + slices[i] = diff_clipped(slices[i], volumes.getCollision(0, layer_begin + i, true)); //FIXME parent_uses_min || draw_area.element->state.use_min_xy_dist); + + size_t num_empty = 0; + if (slices.front().empty()) { + // Some of the initial layers are empty. + num_empty = std::find_if(slices.begin(), slices.end(), [](auto &s) { return !s.empty(); }) - slices.begin(); + } else { + if (branch.has_root) { + if (branch.path.front()->state.to_model_gracious) { + if (config.settings.support_floor_layers > 0) + //FIXME one may just take the whole tree slice as bottom interface. + bottom_contacts.emplace_back(intersection_clipped(slices.front(), volumes.getPlaceableAreas(0, layer_begin, [] {}))); + } else if (layer_begin > 0) { + // Drop down areas that do rest non - gracefully on the model to ensure the branch actually rests on something. + struct BottomExtraSlice { + Polygons polygons; + double area; + }; + std::vector bottom_extra_slices; + Polygons rest_support; + coord_t bottom_radius = support_element_radius(config, *branch.path.front()); + // Don't propagate further than 1.5 * bottom radius. + //LayerIndex layers_propagate_max = 2 * bottom_radius / config.layer_height; + LayerIndex layers_propagate_max = 5 * bottom_radius / config.layer_height; + LayerIndex layer_bottommost = branch.path.front()->state.verylost ? + // If the tree bottom is hanging in the air, bring it down to some surface. + 0 : + //FIXME the "verylost" branches should stop when crossing another support. + std::max(0, layer_begin - layers_propagate_max); + double support_area_min_radius = M_PI * sqr(double(config.branch_radius)); + double support_area_stop = std::max(0.2 * M_PI * sqr(double(bottom_radius)), 0.5 * support_area_min_radius); + // Only propagate until the rest area is smaller than this threshold. + //double support_area_min = 0.1 * support_area_min_radius; + for (LayerIndex layer_idx = layer_begin - 1; layer_idx >= layer_bottommost; -- layer_idx) { + rest_support = diff_clipped(rest_support.empty() ? slices.front() : rest_support, volumes.getCollision(0, layer_idx, false)); + double rest_support_area = area(rest_support); + if (rest_support_area < support_area_stop) + // Don't propagate a fraction of the tree contact surface. + break; + bottom_extra_slices.push_back({ rest_support, rest_support_area }); + } + // Now remove those bottom slices that are not supported at all. +#if 0 + while (! bottom_extra_slices.empty()) { + Polygons this_bottom_contacts = intersection_clipped( + bottom_extra_slices.back().polygons, volumes.getPlaceableAreas(0, layer_begin - LayerIndex(bottom_extra_slices.size()), [] {})); + if (area(this_bottom_contacts) < support_area_min) + bottom_extra_slices.pop_back(); + else { + // At least a fraction of the tree bottom is considered to be supported. + if (config.settings.support_floor_layers > 0) + // Turn this fraction of the tree bottom into a contact layer. + bottom_contacts.emplace_back(std::move(this_bottom_contacts)); + break; + } + } +#endif + if (config.settings.support_floor_layers > 0) + for (int i = int(bottom_extra_slices.size()) - 2; i >= 0; -- i) + bottom_contacts.emplace_back( + intersection_clipped(bottom_extra_slices[i].polygons, volumes.getPlaceableAreas(0, layer_begin - i - 1, [] {}))); + layer_begin -= LayerIndex(bottom_extra_slices.size()); + slices.insert(slices.begin(), bottom_extra_slices.size(), {}); + auto it_dst = slices.begin(); + for (auto it_src = bottom_extra_slices.rbegin(); it_src != bottom_extra_slices.rend(); ++ it_src) + *it_dst ++ = std::move(it_src->polygons); + } + } + +#if 0 + //FIXME branch.has_tip seems to not be reliable. + if (branch.has_tip && interface_placer.support_parameters.has_top_contacts) + // Add top slices to top contacts / interfaces / base interfaces. + for (int i = int(branch.path.size()) - 1; i >= 0; -- i) { + const SupportElement &el = *branch.path[i]; + if (el.state.missing_roof_layers == 0) + break; + //FIXME Move or not? + interface_placer.add_roof(std::move(slices[int(slices.size()) - i - 1]), el.state.layer_idx, + interface_placer.support_parameters.num_top_interface_layers + 1 - el.state.missing_roof_layers); + } +#endif + } + + layer_begin += LayerIndex(num_empty); + while (! slices.empty() && slices.back().empty()) { + slices.pop_back(); + -- layer_end; + } + if (layer_begin < layer_end) { + LayerIndex new_begin = tree.first_layer_id == -1 ? layer_begin : std::min(tree.first_layer_id, layer_begin); + LayerIndex new_end = tree.first_layer_id == -1 ? layer_end : std::max(tree.first_layer_id + LayerIndex(tree.slices.size()), layer_end); + size_t new_size = size_t(new_end - new_begin); + if (tree.first_layer_id == -1) { + } else if (tree.slices.capacity() < new_size) { + std::vector new_slices; + new_slices.reserve(new_size); + if (LayerIndex dif = tree.first_layer_id - new_begin; dif > 0) + new_slices.insert(new_slices.end(), dif, {}); + append(new_slices, std::move(tree.slices)); + tree.slices.swap(new_slices); + } else if (LayerIndex dif = tree.first_layer_id - new_begin; dif > 0) + tree.slices.insert(tree.slices.begin(), tree.first_layer_id - new_begin, {}); + tree.slices.insert(tree.slices.end(), new_size - tree.slices.size(), {}); + layer_begin -= LayerIndex(num_empty); + for (LayerIndex i = layer_begin; i != layer_end; ++ i) { + int j = i - layer_begin; + if (Polygons &src = slices[j]; ! src.empty()) { + Slice &dst = tree.slices[i - new_begin]; + if (++ dst.num_branches > 1) { + append(dst.polygons, std::move(src)); + if (j < int(bottom_contacts.size())) + append(dst.bottom_contacts, std::move(bottom_contacts[j])); + } else { + dst.polygons = std::move(std::move(src)); + if (j < int(bottom_contacts.size())) + dst.bottom_contacts = std::move(bottom_contacts[j]); + } + } + } + tree.first_layer_id = new_begin; + } + } + } + }, tbb::simple_partitioner()); + + tbb::parallel_for(tbb::blocked_range(0, trees.size(), 1), + [&trees, &throw_on_cancel](const tbb::blocked_range &range) { + for (size_t tree_id = range.begin(); tree_id < range.end(); ++ tree_id) { + Tree &tree = trees[tree_id]; + for (Slice &slice : tree.slices) + if (slice.num_branches > 1) { + slice.polygons = union_(slice.polygons); + slice.bottom_contacts = union_(slice.bottom_contacts); + slice.num_branches = 1; + } + throw_on_cancel(); + } + }, tbb::simple_partitioner()); + + size_t num_layers = 0; + for (Tree &tree : trees) + if (tree.first_layer_id >= 0) + num_layers = std::max(num_layers, size_t(tree.first_layer_id + tree.slices.size())); + + std::vector slices(num_layers, Slice{}); + for (Tree &tree : trees) + if (tree.first_layer_id >= 0) { + for (LayerIndex i = tree.first_layer_id; i != tree.first_layer_id + LayerIndex(tree.slices.size()); ++ i) + if (Slice &src = tree.slices[i - tree.first_layer_id]; ! src.polygons.empty()) { + Slice &dst = slices[i]; + if (++ dst.num_branches > 1) { + append(dst.polygons, std::move(src.polygons)); + append(dst.bottom_contacts, std::move(src.bottom_contacts)); + } else { + dst.polygons = std::move(src.polygons); + dst.bottom_contacts = std::move(src.bottom_contacts); + } + } + } + + tbb::parallel_for(tbb::blocked_range(0, std::min(move_bounds.size(), slices.size()), 1), + [&print_object, &config, &slices, &bottom_contacts, &top_contacts, &intermediate_layers, &layer_storage, &throw_on_cancel](const tbb::blocked_range &range) { + for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++layer_idx) { + Slice &slice = slices[layer_idx]; + assert(intermediate_layers[layer_idx] == nullptr); + Polygons base_layer_polygons = slice.num_branches > 1 ? union_(slice.polygons) : std::move(slice.polygons); + Polygons bottom_contact_polygons = slice.num_branches > 1 ? union_(slice.bottom_contacts) : std::move(slice.bottom_contacts); + + if (! base_layer_polygons.empty()) { + // Most of the time in this function is this union call. Can take 300+ ms when a lot of areas are to be unioned. + base_layer_polygons = smooth_outward(union_(base_layer_polygons), config.support_line_width); //FIXME was .smooth(50); + //smooth_outward(closing(std::move(bottom), closing_distance + minimum_island_radius, closing_distance, SUPPORT_SURFACES_OFFSET_PARAMETERS), smoothing_distance) : + // simplify a bit, to ensure the output does not contain outrageous amounts of vertices. Should not be necessary, just a precaution. + base_layer_polygons = polygons_simplify(base_layer_polygons, std::min(scaled(0.03), double(config.resolution)), polygons_strictly_simple); + } + + // Subtract top contact layer polygons from support base. + SupportGeneratorLayer *top_contact_layer = top_contacts.empty() ? nullptr : top_contacts[layer_idx]; + if (top_contact_layer && ! top_contact_layer->polygons.empty() && ! base_layer_polygons.empty()) { + base_layer_polygons = diff(base_layer_polygons, top_contact_layer->polygons); + if (! bottom_contact_polygons.empty()) + //FIXME it may be better to clip bottom contacts with top contacts first after they are propagated to produce interface layers. + bottom_contact_polygons = diff(bottom_contact_polygons, top_contact_layer->polygons); + } + if (! bottom_contact_polygons.empty()) { + base_layer_polygons = diff(base_layer_polygons, bottom_contact_polygons); + SupportGeneratorLayer *bottom_contact_layer = bottom_contacts[layer_idx] = &layer_allocate( + layer_storage, SupporLayerType::BottomContact, print_object.slicing_parameters(), config, layer_idx); + bottom_contact_layer->polygons = std::move(bottom_contact_polygons); + } + if (! base_layer_polygons.empty()) { + SupportGeneratorLayer *base_layer = intermediate_layers[layer_idx] = &layer_allocate( + layer_storage, SupporLayerType::Base, print_object.slicing_parameters(), config, layer_idx); + base_layer->polygons = union_(base_layer_polygons); + } + + throw_on_cancel(); + } + }, tbb::simple_partitioner()); +} + +} // namespace FFFTreeSupport + +} // namespace Slic3r diff --git a/src/libslic3r/Support/OrganicSupport.hpp b/src/libslic3r/Support/OrganicSupport.hpp new file mode 100644 index 0000000000..c7b13b9db5 --- /dev/null +++ b/src/libslic3r/Support/OrganicSupport.hpp @@ -0,0 +1,43 @@ +///|/ Copyright (c) Prusa Research 2023 Vojtěch Bubník @bubnikv +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +#ifndef slic3r_OrganicSupport_hpp +#define slic3r_OrganicSupport_hpp + +#include "SupportCommon.hpp" +#include "TreeSupport.hpp" + +namespace Slic3r +{ + +class PrintObject; + +namespace FFFTreeSupport +{ + +class TreeModelVolumes; + +// Organic specific: Smooth branches and produce one cummulative mesh to be sliced. +void organic_draw_branches( + PrintObject &print_object, + TreeModelVolumes &volumes, + const TreeSupportSettings &config, + std::vector &move_bounds, + + // I/O: + SupportGeneratorLayersPtr &bottom_contacts, + SupportGeneratorLayersPtr &top_contacts, + InterfacePlacer &interface_placer, + + // Output: + SupportGeneratorLayersPtr &intermediate_layers, + SupportGeneratorLayerStorage &layer_storage, + + std::function throw_on_cancel); + +} // namespace FFFTreeSupport + +} // namespace Slic3r + +#endif // slic3r_OrganicSupport_hpp \ No newline at end of file diff --git a/src/libslic3r/Support/SupportCommon.cpp b/src/libslic3r/Support/SupportCommon.cpp new file mode 100644 index 0000000000..50e19cca0d --- /dev/null +++ b/src/libslic3r/Support/SupportCommon.cpp @@ -0,0 +1,2003 @@ +///|/ Copyright (c) Prusa Research 2023 Vojtěch Bubník @bubnikv, Pavel Mikuš @Godrak +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +#include "../ClipperUtils.hpp" +// #include "../ClipperZUtils.hpp" +#include "../ExtrusionEntityCollection.hpp" +#include "../Layer.hpp" +#include "../Print.hpp" +#include "../Fill/FillBase.hpp" +#include "../MutablePolygon.hpp" +#include "../Geometry.hpp" +#include "../Point.hpp" + +#include +#include + +#include + +#include "SupportCommon.hpp" +#include "SupportLayer.hpp" +#include "SupportParameters.hpp" + +// #define SLIC3R_DEBUG + +// Make assert active if SLIC3R_DEBUG +#ifdef SLIC3R_DEBUG + #define DEBUG + #define _DEBUG + #undef NDEBUG + #include "../utils.hpp" + #include "../SVG.hpp" +#endif + +#include + +namespace Slic3r::FFFSupport { + +// how much we extend support around the actual contact area +//FIXME this should be dependent on the nozzle diameter! +#define SUPPORT_MATERIAL_MARGIN 1.5 + +//#define SUPPORT_SURFACES_OFFSET_PARAMETERS ClipperLib::jtMiter, 3. +//#define SUPPORT_SURFACES_OFFSET_PARAMETERS ClipperLib::jtMiter, 1.5 +#define SUPPORT_SURFACES_OFFSET_PARAMETERS ClipperLib::jtSquare, 0. + +void remove_bridges_from_contacts( + const PrintConfig &print_config, + const Layer &lower_layer, + const LayerRegion &layerm, + float fw, + Polygons &contact_polygons) +{ + // compute the area of bridging perimeters + Polygons bridges; + { + // Surface supporting this layer, expanded by 0.5 * nozzle_diameter, as we consider this kind of overhang to be sufficiently supported. + Polygons lower_grown_slices = expand(lower_layer.lslices, + //FIXME to mimic the decision in the perimeter generator, we should use half the external perimeter width. + 0.5f * float(scale_(print_config.nozzle_diameter.get_at(layerm.region().config().wall_filament - 1))), + SUPPORT_SURFACES_OFFSET_PARAMETERS); + // Collect perimeters of this layer. + //FIXME split_at_first_point() could split a bridge mid-way + #if 0 + Polylines overhang_perimeters = layerm.perimeters.as_polylines(); + // workaround for Clipper bug, see Slic3r::Polygon::clip_as_polyline() + for (Polyline &polyline : overhang_perimeters) + polyline.points[0].x += 1; + // Trim the perimeters of this layer by the lower layer to get the unsupported pieces of perimeters. + overhang_perimeters = diff_pl(overhang_perimeters, lower_grown_slices); + #else + Polylines overhang_perimeters = diff_pl(layerm.perimeters.as_polylines(), lower_grown_slices); + #endif + + // only consider straight overhangs + // only consider overhangs having endpoints inside layer's slices + // convert bridging polylines into polygons by inflating them with their thickness + // since we're dealing with bridges, we can't assume width is larger than spacing, + // so we take the largest value and also apply safety offset to be ensure no gaps + // are left in between + Flow perimeter_bridge_flow = layerm.bridging_flow(frPerimeter); + //FIXME one may want to use a maximum of bridging flow width and normal flow width, as the perimeters are calculated using the normal flow + // and then turned to bridging flow, thus their centerlines are derived from non-bridging flow and expanding them by a bridging flow + // may not expand them to the edge of their respective islands. + const float w = float(0.5 * std::max(perimeter_bridge_flow.scaled_width(), perimeter_bridge_flow.scaled_spacing())) + scaled(0.001); + for (Polyline &polyline : overhang_perimeters) + if (polyline.is_straight()) { + // This is a bridge + polyline.extend_start(fw); + polyline.extend_end(fw); + // Is the straight perimeter segment supported at both sides? + Point pts[2] = { polyline.first_point(), polyline.last_point() }; + bool supported[2] = { false, false }; + for (size_t i = 0; i < lower_layer.lslices.size() && ! (supported[0] && supported[1]); ++ i) + for (int j = 0; j < 2; ++ j) + if (! supported[j] && lower_layer.lslices_bboxes[i].contains(pts[j]) && lower_layer.lslices[i].contains(pts[j])) + supported[j] = true; + if (supported[0] && supported[1]) + // Offset a polyline into a thick line. + polygons_append(bridges, offset(polyline, w)); + } + bridges = union_(bridges); + } + // remove the entire bridges and only support the unsupported edges + //FIXME the brided regions are already collected as layerm.bridged. Use it? + for (const Surface &surface : layerm.fill_surfaces.surfaces) + if (surface.surface_type == stBottomBridge && surface.bridge_angle >= 0.0) + polygons_append(bridges, surface.expolygon); + //FIXME add the gap filled areas. Extrude the gaps with a bridge flow? + // Remove the unsupported ends of the bridges from the bridged areas. + //FIXME add supports at regular intervals to support long bridges! + bridges = diff(bridges, + // Offset unsupported edges into polygons. + offset(layerm.unsupported_bridge_edges, scale_(SUPPORT_MATERIAL_MARGIN), SUPPORT_SURFACES_OFFSET_PARAMETERS)); + // Remove bridged areas from the supported areas. + contact_polygons = diff(contact_polygons, bridges, ApplySafetyOffset::Yes); + + #ifdef SLIC3R_DEBUG + static int iRun = 0; + SVG::export_expolygons(debug_out_path("support-top-contacts-remove-bridges-run%d.svg", iRun ++), + { { { union_ex(offset(layerm.unsupported_bridge_edges(), scale_(SUPPORT_MATERIAL_MARGIN), SUPPORT_SURFACES_OFFSET_PARAMETERS)) }, { "unsupported_bridge_edges", "orange", 0.5f } }, + { { union_ex(contact_polygons) }, { "contact_polygons", "blue", 0.5f } }, + { { union_ex(bridges) }, { "bridges", "red", "black", "", scaled(0.1f), 0.5f } } }); + #endif /* SLIC3R_DEBUG */ +} + +// Convert some of the intermediate layers into top/bottom interface layers as well as base interface layers. +std::pair generate_interface_layers( + const PrintObjectConfig &config, + const SupportParameters &support_params, + const SupportGeneratorLayersPtr &bottom_contacts, + const SupportGeneratorLayersPtr &top_contacts, + // Input / output, will be merged with output. Only provided for Organic supports. + SupportGeneratorLayersPtr &top_interface_layers, + SupportGeneratorLayersPtr &top_base_interface_layers, + // Input, will be trimmed with the newly created interface layers. + SupportGeneratorLayersPtr &intermediate_layers, + SupportGeneratorLayerStorage &layer_storage) +{ + std::pair base_and_interface_layers; + + if (! intermediate_layers.empty() && support_params.has_interfaces()) { + // For all intermediate layers, collect top contact surfaces, which are not further than support_material_interface_layers. + BOOST_LOG_TRIVIAL(debug) << "PrintObjectSupportMaterial::generate_interface_layers() in parallel - start"; + const bool snug_supports = config.support_style.value == smsSnug; + const bool smooth_supports = config.support_style.value != smsGrid; + SupportGeneratorLayersPtr &interface_layers = base_and_interface_layers.first; + SupportGeneratorLayersPtr &base_interface_layers = base_and_interface_layers.second; + interface_layers.assign(intermediate_layers.size(), nullptr); + if (support_params.has_base_interfaces()) + base_interface_layers.assign(intermediate_layers.size(), nullptr); + const auto smoothing_distance = support_params.support_material_interface_flow.scaled_spacing() * 1.5; + const auto minimum_island_radius = support_params.support_material_interface_flow.scaled_spacing() / support_params.interface_density; + const auto closing_distance = smoothing_distance; // scaled(config.support_material_closing_radius.value); + // Insert a new layer into base_interface_layers, if intersection with base exists. + auto insert_layer = [&layer_storage, smooth_supports, closing_distance, smoothing_distance, minimum_island_radius]( + SupportGeneratorLayer &intermediate_layer, Polygons &bottom, Polygons &&top, SupportGeneratorLayer *top_interface_layer, + const Polygons *subtract, SupporLayerType type) -> SupportGeneratorLayer* { + bool has_top_interface = top_interface_layer && ! top_interface_layer->polygons.empty(); + assert(! bottom.empty() || ! top.empty() || has_top_interface); + // Merge top into bottom, unite them with a safety offset. + append(bottom, std::move(top)); + // Merge top / bottom interfaces. For snug supports, merge using closing distance and regularize (close concave corners). + bottom = intersection( + smooth_supports ? + smooth_outward(closing(std::move(bottom), closing_distance + minimum_island_radius, closing_distance, SUPPORT_SURFACES_OFFSET_PARAMETERS), smoothing_distance) : + union_safety_offset(std::move(bottom)), + intermediate_layer.polygons); + if (has_top_interface) { + // Don't trim the precomputed Organic supports top interface with base layer + // as the precomputed top interface likely expands over multiple tree tips. + bottom = union_(std::move(top_interface_layer->polygons), bottom); + top_interface_layer->polygons.clear(); + } + if (! bottom.empty()) { + //FIXME Remove non-printable tiny islands, let them be printed using the base support. + //bottom = opening(std::move(bottom), minimum_island_radius); + if (! bottom.empty()) { + SupportGeneratorLayer &layer_new = top_interface_layer ? *top_interface_layer : layer_storage.allocate(type); + layer_new.polygons = std::move(bottom); + layer_new.print_z = intermediate_layer.print_z; + layer_new.bottom_z = intermediate_layer.bottom_z; + layer_new.height = intermediate_layer.height; + layer_new.bridging = intermediate_layer.bridging; + // Subtract the interface from the base regions. + intermediate_layer.polygons = diff(intermediate_layer.polygons, layer_new.polygons); + if (subtract) + // Trim the base interface layer with the interface layer. + layer_new.polygons = diff(std::move(layer_new.polygons), *subtract); + //FIXME filter layer_new.polygons islands by a minimum area? + // $interface_area = [ grep abs($_->area) >= $area_threshold, @$interface_area ]; + return &layer_new; + } + } + return nullptr; + }; + tbb::parallel_for(tbb::blocked_range(0, int(intermediate_layers.size())), + [&bottom_contacts, &top_contacts, &top_interface_layers, &top_base_interface_layers, &intermediate_layers, &insert_layer, &support_params, + snug_supports, &interface_layers, &base_interface_layers](const tbb::blocked_range& range) { + // Gather the top / bottom contact layers intersecting with num_interface_layers resp. num_interface_layers_only intermediate layers above / below + // this intermediate layer. + // Index of the first top contact layer intersecting the current intermediate layer. + auto idx_top_contact_first = -1; + // Index of the first bottom contact layer intersecting the current intermediate layer. + auto idx_bottom_contact_first = -1; + // Index of the first top interface layer intersecting the current intermediate layer. + auto idx_top_interface_first = -1; + // Index of the first top contact interface layer intersecting the current intermediate layer. + auto idx_top_base_interface_first = -1; + auto num_intermediate = int(intermediate_layers.size()); + for (int idx_intermediate_layer = range.begin(); idx_intermediate_layer < range.end(); ++ idx_intermediate_layer) { + SupportGeneratorLayer &intermediate_layer = *intermediate_layers[idx_intermediate_layer]; + Polygons polygons_top_contact_projected_interface; + Polygons polygons_top_contact_projected_base; + Polygons polygons_bottom_contact_projected_interface; + Polygons polygons_bottom_contact_projected_base; + if (support_params.num_top_interface_layers > 0) { + // Top Z coordinate of a slab, over which we are collecting the top / bottom contact surfaces + coordf_t top_z = intermediate_layers[std::min(num_intermediate - 1, idx_intermediate_layer + int(support_params.num_top_interface_layers) - 1)]->print_z; + coordf_t top_inteface_z = std::numeric_limits::max(); + if (support_params.num_top_base_interface_layers > 0) + // Some top base interface layers will be generated. + top_inteface_z = support_params.num_top_interface_layers_only() == 0 ? + // Only base interface layers to generate. + - std::numeric_limits::max() : + intermediate_layers[std::min(num_intermediate - 1, idx_intermediate_layer + int(support_params.num_top_interface_layers_only()) - 1)]->print_z; + // Move idx_top_contact_first up until above the current print_z. + idx_top_contact_first = idx_higher_or_equal(top_contacts, idx_top_contact_first, [&intermediate_layer](const SupportGeneratorLayer *layer){ return layer->print_z >= intermediate_layer.print_z; }); // - EPSILON + // Collect the top contact areas above this intermediate layer, below top_z. + for (int idx_top_contact = idx_top_contact_first; idx_top_contact < int(top_contacts.size()); ++ idx_top_contact) { + const SupportGeneratorLayer &top_contact_layer = *top_contacts[idx_top_contact]; + //FIXME maybe this adds one interface layer in excess? + if (top_contact_layer.bottom_z - EPSILON > top_z) + break; + polygons_append(top_contact_layer.bottom_z - EPSILON > top_inteface_z ? polygons_top_contact_projected_base : polygons_top_contact_projected_interface, + // For snug supports, project the overhang polygons covering the whole overhang, so that they will merge without a gap with support polygons of the other layers. + // For grid supports, merging of support regions will be performed by the projection into grid. + snug_supports ? *top_contact_layer.overhang_polygons : top_contact_layer.polygons); + } + } + if (support_params.num_bottom_interface_layers > 0) { + // Bottom Z coordinate of a slab, over which we are collecting the top / bottom contact surfaces + coordf_t bottom_z = intermediate_layers[std::max(0, idx_intermediate_layer - int(support_params.num_bottom_interface_layers) + 1)]->bottom_z; + coordf_t bottom_interface_z = - std::numeric_limits::max(); + if (support_params.num_bottom_base_interface_layers > 0) + // Some bottom base interface layers will be generated. + bottom_interface_z = support_params.num_bottom_interface_layers_only() == 0 ? + // Only base interface layers to generate. + std::numeric_limits::max() : + intermediate_layers[std::max(0, idx_intermediate_layer - int(support_params.num_bottom_interface_layers_only()))]->bottom_z; + // Move idx_bottom_contact_first up until touching bottom_z. + idx_bottom_contact_first = idx_higher_or_equal(bottom_contacts, idx_bottom_contact_first, [bottom_z](const SupportGeneratorLayer *layer){ return layer->print_z >= bottom_z - EPSILON; }); + // Collect the top contact areas above this intermediate layer, below top_z. + for (int idx_bottom_contact = idx_bottom_contact_first; idx_bottom_contact < int(bottom_contacts.size()); ++ idx_bottom_contact) { + const SupportGeneratorLayer &bottom_contact_layer = *bottom_contacts[idx_bottom_contact]; + if (bottom_contact_layer.print_z - EPSILON > intermediate_layer.bottom_z) + break; + polygons_append(bottom_contact_layer.print_z - EPSILON > bottom_interface_z ? polygons_bottom_contact_projected_interface : polygons_bottom_contact_projected_base, bottom_contact_layer.polygons); + } + } + auto resolve_same_layer = [](SupportGeneratorLayersPtr &layers, int &idx, coordf_t print_z) -> SupportGeneratorLayer* { + if (! layers.empty()) { + idx = idx_higher_or_equal(layers, idx, [print_z](const SupportGeneratorLayer *layer) { return layer->print_z > print_z - EPSILON; }); + if (idx < int(layers.size()) && layers[idx]->print_z < print_z + EPSILON) + return layers[idx]; + } + return nullptr; + }; + SupportGeneratorLayer *top_interface_layer = resolve_same_layer(top_interface_layers, idx_top_interface_first, intermediate_layer.print_z); + SupportGeneratorLayer *top_base_interface_layer = resolve_same_layer(top_base_interface_layers, idx_top_base_interface_first, intermediate_layer.print_z); + SupportGeneratorLayer *interface_layer = nullptr; + if (! polygons_bottom_contact_projected_interface.empty() || ! polygons_top_contact_projected_interface.empty() || + (top_interface_layer && ! top_interface_layer->polygons.empty())) { + interface_layer = insert_layer( + intermediate_layer, polygons_bottom_contact_projected_interface, std::move(polygons_top_contact_projected_interface), top_interface_layer, + nullptr, polygons_top_contact_projected_interface.empty() ? SupporLayerType::BottomInterface : SupporLayerType::TopInterface); + interface_layers[idx_intermediate_layer] = interface_layer; + } + if (! polygons_bottom_contact_projected_base.empty() || ! polygons_top_contact_projected_base.empty() || + (top_base_interface_layer && ! top_base_interface_layer->polygons.empty())) + base_interface_layers[idx_intermediate_layer] = insert_layer( + intermediate_layer, polygons_bottom_contact_projected_base, std::move(polygons_top_contact_projected_base), top_base_interface_layer, + interface_layer ? &interface_layer->polygons : nullptr, SupporLayerType::Base); + } + }); + + // Compress contact_out, remove the nullptr items. + // The parallel_for above may not have merged all the interface and base_interface layers + // generated by the Organic supports code, do it here. + auto merge_remove_empty = [](SupportGeneratorLayersPtr &in1, SupportGeneratorLayersPtr &in2) { + auto remove_empty = [](SupportGeneratorLayersPtr &vec) { + vec.erase( + std::remove_if(vec.begin(), vec.end(), [](const SupportGeneratorLayer *ptr) { return ptr == nullptr || ptr->polygons.empty(); }), + vec.end()); + }; + remove_empty(in1); + remove_empty(in2); + if (in2.empty()) + return std::move(in1); + else if (in1.empty()) + return std::move(in2); + else { + SupportGeneratorLayersPtr out(in1.size() + in2.size(), nullptr); + std::merge(in1.begin(), in1.end(), in2.begin(), in2.end(), out.begin(), [](auto* l, auto* r) { return l->print_z < r->print_z; }); + return out; + } + }; + interface_layers = merge_remove_empty(interface_layers, top_interface_layers); + base_interface_layers = merge_remove_empty(base_interface_layers, top_base_interface_layers); + BOOST_LOG_TRIVIAL(debug) << "PrintObjectSupportMaterial::generate_interface_layers() in parallel - end"; + } + + return base_and_interface_layers; +} + +SupportGeneratorLayersPtr generate_raft_base( + const PrintObject &object, + const SupportParameters &support_params, + const SlicingParameters &slicing_params, + const SupportGeneratorLayersPtr &top_contacts, + const SupportGeneratorLayersPtr &interface_layers, + const SupportGeneratorLayersPtr &base_interface_layers, + const SupportGeneratorLayersPtr &base_layers, + SupportGeneratorLayerStorage &layer_storage) +{ + // If there is brim to be generated, calculate the trimming regions. + Polygons brim; + if (object.has_brim()) { + // The object does not have a raft. + // Calculate the area covered by the brim. + const BrimType brim_type = object.config().brim_type; + const bool brim_outer = brim_type == btOuterOnly || brim_type == btOuterAndInner; + const bool brim_inner = brim_type == btInnerOnly || brim_type == btOuterAndInner; + const auto brim_separation = scaled(object.config().brim_object_gap.value + object.config().brim_width.value); + for (const ExPolygon &ex : object.layers().front()->lslices) { + if (brim_outer && brim_inner) + polygons_append(brim, offset(ex, brim_separation)); + else { + if (brim_outer) + polygons_append(brim, offset(ex.contour, brim_separation, ClipperLib::jtRound, float(scale_(0.1)))); + else + brim.emplace_back(ex.contour); + if (brim_inner) { + Polygons holes = ex.holes; + polygons_reverse(holes); + holes = shrink(holes, brim_separation, ClipperLib::jtRound, float(scale_(0.1))); + polygons_reverse(holes); + polygons_append(brim, std::move(holes)); + } else + polygons_append(brim, ex.holes); + } + } + brim = union_(brim); + } + + // How much to inflate the support columns to be stable. This also applies to the 1st layer, if no raft layers are to be printed. + const float inflate_factor_fine = float(scale_((slicing_params.raft_layers() > 1) ? 0.5 : EPSILON)); + const float inflate_factor_1st_layer = std::max(0.f, float(scale_(object.config().raft_first_layer_expansion)) - inflate_factor_fine); + SupportGeneratorLayer *contacts = top_contacts .empty() ? nullptr : top_contacts .front(); + SupportGeneratorLayer *interfaces = interface_layers .empty() ? nullptr : interface_layers .front(); + SupportGeneratorLayer *base_interfaces = base_interface_layers.empty() ? nullptr : base_interface_layers.front(); + SupportGeneratorLayer *columns_base = base_layers .empty() ? nullptr : base_layers .front(); + if (contacts != nullptr && contacts->print_z > std::max(slicing_params.first_print_layer_height, slicing_params.raft_contact_top_z) + EPSILON) + // This is not the raft contact layer. + contacts = nullptr; + if (interfaces != nullptr && interfaces->bottom_print_z() > slicing_params.raft_interface_top_z + EPSILON) + // This is not the raft column base layer. + interfaces = nullptr; + if (base_interfaces != nullptr && base_interfaces->bottom_print_z() > slicing_params.raft_interface_top_z + EPSILON) + // This is not the raft column base layer. + base_interfaces = nullptr; + if (columns_base != nullptr && columns_base->bottom_print_z() > slicing_params.raft_interface_top_z + EPSILON) + // This is not the raft interface layer. + columns_base = nullptr; + + Polygons interface_polygons; + if (contacts != nullptr && ! contacts->polygons.empty()) + polygons_append(interface_polygons, expand(contacts->polygons, inflate_factor_fine, SUPPORT_SURFACES_OFFSET_PARAMETERS)); + if (interfaces != nullptr && ! interfaces->polygons.empty()) + polygons_append(interface_polygons, expand(interfaces->polygons, inflate_factor_fine, SUPPORT_SURFACES_OFFSET_PARAMETERS)); + if (base_interfaces != nullptr && ! base_interfaces->polygons.empty()) + polygons_append(interface_polygons, expand(base_interfaces->polygons, inflate_factor_fine, SUPPORT_SURFACES_OFFSET_PARAMETERS)); + + // Output vector. + SupportGeneratorLayersPtr raft_layers; + + if (slicing_params.raft_layers() > 1) { + Polygons base; + Polygons columns; + Polygons first_layer; + if (columns_base != nullptr) { + if (columns_base->bottom_print_z() > slicing_params.raft_interface_top_z - EPSILON) { + // Classic supports with colums above the raft interface. + base = columns_base->polygons; + columns = base; + if (! interface_polygons.empty()) + // Trim the 1st layer columns with the inflated interface polygons. + columns = diff(columns, interface_polygons); + } else { + // Organic supports with raft on print bed. + assert(is_approx(columns_base->print_z, slicing_params.first_print_layer_height)); + first_layer = columns_base->polygons; + } + } + if (! interface_polygons.empty()) { + // Merge the untrimmed columns base with the expanded raft interface, to be used for the support base and interface. + base = union_(base, interface_polygons); + } + // Do not add the raft contact layer, only add the raft layers below the contact layer. + // Insert the 1st layer. + { + SupportGeneratorLayer &new_layer = layer_storage.allocate_unguarded(slicing_params.base_raft_layers > 0 ? SupporLayerType::RaftBase : SupporLayerType::RaftInterface); + raft_layers.push_back(&new_layer); + new_layer.print_z = slicing_params.first_print_layer_height; + new_layer.height = slicing_params.first_print_layer_height; + new_layer.bottom_z = 0.; + first_layer = union_(std::move(first_layer), base); + new_layer.polygons = inflate_factor_1st_layer > 0 ? expand(first_layer, inflate_factor_1st_layer) : first_layer; + } + // Insert the base layers. + for (size_t i = 1; i < slicing_params.base_raft_layers; ++ i) { + coordf_t print_z = raft_layers.back()->print_z; + SupportGeneratorLayer &new_layer = layer_storage.allocate_unguarded(SupporLayerType::RaftBase); + raft_layers.push_back(&new_layer); + new_layer.print_z = print_z + slicing_params.base_raft_layer_height; + new_layer.height = slicing_params.base_raft_layer_height; + new_layer.bottom_z = print_z; + new_layer.polygons = base; + } + // Insert the interface layers. + for (size_t i = 1; i < slicing_params.interface_raft_layers; ++ i) { + coordf_t print_z = raft_layers.back()->print_z; + SupportGeneratorLayer &new_layer = layer_storage.allocate_unguarded(SupporLayerType::RaftInterface); + raft_layers.push_back(&new_layer); + new_layer.print_z = print_z + slicing_params.interface_raft_layer_height; + new_layer.height = slicing_params.interface_raft_layer_height; + new_layer.bottom_z = print_z; + new_layer.polygons = interface_polygons; + //FIXME misusing contact_polygons for support columns. + new_layer.contact_polygons = std::make_unique(columns); + } + } else { + if (columns_base != nullptr) { + // Expand the bases of the support columns in the 1st layer. + Polygons &raft = columns_base->polygons; + Polygons trimming = offset(object.layers().front()->lslices, (float)scale_(support_params.gap_xy), SUPPORT_SURFACES_OFFSET_PARAMETERS); + if (inflate_factor_1st_layer > SCALED_EPSILON) { + // Inflate in multiple steps to avoid leaking of the support 1st layer through object walls. + auto nsteps = std::max(5, int(ceil(inflate_factor_1st_layer / support_params.first_layer_flow.scaled_width()))); + float step = inflate_factor_1st_layer / nsteps; + for (int i = 0; i < nsteps; ++ i) + raft = diff(expand(raft, step), trimming); + } else + raft = diff(raft, trimming); + if (! interface_polygons.empty()) + columns_base->polygons = diff(columns_base->polygons, interface_polygons); + } + if (! brim.empty()) { + if (columns_base) + columns_base->polygons = diff(columns_base->polygons, brim); + if (contacts) + contacts->polygons = diff(contacts->polygons, brim); + if (interfaces) + interfaces->polygons = diff(interfaces->polygons, brim); + if (base_interfaces) + base_interfaces->polygons = diff(base_interfaces->polygons, brim); + } + } + + return raft_layers; +} + +static inline void fill_expolygon_generate_paths( + ExtrusionEntitiesPtr &dst, + ExPolygon &&expolygon, + Fill *filler, + const FillParams &fill_params, + float density, + ExtrusionRole role, + const Flow &flow) +{ + Surface surface(stInternal, std::move(expolygon)); + Polylines polylines; + try { + assert(!fill_params.use_arachne); + polylines = filler->fill_surface(&surface, fill_params); + } catch (InfillFailedException &) { + } + extrusion_entities_append_paths( + dst, + std::move(polylines), + role, + flow.mm3_per_mm(), flow.width(), flow.height()); +} + +static inline void fill_expolygons_generate_paths( + ExtrusionEntitiesPtr &dst, + ExPolygons &&expolygons, + Fill *filler, + const FillParams &fill_params, + float density, + ExtrusionRole role, + const Flow &flow) +{ + for (ExPolygon &expoly : expolygons) + fill_expolygon_generate_paths(dst, std::move(expoly), filler, fill_params, density, role, flow); +} + +static inline void fill_expolygons_generate_paths( + ExtrusionEntitiesPtr &dst, + ExPolygons &&expolygons, + Fill *filler, + float density, + ExtrusionRole role, + const Flow &flow) +{ + FillParams fill_params; + fill_params.density = density; + fill_params.dont_adjust = true; + fill_expolygons_generate_paths(dst, std::move(expolygons), filler, fill_params, density, role, flow); +} + +static Polylines draw_perimeters(const ExPolygon &expoly, double clip_length) +{ + // Draw the perimeters. + Polylines polylines; + polylines.reserve(expoly.holes.size() + 1); + for (size_t i = 0; i <= expoly.holes.size(); ++ i) { + Polyline pl(i == 0 ? expoly.contour.points : expoly.holes[i - 1].points); + pl.points.emplace_back(pl.points.front()); + if (i > 0) + // It is a hole, reverse it. + pl.reverse(); + // so that all contours are CCW oriented. + pl.clip_end(clip_length); + polylines.emplace_back(std::move(pl)); + } + return polylines; +} + +static inline void tree_supports_generate_paths( + ExtrusionEntitiesPtr &dst, + const Polygons &polygons, + const Flow &flow, + const SupportParameters &support_params) +{ + // Offset expolygon inside, returns number of expolygons collected (0 or 1). + // Vertices of output paths are marked with Z = source contour index of the expoly. + // Vertices at the intersection of source contours are marked with Z = -1. + auto shrink_expolygon_with_contour_idx = [](const Slic3r::ExPolygon &expoly, const float delta, ClipperLib::JoinType joinType, double miterLimit, ClipperLib_Z::Paths &out) -> int + { + assert(delta > 0); + auto append_paths_with_z = [](ClipperLib::Paths &src, coord_t contour_idx, ClipperLib_Z::Paths &dst) { + dst.reserve(next_highest_power_of_2(dst.size() + src.size())); + for (const ClipperLib::Path &contour : src) { + ClipperLib_Z::Path tmp; + tmp.reserve(contour.size()); + for (const Point &p : contour) + tmp.emplace_back(p.x(), p.y(), contour_idx); + dst.emplace_back(std::move(tmp)); + } + }; + + // 1) Offset the outer contour. + ClipperLib_Z::Paths contours; + { + ClipperLib::ClipperOffset co; + if (joinType == jtRound) + co.ArcTolerance = miterLimit; + else + co.MiterLimit = miterLimit; + co.ShortestEdgeLength = double(delta * 0.005); + co.AddPath(expoly.contour.points, joinType, ClipperLib::etClosedPolygon); + ClipperLib::Paths contours_raw; + co.Execute(contours_raw, - delta); + if (contours_raw.empty()) + // No need to try to offset the holes. + return 0; + append_paths_with_z(contours_raw, 0, contours); + } + + if (expoly.holes.empty()) { + // No need to subtract holes from the offsetted expolygon, we are done. + append(out, std::move(contours)); + } else { + // 2) Offset the holes one by one, collect the offsetted holes. + ClipperLib_Z::Paths holes; + { + for (const Polygon &hole : expoly.holes) { + ClipperLib::ClipperOffset co; + if (joinType == jtRound) + co.ArcTolerance = miterLimit; + else + co.MiterLimit = miterLimit; + co.ShortestEdgeLength = double(delta * 0.005); + co.AddPath(hole.points, joinType, ClipperLib::etClosedPolygon); + ClipperLib::Paths out2; + // Execute reorients the contours so that the outer most contour has a positive area. Thus the output + // contours will be CCW oriented even though the input paths are CW oriented. + // Offset is applied after contour reorientation, thus the signum of the offset value is reversed. + co.Execute(out2, delta); + append_paths_with_z(out2, 1 + (&hole - expoly.holes.data()), holes); + } + } + + // 3) Subtract holes from the contours. + if (holes.empty()) { + // No hole remaining after an offset. Just copy the outer contour. + append(out, std::move(contours)); + } else { + // Negative offset. There is a chance, that the offsetted hole intersects the outer contour. + // Subtract the offsetted holes from the offsetted contours. + ClipperLib_Z::Clipper clipper; + clipper.ZFillFunction([](const ClipperLib_Z::IntPoint &e1bot, const ClipperLib_Z::IntPoint &e1top, const ClipperLib_Z::IntPoint &e2bot, const ClipperLib_Z::IntPoint &e2top, ClipperLib_Z::IntPoint &pt) { + //pt.z() = std::max(std::max(e1bot.z(), e1top.z()), std::max(e2bot.z(), e2top.z())); + // Just mark the intersection. + pt.z() = -1; + }); + clipper.AddPaths(contours, ClipperLib_Z::ptSubject, true); + clipper.AddPaths(holes, ClipperLib_Z::ptClip, true); + ClipperLib_Z::Paths output; + clipper.Execute(ClipperLib_Z::ctDifference, output, ClipperLib_Z::pftNonZero, ClipperLib_Z::pftNonZero); + if (! output.empty()) { + append(out, std::move(output)); + } else { + // The offsetted holes have eaten up the offsetted outer contour. + return 0; + } + } + } + + return 1; + }; + + const double spacing = flow.scaled_spacing(); + // Clip the sheath path to avoid the extruder to get exactly on the first point of the loop. + const double clip_length = spacing * 0.15; + const double anchor_length = spacing * 6.; + ClipperLib_Z::Paths anchor_candidates; + for (ExPolygon& expoly : closing_ex(polygons, float(SCALED_EPSILON), float(SCALED_EPSILON + 0.5 * flow.scaled_width()))) { + std::unique_ptr eec; + if (support_params.tree_branch_diameter_double_wall_area_scaled > 0) + if (double area = expoly.area(); area > support_params.tree_branch_diameter_double_wall_area_scaled) { + eec = std::make_unique(); + // Don't reoder internal / external loops of the same island, always start with the internal loop. + eec->no_sort = true; + // Make the tree branch stable by adding another perimeter. + ExPolygons level2 = offset2_ex({ expoly }, -1.5 * flow.scaled_width(), 0.5 * flow.scaled_width()); + if (level2.size() == 1) { + Polylines polylines; + extrusion_entities_append_paths(eec->entities, draw_perimeters(expoly, clip_length), ExtrusionRole::erSupportMaterial, flow.mm3_per_mm(), flow.width(), flow.height(), + // Disable reversal of the path, always start with the anchor, always print CCW. + false); + expoly = level2.front(); + } + } + + // Try to produce one more perimeter to place the seam anchor. + // First genrate a 2nd perimeter loop as a source for anchor candidates. + // The anchor candidate points are annotated with an index of the source contour or with -1 if on intersection. + anchor_candidates.clear(); + shrink_expolygon_with_contour_idx(expoly, flow.scaled_width(), DefaultJoinType, 1.2, anchor_candidates); + // Orient all contours CW. + for (auto &path : anchor_candidates) + if (ClipperLib_Z::Area(path) > 0) + std::reverse(path.begin(), path.end()); + + // Draw the perimeters. + Polylines polylines; + polylines.reserve(expoly.holes.size() + 1); + for (int idx_loop = 0; idx_loop < int(expoly.num_contours()); ++ idx_loop) { + // Open the loop with a seam. + const Polygon &loop = expoly.contour_or_hole(idx_loop); + Polyline pl(loop.points); + // Orient all contours CW, because the anchor will be added to the end of polyline while we want to start a loop with the anchor. + if (idx_loop == 0) + // It is an outer contour. + pl.reverse(); + pl.points.emplace_back(pl.points.front()); + pl.clip_end(clip_length); + if (pl.size() < 2) + continue; + // Find the foot of the seam point on anchor_candidates. Only pick an anchor point that was created by offsetting the source contour. + ClipperLib_Z::Path *closest_contour = nullptr; + Vec2d closest_point; + int closest_point_idx = -1; + double closest_point_t = 0.; + double d2min = std::numeric_limits::max(); + Vec2d seam_pt = pl.back().cast(); + for (ClipperLib_Z::Path &path : anchor_candidates) + for (int i = 0; i < int(path.size()); ++ i) { + int j = next_idx_modulo(i, path); + if (path[i].z() == idx_loop || path[j].z() == idx_loop) { + Vec2d pi(path[i].x(), path[i].y()); + Vec2d pj(path[j].x(), path[j].y()); + Vec2d v = pj - pi; + Vec2d w = seam_pt - pi; + auto l2 = v.squaredNorm(); + auto t = std::clamp((l2 == 0) ? 0 : v.dot(w) / l2, 0., 1.); + if ((path[i].z() == idx_loop || t > EPSILON) && (path[j].z() == idx_loop || t < 1. - EPSILON)) { + // Closest point. + Vec2d fp = pi + v * t; + double d2 = (fp - seam_pt).squaredNorm(); + if (d2 < d2min) { + d2min = d2; + closest_contour = &path; + closest_point = fp; + closest_point_idx = i; + closest_point_t = t; + } + } + } + } + if (d2min < sqr(flow.scaled_width() * 3.)) { + // Try to cut an anchor from the closest_contour. + // Both closest_contour and pl are CW oriented. + pl.points.emplace_back(closest_point.cast()); + const ClipperLib_Z::Path &path = *closest_contour; + double remaining_length = anchor_length - (seam_pt - closest_point).norm(); + int i = closest_point_idx; + int j = next_idx_modulo(i, *closest_contour); + Vec2d pi(path[i].x(), path[i].y()); + Vec2d pj(path[j].x(), path[j].y()); + Vec2d v = pj - pi; + double l = v.norm(); + if (remaining_length < (1. - closest_point_t) * l) { + // Just trim the current line. + pl.points.emplace_back((closest_point + v * (remaining_length / l)).cast()); + } else { + // Take the rest of the current line, continue with the other lines. + pl.points.emplace_back(path[j].x(), path[j].y()); + pi = pj; + for (i = j; path[i].z() == idx_loop && remaining_length > 0; i = j, pi = pj) { + j = next_idx_modulo(i, path); + pj = Vec2d(path[j].x(), path[j].y()); + v = pj - pi; + l = v.norm(); + if (i == closest_point_idx) { + // Back at the first segment. Most likely this should not happen and we may end the anchor. + break; + } + if (remaining_length <= l) { + pl.points.emplace_back((pi + v * (remaining_length / l)).cast()); + break; + } + pl.points.emplace_back(path[j].x(), path[j].y()); + remaining_length -= l; + } + } + } + // Start with the anchor. + pl.reverse(); + polylines.emplace_back(std::move(pl)); + } + + ExtrusionEntitiesPtr &out = eec ? eec->entities : dst; + extrusion_entities_append_paths(out, std::move(polylines), ExtrusionRole::erSupportMaterial, flow.mm3_per_mm(), flow.width(), flow.height(), + // Disable reversal of the path, always start with the anchor, always print CCW. + false); + if (eec) { + std::reverse(eec->entities.begin(), eec->entities.end()); + dst.emplace_back(eec.release()); + } + } +} + +static inline void fill_expolygons_with_sheath_generate_paths( + ExtrusionEntitiesPtr &dst, + const Polygons &polygons, + Fill *filler, + float density, + ExtrusionRole role, + const Flow &flow, + bool with_sheath, + bool no_sort) +{ + if (polygons.empty()) + return; + + if (! with_sheath) { + fill_expolygons_generate_paths(dst, closing_ex(polygons, float(SCALED_EPSILON)), filler, density, role, flow); + return; + } + + FillParams fill_params; + fill_params.density = density; + fill_params.dont_adjust = true; + + const double spacing = flow.scaled_spacing(); + // Clip the sheath path to avoid the extruder to get exactly on the first point of the loop. + const double clip_length = spacing * 0.15; + + for (ExPolygon &expoly : closing_ex(polygons, float(SCALED_EPSILON), float(SCALED_EPSILON + 0.5*flow.scaled_width()))) { + // Don't reorder the skirt and its infills. + std::unique_ptr eec; + if (no_sort) { + eec = std::make_unique(); + eec->no_sort = true; + } + ExtrusionEntitiesPtr &out = no_sort ? eec->entities : dst; + extrusion_entities_append_paths(out, draw_perimeters(expoly, clip_length), ExtrusionRole::erSupportMaterial, flow.mm3_per_mm(), flow.width(), flow.height()); + // Fill in the rest. + fill_expolygons_generate_paths(out, offset_ex(expoly, float(-0.4 * spacing)), filler, fill_params, density, role, flow); + if (no_sort && ! eec->empty()) + dst.emplace_back(eec.release()); + } +} + +// Support layers, partially processed. +struct SupportGeneratorLayerExtruded +{ + SupportGeneratorLayerExtruded& operator=(SupportGeneratorLayerExtruded &&rhs) { + this->layer = rhs.layer; + this->extrusions = std::move(rhs.extrusions); + m_polygons_to_extrude = std::move(rhs.m_polygons_to_extrude); + rhs.layer = nullptr; + return *this; + } + + bool empty() const { + return layer == nullptr || layer->polygons.empty(); + } + + void set_polygons_to_extrude(Polygons &&polygons) { + if (m_polygons_to_extrude == nullptr) + m_polygons_to_extrude = std::make_unique(std::move(polygons)); + else + *m_polygons_to_extrude = std::move(polygons); + } + Polygons& polygons_to_extrude() { return (m_polygons_to_extrude == nullptr) ? layer->polygons : *m_polygons_to_extrude; } + const Polygons& polygons_to_extrude() const { return (m_polygons_to_extrude == nullptr) ? layer->polygons : *m_polygons_to_extrude; } + + bool could_merge(const SupportGeneratorLayerExtruded &other) const { + return ! this->empty() && ! other.empty() && + std::abs(this->layer->height - other.layer->height) < EPSILON && + this->layer->bridging == other.layer->bridging; + } + + // Merge regions, perform boolean union over the merged polygons. + void merge(SupportGeneratorLayerExtruded &&other) { + assert(this->could_merge(other)); + // 1) Merge the rest polygons to extrude, if there are any. + if (other.m_polygons_to_extrude != nullptr) { + if (m_polygons_to_extrude == nullptr) { + // This layer has no extrusions generated yet, if it has no m_polygons_to_extrude (its area to extrude was not reduced yet). + assert(this->extrusions.empty()); + m_polygons_to_extrude = std::make_unique(this->layer->polygons); + } + Slic3r::polygons_append(*m_polygons_to_extrude, std::move(*other.m_polygons_to_extrude)); + *m_polygons_to_extrude = union_safety_offset(*m_polygons_to_extrude); + other.m_polygons_to_extrude.reset(); + } else if (m_polygons_to_extrude != nullptr) { + assert(other.m_polygons_to_extrude == nullptr); + // The other layer has no extrusions generated yet, if it has no m_polygons_to_extrude (its area to extrude was not reduced yet). + assert(other.extrusions.empty()); + Slic3r::polygons_append(*m_polygons_to_extrude, other.layer->polygons); + *m_polygons_to_extrude = union_safety_offset(*m_polygons_to_extrude); + } + // 2) Merge the extrusions. + this->extrusions.insert(this->extrusions.end(), other.extrusions.begin(), other.extrusions.end()); + other.extrusions.clear(); + // 3) Merge the infill polygons. + Slic3r::polygons_append(this->layer->polygons, std::move(other.layer->polygons)); + this->layer->polygons = union_safety_offset(this->layer->polygons); + other.layer->polygons.clear(); + } + + void polygons_append(Polygons &dst) const { + if (layer != NULL && ! layer->polygons.empty()) + Slic3r::polygons_append(dst, layer->polygons); + } + + // The source layer. It carries the height and extrusion type (bridging / non bridging, extrusion height). + SupportGeneratorLayer *layer { nullptr }; + // Collect extrusions. They will be exported sorted by the bottom height. + ExtrusionEntitiesPtr extrusions; + +private: + // In case the extrusions are non-empty, m_polygons_to_extrude may contain the rest areas yet to be filled by additional support. + // This is useful mainly for the loop interfaces, which are generated before the zig-zag infills. + std::unique_ptr m_polygons_to_extrude; +}; + +typedef std::vector SupportGeneratorLayerExtrudedPtrs; + +struct LoopInterfaceProcessor +{ + LoopInterfaceProcessor(coordf_t circle_r) : + n_contact_loops(0), + circle_radius(circle_r), + circle_distance(circle_r * 3.) + { + // Shape of the top contact area. + circle.points.reserve(6); + for (size_t i = 0; i < 6; ++ i) { + double angle = double(i) * M_PI / 3.; + circle.points.push_back(Point(circle_radius * cos(angle), circle_radius * sin(angle))); + } + } + + // Generate loop contacts at the top_contact_layer, + // trim the top_contact_layer->polygons with the areas covered by the loops. + void generate(SupportGeneratorLayerExtruded &top_contact_layer, const Flow &interface_flow_src) const; + + int n_contact_loops; + coordf_t circle_radius; + coordf_t circle_distance; + Polygon circle; +}; + +void LoopInterfaceProcessor::generate(SupportGeneratorLayerExtruded &top_contact_layer, const Flow &interface_flow_src) const +{ + if (n_contact_loops == 0 || top_contact_layer.empty()) + return; + + Flow flow = interface_flow_src.with_height(top_contact_layer.layer->height); + + Polygons overhang_polygons; + if (top_contact_layer.layer->overhang_polygons != nullptr) + overhang_polygons = std::move(*top_contact_layer.layer->overhang_polygons); + + // Generate the outermost loop. + // Find centerline of the external loop (or any other kind of extrusions should the loop be skipped) + ExPolygons top_contact_expolygons = offset_ex(union_ex(top_contact_layer.layer->polygons), - 0.5f * flow.scaled_width()); + + // Grid size and bit shifts for quick and exact to/from grid coordinates manipulation. + coord_t circle_grid_resolution = 1; + coord_t circle_grid_powerof2 = 0; + { + // epsilon to account for rounding errors + coord_t circle_grid_resolution_non_powerof2 = coord_t(2. * circle_distance + 3.); + while (circle_grid_resolution < circle_grid_resolution_non_powerof2) { + circle_grid_resolution <<= 1; + ++ circle_grid_powerof2; + } + } + + struct PointAccessor { + const Point* operator()(const Point &pt) const { return &pt; } + }; + typedef ClosestPointInRadiusLookup ClosestPointLookupType; + + Polygons loops0; + { + // find centerline of the external loop of the contours + // Only consider the loops facing the overhang. + Polygons external_loops; + // Holes in the external loops. + Polygons circles; + Polygons overhang_with_margin = offset(union_ex(overhang_polygons), 0.5f * flow.scaled_width()); + for (ExPolygons::iterator it_contact_expoly = top_contact_expolygons.begin(); it_contact_expoly != top_contact_expolygons.end(); ++ it_contact_expoly) { + // Store the circle centers placed for an expolygon into a regular grid, hashed by the circle centers. + ClosestPointLookupType circle_centers_lookup(coord_t(circle_distance - SCALED_EPSILON)); + Points circle_centers; + Point center_last; + // For each contour of the expolygon, start with the outer contour, continue with the holes. + for (size_t i_contour = 0; i_contour <= it_contact_expoly->holes.size(); ++ i_contour) { + Polygon &contour = (i_contour == 0) ? it_contact_expoly->contour : it_contact_expoly->holes[i_contour - 1]; + const Point *seg_current_pt = nullptr; + coordf_t seg_current_t = 0.; + if (! intersection_pl(contour.split_at_first_point(), overhang_with_margin).empty()) { + // The contour is below the overhang at least to some extent. + //FIXME ideally one would place the circles below the overhang only. + // Walk around the contour and place circles so their centers are not closer than circle_distance from each other. + if (circle_centers.empty()) { + // Place the first circle. + seg_current_pt = &contour.points.front(); + seg_current_t = 0.; + center_last = *seg_current_pt; + circle_centers_lookup.insert(center_last); + circle_centers.push_back(center_last); + } + for (Points::const_iterator it = contour.points.begin() + 1; it != contour.points.end(); ++it) { + // Is it possible to place a circle on this segment? Is it not too close to any of the circles already placed on this contour? + const Point &p1 = *(it-1); + const Point &p2 = *it; + // Intersection of a ray (p1, p2) with a circle placed at center_last, with radius of circle_distance. + const Vec2d v_seg(coordf_t(p2(0)) - coordf_t(p1(0)), coordf_t(p2(1)) - coordf_t(p1(1))); + const Vec2d v_cntr(coordf_t(p1(0) - center_last(0)), coordf_t(p1(1) - center_last(1))); + coordf_t a = v_seg.squaredNorm(); + coordf_t b = 2. * v_seg.dot(v_cntr); + coordf_t c = v_cntr.squaredNorm() - circle_distance * circle_distance; + coordf_t disc = b * b - 4. * a * c; + if (disc > 0.) { + // The circle intersects a ray. Avoid the parts of the segment inside the circle. + coordf_t t1 = (-b - sqrt(disc)) / (2. * a); + coordf_t t2 = (-b + sqrt(disc)) / (2. * a); + coordf_t t0 = (seg_current_pt == &p1) ? seg_current_t : 0.; + // Take the lowest t in , excluding . + coordf_t t; + if (t0 <= t1) + t = t0; + else if (t2 <= 1.) + t = t2; + else { + // Try the following segment. + seg_current_pt = nullptr; + continue; + } + seg_current_pt = &p1; + seg_current_t = t; + center_last = Point(p1(0) + coord_t(v_seg(0) * t), p1(1) + coord_t(v_seg(1) * t)); + // It has been verified that the new point is far enough from center_last. + // Ensure, that it is far enough from all the centers. + std::pair circle_closest = circle_centers_lookup.find(center_last); + if (circle_closest.first != nullptr) { + -- it; + continue; + } + } else { + // All of the segment is outside the circle. Take the first point. + seg_current_pt = &p1; + seg_current_t = 0.; + center_last = p1; + } + // Place the first circle. + circle_centers_lookup.insert(center_last); + circle_centers.push_back(center_last); + } + external_loops.push_back(std::move(contour)); + for (const Point ¢er : circle_centers) { + circles.push_back(circle); + circles.back().translate(center); + } + } + } + } + // Apply a pattern to the external loops. + loops0 = diff(external_loops, circles); + } + + Polylines loop_lines; + { + // make more loops + Polygons loop_polygons = loops0; + for (int i = 1; i < n_contact_loops; ++ i) + polygons_append(loop_polygons, + opening( + loops0, + i * flow.scaled_spacing() + 0.5f * flow.scaled_spacing(), + 0.5f * flow.scaled_spacing())); + // Clip such loops to the side oriented towards the object. + // Collect split points, so they will be recognized after the clipping. + // At the split points the clipped pieces will be stitched back together. + loop_lines.reserve(loop_polygons.size()); + std::unordered_map map_split_points; + for (Polygons::const_iterator it = loop_polygons.begin(); it != loop_polygons.end(); ++ it) { + assert(map_split_points.find(it->first_point()) == map_split_points.end()); + map_split_points[it->first_point()] = -1; + loop_lines.push_back(it->split_at_first_point()); + } + loop_lines = intersection_pl(loop_lines, expand(overhang_polygons, scale_(SUPPORT_MATERIAL_MARGIN))); + // Because a closed loop has been split to a line, loop_lines may contain continuous segments split to 2 pieces. + // Try to connect them. + for (int i_line = 0; i_line < int(loop_lines.size()); ++ i_line) { + Polyline &polyline = loop_lines[i_line]; + auto it = map_split_points.find(polyline.first_point()); + if (it != map_split_points.end()) { + // This is a stitching point. + // If this assert triggers, multiple source polygons likely intersected at this point. + assert(it->second != -2); + if (it->second < 0) { + // First occurence. + it->second = i_line; + } else { + // Second occurence. Join the lines. + Polyline &polyline_1st = loop_lines[it->second]; + assert(polyline_1st.first_point() == it->first || polyline_1st.last_point() == it->first); + if (polyline_1st.first_point() == it->first) + polyline_1st.reverse(); + polyline_1st.append(std::move(polyline)); + it->second = -2; + } + continue; + } + it = map_split_points.find(polyline.last_point()); + if (it != map_split_points.end()) { + // This is a stitching point. + // If this assert triggers, multiple source polygons likely intersected at this point. + assert(it->second != -2); + if (it->second < 0) { + // First occurence. + it->second = i_line; + } else { + // Second occurence. Join the lines. + Polyline &polyline_1st = loop_lines[it->second]; + assert(polyline_1st.first_point() == it->first || polyline_1st.last_point() == it->first); + if (polyline_1st.first_point() == it->first) + polyline_1st.reverse(); + polyline.reverse(); + polyline_1st.append(std::move(polyline)); + it->second = -2; + } + } + } + // Remove empty lines. + remove_degenerate(loop_lines); + } + + // add the contact infill area to the interface area + // note that growing loops by $circle_radius ensures no tiny + // extrusions are left inside the circles; however it creates + // a very large gap between loops and contact_infill_polygons, so maybe another + // solution should be found to achieve both goals + // Store the trimmed polygons into a separate polygon set, so the original infill area remains intact for + // "modulate by layer thickness". + top_contact_layer.set_polygons_to_extrude(diff(top_contact_layer.layer->polygons, offset(loop_lines, float(circle_radius * 1.1)))); + + // Transform loops into ExtrusionPath objects. + extrusion_entities_append_paths( + top_contact_layer.extrusions, + std::move(loop_lines), + ExtrusionRole::erSupportMaterialInterface, flow.mm3_per_mm(), flow.width(), flow.height()); +} + +#ifdef SLIC3R_DEBUG +static std::string dbg_index_to_color(int idx) +{ + if (idx < 0) + return "yellow"; + idx = idx % 3; + switch (idx) { + case 0: return "red"; + case 1: return "green"; + default: return "blue"; + } +} +#endif /* SLIC3R_DEBUG */ + +// When extruding a bottom interface layer over an object, the bottom interface layer is extruded in a thin air, therefore +// it is being extruded with a bridging flow to not shrink excessively (the die swell effect). +// Tiny extrusions are better avoided and it is always better to anchor the thread to an existing support structure if possible. +// Therefore the bottom interface spots are expanded a bit. The expanded regions may overlap with another bottom interface layers, +// leading to over extrusion, where they overlap. The over extrusion is better avoided as it often makes the interface layers +// to stick too firmly to the object. +// +// Modulate thickness (increase bottom_z) of extrusions_in_out generated for this_layer +// if they overlap with overlapping_layers, whose print_z is above this_layer.bottom_z() and below this_layer.print_z. +static void modulate_extrusion_by_overlapping_layers( + // Extrusions generated for this_layer. + ExtrusionEntitiesPtr &extrusions_in_out, + const SupportGeneratorLayer &this_layer, + // Multiple layers overlapping with this_layer, sorted bottom up. + const SupportGeneratorLayersPtr &overlapping_layers) +{ + size_t n_overlapping_layers = overlapping_layers.size(); + if (n_overlapping_layers == 0 || extrusions_in_out.empty()) + // The extrusions do not overlap with any other extrusion. + return; + + // Get the initial extrusion parameters. + ExtrusionPath *extrusion_path_template = dynamic_cast(extrusions_in_out.front()); + assert(extrusion_path_template != nullptr); + ExtrusionRole extrusion_role = extrusion_path_template->role(); + float extrusion_width = extrusion_path_template->width; + + struct ExtrusionPathFragment + { + ExtrusionPathFragment() : mm3_per_mm(-1), width(-1), height(-1) {}; + ExtrusionPathFragment(double mm3_per_mm, float width, float height) : mm3_per_mm(mm3_per_mm), width(width), height(height) {}; + + Polylines polylines; + double mm3_per_mm; + float width; + float height; + }; + + // Split the extrusions by the overlapping layers, reduce their extrusion rate. + // The last path_fragment is from this_layer. + std::vector path_fragments( + n_overlapping_layers + 1, + ExtrusionPathFragment(extrusion_path_template->mm3_per_mm, extrusion_path_template->width, extrusion_path_template->height)); + // Don't use it, it will be released. + extrusion_path_template = nullptr; + +#ifdef SLIC3R_DEBUG + static int iRun = 0; + ++ iRun; + BoundingBox bbox; + for (size_t i_overlapping_layer = 0; i_overlapping_layer < n_overlapping_layers; ++ i_overlapping_layer) { + const SupportGeneratorLayer &overlapping_layer = *overlapping_layers[i_overlapping_layer]; + bbox.merge(get_extents(overlapping_layer.polygons)); + } + for (ExtrusionEntitiesPtr::const_iterator it = extrusions_in_out.begin(); it != extrusions_in_out.end(); ++ it) { + ExtrusionPath *path = dynamic_cast(*it); + assert(path != nullptr); + bbox.merge(get_extents(path->polyline)); + } + SVG svg(debug_out_path("support-fragments-%d-%lf.svg", iRun, this_layer.print_z).c_str(), bbox); + const float transparency = 0.5f; + // Filled polygons for the overlapping regions. + svg.draw(union_ex(this_layer.polygons), dbg_index_to_color(-1), transparency); + for (size_t i_overlapping_layer = 0; i_overlapping_layer < n_overlapping_layers; ++ i_overlapping_layer) { + const SupportGeneratorLayer &overlapping_layer = *overlapping_layers[i_overlapping_layer]; + svg.draw(union_ex(overlapping_layer.polygons), dbg_index_to_color(int(i_overlapping_layer)), transparency); + } + // Contours of the overlapping regions. + svg.draw(to_polylines(this_layer.polygons), dbg_index_to_color(-1), scale_(0.2)); + for (size_t i_overlapping_layer = 0; i_overlapping_layer < n_overlapping_layers; ++ i_overlapping_layer) { + const SupportGeneratorLayer &overlapping_layer = *overlapping_layers[i_overlapping_layer]; + svg.draw(to_polylines(overlapping_layer.polygons), dbg_index_to_color(int(i_overlapping_layer)), scale_(0.1)); + } + // Fill extrusion, the source. + for (ExtrusionEntitiesPtr::const_iterator it = extrusions_in_out.begin(); it != extrusions_in_out.end(); ++ it) { + ExtrusionPath *path = dynamic_cast(*it); + std::string color_name; + switch ((it - extrusions_in_out.begin()) % 9) { + case 0: color_name = "magenta"; break; + case 1: color_name = "deepskyblue"; break; + case 2: color_name = "coral"; break; + case 3: color_name = "goldenrod"; break; + case 4: color_name = "orange"; break; + case 5: color_name = "olivedrab"; break; + case 6: color_name = "blueviolet"; break; + case 7: color_name = "brown"; break; + default: color_name = "orchid"; break; + } + svg.draw(path->polyline, color_name, scale_(0.2)); + } +#endif /* SLIC3R_DEBUG */ + + // End points of the original paths. + std::vector> path_ends; + // Collect the paths of this_layer. + { + Polylines &polylines = path_fragments.back().polylines; + for (ExtrusionEntity *ee : extrusions_in_out) { + ExtrusionPath *path = dynamic_cast(ee); + assert(path != nullptr); + polylines.emplace_back(Polyline(std::move(path->polyline))); + path_ends.emplace_back(std::pair(polylines.back().points.front(), polylines.back().points.back())); + delete path; + } + } + // Destroy the original extrusion paths, their polylines were moved to path_fragments already. + // This will be the destination for the new paths. + extrusions_in_out.clear(); + + // Fragment the path segments by overlapping layers. The overlapping layers are sorted by an increasing print_z. + // Trim by the highest overlapping layer first. + for (int i_overlapping_layer = int(n_overlapping_layers) - 1; i_overlapping_layer >= 0; -- i_overlapping_layer) { + const SupportGeneratorLayer &overlapping_layer = *overlapping_layers[i_overlapping_layer]; + ExtrusionPathFragment &frag = path_fragments[i_overlapping_layer]; + Polygons polygons_trimming = offset(union_ex(overlapping_layer.polygons), float(scale_(0.5*extrusion_width))); + frag.polylines = intersection_pl(path_fragments.back().polylines, polygons_trimming); + path_fragments.back().polylines = diff_pl(path_fragments.back().polylines, polygons_trimming); + // Adjust the extrusion parameters for a reduced layer height and a non-bridging flow (nozzle_dmr = -1, does not matter). + assert(this_layer.print_z > overlapping_layer.print_z); + frag.height = float(this_layer.print_z - overlapping_layer.print_z); + frag.mm3_per_mm = Flow(frag.width, frag.height, -1.f).mm3_per_mm(); +#ifdef SLIC3R_DEBUG + svg.draw(frag.polylines, dbg_index_to_color(i_overlapping_layer), scale_(0.1)); +#endif /* SLIC3R_DEBUG */ + } + +#ifdef SLIC3R_DEBUG + svg.draw(path_fragments.back().polylines, dbg_index_to_color(-1), scale_(0.1)); + svg.Close(); +#endif /* SLIC3R_DEBUG */ + + // Now chain the split segments using hashing and a nearly exact match, maintaining the order of segments. + // Create a single ExtrusionPath or ExtrusionEntityCollection per source ExtrusionPath. + // Map of fragment start/end points to a pair of + // Because a non-exact matching is used for the end points, a multi-map is used. + // As the clipper library may reverse the order of some clipped paths, store both ends into the map. + struct ExtrusionPathFragmentEnd + { + ExtrusionPathFragmentEnd(size_t alayer_idx, size_t apolyline_idx, bool ais_start) : + layer_idx(alayer_idx), polyline_idx(apolyline_idx), is_start(ais_start) {} + size_t layer_idx; + size_t polyline_idx; + bool is_start; + }; + class ExtrusionPathFragmentEndPointAccessor { + public: + ExtrusionPathFragmentEndPointAccessor(const std::vector &path_fragments) : m_path_fragments(path_fragments) {} + // Return an end point of a fragment, or nullptr if the fragment has been consumed already. + const Point* operator()(const ExtrusionPathFragmentEnd &fragment_end) const { + const Polyline &polyline = m_path_fragments[fragment_end.layer_idx].polylines[fragment_end.polyline_idx]; + return polyline.points.empty() ? nullptr : + (fragment_end.is_start ? &polyline.points.front() : &polyline.points.back()); + } + private: + ExtrusionPathFragmentEndPointAccessor& operator=(const ExtrusionPathFragmentEndPointAccessor&) { + return *this; + } + + const std::vector &m_path_fragments; + }; + const coord_t search_radius = 7; + ClosestPointInRadiusLookup map_fragment_starts( + search_radius, ExtrusionPathFragmentEndPointAccessor(path_fragments)); + for (size_t i_overlapping_layer = 0; i_overlapping_layer <= n_overlapping_layers; ++ i_overlapping_layer) { + const Polylines &polylines = path_fragments[i_overlapping_layer].polylines; + for (size_t i_polyline = 0; i_polyline < polylines.size(); ++ i_polyline) { + // Map a starting point of a polyline to a pair of + if (polylines[i_polyline].points.size() >= 2) { + map_fragment_starts.insert(ExtrusionPathFragmentEnd(i_overlapping_layer, i_polyline, true)); + map_fragment_starts.insert(ExtrusionPathFragmentEnd(i_overlapping_layer, i_polyline, false)); + } + } + } + + // For each source path: + for (size_t i_path = 0; i_path < path_ends.size(); ++ i_path) { + const Point &pt_start = path_ends[i_path].first; + const Point &pt_end = path_ends[i_path].second; + Point pt_current = pt_start; + // Find a chain of fragments with the original / reduced print height. + ExtrusionMultiPath multipath; + for (;;) { + // Find a closest end point to pt_current. + std::pair end_and_dist2 = map_fragment_starts.find(pt_current); + // There may be a bug in Clipper flipping the order of two last points in a fragment? + // assert(end_and_dist2.first != nullptr); + assert(end_and_dist2.first == nullptr || end_and_dist2.second < search_radius * search_radius); + if (end_and_dist2.first == nullptr) { + // New fragment connecting to pt_current was not found. + // Verify that the last point found is close to the original end point of the unfragmented path. + //const double d2 = (pt_end - pt_current).cast.squaredNorm(); + //assert(d2 < coordf_t(search_radius * search_radius)); + // End of the path. + break; + } + const ExtrusionPathFragmentEnd &fragment_end_min = *end_and_dist2.first; + // Fragment to consume. + ExtrusionPathFragment &frag = path_fragments[fragment_end_min.layer_idx]; + Polyline &frag_polyline = frag.polylines[fragment_end_min.polyline_idx]; + // Path to append the fragment to. + ExtrusionPath *path = multipath.paths.empty() ? nullptr : &multipath.paths.back(); + if (path != nullptr) { + // Verify whether the path is compatible with the current fragment. + assert(this_layer.layer_type == SupporLayerType::BottomContact || path->height != frag.height || path->mm3_per_mm != frag.mm3_per_mm); + if (path->height != frag.height || path->mm3_per_mm != frag.mm3_per_mm) { + path = nullptr; + } + // Merging with the previous path. This can only happen if the current layer was reduced by a base layer, which was split into a base and interface layer. + } + if (path == nullptr) { + // Allocate a new path. + multipath.paths.push_back(ExtrusionPath(extrusion_role, frag.mm3_per_mm, frag.width, frag.height)); + path = &multipath.paths.back(); + } + // The Clipper library may flip the order of the clipped polylines arbitrarily. + // Reverse the source polyline, if connecting to the end. + if (! fragment_end_min.is_start) + frag_polyline.reverse(); + // Enforce exact overlap of the end points of successive fragments. + assert(frag_polyline.points.front() == pt_current); + frag_polyline.points.front() = pt_current; + // Don't repeat the first point. + if (! path->polyline.points.empty()) + path->polyline.points.pop_back(); + // Consume the fragment's polyline, remove it from the input fragments, so it will be ignored the next time. + path->polyline.append(std::move(frag_polyline)); + frag_polyline.points.clear(); + pt_current = path->polyline.points.back(); + if (pt_current == pt_end) { + // End of the path. + break; + } + } + if (!multipath.paths.empty()) { + if (multipath.paths.size() == 1) { + // This path was not fragmented. + extrusions_in_out.push_back(new ExtrusionPath(std::move(multipath.paths.front()))); + } else { + // This path was fragmented. Copy the collection as a whole object, so the order inside the collection will not be changed + // during the chaining of extrusions_in_out. + extrusions_in_out.push_back(new ExtrusionMultiPath(std::move(multipath))); + } + } + } + // If there are any non-consumed fragments, add them separately. + //FIXME this shall not happen, if the Clipper works as expected and all paths split to fragments could be re-connected. + for (auto it_fragment = path_fragments.begin(); it_fragment != path_fragments.end(); ++ it_fragment) + extrusion_entities_append_paths(extrusions_in_out, std::move(it_fragment->polylines), extrusion_role, it_fragment->mm3_per_mm, it_fragment->width, it_fragment->height); +} + +// Support layer that is covered by some form of dense interface. +static constexpr const std::initializer_list support_types_interface{ + SupporLayerType::RaftInterface, SupporLayerType::BottomContact, SupporLayerType::BottomInterface, SupporLayerType::TopContact, SupporLayerType::TopInterface +}; + +SupportGeneratorLayersPtr generate_support_layers( + PrintObject &object, + const SupportGeneratorLayersPtr &raft_layers, + const SupportGeneratorLayersPtr &bottom_contacts, + const SupportGeneratorLayersPtr &top_contacts, + const SupportGeneratorLayersPtr &intermediate_layers, + const SupportGeneratorLayersPtr &interface_layers, + const SupportGeneratorLayersPtr &base_interface_layers) +{ + // Install support layers into the object. + // A support layer installed on a PrintObject has a unique print_z. + SupportGeneratorLayersPtr layers_sorted; + layers_sorted.reserve(raft_layers.size() + bottom_contacts.size() + top_contacts.size() + intermediate_layers.size() + interface_layers.size() + base_interface_layers.size()); + append(layers_sorted, raft_layers); + append(layers_sorted, bottom_contacts); + append(layers_sorted, top_contacts); + append(layers_sorted, intermediate_layers); + append(layers_sorted, interface_layers); + append(layers_sorted, base_interface_layers); + // Sort the layers lexicographically by a raising print_z and a decreasing height. + std::sort(layers_sorted.begin(), layers_sorted.end(), [](auto *l1, auto *l2) { return *l1 < *l2; }); + int layer_id = 0; + int layer_id_interface = 0; + assert(object.support_layers().empty()); + for (size_t i = 0; i < layers_sorted.size();) { + // Find the last layer with roughly the same print_z, find the minimum layer height of all. + // Due to the floating point inaccuracies, the print_z may not be the same even if in theory they should. + size_t j = i + 1; + coordf_t zmax = layers_sorted[i]->print_z + EPSILON; + for (; j < layers_sorted.size() && layers_sorted[j]->print_z <= zmax; ++j) ; + // Assign an average print_z to the set of layers with nearly equal print_z. + coordf_t zavg = 0.5 * (layers_sorted[i]->print_z + layers_sorted[j - 1]->print_z); + coordf_t height_min = layers_sorted[i]->height; + bool empty = true; + // For snug supports, layers where the direction of the support interface shall change are accounted for. + size_t num_interfaces = 0; + size_t num_top_contacts = 0; + double top_contact_bottom_z = 0; + for (size_t u = i; u < j; ++u) { + SupportGeneratorLayer &layer = *layers_sorted[u]; + if (! layer.polygons.empty()) { + empty = false; + num_interfaces += one_of(layer.layer_type, support_types_interface); + if (layer.layer_type == SupporLayerType::TopContact) { + ++ num_top_contacts; + assert(num_top_contacts <= 1); + // All top contact layers sharing this print_z shall also share bottom_z. + //assert(num_top_contacts == 1 || (top_contact_bottom_z - layer.bottom_z) < EPSILON); + top_contact_bottom_z = layer.bottom_z; + } + } + layer.print_z = zavg; + height_min = std::min(height_min, layer.height); + } + if (! empty) { + // Here the upper_layer and lower_layer pointers are left to null at the support layers, + // as they are never used. These pointers are candidates for removal. + bool this_layer_contacts_only = num_top_contacts > 0 && num_top_contacts == num_interfaces; + size_t this_layer_id_interface = layer_id_interface; + if (this_layer_contacts_only) { + // Find a supporting layer for its interface ID. + for (auto it = object.support_layers().rbegin(); it != object.support_layers().rend(); ++ it) + if (const SupportLayer &other_layer = **it; std::abs(other_layer.print_z - top_contact_bottom_z) < EPSILON) { + // other_layer supports this top contact layer. Assign a different support interface direction to this layer + // from the layer that supports it. + this_layer_id_interface = other_layer.interface_id() + 1; + } + } + object.add_support_layer(layer_id ++, this_layer_id_interface, height_min, zavg); + if (num_interfaces && ! this_layer_contacts_only) + ++ layer_id_interface; + } + i = j; + } + return layers_sorted; +} + +void generate_support_toolpaths( + SupportLayerPtrs &support_layers, + const PrintObjectConfig &config, + const SupportParameters &support_params, + const SlicingParameters &slicing_params, + const SupportGeneratorLayersPtr &raft_layers, + const SupportGeneratorLayersPtr &bottom_contacts, + const SupportGeneratorLayersPtr &top_contacts, + const SupportGeneratorLayersPtr &intermediate_layers, + const SupportGeneratorLayersPtr &interface_layers, + const SupportGeneratorLayersPtr &base_interface_layers) +{ + // loop_interface_processor with a given circle radius. + LoopInterfaceProcessor loop_interface_processor(1.5 * support_params.support_material_interface_flow.scaled_width()); + loop_interface_processor.n_contact_loops = config.support_interface_loop_pattern.value ? 1 : 0; + + std::vector angles { support_params.base_angle }; + if (config.support_base_pattern == smpRectilinearGrid) + angles.push_back(support_params.interface_angle); + + BoundingBox bbox_object(Point(-scale_(1.), -scale_(1.0)), Point(scale_(1.), scale_(1.))); + +// const coordf_t link_max_length_factor = 3.; + const coordf_t link_max_length_factor = 0.; + + // Insert the raft base layers. + auto n_raft_layers = std::min(support_layers.size(), std::max(0, int(slicing_params.raft_layers()) - 1)); + + tbb::parallel_for(tbb::blocked_range(0, n_raft_layers), + [&support_layers, &raft_layers, &intermediate_layers, &config, &support_params, &slicing_params, + &bbox_object, link_max_length_factor] + (const tbb::blocked_range& range) { + for (size_t support_layer_id = range.begin(); support_layer_id < range.end(); ++ support_layer_id) + { + assert(support_layer_id < raft_layers.size()); + SupportLayer &support_layer = *support_layers[support_layer_id]; + assert(support_layer.support_fills.entities.empty()); + SupportGeneratorLayer &raft_layer = *raft_layers[support_layer_id]; + + std::unique_ptr filler_interface = std::unique_ptr(Fill::new_from_type(support_params.raft_interface_fill_pattern)); + std::unique_ptr filler_support = std::unique_ptr(Fill::new_from_type(support_params.base_fill_pattern)); + filler_interface->set_bounding_box(bbox_object); + filler_support->set_bounding_box(bbox_object); + + // Print the tree supports cutting through the raft with the exception of the 1st layer, where a full support layer will be printed below + // both the raft and the trees. + // Trim the raft layers with the tree polygons. + const Polygons &tree_polygons = + support_layer_id > 0 && support_layer_id < intermediate_layers.size() && is_approx(intermediate_layers[support_layer_id]->print_z, support_layer.print_z) ? + intermediate_layers[support_layer_id]->polygons : Polygons(); + + // Print the support base below the support columns, or the support base for the support columns plus the contacts. + if (support_layer_id > 0) { + const Polygons &to_infill_polygons = (support_layer_id < slicing_params.base_raft_layers) ? + raft_layer.polygons : + //FIXME misusing contact_polygons for support columns. + ((raft_layer.contact_polygons == nullptr) ? Polygons() : *raft_layer.contact_polygons); + // Trees may cut through the raft layers down to a print bed. + Flow flow(float(support_params.support_material_flow.width()), float(raft_layer.height), support_params.support_material_flow.nozzle_diameter()); + assert(!raft_layer.bridging); + if (! to_infill_polygons.empty()) { + Fill *filler = filler_support.get(); + filler->angle = support_params.raft_angle_base; + filler->spacing = support_params.support_material_flow.spacing(); + filler->link_max_length = coord_t(scale_(filler->spacing * link_max_length_factor / support_params.support_density)); + fill_expolygons_with_sheath_generate_paths( + // Destination + support_layer.support_fills.entities, + // Regions to fill + tree_polygons.empty() ? to_infill_polygons : diff(to_infill_polygons, tree_polygons), + // Filler and its parameters + filler, float(support_params.support_density), + // Extrusion parameters + ExtrusionRole::erSupportMaterial, flow, + support_params.with_sheath, false); + } + if (! tree_polygons.empty()) + tree_supports_generate_paths(support_layer.support_fills.entities, tree_polygons, flow, support_params); + } + + Fill *filler = filler_interface.get(); + Flow flow = support_params.first_layer_flow; + float density = 0.f; + if (support_layer_id == 0) { + // Base flange. + filler->angle = support_params.raft_angle_1st_layer; + filler->spacing = support_params.first_layer_flow.spacing(); + density = float(config.raft_first_layer_density.value * 0.01); + } else if (support_layer_id >= slicing_params.base_raft_layers) { + filler->angle = support_params.raft_interface_angle(support_layer.interface_id()); + // We don't use $base_flow->spacing because we need a constant spacing + // value that guarantees that all layers are correctly aligned. + filler->spacing = support_params.support_material_flow.spacing(); + assert(! raft_layer.bridging); + flow = Flow(float(support_params.raft_interface_flow.width()), float(raft_layer.height), support_params.raft_interface_flow.nozzle_diameter()); + density = float(support_params.raft_interface_density); + } else + continue; + filler->link_max_length = coord_t(scale_(filler->spacing * link_max_length_factor / density)); + fill_expolygons_with_sheath_generate_paths( + // Destination + support_layer.support_fills.entities, + // Regions to fill + tree_polygons.empty() ? raft_layer.polygons : diff(raft_layer.polygons, tree_polygons), + // Filler and its parameters + filler, density, + // Extrusion parameters + (support_layer_id < slicing_params.base_raft_layers) ? ExtrusionRole::erSupportMaterial : ExtrusionRole::erSupportMaterialInterface, flow, + // sheath at first layer + support_layer_id == 0, support_layer_id == 0); + } + }); + + struct LayerCacheItem { + LayerCacheItem(SupportGeneratorLayerExtruded *layer_extruded = nullptr) : layer_extruded(layer_extruded) {} + SupportGeneratorLayerExtruded *layer_extruded; + std::vector overlapping; + }; + struct LayerCache { + SupportGeneratorLayerExtruded bottom_contact_layer; + SupportGeneratorLayerExtruded top_contact_layer; + SupportGeneratorLayerExtruded base_layer; + SupportGeneratorLayerExtruded interface_layer; + SupportGeneratorLayerExtruded base_interface_layer; + boost::container::static_vector nonempty; + + void add_nonempty_and_sort() { + for (SupportGeneratorLayerExtruded *item : { &bottom_contact_layer, &top_contact_layer, &interface_layer, &base_interface_layer, &base_layer }) + if (! item->empty()) + this->nonempty.emplace_back(item); + // Sort the layers with the same print_z coordinate by their heights, thickest first. + std::stable_sort(this->nonempty.begin(), this->nonempty.end(), [](const LayerCacheItem &lc1, const LayerCacheItem &lc2) { return lc1.layer_extruded->layer->height > lc2.layer_extruded->layer->height; }); + } + }; + std::vector layer_caches(support_layers.size()); + + tbb::parallel_for(tbb::blocked_range(n_raft_layers, support_layers.size()), + [&config, &slicing_params, &support_params, &support_layers, &bottom_contacts, &top_contacts, &intermediate_layers, &interface_layers, &base_interface_layers, &layer_caches, &loop_interface_processor, + &bbox_object, &angles, n_raft_layers, link_max_length_factor] + (const tbb::blocked_range& range) { + // Indices of the 1st layer in their respective container at the support layer height. + size_t idx_layer_bottom_contact = size_t(-1); + size_t idx_layer_top_contact = size_t(-1); + size_t idx_layer_intermediate = size_t(-1); + size_t idx_layer_interface = size_t(-1); + size_t idx_layer_base_interface = size_t(-1); + const auto fill_type_first_layer = ipRectilinear; + auto filler_interface = std::unique_ptr(Fill::new_from_type(support_params.contact_fill_pattern)); + // Filler for the 1st layer interface, if different from filler_interface. + auto filler_first_layer_ptr = std::unique_ptr(range.begin() == 0 && support_params.contact_fill_pattern != fill_type_first_layer ? Fill::new_from_type(fill_type_first_layer) : nullptr); + // Pointer to the 1st layer interface filler. + auto filler_first_layer = filler_first_layer_ptr ? filler_first_layer_ptr.get() : filler_interface.get(); + // Filler for the 1st layer interface, if different from filler_interface. + auto filler_raft_contact_ptr = std::unique_ptr(range.begin() == n_raft_layers && config.support_interface_top_layers.value == 0 ? + Fill::new_from_type(support_params.raft_interface_fill_pattern) : nullptr); + // Pointer to the 1st layer interface filler. + auto filler_raft_contact = filler_raft_contact_ptr ? filler_raft_contact_ptr.get() : filler_interface.get(); + // Filler for the base interface (to be used for soluble interface / non soluble base, to produce non soluble interface layer below soluble interface layer). + auto filler_base_interface = std::unique_ptr(base_interface_layers.empty() ? nullptr : + Fill::new_from_type(support_params.interface_density > 0.95 || support_params.with_sheath ? ipRectilinear : ipSupportBase)); + auto filler_support = std::unique_ptr(Fill::new_from_type(support_params.base_fill_pattern)); + filler_interface->set_bounding_box(bbox_object); + if (filler_first_layer_ptr) + filler_first_layer_ptr->set_bounding_box(bbox_object); + if (filler_raft_contact_ptr) + filler_raft_contact_ptr->set_bounding_box(bbox_object); + if (filler_base_interface) + filler_base_interface->set_bounding_box(bbox_object); + filler_support->set_bounding_box(bbox_object); + for (size_t support_layer_id = range.begin(); support_layer_id < range.end(); ++ support_layer_id) + { + SupportLayer &support_layer = *support_layers[support_layer_id]; + LayerCache &layer_cache = layer_caches[support_layer_id]; + const float support_interface_angle = config.support_style.value == smsGrid ? + support_params.interface_angle : support_params.raft_interface_angle(support_layer.interface_id()); + + // Find polygons with the same print_z. + SupportGeneratorLayerExtruded &bottom_contact_layer = layer_cache.bottom_contact_layer; + SupportGeneratorLayerExtruded &top_contact_layer = layer_cache.top_contact_layer; + SupportGeneratorLayerExtruded &base_layer = layer_cache.base_layer; + SupportGeneratorLayerExtruded &interface_layer = layer_cache.interface_layer; + SupportGeneratorLayerExtruded &base_interface_layer = layer_cache.base_interface_layer; + // Increment the layer indices to find a layer at support_layer.print_z. + { + auto fun = [&support_layer](const SupportGeneratorLayer *l){ return l->print_z >= support_layer.print_z - EPSILON; }; + idx_layer_bottom_contact = idx_higher_or_equal(bottom_contacts, idx_layer_bottom_contact, fun); + idx_layer_top_contact = idx_higher_or_equal(top_contacts, idx_layer_top_contact, fun); + idx_layer_intermediate = idx_higher_or_equal(intermediate_layers, idx_layer_intermediate, fun); + idx_layer_interface = idx_higher_or_equal(interface_layers, idx_layer_interface, fun); + idx_layer_base_interface = idx_higher_or_equal(base_interface_layers, idx_layer_base_interface,fun); + } + // Copy polygons from the layers. + if (idx_layer_bottom_contact < bottom_contacts.size() && bottom_contacts[idx_layer_bottom_contact]->print_z < support_layer.print_z + EPSILON) + bottom_contact_layer.layer = bottom_contacts[idx_layer_bottom_contact]; + if (idx_layer_top_contact < top_contacts.size() && top_contacts[idx_layer_top_contact]->print_z < support_layer.print_z + EPSILON) + top_contact_layer.layer = top_contacts[idx_layer_top_contact]; + if (idx_layer_interface < interface_layers.size() && interface_layers[idx_layer_interface]->print_z < support_layer.print_z + EPSILON) + interface_layer.layer = interface_layers[idx_layer_interface]; + if (idx_layer_base_interface < base_interface_layers.size() && base_interface_layers[idx_layer_base_interface]->print_z < support_layer.print_z + EPSILON) + base_interface_layer.layer = base_interface_layers[idx_layer_base_interface]; + if (idx_layer_intermediate < intermediate_layers.size() && intermediate_layers[idx_layer_intermediate]->print_z < support_layer.print_z + EPSILON) + base_layer.layer = intermediate_layers[idx_layer_intermediate]; + + // This layer is a raft contact layer. Any contact polygons at this layer are raft contacts. + bool raft_layer = slicing_params.interface_raft_layers && top_contact_layer.layer && is_approx(top_contact_layer.layer->print_z, slicing_params.raft_contact_top_z); + if (config.support_interface_top_layers == 0) { + // If no top interface layers were requested, we treat the contact layer exactly as a generic base layer. + // Don't merge the raft contact layer though. + if (support_params.can_merge_support_regions && ! raft_layer) { + if (base_layer.could_merge(top_contact_layer)) + base_layer.merge(std::move(top_contact_layer)); + else if (base_layer.empty()) + base_layer = std::move(top_contact_layer); + } + } else { + loop_interface_processor.generate(top_contact_layer, support_params.support_material_interface_flow); + // If no loops are allowed, we treat the contact layer exactly as a generic interface layer. + // Merge interface_layer into top_contact_layer, as the top_contact_layer is not synchronized and therefore it will be used + // to trim other layers. + if (top_contact_layer.could_merge(interface_layer) && ! raft_layer) + top_contact_layer.merge(std::move(interface_layer)); + } + if ((config.support_interface_top_layers == 0 || config.support_interface_bottom_layers == 0) && support_params.can_merge_support_regions) { + if (base_layer.could_merge(bottom_contact_layer)) + base_layer.merge(std::move(bottom_contact_layer)); + else if (base_layer.empty() && ! bottom_contact_layer.empty() && ! bottom_contact_layer.layer->bridging) + base_layer = std::move(bottom_contact_layer); + } else if (bottom_contact_layer.could_merge(top_contact_layer) && ! raft_layer) + top_contact_layer.merge(std::move(bottom_contact_layer)); + else if (bottom_contact_layer.could_merge(interface_layer)) + bottom_contact_layer.merge(std::move(interface_layer)); + +#if 0 + if ( ! interface_layer.empty() && ! base_layer.empty()) { + // turn base support into interface when it's contained in our holes + // (this way we get wider interface anchoring) + //FIXME The intention of the code below is unclear. One likely wanted to just merge small islands of base layers filling in the holes + // inside interface layers, but the code below fills just too much, see GH #4570 + Polygons islands = top_level_islands(interface_layer.layer->polygons); + polygons_append(interface_layer.layer->polygons, intersection(base_layer.layer->polygons, islands)); + base_layer.layer->polygons = diff(base_layer.layer->polygons, islands); + } +#endif + + // Top and bottom contacts, interface layers. + enum class InterfaceLayerType { TopContact, BottomContact, RaftContact, Interface, InterfaceAsBase }; + auto extrude_interface = [&](SupportGeneratorLayerExtruded &layer_ex, InterfaceLayerType interface_layer_type) { + if (! layer_ex.empty() && ! layer_ex.polygons_to_extrude().empty()) { + bool interface_as_base = interface_layer_type == InterfaceLayerType::InterfaceAsBase; + bool raft_contact = interface_layer_type == InterfaceLayerType::RaftContact; + //FIXME Bottom interfaces are extruded with the briding flow. Some bridging layers have its height slightly reduced, therefore + // the bridging flow does not quite apply. Reduce the flow to area of an ellipse? (A = pi * a * b) + auto *filler = raft_contact ? filler_raft_contact : filler_interface.get(); + auto interface_flow = layer_ex.layer->bridging ? + Flow::bridging_flow(layer_ex.layer->height, support_params.support_material_bottom_interface_flow.nozzle_diameter()) : + (raft_contact ? &support_params.raft_interface_flow : + interface_as_base ? &support_params.support_material_flow : &support_params.support_material_interface_flow) + ->with_height(float(layer_ex.layer->height)); + filler->angle = interface_as_base ? + // If zero interface layers are configured, use the same angle as for the base layers. + angles[support_layer_id % angles.size()] : + // Use interface angle for the interface layers. + raft_contact ? + support_params.raft_interface_angle(support_layer.interface_id()) : + support_interface_angle; + double density = raft_contact ? support_params.raft_interface_density : interface_as_base ? support_params.support_density : support_params.interface_density; + filler->spacing = raft_contact ? support_params.raft_interface_flow.spacing() : + interface_as_base ? support_params.support_material_flow.spacing() : support_params.support_material_interface_flow.spacing(); + filler->link_max_length = coord_t(scale_(filler->spacing * link_max_length_factor / density)); + fill_expolygons_generate_paths( + // Destination + layer_ex.extrusions, + // Regions to fill + union_safety_offset_ex(layer_ex.polygons_to_extrude()), + // Filler and its parameters + filler, float(density), + // Extrusion parameters + ExtrusionRole::erSupportMaterialInterface, interface_flow); + } + }; + const bool top_interfaces = config.support_interface_top_layers.value != 0; + const bool bottom_interfaces = top_interfaces && config.support_interface_bottom_layers != 0; + extrude_interface(top_contact_layer, raft_layer ? InterfaceLayerType::RaftContact : top_interfaces ? InterfaceLayerType::TopContact : InterfaceLayerType::InterfaceAsBase); + extrude_interface(bottom_contact_layer, bottom_interfaces ? InterfaceLayerType::BottomContact : InterfaceLayerType::InterfaceAsBase); + extrude_interface(interface_layer, top_interfaces ? InterfaceLayerType::Interface : InterfaceLayerType::InterfaceAsBase); + + // Base interface layers under soluble interfaces + if ( ! base_interface_layer.empty() && ! base_interface_layer.polygons_to_extrude().empty()) { + Fill *filler = filler_base_interface.get(); + //FIXME Bottom interfaces are extruded with the briding flow. Some bridging layers have its height slightly reduced, therefore + // the bridging flow does not quite apply. Reduce the flow to area of an ellipse? (A = pi * a * b) + assert(! base_interface_layer.layer->bridging); + Flow interface_flow = support_params.support_material_flow.with_height(float(base_interface_layer.layer->height)); + filler->angle = support_interface_angle; + filler->spacing = support_params.support_material_interface_flow.spacing(); + filler->link_max_length = coord_t(scale_(filler->spacing * link_max_length_factor / support_params.interface_density)); + fill_expolygons_generate_paths( + // Destination + base_interface_layer.extrusions, + //base_layer_interface.extrusions, + // Regions to fill + union_safety_offset_ex(base_interface_layer.polygons_to_extrude()), + // Filler and its parameters + filler, float(support_params.interface_density), + // Extrusion parameters + ExtrusionRole::erSupportMaterial, interface_flow); + } + + // Base support or flange. + if (! base_layer.empty() && ! base_layer.polygons_to_extrude().empty()) { + Fill *filler = filler_support.get(); + filler->angle = angles[support_layer_id % angles.size()]; + // We don't use $base_flow->spacing because we need a constant spacing + // value that guarantees that all layers are correctly aligned. + assert(! base_layer.layer->bridging); + auto flow = support_params.support_material_flow.with_height(float(base_layer.layer->height)); + filler->spacing = support_params.support_material_flow.spacing(); + filler->link_max_length = coord_t(scale_(filler->spacing * link_max_length_factor / support_params.support_density)); + float density = float(support_params.support_density); + bool sheath = support_params.with_sheath; + bool no_sort = false; + bool done = false; + if (base_layer.layer->bottom_z < EPSILON) { + // Base flange (the 1st layer). + filler = filler_first_layer; + filler->angle = Geometry::deg2rad(float(config.support_angle.value + 90.)); + density = float(config.raft_first_layer_density.value * 0.01); + flow = support_params.first_layer_flow; + // use the proper spacing for first layer as we don't need to align + // its pattern to the other layers + //FIXME When paralellizing, each thread shall have its own copy of the fillers. + filler->spacing = flow.spacing(); + filler->link_max_length = coord_t(scale_(filler->spacing * link_max_length_factor / density)); + sheath = true; + no_sort = true; + } else if (config.support_style == SupportMaterialStyle::smsOrganic) { + tree_supports_generate_paths(base_layer.extrusions, base_layer.polygons_to_extrude(), flow, support_params); + done = true; + } + if (! done) + fill_expolygons_with_sheath_generate_paths( + // Destination + base_layer.extrusions, + // Regions to fill + base_layer.polygons_to_extrude(), + // Filler and its parameters + filler, density, + // Extrusion parameters + ExtrusionRole::erSupportMaterial, flow, + sheath, no_sort); + } + + // Merge base_interface_layers to base_layers to avoid unneccessary retractions + if (! base_layer.empty() && ! base_interface_layer.empty() && ! base_layer.polygons_to_extrude().empty() && ! base_interface_layer.polygons_to_extrude().empty() && + base_layer.could_merge(base_interface_layer)) + base_layer.merge(std::move(base_interface_layer)); + + layer_cache.add_nonempty_and_sort(); + + // Collect the support areas with this print_z into islands, as there is no need + // for retraction over these islands. + Polygons polys; + // Collect the extrusions, sorted by the bottom extrusion height. + for (LayerCacheItem &layer_cache_item : layer_cache.nonempty) { + // Collect islands to polys. + layer_cache_item.layer_extruded->polygons_append(polys); + // The print_z of the top contact surfaces and bottom_z of the bottom contact surfaces are "free" + // in a sense that they are not synchronized with other support layers. As the top and bottom contact surfaces + // are inflated to achieve a better anchoring, it may happen, that these surfaces will at least partially + // overlap in Z with another support layers, leading to over-extrusion. + // Mitigate the over-extrusion by modulating the extrusion rate over these regions. + // The print head will follow the same print_z, but the layer thickness will be reduced + // where it overlaps with another support layer. + //FIXME When printing a briging path, what is an equivalent height of the squished extrudate of the same width? + // Collect overlapping top/bottom surfaces. + layer_cache_item.overlapping.reserve(20); + coordf_t bottom_z = layer_cache_item.layer_extruded->layer->bottom_print_z() + EPSILON; + auto add_overlapping = [&layer_cache_item, bottom_z](const SupportGeneratorLayersPtr &layers, size_t idx_top) { + for (int i = int(idx_top) - 1; i >= 0 && layers[i]->print_z > bottom_z; -- i) + layer_cache_item.overlapping.push_back(layers[i]); + }; + add_overlapping(top_contacts, idx_layer_top_contact); + if (layer_cache_item.layer_extruded->layer->layer_type == SupporLayerType::BottomContact) { + // Bottom contact layer may overlap with a base layer, which may be changed to interface layer. + add_overlapping(intermediate_layers, idx_layer_intermediate); + add_overlapping(interface_layers, idx_layer_interface); + add_overlapping(base_interface_layers, idx_layer_base_interface); + } + // Order the layers by lexicographically by an increasing print_z and a decreasing layer height. + std::stable_sort(layer_cache_item.overlapping.begin(), layer_cache_item.overlapping.end(), [](auto *l1, auto *l2) { return *l1 < *l2; }); + } + assert(support_layer.support_islands.empty()); + if (! polys.empty()) { + support_layer.support_islands = union_ex(polys); + // support_layer.support_islands_bboxes.reserve(support_layer.support_islands.size()); + // for (const ExPolygon &expoly : support_layer.support_islands) + // support_layer.support_islands_bboxes.emplace_back(get_extents(expoly).inflated(SCALED_EPSILON)); + } + } // for each support_layer_id + }); + + // Now modulate the support layer height in parallel. + tbb::parallel_for(tbb::blocked_range(n_raft_layers, support_layers.size()), + [&support_layers, &layer_caches] + (const tbb::blocked_range& range) { + for (size_t support_layer_id = range.begin(); support_layer_id < range.end(); ++ support_layer_id) { + SupportLayer &support_layer = *support_layers[support_layer_id]; + LayerCache &layer_cache = layer_caches[support_layer_id]; + // For all extrusion types at this print_z, ordered by decreasing layer height: + for (LayerCacheItem &layer_cache_item : layer_cache.nonempty) { + // Trim the extrusion height from the bottom by the overlapping layers. + modulate_extrusion_by_overlapping_layers(layer_cache_item.layer_extruded->extrusions, *layer_cache_item.layer_extruded->layer, layer_cache_item.overlapping); + support_layer.support_fills.append(std::move(layer_cache_item.layer_extruded->extrusions)); + } + } + }); + +#ifndef NDEBUG + struct Test { + static bool verify_nonempty(const ExtrusionEntityCollection *collection) { + for (const ExtrusionEntity *ee : collection->entities) { + if (const ExtrusionPath *path = dynamic_cast(ee)) + assert(! path->empty()); + else if (const ExtrusionMultiPath *multipath = dynamic_cast(ee)) + assert(! multipath->empty()); + else if (const ExtrusionEntityCollection *eecol = dynamic_cast(ee)) { + assert(! eecol->empty()); + return verify_nonempty(eecol); + } else + assert(false); + } + return true; + } + }; + for (const SupportLayer *support_layer : support_layers) + assert(Test::verify_nonempty(&support_layer->support_fills)); +#endif // NDEBUG +} + +/* +void PrintObjectSupportMaterial::clip_by_pillars( + const PrintObject &object, + LayersPtr &bottom_contacts, + LayersPtr &top_contacts, + LayersPtr &intermediate_contacts); + +{ + // this prevents supplying an empty point set to BoundingBox constructor + if (top_contacts.empty()) + return; + + coord_t pillar_size = scale_(PILLAR_SIZE); + coord_t pillar_spacing = scale_(PILLAR_SPACING); + + // A regular grid of pillars, filling the 2D bounding box. + Polygons grid; + { + // Rectangle with a side of 2.5x2.5mm. + Polygon pillar; + pillar.points.push_back(Point(0, 0)); + pillar.points.push_back(Point(pillar_size, 0)); + pillar.points.push_back(Point(pillar_size, pillar_size)); + pillar.points.push_back(Point(0, pillar_size)); + + // 2D bounding box of the projection of all contact polygons. + BoundingBox bbox; + for (LayersPtr::const_iterator it = top_contacts.begin(); it != top_contacts.end(); ++ it) + bbox.merge(get_extents((*it)->polygons)); + grid.reserve(size_t(ceil(bb.size()(0) / pillar_spacing)) * size_t(ceil(bb.size()(1) / pillar_spacing))); + for (coord_t x = bb.min(0); x <= bb.max(0) - pillar_size; x += pillar_spacing) { + for (coord_t y = bb.min(1); y <= bb.max(1) - pillar_size; y += pillar_spacing) { + grid.push_back(pillar); + for (size_t i = 0; i < pillar.points.size(); ++ i) + grid.back().points[i].translate(Point(x, y)); + } + } + } + + // add pillars to every layer + for my $i (0..n_support_z) { + $shape->[$i] = [ @$grid ]; + } + + // build capitals + for my $i (0..n_support_z) { + my $z = $support_z->[$i]; + + my $capitals = intersection( + $grid, + $contact->{$z} // [], + ); + + // work on one pillar at time (if any) to prevent the capitals from being merged + // but store the contact area supported by the capital because we need to make + // sure nothing is left + my $contact_supported_by_capitals = []; + foreach my $capital (@$capitals) { + // enlarge capital tops + $capital = offset([$capital], +($pillar_spacing - $pillar_size)/2); + push @$contact_supported_by_capitals, @$capital; + + for (my $j = $i-1; $j >= 0; $j--) { + my $jz = $support_z->[$j]; + $capital = offset($capital, -$self->interface_flow->scaled_width/2); + last if !@$capitals; + push @{ $shape->[$j] }, @$capital; + } + } + + // Capitals will not generally cover the whole contact area because there will be + // remainders. For now we handle this situation by projecting such unsupported + // areas to the ground, just like we would do with a normal support. + my $contact_not_supported_by_capitals = diff( + $contact->{$z} // [], + $contact_supported_by_capitals, + ); + if (@$contact_not_supported_by_capitals) { + for (my $j = $i-1; $j >= 0; $j--) { + push @{ $shape->[$j] }, @$contact_not_supported_by_capitals; + } + } + } +} + +sub clip_with_shape { + my ($self, $support, $shape) = @_; + + foreach my $i (keys %$support) { + // don't clip bottom layer with shape so that we + // can generate a continuous base flange + // also don't clip raft layers + next if $i == 0; + next if $i < $self->object_config->raft_layers; + $support->{$i} = intersection( + $support->{$i}, + $shape->[$i], + ); + } +} +*/ + +} // namespace Slic3r diff --git a/src/libslic3r/Support/SupportCommon.hpp b/src/libslic3r/Support/SupportCommon.hpp new file mode 100644 index 0000000000..f8df25e503 --- /dev/null +++ b/src/libslic3r/Support/SupportCommon.hpp @@ -0,0 +1,161 @@ +///|/ Copyright (c) Prusa Research 2023 Vojtěch Bubník @bubnikv +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +#ifndef slic3r_SupportCommon_hpp_ +#define slic3r_SupportCommon_hpp_ + +#include "../Layer.hpp" +#include "../Polygon.hpp" +#include "../Print.hpp" +#include "SupportLayer.hpp" +#include "SupportParameters.hpp" + +namespace Slic3r { + +class PrintObject; +class SupportLayer; + +namespace FFFSupport { + +// Remove bridges from support contact areas. +// To be called if PrintObjectConfig::dont_support_bridges. +void remove_bridges_from_contacts( + const PrintConfig &print_config, + const Layer &lower_layer, + const LayerRegion &layerm, + float fw, + Polygons &contact_polygons); + +// Turn some of the base layers into base interface layers. +// For soluble interfaces with non-soluble bases, print maximum two first interface layers with the base +// extruder to improve adhesion of the soluble filament to the base. +// For Organic supports, merge top_interface_layers & top_base_interface_layers with the interfaces +// produced by this function. +std::pair generate_interface_layers( + const PrintObjectConfig &config, + const SupportParameters &support_params, + const SupportGeneratorLayersPtr &bottom_contacts, + const SupportGeneratorLayersPtr &top_contacts, + // Input / output, will be merged with output + SupportGeneratorLayersPtr &top_interface_layers, + SupportGeneratorLayersPtr &top_base_interface_layers, + // Input, will be trimmed with the newly created interface layers. + SupportGeneratorLayersPtr &intermediate_layers, + SupportGeneratorLayerStorage &layer_storage); + +// Generate raft layers, also expand the 1st support layer +// in case there is no raft layer to improve support adhesion. +SupportGeneratorLayersPtr generate_raft_base( + const PrintObject &object, + const SupportParameters &support_params, + const SlicingParameters &slicing_params, + const SupportGeneratorLayersPtr &top_contacts, + const SupportGeneratorLayersPtr &interface_layers, + const SupportGeneratorLayersPtr &base_interface_layers, + const SupportGeneratorLayersPtr &base_layers, + SupportGeneratorLayerStorage &layer_storage); + +// returns sorted layers +SupportGeneratorLayersPtr generate_support_layers( + PrintObject &object, + const SupportGeneratorLayersPtr &raft_layers, + const SupportGeneratorLayersPtr &bottom_contacts, + const SupportGeneratorLayersPtr &top_contacts, + const SupportGeneratorLayersPtr &intermediate_layers, + const SupportGeneratorLayersPtr &interface_layers, + const SupportGeneratorLayersPtr &base_interface_layers); + +// Produce the support G-code. +// Used by both classic and tree supports. +void generate_support_toolpaths( + SupportLayerPtrs &support_layers, + const PrintObjectConfig &config, + const SupportParameters &support_params, + const SlicingParameters &slicing_params, + const SupportGeneratorLayersPtr &raft_layers, + const SupportGeneratorLayersPtr &bottom_contacts, + const SupportGeneratorLayersPtr &top_contacts, + const SupportGeneratorLayersPtr &intermediate_layers, + const SupportGeneratorLayersPtr &interface_layers, + const SupportGeneratorLayersPtr &base_interface_layers); + +// FN_HIGHER_EQUAL: the provided object pointer has a Z value >= of an internal threshold. +// Find the first item with Z value >= of an internal threshold of fn_higher_equal. +// If no vec item with Z value >= of an internal threshold of fn_higher_equal is found, return vec.size() +// If the initial idx is size_t(-1), then use binary search. +// Otherwise search linearly upwards. +template +IndexType idx_higher_or_equal(IteratorType begin, IteratorType end, IndexType idx, FN_HIGHER_EQUAL fn_higher_equal) +{ + auto size = int(end - begin); + if (size == 0) { + idx = 0; + } else if (idx == IndexType(-1)) { + // First of the batch of layers per thread pool invocation. Use binary search. + int idx_low = 0; + int idx_high = std::max(0, size - 1); + while (idx_low + 1 < idx_high) { + int idx_mid = (idx_low + idx_high) / 2; + if (fn_higher_equal(begin[idx_mid])) + idx_high = idx_mid; + else + idx_low = idx_mid; + } + idx = fn_higher_equal(begin[idx_low]) ? idx_low : + (fn_higher_equal(begin[idx_high]) ? idx_high : size); + } else { + // For the other layers of this batch of layers, search incrementally, which is cheaper than the binary search. + while (int(idx) < size && ! fn_higher_equal(begin[idx])) + ++ idx; + } + return idx; +} +template +IndexType idx_higher_or_equal(const std::vector& vec, IndexType idx, FN_HIGHER_EQUAL fn_higher_equal) +{ + return idx_higher_or_equal(vec.begin(), vec.end(), idx, fn_higher_equal); +} + +// FN_LOWER_EQUAL: the provided object pointer has a Z value <= of an internal threshold. +// Find the first item with Z value <= of an internal threshold of fn_lower_equal. +// If no vec item with Z value <= of an internal threshold of fn_lower_equal is found, return -1. +// If the initial idx is < -1, then use binary search. +// Otherwise search linearly downwards. +template +int idx_lower_or_equal(IT begin, IT end, int idx, FN_LOWER_EQUAL fn_lower_equal) +{ + auto size = int(end - begin); + if (size == 0) { + idx = -1; + } else if (idx < -1) { + // First of the batch of layers per thread pool invocation. Use binary search. + int idx_low = 0; + int idx_high = std::max(0, size - 1); + while (idx_low + 1 < idx_high) { + int idx_mid = (idx_low + idx_high) / 2; + if (fn_lower_equal(begin[idx_mid])) + idx_low = idx_mid; + else + idx_high = idx_mid; + } + idx = fn_lower_equal(begin[idx_high]) ? idx_high : + (fn_lower_equal(begin[idx_low ]) ? idx_low : -1); + } else { + // For the other layers of this batch of layers, search incrementally, which is cheaper than the binary search. + while (idx >= 0 && ! fn_lower_equal(begin[idx])) + -- idx; + } + return idx; +} +template +int idx_lower_or_equal(const std::vector &vec, int idx, FN_LOWER_EQUAL fn_lower_equal) +{ + return idx_lower_or_equal(vec.begin(), vec.end(), idx, fn_lower_equal); +} + +} // namespace FFFSupport + +} // namespace Slic3r + +#endif /* slic3r_SupportCommon_hpp_ */ diff --git a/src/libslic3r/Support/SupportDebug.cpp b/src/libslic3r/Support/SupportDebug.cpp new file mode 100644 index 0000000000..24e92a0eb1 --- /dev/null +++ b/src/libslic3r/Support/SupportDebug.cpp @@ -0,0 +1,112 @@ +///|/ Copyright (c) Prusa Research 2023 Vojtěch Bubník @bubnikv +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +#if 1 //#ifdef SLIC3R_DEBUG + +#include "../ClipperUtils.hpp" +#include "../SVG.hpp" +#include "../Layer.hpp" + +#include "SupportLayer.hpp" + +namespace Slic3r::FFFSupport { + +const char* support_surface_type_to_color_name(const SupporLayerType surface_type) +{ + switch (surface_type) { + case SupporLayerType::TopContact: return "rgb(255,0,0)"; // "red"; + case SupporLayerType::TopInterface: return "rgb(0,255,0)"; // "green"; + case SupporLayerType::Base: return "rgb(0,0,255)"; // "blue"; + case SupporLayerType::BottomInterface:return "rgb(255,255,128)"; // yellow + case SupporLayerType::BottomContact: return "rgb(255,0,255)"; // magenta + case SupporLayerType::RaftInterface: return "rgb(0,255,255)"; + case SupporLayerType::RaftBase: return "rgb(128,128,128)"; + case SupporLayerType::Unknown: return "rgb(128,0,0)"; // maroon + default: return "rgb(64,64,64)"; + }; +} + +Point export_support_surface_type_legend_to_svg_box_size() +{ + return Point(scale_(1.+10.*8.), scale_(3.)); +} + +void export_support_surface_type_legend_to_svg(SVG &svg, const Point &pos) +{ + // 1st row + coord_t pos_x0 = pos(0) + scale_(1.); + coord_t pos_x = pos_x0; + coord_t pos_y = pos(1) + scale_(1.5); + coord_t step_x = scale_(10.); + svg.draw_legend(Point(pos_x, pos_y), "top contact" , support_surface_type_to_color_name(SupporLayerType::TopContact)); + pos_x += step_x; + svg.draw_legend(Point(pos_x, pos_y), "top iface" , support_surface_type_to_color_name(SupporLayerType::TopInterface)); + pos_x += step_x; + svg.draw_legend(Point(pos_x, pos_y), "base" , support_surface_type_to_color_name(SupporLayerType::Base)); + pos_x += step_x; + svg.draw_legend(Point(pos_x, pos_y), "bottom iface" , support_surface_type_to_color_name(SupporLayerType::BottomInterface)); + pos_x += step_x; + svg.draw_legend(Point(pos_x, pos_y), "bottom contact" , support_surface_type_to_color_name(SupporLayerType::BottomContact)); + // 2nd row + pos_x = pos_x0; + pos_y = pos(1)+scale_(2.8); + svg.draw_legend(Point(pos_x, pos_y), "raft interface" , support_surface_type_to_color_name(SupporLayerType::RaftInterface)); + pos_x += step_x; + svg.draw_legend(Point(pos_x, pos_y), "raft base" , support_surface_type_to_color_name(SupporLayerType::RaftBase)); + pos_x += step_x; + svg.draw_legend(Point(pos_x, pos_y), "unknown" , support_surface_type_to_color_name(SupporLayerType::Unknown)); + pos_x += step_x; + svg.draw_legend(Point(pos_x, pos_y), "intermediate" , support_surface_type_to_color_name(SupporLayerType::Intermediate)); +} + +void export_print_z_polygons_to_svg(const char *path, SupportGeneratorLayer ** const layers, int n_layers) +{ + BoundingBox bbox; + for (int i = 0; i < n_layers; ++ i) + bbox.merge(get_extents(layers[i]->polygons)); + Point legend_size = export_support_surface_type_legend_to_svg_box_size(); + Point legend_pos(bbox.min(0), bbox.max(1)); + bbox.merge(Point(std::max(bbox.min(0) + legend_size(0), bbox.max(0)), bbox.max(1) + legend_size(1))); + SVG svg(path, bbox); + const float transparency = 0.5f; + for (int i = 0; i < n_layers; ++ i) + svg.draw(union_ex(layers[i]->polygons), support_surface_type_to_color_name(layers[i]->layer_type), transparency); + for (int i = 0; i < n_layers; ++ i) + svg.draw(to_polylines(layers[i]->polygons), support_surface_type_to_color_name(layers[i]->layer_type)); + export_support_surface_type_legend_to_svg(svg, legend_pos); + svg.Close(); +} + +void export_print_z_polygons_and_extrusions_to_svg( + const char *path, + SupportGeneratorLayer ** const layers, + int n_layers, + SupportLayer &support_layer) +{ + BoundingBox bbox; + for (int i = 0; i < n_layers; ++ i) + bbox.merge(get_extents(layers[i]->polygons)); + Point legend_size = export_support_surface_type_legend_to_svg_box_size(); + Point legend_pos(bbox.min(0), bbox.max(1)); + bbox.merge(Point(std::max(bbox.min(0) + legend_size(0), bbox.max(0)), bbox.max(1) + legend_size(1))); + SVG svg(path, bbox); + const float transparency = 0.5f; + for (int i = 0; i < n_layers; ++ i) + svg.draw(union_ex(layers[i]->polygons), support_surface_type_to_color_name(layers[i]->layer_type), transparency); + for (int i = 0; i < n_layers; ++ i) + svg.draw(to_polylines(layers[i]->polygons), support_surface_type_to_color_name(layers[i]->layer_type)); + + Polygons polygons_support, polygons_interface; + support_layer.support_fills.polygons_covered_by_width(polygons_support, float(SCALED_EPSILON)); +// support_layer.support_interface_fills.polygons_covered_by_width(polygons_interface, SCALED_EPSILON); + svg.draw(union_ex(polygons_support), "brown"); + svg.draw(union_ex(polygons_interface), "black"); + + export_support_surface_type_legend_to_svg(svg, legend_pos); + svg.Close(); +} + +} // namespace Slic3r + +#endif /* SLIC3R_DEBUG */ diff --git a/src/libslic3r/Support/SupportDebug.hpp b/src/libslic3r/Support/SupportDebug.hpp new file mode 100644 index 0000000000..fb2375efbd --- /dev/null +++ b/src/libslic3r/Support/SupportDebug.hpp @@ -0,0 +1,22 @@ +///|/ Copyright (c) Prusa Research 2023 Vojtěch Bubník @bubnikv +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +#ifndef slic3r_SupportCommon_hpp_ +#define slic3r_SupportCommon_hpp_ + +namespace Slic3r { + +class SupportGeneratorLayer; +class SupportLayer; + +namespace FFFSupport { + +void export_print_z_polygons_to_svg(const char *path, SupportGeneratorLayer ** const layers, size_t n_layers); +void export_print_z_polygons_and_extrusions_to_svg(const char *path, SupportGeneratorLayer ** const layers, size_t n_layers, SupportLayer& support_layer); + +} // namespace FFFSupport + +} // namespace Slic3r + +#endif /* slic3r_SupportCommon_hpp_ */ diff --git a/src/libslic3r/Support/SupportLayer.hpp b/src/libslic3r/Support/SupportLayer.hpp new file mode 100644 index 0000000000..e017d7421c --- /dev/null +++ b/src/libslic3r/Support/SupportLayer.hpp @@ -0,0 +1,150 @@ +///|/ Copyright (c) Prusa Research 2023 Vojtěch Bubník @bubnikv, Pavel Mikuš @Godrak +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +#ifndef slic3r_SupportLayer_hpp_ +#define slic3r_SupportLayer_hpp_ + +#include +#include +// for Slic3r::deque +#include "../libslic3r.h" +#include "../ClipperUtils.hpp" +#include "../Polygon.hpp" + +namespace Slic3r::FFFSupport { + +// Support layer type to be used by SupportGeneratorLayer. This type carries a much more detailed information +// about the support layer type than the final support layers stored in a PrintObject. +enum class SupporLayerType { + Unknown = 0, + // Ratft base layer, to be printed with the support material. + RaftBase, + // Raft interface layer, to be printed with the support interface material. + RaftInterface, + // Bottom contact layer placed over a top surface of an object. To be printed with a support interface material. + BottomContact, + // Dense interface layer, to be printed with the support interface material. + // This layer is separated from an object by an BottomContact layer. + BottomInterface, + // Sparse base support layer, to be printed with a support material. + Base, + // Dense interface layer, to be printed with the support interface material. + // This layer is separated from an object with TopContact layer. + TopInterface, + // Top contact layer directly supporting an overhang. To be printed with a support interface material. + TopContact, + // Some undecided type yet. It will turn into Base first, then it may turn into BottomInterface or TopInterface. + Intermediate, +}; + +// A support layer type used internally by the SupportMaterial class. This class carries a much more detailed +// information about the support layer than the layers stored in the PrintObject, mainly +// the SupportGeneratorLayer is aware of the bridging flow and the interface gaps between the object and the support. +class SupportGeneratorLayer +{ +public: + void reset() { + *this = SupportGeneratorLayer(); + } + + bool operator==(const SupportGeneratorLayer &layer2) const { + return print_z == layer2.print_z && height == layer2.height && bridging == layer2.bridging; + } + + // Order the layers by lexicographically by an increasing print_z and a decreasing layer height. + bool operator<(const SupportGeneratorLayer &layer2) const { + if (print_z < layer2.print_z) { + return true; + } else if (print_z == layer2.print_z) { + if (height > layer2.height) + return true; + else if (height == layer2.height) { + // Bridging layers first. + return bridging && ! layer2.bridging; + } else + return false; + } else + return false; + } + + void merge(SupportGeneratorLayer &&rhs) { + // The union_() does not support move semantic yet, but maybe one day it will. + this->polygons = union_(this->polygons, std::move(rhs.polygons)); + auto merge = [](std::unique_ptr &dst, std::unique_ptr &src) { + if (! dst || dst->empty()) + dst = std::move(src); + else if (src && ! src->empty()) + *dst = union_(*dst, std::move(*src)); + }; + merge(this->contact_polygons, rhs.contact_polygons); + merge(this->overhang_polygons, rhs.overhang_polygons); + merge(this->enforcer_polygons, rhs.enforcer_polygons); + rhs.reset(); + } + + // For the bridging flow, bottom_print_z will be above bottom_z to account for the vertical separation. + // For the non-bridging flow, bottom_print_z will be equal to bottom_z. + coordf_t bottom_print_z() const { return print_z - height; } + + // To sort the extremes of top / bottom interface layers. + coordf_t extreme_z() const { return (this->layer_type == SupporLayerType::TopContact) ? this->bottom_z : this->print_z; } + + SupporLayerType layer_type { SupporLayerType::Unknown }; + // Z used for printing, in unscaled coordinates. + coordf_t print_z { 0 }; + // Bottom Z of this layer. For soluble layers, bottom_z + height = print_z, + // otherwise bottom_z + gap + height = print_z. + coordf_t bottom_z { 0 }; + // Layer height in unscaled coordinates. + coordf_t height { 0 }; + // Index of a PrintObject layer_id supported by this layer. This will be set for top contact layers. + // If this is not a contact layer, it will be set to size_t(-1). + size_t idx_object_layer_above { size_t(-1) }; + // Index of a PrintObject layer_id, which supports this layer. This will be set for bottom contact layers. + // If this is not a contact layer, it will be set to size_t(-1). + size_t idx_object_layer_below { size_t(-1) }; + // Use a bridging flow when printing this support layer. + bool bridging { false }; + + // Polygons to be filled by the support pattern. + Polygons polygons; + // Currently for the contact layers only. + std::unique_ptr contact_polygons; + std::unique_ptr overhang_polygons; + // Enforcers need to be propagated independently in case the "support on build plate only" option is enabled. + std::unique_ptr enforcer_polygons; +}; + +// Layers are allocated and owned by a deque. Once a layer is allocated, it is maintained +// up to the end of a generate() method. The layer storage may be replaced by an allocator class in the future, +// which would allocate layers by multiple chunks. +class SupportGeneratorLayerStorage { +public: + SupportGeneratorLayer& allocate_unguarded(SupporLayerType layer_type) { + m_storage.emplace_back(); + m_storage.back().layer_type = layer_type; + return m_storage.back(); + } + + SupportGeneratorLayer& allocate(SupporLayerType layer_type) + { + m_mutex.lock(); + m_storage.emplace_back(); + SupportGeneratorLayer *layer_new = &m_storage.back(); + m_mutex.unlock(); + layer_new->layer_type = layer_type; + return *layer_new; + } + +private: + template + using Allocator = tbb::scalable_allocator; + Slic3r::deque> m_storage; + tbb::spin_mutex m_mutex; +}; +using SupportGeneratorLayersPtr = std::vector; + +} // namespace Slic3r + +#endif /* slic3r_SupportLayer_hpp_ */ diff --git a/src/libslic3r/Support/SupportMaterial.cpp b/src/libslic3r/Support/SupportMaterial.cpp new file mode 100644 index 0000000000..8b1d8bc0db --- /dev/null +++ b/src/libslic3r/Support/SupportMaterial.cpp @@ -0,0 +1,2631 @@ +///|/ Copyright (c) Prusa Research 2016 - 2023 Vojtěch Bubník @bubnikv, Pavel Mikuš @Godrak, Lukáš Hejl @hejllukas, Roman Beránek @zavorka, Lukáš Matěna @lukasmatena, Vojtěch Král @vojtechkral +///|/ Copyright (c) SuperSlicer 2023 Remi Durand @supermerill +///|/ Copyright (c) 2016 Sakari Kapanen @Flannelhead +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +#include "../ClipperUtils.hpp" +#include "../ExtrusionEntityCollection.hpp" +#include "../Layer.hpp" +#include "../Print.hpp" +#include "../Fill/FillBase.hpp" +#include "../Geometry.hpp" +#include "../Point.hpp" +#include "../MutablePolygon.hpp" + +#include "Support/SupportCommon.hpp" +#include "SupportMaterial.hpp" + +#include + +#include +#include +#include +#include + +#include +#include + +#define SUPPORT_USE_AGG_RASTERIZER + +#ifdef SUPPORT_USE_AGG_RASTERIZER + #include + #include + #include + #include + #include + #include "PNGReadWrite.hpp" +#else + #include "EdgeGrid.hpp" +#endif // SUPPORT_USE_AGG_RASTERIZER + +// #define SLIC3R_DEBUG + +// Make assert active if SLIC3R_DEBUG +#ifdef SLIC3R_DEBUG + #define DEBUG + #define _DEBUG + #undef NDEBUG + #include "../utils.hpp" + #include "../SVG.hpp" +#endif + +#include + +using namespace Slic3r::FFFSupport; + +namespace Slic3r { + +// how much we extend support around the actual contact area +//FIXME this should be dependent on the nozzle diameter! +#define SUPPORT_MATERIAL_MARGIN 1.5 + +// Increment used to reach MARGIN in steps to avoid trespassing thin objects +#define NUM_MARGIN_STEPS 3 + +// Dimensions of a tree-like structure to save material +#define PILLAR_SIZE (2.5) +#define PILLAR_SPACING 10 + +//#define SUPPORT_SURFACES_OFFSET_PARAMETERS ClipperLib::jtMiter, 3. +//#define SUPPORT_SURFACES_OFFSET_PARAMETERS ClipperLib::jtMiter, 1.5 +#define SUPPORT_SURFACES_OFFSET_PARAMETERS ClipperLib::jtSquare, 0. + +#ifdef SUPPORT_USE_AGG_RASTERIZER +static std::vector rasterize_polygons(const Vec2i &grid_size, const double pixel_size, const Point &left_bottom, const Polygons &polygons) +{ + std::vector data(grid_size.x() * grid_size.y()); + agg::rendering_buffer rendering_buffer(data.data(), unsigned(grid_size.x()), unsigned(grid_size.y()), grid_size.x()); + agg::pixfmt_gray8 pixel_renderer(rendering_buffer); + agg::renderer_base raw_renderer(pixel_renderer); + agg::renderer_scanline_aa_solid> renderer(raw_renderer); + + renderer.color(agg::pixfmt_gray8::color_type(255)); + raw_renderer.clear(agg::pixfmt_gray8::color_type(0)); + + agg::scanline_p8 scanline; + agg::rasterizer_scanline_aa<> rasterizer; + + auto convert_pt = [left_bottom, pixel_size](const Point &pt) { + return Vec2d((pt.x() - left_bottom.x()) / pixel_size, (pt.y() - left_bottom.y()) / pixel_size); + }; + rasterizer.reset(); + for (const Polygon &polygon : polygons) { + agg::path_storage path; + auto it = polygon.points.begin(); + Vec2d pt_front = convert_pt(*it); + path.move_to(pt_front.x(), pt_front.y()); + while (++ it != polygon.points.end()) { + Vec2d pt = convert_pt(*it); + path.line_to(pt.x(), pt.y()); + } + path.line_to(pt_front.x(), pt_front.y()); + rasterizer.add_path(std::move(path)); + } + agg::render_scanlines(rasterizer, scanline, renderer); + return data; +} +// Grid has to have the boundary pixels unset. +static Polygons contours_simplified(const Vec2i &grid_size, const double pixel_size, Point left_bottom, const std::vector &grid, coord_t offset, bool fill_holes) +{ + assert(std::abs(2 * offset) < pixel_size - 10); + + // Fill in empty cells, which have a left / right neighbor filled. + // Fill in empty cells, which have the top / bottom neighbor filled. + std::vector cell_inside_data; + const std::vector &cell_inside = fill_holes ? cell_inside_data : grid; + if (fill_holes) { + cell_inside_data = grid; + for (int r = 1; r + 1 < grid_size.y(); ++ r) { + for (int c = 1; c + 1 < grid_size.x(); ++ c) { + int addr = r * grid_size.x() + c; + if ((grid[addr - 1] != 0 && grid[addr + 1] != 0) || + (grid[addr - grid_size.x()] != 0 && grid[addr + grid_size.x()] != 0)) + cell_inside_data[addr] = true; + } + } + } + + // 1) Collect the lines. + std::vector lines; + std::vector> start_point_to_line_idx; + for (int r = 1; r < grid_size.y(); ++ r) { + for (int c = 1; c < grid_size.x(); ++ c) { + int addr = r * grid_size.x() + c; + bool left = cell_inside[addr - 1] != 0; + bool top = cell_inside[addr - grid_size.x()] != 0; + bool current = cell_inside[addr] != 0; + if (left != current) { + lines.push_back( + left ? + Line(Point(c, r+1), Point(c, r )) : + Line(Point(c, r ), Point(c, r+1))); + start_point_to_line_idx.emplace_back(lines.back().a, int(lines.size()) - 1); + } + if (top != current) { + lines.push_back( + top ? + Line(Point(c , r), Point(c+1, r)) : + Line(Point(c+1, r), Point(c , r))); + start_point_to_line_idx.emplace_back(lines.back().a, int(lines.size()) - 1); + } + } + } + std::sort(start_point_to_line_idx.begin(), start_point_to_line_idx.end(), [](const auto &l, const auto &r){ return l.first < r.first; }); + + // 2) Chain the lines. + std::vector line_processed(lines.size(), false); + Polygons out; + for (int i_candidate = 0; i_candidate < int(lines.size()); ++ i_candidate) { + if (line_processed[i_candidate]) + continue; + Polygon poly; + line_processed[i_candidate] = true; + poly.points.push_back(lines[i_candidate].b); + int i_line_current = i_candidate; + for (;;) { + auto line_range = std::equal_range(std::begin(start_point_to_line_idx), std::end(start_point_to_line_idx), + std::make_pair(lines[i_line_current].b, 0), [](const auto& l, const auto& r) { return l.first < r.first; }); + // The interval has to be non empty, there shall be at least one line continuing the current one. + assert(line_range.first != line_range.second); + int i_next = -1; + for (auto it = line_range.first; it != line_range.second; ++ it) { + if (it->second == i_candidate) { + // closing the loop. + goto end_of_poly; + } + if (line_processed[it->second]) + continue; + if (i_next == -1) { + i_next = it->second; + } else { + // This is a corner, where two lines meet exactly. Pick the line, which encloses a smallest angle with + // the current edge. + const Line &line_current = lines[i_line_current]; + const Line &line_next = lines[it->second]; + const Vector v1 = line_current.vector(); + const Vector v2 = line_next.vector(); + int64_t cross = int64_t(v1(0)) * int64_t(v2(1)) - int64_t(v2(0)) * int64_t(v1(1)); + if (cross > 0) { + // This has to be a convex right angle. There is no better next line. + i_next = it->second; + break; + } + } + } + line_processed[i_next] = true; + i_line_current = i_next; + poly.points.push_back(lines[i_line_current].b); + } + end_of_poly: + out.push_back(std::move(poly)); + } + + // 3) Scale the polygons back into world, shrink slightly and remove collinear points. + for (Polygon &poly : out) { + for (Point &p : poly.points) { +#if 0 + p.x() = (p.x() + 1) * pixel_size + left_bottom.x(); + p.y() = (p.y() + 1) * pixel_size + left_bottom.y(); +#else + p *= pixel_size; + p += left_bottom; +#endif + } + // Shrink the contour slightly, so if the same contour gets discretized and simplified again, one will get the same result. + // Remove collinear points. + Points pts; + pts.reserve(poly.points.size()); + for (size_t j = 0; j < poly.points.size(); ++ j) { + size_t j0 = (j == 0) ? poly.points.size() - 1 : j - 1; + size_t j2 = (j + 1 == poly.points.size()) ? 0 : j + 1; + Point v = poly.points[j2] - poly.points[j0]; + if (v(0) != 0 && v(1) != 0) { + // This is a corner point. Copy it to the output contour. + Point p = poly.points[j]; + p(1) += (v(0) < 0) ? - offset : offset; + p(0) += (v(1) > 0) ? - offset : offset; + pts.push_back(p); + } + } + poly.points = std::move(pts); + } + return out; +} +#endif // SUPPORT_USE_AGG_RASTERIZER + +PrintObjectSupportMaterial::PrintObjectSupportMaterial(const PrintObject *object, const SlicingParameters &slicing_params) : + m_print_config (&object->print()->config()), + m_object_config (&object->config()), + m_slicing_params (slicing_params), + m_support_params (*object) +{ +} + +void PrintObjectSupportMaterial::generate(PrintObject &object) +{ + BOOST_LOG_TRIVIAL(info) << "Support generator - Start"; + + coordf_t max_object_layer_height = 0.; + for (size_t i = 0; i < object.layer_count(); ++ i) + max_object_layer_height = std::max(max_object_layer_height, object.layers()[i]->height); + + // Layer instances will be allocated by std::deque and they will be kept until the end of this function call. + // The layers will be referenced by various LayersPtr (of type std::vector) + SupportGeneratorLayerStorage layer_storage; + + BOOST_LOG_TRIVIAL(info) << "Support generator - Creating top contacts"; + + // Per object layer projection of the object below the layer into print bed. + std::vector buildplate_covered = this->buildplate_covered(object); + + // Determine the top contact surfaces of the support, defined as: + // contact = overhangs - clearance + margin + // This method is responsible for identifying what contact surfaces + // should the support material expose to the object in order to guarantee + // that it will be effective, regardless of how it's built below. + // If raft is to be generated, the 1st top_contact layer will contain the 1st object layer silhouette without holes. + SupportGeneratorLayersPtr top_contacts = this->top_contact_layers(object, buildplate_covered, layer_storage); + if (top_contacts.empty()) + // Nothing is supported, no supports are generated. + return; + +#ifdef SLIC3R_DEBUG + static int iRun = 0; + iRun ++; + for (const SupportGeneratorLayer *layer : top_contacts) + Slic3r::SVG::export_expolygons( + debug_out_path("support-top-contacts-%d-%lf.svg", iRun, layer->print_z), + union_ex(layer->polygons)); +#endif /* SLIC3R_DEBUG */ + + BOOST_LOG_TRIVIAL(info) << "Support generator - Creating bottom contacts"; + + // Determine the bottom contact surfaces of the supports over the top surfaces of the object. + // Depending on whether the support is soluble or not, the contact layer thickness is decided. + // layer_support_areas contains the per object layer support areas. These per object layer support areas + // may get merged and trimmed by this->generate_base_layers() if the support layers are not synchronized with object layers. + std::vector layer_support_areas; + SupportGeneratorLayersPtr bottom_contacts = this->bottom_contact_layers_and_layer_support_areas( + object, top_contacts, buildplate_covered, + layer_storage, layer_support_areas); + +#ifdef SLIC3R_DEBUG + for (size_t layer_id = 0; layer_id < object.layers().size(); ++ layer_id) + Slic3r::SVG::export_expolygons( + debug_out_path("support-areas-%d-%lf.svg", iRun, object.layers()[layer_id]->print_z), + union_ex(layer_support_areas[layer_id])); +#endif /* SLIC3R_DEBUG */ + + BOOST_LOG_TRIVIAL(info) << "Support generator - Creating intermediate layers - indices"; + + // Allocate empty layers between the top / bottom support contact layers + // as placeholders for the base and intermediate support layers. + // The layers may or may not be synchronized with the object layers, depending on the configuration. + // For example, a single nozzle multi material printing will need to generate a waste tower, which in turn + // wastes less material, if there are as little tool changes as possible. + SupportGeneratorLayersPtr intermediate_layers = this->raft_and_intermediate_support_layers( + object, bottom_contacts, top_contacts, layer_storage); + + this->trim_support_layers_by_object(object, top_contacts, m_slicing_params.gap_support_object, m_slicing_params.gap_object_support, m_support_params.gap_xy); + +#ifdef SLIC3R_DEBUG + for (const SupportGeneratorLayer *layer : top_contacts) + Slic3r::SVG::export_expolygons( + debug_out_path("support-top-contacts-trimmed-by-object-%d-%lf.svg", iRun, layer->print_z), + union_ex(layer->polygons)); +#endif + + BOOST_LOG_TRIVIAL(info) << "Support generator - Creating base layers"; + + // Fill in intermediate layers between the top / bottom support contact layers, trim them by the object. + this->generate_base_layers(object, bottom_contacts, top_contacts, intermediate_layers, layer_support_areas); + +#ifdef SLIC3R_DEBUG + for (SupportGeneratorLayersPtr::const_iterator it = intermediate_layers.begin(); it != intermediate_layers.end(); ++ it) + Slic3r::SVG::export_expolygons( + debug_out_path("support-base-layers-%d-%lf.svg", iRun, (*it)->print_z), + union_ex((*it)->polygons)); +#endif /* SLIC3R_DEBUG */ + + BOOST_LOG_TRIVIAL(info) << "Support generator - Trimming top contacts by bottom contacts"; + + // Because the top and bottom contacts are thick slabs, they may overlap causing over extrusion + // and unwanted strong bonds to the object. + // Rather trim the top contacts by their overlapping bottom contacts to leave a gap instead of over extruding + // top contacts over the bottom contacts. + this->trim_top_contacts_by_bottom_contacts(object, bottom_contacts, top_contacts); + + + BOOST_LOG_TRIVIAL(info) << "Support generator - Creating interfaces"; + + // Propagate top / bottom contact layers to generate interface layers + // and base interface layers (for soluble interface / non souble base only) + SupportGeneratorLayersPtr empty_layers; + auto [interface_layers, base_interface_layers] = FFFSupport::generate_interface_layers( + *m_object_config, m_support_params, bottom_contacts, top_contacts, empty_layers, empty_layers, intermediate_layers, layer_storage); + + BOOST_LOG_TRIVIAL(info) << "Support generator - Creating raft"; + + // If raft is to be generated, the 1st top_contact layer will contain the 1st object layer silhouette with holes filled. + // There is also a 1st intermediate layer containing bases of support columns. + // Inflate the bases of the support columns and create the raft base under the object. + SupportGeneratorLayersPtr raft_layers = FFFSupport::generate_raft_base(object, m_support_params, m_slicing_params, top_contacts, interface_layers, base_interface_layers, intermediate_layers, layer_storage); + +#ifdef SLIC3R_DEBUG + for (const SupportGeneratorLayer *l : interface_layers) + Slic3r::SVG::export_expolygons( + debug_out_path("support-interface-layers-%d-%lf.svg", iRun, l->print_z), + union_ex(l->polygons)); + for (const SupportGeneratorLayer *l : base_interface_layers) + Slic3r::SVG::export_expolygons( + debug_out_path("support-base-interface-layers-%d-%lf.svg", iRun, l->print_z), + union_ex(l->polygons)); +#endif // SLIC3R_DEBUG + +/* + // Clip with the pillars. + if (! shape.empty()) { + this->clip_with_shape(interface, shape); + this->clip_with_shape(base, shape); + } +*/ + + BOOST_LOG_TRIVIAL(info) << "Support generator - Creating layers"; + +// For debugging purposes, one may want to show only some of the support extrusions. +// raft_layers.clear(); +// bottom_contacts.clear(); +// top_contacts.clear(); +// intermediate_layers.clear(); +// interface_layers.clear(); + +#ifdef SLIC3R_DEBUG + SupportGeneratorLayersPtr layers_sorted = +#endif // SLIC3R_DEBUG + generate_support_layers(object, raft_layers, bottom_contacts, top_contacts, intermediate_layers, interface_layers, base_interface_layers); + + BOOST_LOG_TRIVIAL(info) << "Support generator - Generating tool paths"; + +#if 0 // #ifdef SLIC3R_DEBUG + { + size_t layer_id = 0; + for (int i = 0; i < int(layers_sorted.size());) { + // Find the last layer with roughly the same print_z, find the minimum layer height of all. + // Due to the floating point inaccuracies, the print_z may not be the same even if in theory they should. + int j = i + 1; + coordf_t zmax = layers_sorted[i]->print_z + EPSILON; + bool empty = layers_sorted[i]->polygons.empty(); + for (; j < layers_sorted.size() && layers_sorted[j]->print_z <= zmax; ++j) + if (!layers_sorted[j]->polygons.empty()) + empty = false; + if (!empty) { + export_print_z_polygons_to_svg( + debug_out_path("support-%d-%lf-before.svg", iRun, layers_sorted[i]->print_z).c_str(), + layers_sorted.data() + i, j - i); + export_print_z_polygons_and_extrusions_to_svg( + debug_out_path("support-w-fills-%d-%lf-before.svg", iRun, layers_sorted[i]->print_z).c_str(), + layers_sorted.data() + i, j - i, + *object.support_layers()[layer_id]); + ++layer_id; + } + i = j; + } + } +#endif /* SLIC3R_DEBUG */ + + // Generate the actual toolpaths and save them into each layer. + generate_support_toolpaths(object.support_layers(), *m_object_config, m_support_params, m_slicing_params, raft_layers, bottom_contacts, top_contacts, intermediate_layers, interface_layers, base_interface_layers); + +#ifdef SLIC3R_DEBUG + { + size_t layer_id = 0; + for (int i = 0; i < int(layers_sorted.size());) { + // Find the last layer with roughly the same print_z, find the minimum layer height of all. + // Due to the floating point inaccuracies, the print_z may not be the same even if in theory they should. + int j = i + 1; + coordf_t zmax = layers_sorted[i]->print_z + EPSILON; + bool empty = layers_sorted[i]->polygons.empty(); + for (; j < layers_sorted.size() && layers_sorted[j]->print_z <= zmax; ++j) + if (! layers_sorted[j]->polygons.empty()) + empty = false; + if (! empty) { + export_print_z_polygons_to_svg( + debug_out_path("support-%d-%lf.svg", iRun, layers_sorted[i]->print_z).c_str(), + layers_sorted.data() + i, j - i); + export_print_z_polygons_and_extrusions_to_svg( + debug_out_path("support-w-fills-%d-%lf.svg", iRun, layers_sorted[i]->print_z).c_str(), + layers_sorted.data() + i, j - i, + *object.support_layers()[layer_id]); + ++layer_id; + } + i = j; + } + } +#endif /* SLIC3R_DEBUG */ + + BOOST_LOG_TRIVIAL(info) << "Support generator - End"; +} + +// Collect all polygons of all regions in a layer with a given surface type. +Polygons collect_region_slices_by_type(const Layer &layer, SurfaceType surface_type) +{ + // 1) Count the new polygons first. + size_t n_polygons_new = 0; + for (const LayerRegion *region : layer.regions()) + for (const Surface &surface : region->slices.surfaces) + if (surface.surface_type == surface_type) + n_polygons_new += surface.expolygon.holes.size() + 1; + // 2) Collect the new polygons. + Polygons out; + out.reserve(n_polygons_new); + for (const LayerRegion *region : layer.regions()) + for (const Surface &surface : region->slices.surfaces) + if (surface.surface_type == surface_type) + polygons_append(out, surface.expolygon); + return out; +} + +// Collect outer contours of all slices of this layer. +// This is useful for calculating the support base with holes filled. +Polygons collect_slices_outer(const Layer &layer) +{ + Polygons out; + out.reserve(out.size() + layer.lslices.size()); + for (const ExPolygon &expoly : layer.lslices) + out.emplace_back(expoly.contour); + return out; +} + +struct SupportGridParams { + SupportGridParams(const PrintObjectConfig &object_config, const Flow &support_material_flow) : + style(object_config.support_style.value), + grid_resolution(object_config.support_base_pattern_spacing.value + support_material_flow.spacing()), + support_angle(Geometry::deg2rad(object_config.support_angle.value)), + extrusion_width(support_material_flow.spacing()), + // support_material_closing_radius(object_config.support_material_closing_radius.value), + support_material_closing_radius(2.0), + expansion_to_slice(coord_t(support_material_flow.scaled_spacing() / 2 + 5)), + expansion_to_propagate(-3) {} + + SupportMaterialStyle style; + double grid_resolution; + double support_angle; + double extrusion_width; + double support_material_closing_radius; + coord_t expansion_to_slice; + coord_t expansion_to_propagate; +}; + +class SupportGridPattern +{ +public: + SupportGridPattern( + // Support islands, to be stretched into a grid. Already trimmed with min(lower_layer_offset, m_gap_xy) + const Polygons *support_polygons, + // Trimming polygons, to trim the stretched support islands. support_polygons were already trimmed with trimming_polygons. + const Polygons *trimming_polygons, + const SupportGridParams ¶ms) : + m_style(params.style), + m_support_polygons(support_polygons), m_trimming_polygons(trimming_polygons), + m_support_spacing(params.grid_resolution), m_support_angle(params.support_angle), + m_extrusion_width(params.extrusion_width), + m_support_material_closing_radius(params.support_material_closing_radius) + { + switch (m_style) { + case smsGrid: + { + // Prepare the grid data, it will be reused when extracting support structures. + if (m_support_angle != 0.) { + // Create a copy of the rotated contours. + m_support_polygons_rotated = *support_polygons; + m_trimming_polygons_rotated = *trimming_polygons; + m_support_polygons = &m_support_polygons_rotated; + m_trimming_polygons = &m_trimming_polygons_rotated; + polygons_rotate(m_support_polygons_rotated, - params.support_angle); + polygons_rotate(m_trimming_polygons_rotated, - params.support_angle); + } + + // Resolution of the sparse support grid. + coord_t grid_resolution = coord_t(scale_(m_support_spacing)); + BoundingBox bbox = get_extents(*m_support_polygons); + bbox.offset(20); + // Align the bounding box with the sparse support grid. + bbox.align_to_grid(grid_resolution); + + #ifdef SUPPORT_USE_AGG_RASTERIZER + m_bbox = bbox; + // Oversample the grid to avoid leaking of supports through or around the object walls. + int extrusion_width_scaled = scale_(params.extrusion_width); + int oversampling = std::clamp(int(scale_(m_support_spacing) / (extrusion_width_scaled + 100)), 1, 8); + m_pixel_size = std::max(extrusion_width_scaled + 21, scale_(m_support_spacing / oversampling)); + // Add one empty column / row boundaries. + m_bbox.offset(m_pixel_size); + // Grid size fitting the support polygons plus one pixel boundary around the polygons. + Vec2i grid_size_raw(int(ceil((m_bbox.max.x() - m_bbox.min.x()) / m_pixel_size)), + int(ceil((m_bbox.max.y() - m_bbox.min.y()) / m_pixel_size))); + // Overlay macro blocks of (oversampling x oversampling) over the grid. + Vec2i grid_blocks((grid_size_raw.x() + oversampling - 1 - 2) / oversampling, + (grid_size_raw.y() + oversampling - 1 - 2) / oversampling); + // and resize the grid to fit the macro blocks + one pixel boundary. + m_grid_size = grid_blocks * oversampling + Vec2i(2, 2); + assert(m_grid_size.x() >= grid_size_raw.x()); + assert(m_grid_size.y() >= grid_size_raw.y()); + m_grid2 = rasterize_polygons(m_grid_size, m_pixel_size, m_bbox.min, *m_support_polygons); + + seed_fill_block(m_grid2, m_grid_size, + dilate_trimming_region(rasterize_polygons(m_grid_size, m_pixel_size, m_bbox.min, *m_trimming_polygons), m_grid_size), + grid_blocks, oversampling); + + #ifdef SLIC3R_DEBUG + { + static int irun; + Slic3r::png::write_gray_to_file_scaled(debug_out_path("support-rasterizer-%d.png", irun++), m_grid_size.x(), m_grid_size.y(), m_grid2.data(), 4); + } + #endif // SLIC3R_DEBUG + + #else // SUPPORT_USE_AGG_RASTERIZER + // Create an EdgeGrid, initialize it with projection, initialize signed distance field. + m_grid.set_bbox(bbox); + m_grid.create(*m_support_polygons, grid_resolution); + #if 0 + if (m_grid.has_intersecting_edges()) { + // EdgeGrid fails to produce valid signed distance function for self-intersecting polygons. + m_support_polygons_rotated = simplify_polygons(*m_support_polygons); + m_support_polygons = &m_support_polygons_rotated; + m_grid.set_bbox(bbox); + m_grid.create(*m_support_polygons, grid_resolution); + // assert(! m_grid.has_intersecting_edges()); + printf("SupportGridPattern: fixing polygons with intersection %s\n", + m_grid.has_intersecting_edges() ? "FAILED" : "SUCCEEDED"); + } + #endif + m_grid.calculate_sdf(); + #endif // SUPPORT_USE_AGG_RASTERIZER + break; + } + + case smsSnug: + default: + // nothing to prepare + break; + } + } + + // Extract polygons from the grid, offsetted by offset_in_grid, + // and trim the extracted polygons by trimming_polygons. + // Trimming by the trimming_polygons may split the extracted polygons into pieces. + // Remove all the pieces, which do not contain any of the island_samples. + Polygons extract_support(const coord_t offset_in_grid, bool fill_holes +#ifdef SLIC3R_DEBUG + , const char *step_name, int iRun, size_t layer_id, double print_z +#endif + ) + { + switch (m_style) { + case smsGrid: + { + #ifdef SUPPORT_USE_AGG_RASTERIZER + Polygons support_polygons_simplified = contours_simplified(m_grid_size, m_pixel_size, m_bbox.min, m_grid2, offset_in_grid, fill_holes); + #else // SUPPORT_USE_AGG_RASTERIZER + // Generate islands, so each island may be tested for overlap with island_samples. + assert(std::abs(2 * offset_in_grid) < m_grid.resolution()); + Polygons support_polygons_simplified = m_grid.contours_simplified(offset_in_grid, fill_holes); + #endif // SUPPORT_USE_AGG_RASTERIZER + + ExPolygons islands = diff_ex(support_polygons_simplified, *m_trimming_polygons); + + // Extract polygons, which contain some of the island_samples. + Polygons out; + + // Sample a single point per input support polygon, keep it as a reference to maintain corresponding + // polygons if ever these polygons get split into parts by the trimming polygons. + // As offset_in_grid may be negative, m_support_polygons may stick slightly outside of islands. + // Trim ti with islands. + Points samples = island_samples( + offset_in_grid > 0 ? + // Expanding, thus m_support_polygons are all inside islands. + union_ex(*m_support_polygons) : + // Shrinking, thus m_support_polygons may be trimmed a tiny bit by islands. + intersection_ex(*m_support_polygons, islands)); + + std::vector> samples_inside; + for (ExPolygon &island : islands) { + BoundingBox bbox = get_extents(island.contour); + // Samples are sorted lexicographically. + auto it_lower = std::lower_bound(samples.begin(), samples.end(), Point(bbox.min - Point(1, 1))); + auto it_upper = std::upper_bound(samples.begin(), samples.end(), Point(bbox.max + Point(1, 1))); + samples_inside.clear(); + for (auto it = it_lower; it != it_upper; ++ it) + if (bbox.contains(*it)) + samples_inside.push_back(std::make_pair(*it, false)); + if (! samples_inside.empty()) { + // For all samples_inside count the boundary crossing. + for (size_t i_contour = 0; i_contour <= island.holes.size(); ++ i_contour) { + Polygon &contour = (i_contour == 0) ? island.contour : island.holes[i_contour - 1]; + Points::const_iterator i = contour.points.begin(); + Points::const_iterator j = contour.points.end() - 1; + for (; i != contour.points.end(); j = i ++) { + //FIXME this test is not numerically robust. Particularly, it does not handle horizontal segments at y == point(1) well. + // Does the ray with y == point(1) intersect this line segment? + for (auto &sample_inside : samples_inside) { + if (((*i)(1) > sample_inside.first(1)) != ((*j)(1) > sample_inside.first(1))) { + double x1 = (double)sample_inside.first(0); + double x2 = (double)(*i)(0) + (double)((*j)(0) - (*i)(0)) * (double)(sample_inside.first(1) - (*i)(1)) / (double)((*j)(1) - (*i)(1)); + if (x1 < x2) + sample_inside.second = !sample_inside.second; + } + } + } + } + // If any of the sample is inside this island, add this island to the output. + for (auto &sample_inside : samples_inside) + if (sample_inside.second) { + polygons_append(out, std::move(island)); + island.clear(); + break; + } + } + } + + #ifdef SLIC3R_DEBUG + BoundingBox bbox = get_extents(*m_trimming_polygons); + if (! islands.empty()) + bbox.merge(get_extents(islands)); + if (!out.empty()) + bbox.merge(get_extents(out)); + if (!support_polygons_simplified.empty()) + bbox.merge(get_extents(support_polygons_simplified)); + SVG svg(debug_out_path("extract_support_from_grid_trimmed-%s-%d-%d-%lf.svg", step_name, iRun, layer_id, print_z).c_str(), bbox); + svg.draw(union_ex(support_polygons_simplified), "gray", 0.25f); + svg.draw(islands, "red", 0.5f); + svg.draw(union_ex(out), "green", 0.5f); + svg.draw(union_ex(*m_support_polygons), "blue", 0.5f); + svg.draw_outline(islands, "red", "red", scale_(0.05)); + svg.draw_outline(union_ex(out), "green", "green", scale_(0.05)); + svg.draw_outline(union_ex(*m_support_polygons), "blue", "blue", scale_(0.05)); + for (const Point &pt : samples) + svg.draw(pt, "black", coord_t(scale_(0.15))); + svg.Close(); + #endif /* SLIC3R_DEBUG */ + + if (m_support_angle != 0.) + polygons_rotate(out, m_support_angle); + return out; + } + case smsTreeSlim: + case smsTreeStrong: + case smsTreeHybrid: + case smsOrganic: +// assert(false); + [[fallthrough]]; + case smsSnug: + // Merge the support polygons by applying morphological closing and inwards smoothing. + auto closing_distance = scaled(m_support_material_closing_radius); + auto smoothing_distance = scaled(m_extrusion_width); +#ifdef SLIC3R_DEBUG + SVG::export_expolygons(debug_out_path("extract_support_from_grid_trimmed-%s-%d-%d-%lf.svg", step_name, iRun, layer_id, print_z), + { { { diff_ex(expand(*m_support_polygons, closing_distance), closing(*m_support_polygons, closing_distance, SUPPORT_SURFACES_OFFSET_PARAMETERS)) }, { "closed", "blue", 0.5f } }, + { { union_ex(smooth_outward(closing(*m_support_polygons, closing_distance, SUPPORT_SURFACES_OFFSET_PARAMETERS), smoothing_distance)) }, { "regularized", "red", "black", "", scaled(0.1f), 0.5f } }, + { { union_ex(*m_support_polygons) }, { "src", "green", 0.5f } }, + }); +#endif /* SLIC3R_DEBUG */ + //FIXME do we want to trim with the object here? On one side the columns will be thinner, on the other side support interfaces may disappear for snug supports. + // return diff(smooth_outward(closing(*m_support_polygons, closing_distance, SUPPORT_SURFACES_OFFSET_PARAMETERS), smoothing_distance), *m_trimming_polygons); + return smooth_outward(closing(*m_support_polygons, closing_distance, SUPPORT_SURFACES_OFFSET_PARAMETERS), smoothing_distance); + } + assert(false); + return Polygons(); + } + +#if defined(SLIC3R_DEBUG) && ! defined(SUPPORT_USE_AGG_RASTERIZER) + void serialize(const std::string &path) + { + FILE *file = ::fopen(path.c_str(), "wb"); + ::fwrite(&m_support_spacing, 8, 1, file); + ::fwrite(&m_support_angle, 8, 1, file); + uint32_t n_polygons = m_support_polygons->size(); + ::fwrite(&n_polygons, 4, 1, file); + for (uint32_t i = 0; i < n_polygons; ++ i) { + const Polygon &poly = (*m_support_polygons)[i]; + uint32_t n_points = poly.size(); + ::fwrite(&n_points, 4, 1, file); + for (uint32_t j = 0; j < n_points; ++ j) { + const Point &pt = poly.points[j]; + ::fwrite(&pt.x(), sizeof(coord_t), 1, file); + ::fwrite(&pt.y(), sizeof(coord_t), 1, file); + } + } + n_polygons = m_trimming_polygons->size(); + ::fwrite(&n_polygons, 4, 1, file); + for (uint32_t i = 0; i < n_polygons; ++ i) { + const Polygon &poly = (*m_trimming_polygons)[i]; + uint32_t n_points = poly.size(); + ::fwrite(&n_points, 4, 1, file); + for (uint32_t j = 0; j < n_points; ++ j) { + const Point &pt = poly.points[j]; + ::fwrite(&pt.x(), sizeof(coord_t), 1, file); + ::fwrite(&pt.y(), sizeof(coord_t), 1, file); + } + } + ::fclose(file); + } + + static SupportGridPattern deserialize(const std::string &path, int which = -1) + { + SupportGridPattern out; + out.deserialize_(path, which); + return out; + } + + // Deserialization constructor + bool deserialize_(const std::string &path, int which = -1) + { + FILE *file = ::fopen(path.c_str(), "rb"); + if (file == nullptr) + return false; + + m_support_polygons = &m_support_polygons_deserialized; + m_trimming_polygons = &m_trimming_polygons_deserialized; + + ::fread(&m_support_spacing, 8, 1, file); + ::fread(&m_support_angle, 8, 1, file); + //FIXME + //m_support_spacing *= 0.01 / 2; + uint32_t n_polygons; + ::fread(&n_polygons, 4, 1, file); + m_support_polygons_deserialized.reserve(n_polygons); + int32_t scale = 1; + for (uint32_t i = 0; i < n_polygons; ++ i) { + Polygon poly; + uint32_t n_points; + ::fread(&n_points, 4, 1, file); + poly.points.reserve(n_points); + for (uint32_t j = 0; j < n_points; ++ j) { + coord_t x, y; + ::fread(&x, sizeof(coord_t), 1, file); + ::fread(&y, sizeof(coord_t), 1, file); + poly.points.emplace_back(Point(x * scale, y * scale)); + } + if (which == -1 || which == i) + m_support_polygons_deserialized.emplace_back(std::move(poly)); + printf("Polygon %d, area: %lf\n", i, area(poly.points)); + } + ::fread(&n_polygons, 4, 1, file); + m_trimming_polygons_deserialized.reserve(n_polygons); + for (uint32_t i = 0; i < n_polygons; ++ i) { + Polygon poly; + uint32_t n_points; + ::fread(&n_points, 4, 1, file); + poly.points.reserve(n_points); + for (uint32_t j = 0; j < n_points; ++ j) { + coord_t x, y; + ::fread(&x, sizeof(coord_t), 1, file); + ::fread(&y, sizeof(coord_t), 1, file); + poly.points.emplace_back(Point(x * scale, y * scale)); + } + m_trimming_polygons_deserialized.emplace_back(std::move(poly)); + } + ::fclose(file); + + m_support_polygons_deserialized = simplify_polygons(m_support_polygons_deserialized, false); + //m_support_polygons_deserialized = to_polygons(union_ex(m_support_polygons_deserialized, false)); + + // Create an EdgeGrid, initialize it with projection, initialize signed distance field. + coord_t grid_resolution = coord_t(scale_(m_support_spacing)); + BoundingBox bbox = get_extents(*m_support_polygons); + bbox.offset(20); + bbox.align_to_grid(grid_resolution); + m_grid.set_bbox(bbox); + m_grid.create(*m_support_polygons, grid_resolution); + m_grid.calculate_sdf(); + return true; + } + + const Polygons& support_polygons() const { return *m_support_polygons; } + const Polygons& trimming_polygons() const { return *m_trimming_polygons; } + const EdgeGrid::Grid& grid() const { return m_grid; } + +#endif // defined(SLIC3R_DEBUG) && ! defined(SUPPORT_USE_AGG_RASTERIZER) + +private: + SupportGridPattern() {} + SupportGridPattern& operator=(const SupportGridPattern &rhs); + +#ifdef SUPPORT_USE_AGG_RASTERIZER + // Dilate the trimming region (unmask the boundary pixels). + static std::vector dilate_trimming_region(const std::vector &trimming, const Vec2i &grid_size) + { + std::vector dilated(trimming.size(), 0); + for (int r = 1; r + 1 < grid_size.y(); ++ r) + for (int c = 1; c + 1 < grid_size.x(); ++ c) { + //int addr = c + r * m_grid_size.x(); + // 4-neighborhood is not sufficient. + // dilated[addr] = trimming[addr] != 0 && trimming[addr - 1] != 0 && trimming[addr + 1] != 0 && trimming[addr - m_grid_size.x()] != 0 && trimming[addr + m_grid_size.x()] != 0; + // 8-neighborhood + int addr = c + (r - 1) * grid_size.x(); + bool b = trimming[addr - 1] != 0 && trimming[addr] != 0 && trimming[addr + 1] != 0; + addr += grid_size.x(); + b = b && trimming[addr - 1] != 0 && trimming[addr] != 0 && trimming[addr + 1] != 0; + addr += grid_size.x(); + b = b && trimming[addr - 1] != 0 && trimming[addr] != 0 && trimming[addr + 1] != 0; + dilated[addr - grid_size.x()] = b; + } + return dilated; + } + + // Seed fill each of the (oversampling x oversampling) block up to the dilated trimming region. + static void seed_fill_block(std::vector &grid, Vec2i grid_size, const std::vector &trimming,const Vec2i &grid_blocks, int oversampling) + { + int size = oversampling; + int stride = grid_size.x(); + for (int block_r = 0; block_r < grid_blocks.y(); ++ block_r) + for (int block_c = 0; block_c < grid_blocks.x(); ++ block_c) { + // Propagate the support pixels over the macro cell up to the trimming mask. + int addr = block_c * size + 1 + (block_r * size + 1) * stride; + unsigned char *grid_data = grid.data() + addr; + const unsigned char *mask_data = trimming.data() + addr; + // Top to bottom propagation. + #define PROPAGATION_STEP(offset) \ + do { \ + int addr = r * stride + c; \ + int addr2 = addr + offset; \ + if (grid_data[addr2] && ! mask_data[addr] && ! mask_data[addr2]) \ + grid_data[addr] = 1; \ + } while (0); + for (int r = 0; r < size; ++ r) { + if (r > 0) + for (int c = 0; c < size; ++ c) + PROPAGATION_STEP(- stride); + for (int c = 1; c < size; ++ c) + PROPAGATION_STEP(- 1); + for (int c = size - 2; c >= 0; -- c) + PROPAGATION_STEP(+ 1); + } + // Bottom to top propagation. + for (int r = size - 2; r >= 0; -- r) { + for (int c = 0; c < size; ++ c) + PROPAGATION_STEP(+ stride); + for (int c = 1; c < size; ++ c) + PROPAGATION_STEP(- 1); + for (int c = size - 2; c >= 0; -- c) + PROPAGATION_STEP(+ 1); + } + #undef PROPAGATION_STEP + } + } +#endif // SUPPORT_USE_AGG_RASTERIZER + +#if 0 + // Get some internal point of an expolygon, to be used as a representative + // sample to test, whether this island is inside another island. + //FIXME this was quick, but not sufficiently robust. + static Point island_sample(const ExPolygon &expoly) + { + // Find the lowest point lexicographically. + const Point *pt_min = &expoly.contour.points.front(); + for (size_t i = 1; i < expoly.contour.points.size(); ++ i) + if (expoly.contour.points[i] < *pt_min) + pt_min = &expoly.contour.points[i]; + + // Lowest corner will always be convex, in worst case denegenerate with zero angle. + const Point &p1 = (pt_min == &expoly.contour.points.front()) ? expoly.contour.points.back() : *(pt_min - 1); + const Point &p2 = *pt_min; + const Point &p3 = (pt_min == &expoly.contour.points.back()) ? expoly.contour.points.front() : *(pt_min + 1); + + Vector v = (p3 - p2) + (p1 - p2); + double l2 = double(v(0))*double(v(0))+double(v(1))*double(v(1)); + if (l2 == 0.) + return p2; + double coef = 20. / sqrt(l2); + return Point(p2(0) + coef * v(0), p2(1) + coef * v(1)); + } +#endif + + // Sample one internal point per expolygon. + // FIXME this is quite an overkill to calculate a complete offset just to get a single point, but at least it is robust. + static Points island_samples(const ExPolygons &expolygons) + { + Points pts; + pts.reserve(expolygons.size()); + for (const ExPolygon &expoly : expolygons) + if (expoly.contour.points.size() > 2) { + #if 0 + pts.push_back(island_sample(expoly)); + #else + Polygons polygons = offset(expoly, - 20.f); + for (const Polygon &poly : polygons) + if (! poly.points.empty()) { + // Take a small fixed number of samples of this polygon for robustness. + int num_points = int(poly.points.size()); + int num_samples = std::min(num_points, 4); + int stride = num_points / num_samples; + for (int i = 0; i < num_points; i += stride) + pts.push_back(poly.points[i]); + break; + } + #endif + } + // Sort the points lexicographically, so a binary search could be used to locate points inside a bounding box. + std::sort(pts.begin(), pts.end()); + return pts; + } + + SupportMaterialStyle m_style; + const Polygons *m_support_polygons; + const Polygons *m_trimming_polygons; + Polygons m_support_polygons_rotated; + Polygons m_trimming_polygons_rotated; + // Angle in radians, by which the whole support is rotated. + coordf_t m_support_angle; + // X spacing of the support lines parallel with the Y axis. + coordf_t m_support_spacing; + coordf_t m_extrusion_width; + // For snug supports: Morphological closing of support areas. + coordf_t m_support_material_closing_radius; + +#ifdef SUPPORT_USE_AGG_RASTERIZER + Vec2i m_grid_size; + double m_pixel_size; + BoundingBox m_bbox; + std::vector m_grid2; +#else // SUPPORT_USE_AGG_RASTERIZER + Slic3r::EdgeGrid::Grid m_grid; +#endif // SUPPORT_USE_AGG_RASTERIZER + +#ifdef SLIC3R_DEBUG + // support for deserialization of m_support_polygons, m_trimming_polygons + Polygons m_support_polygons_deserialized; + Polygons m_trimming_polygons_deserialized; +#endif /* SLIC3R_DEBUG */ +}; + +namespace SupportMaterialInternal { + static inline bool has_bridging_perimeters(const ExtrusionLoop &loop) + { + for (const ExtrusionPath &ep : loop.paths) + if (ep.role() == ExtrusionRole::erOverhangPerimeter && ! ep.polyline.empty()) + return int(ep.size()) >= (ep.is_closed() ? 3 : 2); + return false; + } + static bool has_bridging_perimeters(const ExtrusionEntityCollection &perimeters) + { + for (const ExtrusionEntity *ee : perimeters.entities) { + if (ee->is_collection()) { + for (const ExtrusionEntity *ee2 : static_cast(ee)->entities) { + assert(! ee2->is_collection()); + if (ee2->is_loop()) + if (has_bridging_perimeters(*static_cast(ee2))) + return true; + } + } else if (ee->is_loop() && has_bridging_perimeters(*static_cast(ee))) + return true; + } + return false; + } + static bool has_bridging_fills(const ExtrusionEntityCollection &fills) + { + for (const ExtrusionEntity *ee : fills.entities) { + assert(ee->is_collection()); + for (const ExtrusionEntity *ee2 : static_cast(ee)->entities) { + assert(! ee2->is_collection()); + assert(! ee2->is_loop()); + if (ee2->role() == ExtrusionRole::erBridgeInfill) + return true; + } + } + return false; + } + static bool has_bridging_extrusions(const Layer &layer) + { + for (const LayerRegion *region : layer.regions()) { + if (SupportMaterialInternal::has_bridging_perimeters(region->perimeters)) + return true; + if (region->fill_surfaces.has(stBottomBridge) && has_bridging_fills(region->fills)) + return true; + } + return false; + } + + static inline void collect_bridging_perimeter_areas(const ExtrusionLoop &loop, const float expansion_scaled, Polygons &out) + { + assert(expansion_scaled >= 0.f); + for (const ExtrusionPath &ep : loop.paths) + if (ep.role() == ExtrusionRole::erOverhangPerimeter && ! ep.polyline.empty()) { + float exp = 0.5f * (float)scale_(ep.width) + expansion_scaled; + if (ep.is_closed()) { + if (ep.size() >= 3) { + // This is a complete loop. + // Add the outer contour first. + Polygon poly; + poly.points = ep.polyline.points; + poly.points.pop_back(); + if (poly.area() < 0) + poly.reverse(); + polygons_append(out, offset(poly, exp, SUPPORT_SURFACES_OFFSET_PARAMETERS)); + Polygons holes = offset(poly, - exp, SUPPORT_SURFACES_OFFSET_PARAMETERS); + polygons_reverse(holes); + polygons_append(out, holes); + } + } else if (ep.size() >= 2) { + // Offset the polyline. + polygons_append(out, offset(ep.polyline, exp, SUPPORT_SURFACES_OFFSET_PARAMETERS)); + } + } + } + static void collect_bridging_perimeter_areas(const ExtrusionEntityCollection &perimeters, const float expansion_scaled, Polygons &out) + { + for (const ExtrusionEntity *ee : perimeters.entities) { + if (ee->is_collection()) { + for (const ExtrusionEntity *ee2 : static_cast(ee)->entities) { + assert(! ee2->is_collection()); + if (ee2->is_loop()) + collect_bridging_perimeter_areas(*static_cast(ee2), expansion_scaled, out); + } + } else if (ee->is_loop()) + collect_bridging_perimeter_areas(*static_cast(ee), expansion_scaled, out); + } + } +} + +std::vector PrintObjectSupportMaterial::buildplate_covered(const PrintObject &object) const +{ + // Build support on a build plate only? If so, then collect and union all the surfaces below the current layer. + // Unfortunately this is an inherently serial process. + const bool buildplate_only = this->build_plate_only(); + std::vector buildplate_covered; + if (buildplate_only) { + BOOST_LOG_TRIVIAL(debug) << "PrintObjectSupportMaterial::buildplate_covered() - start"; + buildplate_covered.assign(object.layers().size(), Polygons()); + //FIXME prefix sum algorithm, parallelize it! Parallelization will also likely be more numerically stable. + for (size_t layer_id = 1; layer_id < object.layers().size(); ++ layer_id) { + const Layer &lower_layer = *object.layers()[layer_id-1]; + // Merge the new slices with the preceding slices. + // Apply the safety offset to the newly added polygons, so they will connect + // with the polygons collected before, + // but don't apply the safety offset during the union operation as it would + // inflate the polygons over and over. + Polygons &covered = buildplate_covered[layer_id]; + covered = buildplate_covered[layer_id - 1]; + polygons_append(covered, offset(lower_layer.lslices, scale_(0.01))); + covered = union_(covered); + } + BOOST_LOG_TRIVIAL(debug) << "PrintObjectSupportMaterial::buildplate_covered() - end"; + } + return buildplate_covered; +} + +struct SupportAnnotations +{ + SupportAnnotations(const PrintObject &object, const std::vector &buildplate_covered) : + enforcers_layers(object.slice_support_enforcers()), + blockers_layers(object.slice_support_blockers()), + buildplate_covered(buildplate_covered) + { + // Append custom supports. + object.project_and_append_custom_facets(false, EnforcerBlockerType::ENFORCER, enforcers_layers); + object.project_and_append_custom_facets(false, EnforcerBlockerType::BLOCKER, blockers_layers); + } + + std::vector enforcers_layers; + std::vector blockers_layers; + const std::vector& buildplate_covered; +}; + +struct SlicesMarginCache +{ + float offset { -1 }; + // Trimming polygons, including possibly the "build plate only" mask. + Polygons polygons; + // Trimming polygons, without the "build plate only" mask. If empty, use polygons. + Polygons all_polygons; +}; + +// Tuple: overhang_polygons, contact_polygons, enforcer_polygons, no_interface_offset +// no_interface_offset: minimum of external perimeter widths +static inline std::tuple detect_overhangs( + const Layer &layer, + const size_t layer_id, + const Polygons &lower_layer_polygons, + const PrintConfig &print_config, + const PrintObjectConfig &object_config, + SupportAnnotations &annotations, + SlicesMarginCache &slices_margin, + const double gap_xy +#ifdef SLIC3R_DEBUG + , size_t iRun +#endif // SLIC3R_DEBUG + ) +{ + // Snug overhang polygons. + Polygons overhang_polygons; + // Expanded for stability, trimmed by gap_xy. + Polygons contact_polygons; + // Enforcers projected to overhangs, trimmed + Polygons enforcer_polygons; + + const bool support_auto = object_config.enable_support.value && is_auto(object_config.support_type.value); + const bool buildplate_only = ! annotations.buildplate_covered.empty(); + // If user specified a custom angle threshold, convert it to radians. + // Zero means automatic overhang detection. + // +1 makes the threshold inclusive + double thresh_angle = object_config.support_threshold_angle.value > 0 ? object_config.support_threshold_angle.value + 1 : 0; + thresh_angle = std::min(thresh_angle, 89.); // BBS should be smaller than 90 + const double threshold_rad = Geometry::deg2rad(thresh_angle); + float no_interface_offset = 0.f; + + if (layer_id == 0) + { + // This is the first object layer, so the object is being printed on a raft and + // we're here just to get the object footprint for the raft. +#if 0 + // The following line was filling excessive holes in the raft, see GH #430 + overhang_polygons = collect_slices_outer(layer); +#else + // Don't fill in the holes. The user may apply a higher raft_expansion if one wants a better 1st layer adhesion. + overhang_polygons = to_polygons(layer.lslices); +#endif + // Expand for better stability. + contact_polygons = object_config.raft_expansion.value > 0 ? expand(overhang_polygons, scaled(object_config.raft_expansion.value)) : overhang_polygons; + } + else if (! layer.regions().empty()) + { + // Generate overhang / contact_polygons for non-raft layers. + const Layer &lower_layer = *layer.lower_layer; + const bool has_enforcer = ! annotations.enforcers_layers.empty() && ! annotations.enforcers_layers[layer_id].empty(); + + // Cache support trimming polygons derived from lower layer polygons, possible merged with "on build plate only" trimming polygons. + auto slices_margin_update = + [&slices_margin, &lower_layer, &lower_layer_polygons, buildplate_only, has_enforcer, &annotations, layer_id] + (float slices_margin_offset, float no_interface_offset) { + if (slices_margin.offset != slices_margin_offset) { + slices_margin.offset = slices_margin_offset; + slices_margin.polygons = (slices_margin_offset == 0.f) ? + lower_layer_polygons : + // What is the purpose of no_interface_offset? Likely to not trim the contact layer by lower layer regions that are too thin to extrude? + offset2(lower_layer.lslices, -no_interface_offset * 0.5f, slices_margin_offset + no_interface_offset * 0.5f, SUPPORT_SURFACES_OFFSET_PARAMETERS); + if (buildplate_only && !annotations.buildplate_covered[layer_id].empty()) { + if (has_enforcer) + // Make a backup of trimming polygons before enforcing "on build plate only". + slices_margin.all_polygons = slices_margin.polygons; + // Trim the inflated contact surfaces by the top surfaces as well. + slices_margin.polygons = union_(slices_margin.polygons, annotations.buildplate_covered[layer_id]); + } + } + }; + + no_interface_offset = std::accumulate(layer.regions().begin(), layer.regions().end(), FLT_MAX, + [](float acc, const LayerRegion *layerm) { return std::min(acc, float(layerm->flow(frExternalPerimeter).scaled_width())); }); + + float lower_layer_offset = 0; + for (LayerRegion *layerm : layer.regions()) { + // Extrusion width accounts for the roundings of the extrudates. + // It is the maximum widh of the extrudate. + float fw = float(layerm->flow(frExternalPerimeter).scaled_width()); + lower_layer_offset = + (layer_id < (size_t)object_config.enforce_support_layers.value) ? + // Enforce a full possible support, ignore the overhang angle. + 0.f : + (threshold_rad > 0. ? + // Overhang defined by an angle. + float(scale_(lower_layer.height / tan(threshold_rad))) : + // Overhang defined by half the extrusion width. + 0.5f * fw); + // Overhang polygons for this layer and region. + Polygons diff_polygons; + Polygons layerm_polygons = to_polygons(layerm->slices.surfaces); + if (lower_layer_offset == 0.f) { + // Support everything. + diff_polygons = diff(layerm_polygons, lower_layer_polygons); + if (buildplate_only) { + // Don't support overhangs above the top surfaces. + // This step is done before the contact surface is calculated by growing the overhang region. + diff_polygons = diff(diff_polygons, annotations.buildplate_covered[layer_id]); + } + } else if (support_auto) { + // Get the regions needing a suport, collapse very tiny spots. + //FIXME cache the lower layer offset if this layer has multiple regions. +#if 0 + //FIXME this solution will trigger stupid supports for sharp corners, see GH #4874 + diff_polygons = opening( + diff(layerm_polygons, + // Likely filtering out thin regions from the lower layer, that will not be covered by perimeters, thus they + // are not supporting this layer. + // However this may lead to a situation where regions at the current layer that are narrow thus not extrudable will generate unnecessary supports. + // For example, see GH issue #3094 + opening(lower_layer_polygons, 0.5f * fw, lower_layer_offset + 0.5f * fw, SUPPORT_SURFACES_OFFSET_PARAMETERS)), + //FIXME This opening is targeted to reduce very thin regions to support, but it may lead to + // no support at all for not so steep overhangs. + 0.1f * fw); +#else + diff_polygons = + diff(layerm_polygons, + expand(lower_layer_polygons, lower_layer_offset, SUPPORT_SURFACES_OFFSET_PARAMETERS)); +#endif + if (buildplate_only && ! annotations.buildplate_covered[layer_id].empty()) { + // Don't support overhangs above the top surfaces. + // This step is done before the contact surface is calculated by growing the overhang region. + diff_polygons = diff(diff_polygons, annotations.buildplate_covered[layer_id]); + } + if (! diff_polygons.empty()) { + // Offset the support regions back to a full overhang, restrict them to the full overhang. + // This is done to increase size of the supporting columns below, as they are calculated by + // propagating these contact surfaces downwards. + diff_polygons = diff( + intersection(expand(diff_polygons, lower_layer_offset, SUPPORT_SURFACES_OFFSET_PARAMETERS), layerm_polygons), + lower_layer_polygons); + } + //FIXME add user defined filtering here based on minimal area or minimum radius or whatever. + } + + if (diff_polygons.empty()) + continue; + + // Apply the "support blockers". + if (! annotations.blockers_layers.empty() && ! annotations.blockers_layers[layer_id].empty()) { + // Expand the blocker a bit. Custom blockers produce strips + // spanning just the projection between the two slices. + // Subtracting them as they are may leave unwanted narrow + // residues of diff_polygons that would then be supported. + diff_polygons = diff(diff_polygons, + expand(union_(annotations.blockers_layers[layer_id]), float(1000.*SCALED_EPSILON))); + } + + #ifdef SLIC3R_DEBUG + { + ::Slic3r::SVG svg(debug_out_path("support-top-contacts-raw-run%d-layer%d-region%d.svg", + iRun, layer_id, + std::find_if(layer.regions().begin(), layer.regions().end(), [layerm](const LayerRegion* other){return other == layerm;}) - layer.regions().begin()), + get_extents(diff_polygons)); + Slic3r::ExPolygons expolys = union_ex(diff_polygons); + svg.draw(expolys); + } + #endif /* SLIC3R_DEBUG */ + + // if (object_config.dont_support_bridges) + // //FIXME Expensive, potentially not precise enough. Misses gap fill extrusions, which bridge. + // remove_bridges_from_contacts(print_config, lower_layer, *layerm, fw, diff_polygons); + + if (diff_polygons.empty()) + continue; + + #ifdef SLIC3R_DEBUG + Slic3r::SVG::export_expolygons( + debug_out_path("support-top-contacts-filtered-run%d-layer%d-region%d-z%f.svg", + iRun, layer_id, + std::find_if(layer.regions().begin(), layer.regions().end(), [layerm](const LayerRegion* other){return other == layerm;}) - layer.regions().begin(), + layer.print_z), + union_ex(diff_polygons)); + #endif /* SLIC3R_DEBUG */ + + //FIXME the overhang_polygons are used to construct the support towers as well. + //if (this->has_contact_loops()) + // Store the exact contour of the overhang for the contact loops. + polygons_append(overhang_polygons, diff_polygons); + + // Let's define the required contact area by using a max gap of half the upper + // extrusion width and extending the area according to the configured margin. + // We increment the area in steps because we don't want our support to overflow + // on the other side of the object (if it's very thin). + { + //FIMXE 1) Make the offset configurable, 2) Make the Z span configurable. + //FIXME one should trim with the layer span colliding with the support layer, this layer + // may be lower than lower_layer, so the support area needed may need to be actually bigger! + // For the same reason, the non-bridging support area may be smaller than the bridging support area! + slices_margin_update(std::min(lower_layer_offset, float(scale_(gap_xy))), no_interface_offset); + // Offset the contact polygons outside. +#if 0 + for (size_t i = 0; i < NUM_MARGIN_STEPS; ++ i) { + diff_polygons = diff( + offset( + diff_polygons, + scaled(SUPPORT_MATERIAL_MARGIN / NUM_MARGIN_STEPS), + ClipperLib::jtRound, + // round mitter limit + scale_(0.05)), + slices_margin.polygons); + } +#else + diff_polygons = diff(diff_polygons, slices_margin.polygons); +#endif + } + polygons_append(contact_polygons, diff_polygons); + } // for each layer.region + + if (has_enforcer) + if (const Polygons &enforcer_polygons_src = annotations.enforcers_layers[layer_id]; ! enforcer_polygons_src.empty()) { + // Enforce supports (as if with 90 degrees of slope) for the regions covered by the enforcer meshes. + #ifdef SLIC3R_DEBUG + ExPolygons enforcers_united = union_ex(enforcer_polygons_src); + #endif // SLIC3R_DEBUG + enforcer_polygons = diff(intersection(layer.lslices, enforcer_polygons_src), + // Inflate just a tiny bit to avoid intersection of the overhang areas with the object. + expand(lower_layer_polygons, 0.05f * no_interface_offset, SUPPORT_SURFACES_OFFSET_PARAMETERS)); + #ifdef SLIC3R_DEBUG + SVG::export_expolygons(debug_out_path("support-top-contacts-enforcers-run%d-layer%d-z%f.svg", iRun, layer_id, layer.print_z), + { { layer.lslices, { "layer.lslices", "gray", 0.2f } }, + { { union_ex(lower_layer_polygons) }, { "lower_layer_polygons", "green", 0.5f } }, + { enforcers_united, { "enforcers", "blue", 0.5f } }, + { { union_safety_offset_ex(enforcer_polygons) }, { "new_contacts", "red", "black", "", scaled(0.1f), 0.5f } } }); + #endif /* SLIC3R_DEBUG */ + if (! enforcer_polygons.empty()) { + polygons_append(overhang_polygons, enforcer_polygons); + slices_margin_update(std::min(lower_layer_offset, float(scale_(gap_xy))), no_interface_offset); + polygons_append(contact_polygons, diff(enforcer_polygons, slices_margin.all_polygons.empty() ? slices_margin.polygons : slices_margin.all_polygons)); + } + } + } + + return std::make_tuple(std::move(overhang_polygons), std::move(contact_polygons), std::move(enforcer_polygons), no_interface_offset); +} + +// Allocate one, possibly two support contact layers. +// For "thick" overhangs, one support layer will be generated to support normal extrusions, the other to support the "thick" extrusions. +static inline std::pair new_contact_layer( + const PrintConfig &print_config, + const PrintObjectConfig &object_config, + const SlicingParameters &slicing_params, + const coordf_t support_layer_height_min, + const Layer &layer, + SupportGeneratorLayerStorage &layer_storage) +{ + double print_z, bottom_z, height; + SupportGeneratorLayer* bridging_layer = nullptr; + assert(layer.id() >= slicing_params.raft_layers()); + size_t layer_id = layer.id() - slicing_params.raft_layers(); + + if (layer_id == 0) { + // This is a raft contact layer sitting directly on the print bed. + assert(slicing_params.has_raft()); + print_z = slicing_params.raft_contact_top_z; + bottom_z = slicing_params.raft_interface_top_z; + height = slicing_params.contact_raft_layer_height; + } else if (slicing_params.soluble_interface) { + // Align the contact surface height with a layer immediately below the supported layer. + // Interface layer will be synchronized with the object. + print_z = layer.bottom_z(); + height = layer.lower_layer->height; + bottom_z = (layer_id == 1) ? slicing_params.object_print_z_min : layer.lower_layer->lower_layer->print_z; + } else { + print_z = layer.bottom_z() - slicing_params.gap_support_object; + bottom_z = print_z; + height = 0.; + // Ignore this contact area if it's too low. + // Don't want to print a layer below the first layer height as it may not stick well. + //FIXME there may be a need for a single layer support, then one may decide to print it either as a bottom contact or a top contact + // and it may actually make sense to do it with a thinner layer than the first layer height. + if (print_z < slicing_params.first_print_layer_height - EPSILON) { + // This contact layer is below the first layer height, therefore not printable. Don't support this surface. + return std::pair(nullptr, nullptr); + } + const bool has_raft = slicing_params.raft_layers() > 1; + const coordf_t min_print_z = has_raft ? slicing_params.raft_contact_top_z : slicing_params.first_print_layer_height; + if (print_z < min_print_z + support_layer_height_min) { + // Align the layer with the 1st layer height or the raft contact layer. + // With raft active, any contact layer below the raft_contact_top_z will be brought to raft_contact_top_z to extend the raft area. + print_z = min_print_z; + bottom_z = has_raft ? slicing_params.raft_interface_top_z : 0; + height = has_raft ? slicing_params.contact_raft_layer_height : min_print_z; + } else { + // Don't know the height of the top contact layer yet. The top contact layer is printed with a normal flow and + // its height will be set adaptively later on. + } + + // Contact layer will be printed with a normal flow, but + // it will support layers printed with a bridging flow. + if (object_config.thick_bridges && SupportMaterialInternal::has_bridging_extrusions(layer)) { + coordf_t bridging_height = 0.; + for (const LayerRegion* region : layer.regions()) + bridging_height += region->region().bridging_height_avg(print_config); + bridging_height /= coordf_t(layer.regions().size()); + coordf_t bridging_print_z = layer.print_z - bridging_height - slicing_params.gap_support_object; + if (bridging_print_z >= min_print_z) { + // Not below the first layer height means this layer is printable. + if (print_z < min_print_z + support_layer_height_min) { + // Align the layer with the 1st layer height or the raft contact layer. + bridging_print_z = min_print_z; + } + if (bridging_print_z < print_z - EPSILON) { + // Allocate the new layer. + bridging_layer = &layer_storage.allocate(SupporLayerType::TopContact); + bridging_layer->idx_object_layer_above = layer_id; + bridging_layer->print_z = bridging_print_z; + if (bridging_print_z == slicing_params.first_print_layer_height) { + bridging_layer->bottom_z = 0; + bridging_layer->height = slicing_params.first_print_layer_height; + } else { + // Don't know the height yet. + bridging_layer->bottom_z = bridging_print_z; + bridging_layer->height = 0; + } + } + } + } + } + + SupportGeneratorLayer &new_layer = layer_storage.allocate(SupporLayerType::TopContact); + new_layer.idx_object_layer_above = layer_id; + new_layer.print_z = print_z; + new_layer.bottom_z = bottom_z; + new_layer.height = height; + return std::make_pair(&new_layer, bridging_layer); +} + +static inline void fill_contact_layer( + SupportGeneratorLayer &new_layer, + size_t layer_id, + const SlicingParameters &slicing_params, + const PrintObjectConfig &object_config, + const SlicesMarginCache &slices_margin, + const Polygons &overhang_polygons, + const Polygons &contact_polygons, + const Polygons &enforcer_polygons, + const Polygons &lower_layer_polygons, + const Flow &support_material_flow, + float no_interface_offset +#ifdef SLIC3R_DEBUG + , size_t iRun, + const Layer &layer +#endif // SLIC3R_DEBUG + ) +{ + const SupportGridParams grid_params(object_config, support_material_flow); + + Polygons lower_layer_polygons_for_dense_interface_cache; + auto lower_layer_polygons_for_dense_interface = [&lower_layer_polygons_for_dense_interface_cache, &lower_layer_polygons, no_interface_offset]() -> const Polygons& { + if (lower_layer_polygons_for_dense_interface_cache.empty()) + lower_layer_polygons_for_dense_interface_cache = + //FIXME no_interface_offset * 0.6f offset is not quite correct, one shall derive it based on an angle thus depending on layer height. + opening(lower_layer_polygons, no_interface_offset * 0.5f, no_interface_offset * (0.6f + 0.5f), SUPPORT_SURFACES_OFFSET_PARAMETERS); + return lower_layer_polygons_for_dense_interface_cache; + }; + + // Stretch support islands into a grid, trim them. + SupportGridPattern support_grid_pattern(&contact_polygons, &slices_margin.polygons, grid_params); + // 1) Contact polygons will be projected down. To keep the interface and base layers from growing, return a contour a tiny bit smaller than the grid cells. + new_layer.contact_polygons = std::make_unique(support_grid_pattern.extract_support(grid_params.expansion_to_propagate, true +#ifdef SLIC3R_DEBUG + , "top_contact_polygons", iRun, layer_id, layer.print_z +#endif // SLIC3R_DEBUG + )); + // 2) infill polygons, expand them by half the extrusion width + a tiny bit of extra. + bool reduce_interfaces = object_config.support_style.value == smsGrid && layer_id > 0 && !slicing_params.soluble_interface; + if (reduce_interfaces) { + // Reduce the amount of dense interfaces: Do not generate dense interfaces below overhangs with 60% overhang of the extrusions. + Polygons dense_interface_polygons = diff(overhang_polygons, lower_layer_polygons_for_dense_interface()); + if (! dense_interface_polygons.empty()) { + dense_interface_polygons = + diff( + // Regularize the contour. + expand(dense_interface_polygons, no_interface_offset * 0.1f), + slices_margin.polygons); + // Support islands, to be stretched into a grid. + //FIXME The regularization of dense_interface_polygons above may stretch dense_interface_polygons outside of the contact polygons, + // thus some dense interface areas may not get supported. Trim the excess with contact_polygons at the following line. + // See for example GH #4874. + Polygons dense_interface_polygons_trimmed = intersection(dense_interface_polygons, *new_layer.contact_polygons); + // Stretch support islands into a grid, trim them. + SupportGridPattern support_grid_pattern(&dense_interface_polygons_trimmed, &slices_margin.polygons, grid_params); + new_layer.polygons = support_grid_pattern.extract_support(grid_params.expansion_to_slice, false +#ifdef SLIC3R_DEBUG + , "top_contact_polygons2", iRun, layer_id, layer.print_z +#endif // SLIC3R_DEBUG + ); + #ifdef SLIC3R_DEBUG + SVG::export_expolygons(debug_out_path("support-top-contacts-final1-run%d-layer%d-z%f.svg", iRun, layer_id, layer.print_z), + { { { union_ex(lower_layer_polygons) }, { "lower_layer_polygons", "gray", 0.2f } }, + { { union_ex(*new_layer.contact_polygons) }, { "new_layer.contact_polygons", "yellow", 0.5f } }, + { { union_ex(slices_margin.polygons) }, { "slices_margin_cached", "blue", 0.5f } }, + { { union_ex(dense_interface_polygons) }, { "dense_interface_polygons", "green", 0.5f } }, + { { union_safety_offset_ex(new_layer.polygons) }, { "new_layer.polygons", "red", "black", "", scaled(0.1f), 0.5f } } }); + //support_grid_pattern.serialize(debug_out_path("support-top-contacts-final-run%d-layer%d-z%f.bin", iRun, layer_id, layer.print_z)); + SVG::export_expolygons(debug_out_path("support-top-contacts-final2-run%d-layer%d-z%f.svg", iRun, layer_id, layer.print_z), + { { { union_ex(lower_layer_polygons) }, { "lower_layer_polygons", "gray", 0.2f } }, + { { union_ex(*new_layer.contact_polygons) }, { "new_layer.contact_polygons", "yellow", 0.5f } }, + { { union_ex(contact_polygons) }, { "contact_polygons", "blue", 0.5f } }, + { { union_ex(dense_interface_polygons) }, { "dense_interface_polygons", "green", 0.5f } }, + { { union_safety_offset_ex(new_layer.polygons) }, { "new_layer.polygons", "red", "black", "", scaled(0.1f), 0.5f } } }); + #endif /* SLIC3R_DEBUG */ + } + } else { + new_layer.polygons = support_grid_pattern.extract_support(grid_params.expansion_to_slice, true +#ifdef SLIC3R_DEBUG + , "top_contact_polygons3", iRun, layer_id, layer.print_z +#endif // SLIC3R_DEBUG + ); + } + + if (! enforcer_polygons.empty() && ! slices_margin.all_polygons.empty() && layer_id > 0) { + // Support enforcers used together with support enforcers. The support enforcers need to be handled separately from the rest of the support. + + SupportGridPattern support_grid_pattern(&enforcer_polygons, &slices_margin.all_polygons, grid_params); + // 1) Contact polygons will be projected down. To keep the interface and base layers from growing, return a contour a tiny bit smaller than the grid cells. + new_layer.enforcer_polygons = std::make_unique(support_grid_pattern.extract_support(grid_params.expansion_to_propagate, true +#ifdef SLIC3R_DEBUG + , "top_contact_polygons4", iRun, layer_id, layer.print_z +#endif // SLIC3R_DEBUG + )); + Polygons new_polygons; + bool needs_union = ! new_layer.polygons.empty(); + if (reduce_interfaces) { + // 2) infill polygons, expand them by half the extrusion width + a tiny bit of extra. + // Reduce the amount of dense interfaces: Do not generate dense interfaces below overhangs with 60% overhang of the extrusions. + Polygons dense_interface_polygons = diff(enforcer_polygons, lower_layer_polygons_for_dense_interface()); + if (! dense_interface_polygons.empty()) { + dense_interface_polygons = + diff( + // Regularize the contour. + expand(dense_interface_polygons, no_interface_offset * 0.1f), + slices_margin.all_polygons); + // Support islands, to be stretched into a grid. + //FIXME The regularization of dense_interface_polygons above may stretch dense_interface_polygons outside of the contact polygons, + // thus some dense interface areas may not get supported. Trim the excess with contact_polygons at the following line. + // See for example GH #4874. + Polygons dense_interface_polygons_trimmed = intersection(dense_interface_polygons, *new_layer.enforcer_polygons); + SupportGridPattern support_grid_pattern(&dense_interface_polygons_trimmed, &slices_margin.all_polygons, grid_params); + // Extend the polygons to extrude with the contact polygons of support enforcers. + new_polygons = support_grid_pattern.extract_support(grid_params.expansion_to_slice, false + #ifdef SLIC3R_DEBUG + , "top_contact_polygons5", iRun, layer_id, layer.print_z + #endif // SLIC3R_DEBUG + ); + } + } else { + new_polygons = support_grid_pattern.extract_support(grid_params.expansion_to_slice, true + #ifdef SLIC3R_DEBUG + , "top_contact_polygons6", iRun, layer_id, layer.print_z + #endif // SLIC3R_DEBUG + ); + } + append(new_layer.polygons, std::move(new_polygons)); + if (needs_union) + new_layer.polygons = union_(new_layer.polygons); + } + +#ifdef SLIC3R_DEBUG + SVG::export_expolygons(debug_out_path("support-top-contacts-final0-run%d-layer%d-z%f.svg", iRun, layer_id, layer.print_z), + { { { union_ex(lower_layer_polygons) }, { "lower_layer_polygons", "gray", 0.2f } }, + { { union_ex(*new_layer.contact_polygons) }, { "new_layer.contact_polygons", "yellow", 0.5f } }, + { { union_ex(contact_polygons) }, { "contact_polygons", "blue", 0.5f } }, + { { union_ex(overhang_polygons) }, { "overhang_polygons", "green", 0.5f } }, + { { union_safety_offset_ex(new_layer.polygons) }, { "new_layer.polygons", "red", "black", "", scaled(0.1f), 0.5f } } }); +#endif /* SLIC3R_DEBUG */ + + // Even after the contact layer was expanded into a grid, some of the contact islands may be too tiny to be extruded. + // Remove those tiny islands from new_layer.polygons and new_layer.contact_polygons. + + // Store the overhang polygons. + // The overhang polygons are used in the path generator for planning of the contact loops. + // if (this->has_contact_loops()). Compared to "polygons", "overhang_polygons" are snug. + new_layer.overhang_polygons = std::make_unique(std::move(overhang_polygons)); + if (! enforcer_polygons.empty()) + new_layer.enforcer_polygons = std::make_unique(std::move(enforcer_polygons)); +} + +// Merge close contact layers conservatively: If two layers are closer than the minimum allowed print layer height (the min_layer_height parameter), +// the top contact layer is merged into the bottom contact layer. +static void merge_contact_layers(const SlicingParameters &slicing_params, double support_layer_height_min, SupportGeneratorLayersPtr &layers) +{ + // Sort the layers, as one layer may produce bridging and non-bridging contact layers with different print_z. + std::sort(layers.begin(), layers.end(), [](const SupportGeneratorLayer *l1, const SupportGeneratorLayer *l2) { return l1->print_z < l2->print_z; }); + + int i = 0; + int k = 0; + { + // Find the span of layers, which are to be printed at the first layer height. + int j = 0; + for (; j < (int)layers.size() && layers[j]->print_z < slicing_params.first_print_layer_height + support_layer_height_min - EPSILON; ++ j); + if (j > 0) { + // Merge the layers layers (0) to (j - 1) into the layers[0]. + SupportGeneratorLayer &dst = *layers.front(); + for (int u = 1; u < j; ++ u) + dst.merge(std::move(*layers[u])); + // Snap the first layer to the 1st layer height. + dst.print_z = slicing_params.first_print_layer_height; + dst.height = slicing_params.first_print_layer_height; + dst.bottom_z = 0; + ++ k; + } + i = j; + } + for (; i < int(layers.size()); ++ k) { + // Find the span of layers closer than m_support_layer_height_min. + int j = i + 1; + coordf_t zmax = layers[i]->print_z + support_layer_height_min + EPSILON; + for (; j < (int)layers.size() && layers[j]->print_z < zmax; ++ j) ; + if (i + 1 < j) { + // Merge the layers layers (i + 1) to (j - 1) into the layers[i]. + SupportGeneratorLayer &dst = *layers[i]; + for (int u = i + 1; u < j; ++ u) + dst.merge(std::move(*layers[u])); + } + if (k < i) + layers[k] = layers[i]; + i = j; + } + if (k < (int)layers.size()) + layers.erase(layers.begin() + k, layers.end()); +} + +// Generate top contact layers supporting overhangs. +// For a soluble interface material synchronize the layer heights with the object, otherwise leave the layer height undefined. +// If supports over bed surface only are requested, don't generate contact layers over an object. +SupportGeneratorLayersPtr PrintObjectSupportMaterial::top_contact_layers( + const PrintObject &object, const std::vector &buildplate_covered, SupportGeneratorLayerStorage &layer_storage) const +{ +#ifdef SLIC3R_DEBUG + static int iRun = 0; + ++ iRun; + #define SLIC3R_IRUN , iRun +#endif /* SLIC3R_DEBUG */ + + // Slice support enforcers / support blockers. + SupportAnnotations annotations(object, buildplate_covered); + + // Output layers, sorted by top Z. + SupportGeneratorLayersPtr contact_out; + + BOOST_LOG_TRIVIAL(debug) << "PrintObjectSupportMaterial::top_contact_layers() in parallel - start"; + // Determine top contact areas. + // If generating raft only (no support), only calculate top contact areas for the 0th layer. + // If having a raft, start with 0th layer, otherwise with 1st layer. + // Note that layer_id < layer->id when raft_layers > 0 as the layer->id incorporates the raft layers. + // So layer_id == 0 means first object layer and layer->id == 0 means first print layer if there are no explicit raft layers. + size_t num_layers = this->has_support() ? object.layer_count() : 1; + // For each overhang layer, two supporting layers may be generated: One for the overhangs extruded with a bridging flow, + // and the other for the overhangs extruded with a normal flow. + contact_out.assign(num_layers * 2, nullptr); + tbb::parallel_for(tbb::blocked_range(this->has_raft() ? 0 : 1, num_layers), + [this, &object, &annotations, &layer_storage, &contact_out] + (const tbb::blocked_range& range) { + for (size_t layer_id = range.begin(); layer_id < range.end(); ++ layer_id) + { + const Layer &layer = *object.layers()[layer_id]; + Polygons lower_layer_polygons = (layer_id == 0) ? Polygons() : to_polygons(object.layers()[layer_id - 1]->lslices); + SlicesMarginCache slices_margin; + + auto [overhang_polygons, contact_polygons, enforcer_polygons, no_interface_offset] = + detect_overhangs(layer, layer_id, lower_layer_polygons, *m_print_config, *m_object_config, annotations, slices_margin, m_support_params.gap_xy + #ifdef SLIC3R_DEBUG + , iRun + #endif // SLIC3R_DEBUG + ); + + // Now apply the contact areas to the layer where they need to be made. + if (! contact_polygons.empty() || ! overhang_polygons.empty()) { + // Allocate the two empty layers. + auto [new_layer, bridging_layer] = new_contact_layer(*m_print_config, *m_object_config, m_slicing_params, m_support_params.support_layer_height_min, layer, layer_storage); + if (new_layer) { + // Fill the non-bridging layer with polygons. + fill_contact_layer(*new_layer, layer_id, m_slicing_params, + *m_object_config, slices_margin, overhang_polygons, contact_polygons, enforcer_polygons, lower_layer_polygons, + m_support_params.support_material_flow, no_interface_offset + #ifdef SLIC3R_DEBUG + , iRun, layer + #endif // SLIC3R_DEBUG + ); + // Insert new layer even if there is no interface generated: Likely the support angle is not steep enough to require dense interface, + // however generating a sparse support will be useful for the object stability. + // if (! new_layer->polygons.empty()) + contact_out[layer_id * 2] = new_layer; + if (bridging_layer != nullptr) { + bridging_layer->polygons = new_layer->polygons; + bridging_layer->contact_polygons = std::make_unique(*new_layer->contact_polygons); + bridging_layer->overhang_polygons = std::make_unique(*new_layer->overhang_polygons); + if (new_layer->enforcer_polygons) + bridging_layer->enforcer_polygons = std::make_unique(*new_layer->enforcer_polygons); + contact_out[layer_id * 2 + 1] = bridging_layer; + } + } + } + } + }); + + // Compress contact_out, remove the nullptr items. + remove_nulls(contact_out); + + // Merge close contact layers conservatively: If two layers are closer than the minimum allowed print layer height (the min_layer_height parameter), + // the top contact layer is merged into the bottom contact layer. + merge_contact_layers(m_slicing_params, m_support_params.support_layer_height_min, contact_out); + + BOOST_LOG_TRIVIAL(debug) << "PrintObjectSupportMaterial::top_contact_layers() in parallel - end"; + + return contact_out; +} + +// Find the bottom contact layers above the top surfaces of this layer. +static inline SupportGeneratorLayer* detect_bottom_contacts( + const SlicingParameters &slicing_params, + const SupportParameters &support_params, + const PrintObject &object, + const Layer &layer, + // Existing top contact layers, to which this newly created bottom contact layer will be snapped to guarantee a minimum layer height. + const SupportGeneratorLayersPtr &top_contacts, + // First top contact layer index overlapping with this new bottom interface layer. + size_t contact_idx, + // To allocate a new layer from. + SupportGeneratorLayerStorage &layer_storage, + // To trim the support areas above this bottom interface layer with this newly created bottom interface layer. + std::vector &layer_support_areas, + // Support areas projected from top to bottom, starting with top support interfaces. + const Polygons &supports_projected +#ifdef SLIC3R_DEBUG + , size_t iRun + , const Polygons &polygons_new +#endif // SLIC3R_DEBUG + ) +{ + Polygons top = collect_region_slices_by_type(layer, stTop); +#ifdef SLIC3R_DEBUG + SVG::export_expolygons(debug_out_path("support-bottom-layers-raw-%d-%lf.svg", iRun, layer.print_z), + { { { union_ex(top) }, { "top", "blue", 0.5f } }, + { { union_safety_offset_ex(supports_projected) }, { "overhangs", "magenta", 0.5f } }, + { layer.lslices, { "layer.lslices", "green", 0.5f } }, + { { union_safety_offset_ex(polygons_new) }, { "polygons_new", "red", "black", "", scaled(0.1f), 0.5f } } }); +#endif /* SLIC3R_DEBUG */ + + // Now find whether any projection of the contact surfaces above layer.print_z not yet supported by any + // top surfaces above layer.print_z falls onto this top surface. + // Touching are the contact surfaces supported exclusively by this top surfaces. + // Don't use a safety offset as it has been applied during insertion of polygons. + if (top.empty()) + return nullptr; + + Polygons touching = intersection(top, supports_projected); + if (touching.empty()) + return nullptr; + + assert(layer.id() >= slicing_params.raft_layers()); + size_t layer_id = layer.id() - slicing_params.raft_layers(); + + // Allocate a new bottom contact layer. + SupportGeneratorLayer &layer_new = layer_storage.allocate_unguarded(SupporLayerType::BottomContact); + // Grow top surfaces so that interface and support generation are generated + // with some spacing from object - it looks we don't need the actual + // top shapes so this can be done here + //FIXME calculate layer height based on the actual thickness of the layer: + // If the layer is extruded with no bridging flow, support just the normal extrusions. + layer_new.height = slicing_params.soluble_interface ? + // Align the interface layer with the object's layer height. + layer.upper_layer->height : + // Place a bridge flow interface layer or the normal flow interface layer over the top surface. + support_params.support_material_bottom_interface_flow.height(); + layer_new.print_z = slicing_params.soluble_interface ? layer.upper_layer->print_z : + layer.print_z + layer_new.height + slicing_params.gap_object_support; + layer_new.bottom_z = layer.print_z; + layer_new.idx_object_layer_below = layer_id; + layer_new.bridging = !slicing_params.soluble_interface && object.config().thick_bridges; + //FIXME how much to inflate the bottom surface, as it is being extruded with a bridging flow? The following line uses a normal flow. + layer_new.polygons = expand(touching, float(support_params.support_material_flow.scaled_width()), SUPPORT_SURFACES_OFFSET_PARAMETERS); + + if (! slicing_params.soluble_interface) { + // Walk the top surfaces, snap the top of the new bottom surface to the closest top of the top surface, + // so there will be no support surfaces generated with thickness lower than m_support_layer_height_min. + for (size_t top_idx = size_t(std::max(0, contact_idx)); + top_idx < top_contacts.size() && top_contacts[top_idx]->print_z < layer_new.print_z + support_params.support_layer_height_min + EPSILON; + ++ top_idx) { + if (top_contacts[top_idx]->print_z > layer_new.print_z - support_params.support_layer_height_min - EPSILON) { + // A top layer has been found, which is close to the new bottom layer. + coordf_t diff = layer_new.print_z - top_contacts[top_idx]->print_z; + assert(std::abs(diff) <= support_params.support_layer_height_min + EPSILON); + if (diff > 0.) { + // The top contact layer is below this layer. Make the bridging layer thinner to align with the existing top layer. + assert(diff < layer_new.height + EPSILON); + assert(layer_new.height - diff >= support_params.support_layer_height_min - EPSILON); + layer_new.print_z = top_contacts[top_idx]->print_z; + layer_new.height -= diff; + } + else { + // The top contact layer is above this layer. One may either make this layer thicker or thinner. + // By making the layer thicker, one will decrease the number of discrete layers with the price of extruding a bit too thick bridges. + // By making the layer thinner, one adds one more discrete layer. + layer_new.print_z = top_contacts[top_idx]->print_z; + layer_new.height -= diff; + } + break; + } + } + } + +#ifdef SLIC3R_DEBUG + Slic3r::SVG::export_expolygons( + debug_out_path("support-bottom-contacts-%d-%lf.svg", iRun, layer_new.print_z), + union_ex(layer_new.polygons)); +#endif /* SLIC3R_DEBUG */ + + // Trim the already created base layers above the current layer intersecting with the new bottom contacts layer. + //FIXME Maybe this is no more needed, as the overlapping base layers are trimmed by the bottom layers at the final stage? + touching = expand(touching, float(SCALED_EPSILON)); + for (int layer_id_above = layer_id + 1; layer_id_above < int(object.total_layer_count()); ++ layer_id_above) { + const Layer &layer_above = *object.layers()[layer_id_above]; + if (layer_above.print_z > layer_new.print_z - EPSILON) + break; + if (Polygons &above = layer_support_areas[layer_id_above]; ! above.empty()) { +#ifdef SLIC3R_DEBUG + SVG::export_expolygons(debug_out_path("support-support-areas-raw-before-trimming-%d-with-%f-%lf.svg", iRun, layer.print_z, layer_above.print_z), + { { { union_ex(touching) }, { "touching", "blue", 0.5f } }, + { { union_safety_offset_ex(above) }, { "above", "red", "black", "", scaled(0.1f), 0.5f } } }); +#endif /* SLIC3R_DEBUG */ + above = diff(above, touching); +#ifdef SLIC3R_DEBUG + Slic3r::SVG::export_expolygons( + debug_out_path("support-support-areas-raw-after-trimming-%d-with-%f-%lf.svg", iRun, layer.print_z, layer_above.print_z), + union_ex(above)); +#endif /* SLIC3R_DEBUG */ + } + } + + return &layer_new; +} + +// Returns polygons to print + polygons to propagate downwards. +// Called twice: First for normal supports, possibly trimmed by "on build plate only", second for support enforcers not trimmed by "on build plate only". +static inline std::pair project_support_to_grid(const Layer &layer, const SupportGridParams &grid_params, const Polygons &overhangs, Polygons *layer_buildplate_covered +#ifdef SLIC3R_DEBUG + , size_t iRun, size_t layer_id, const char *debug_name +#endif /* SLIC3R_DEBUG */ +) +{ + // Remove the areas that touched from the projection that will continue on next, lower, top surfaces. +// Polygons trimming = union_(to_polygons(layer.slices), touching, true); + Polygons trimming = layer_buildplate_covered ? std::move(*layer_buildplate_covered) : offset(layer.lslices, float(SCALED_EPSILON)); + Polygons overhangs_projection = diff(overhangs, trimming); + +#ifdef SLIC3R_DEBUG + SVG::export_expolygons(debug_out_path("support-support-areas-%s-raw-%d-%lf.svg", debug_name, iRun, layer.print_z), + { { { union_ex(trimming) }, { "trimming", "blue", 0.5f } }, + { { union_safety_offset_ex(overhangs_projection) }, { "overhangs_projection", "red", "black", "", scaled(0.1f), 0.5f } } }); +#endif /* SLIC3R_DEBUG */ + + remove_sticks(overhangs_projection); + remove_degenerate(overhangs_projection); + +#ifdef SLIC3R_DEBUG + SVG::export_expolygons(debug_out_path("support-support-areas-%s-raw-cleaned-%d-%lf.svg", debug_name, iRun, layer.print_z), + { { { union_ex(trimming) }, { "trimming", "blue", 0.5f } }, + { { union_ex(overhangs_projection) }, { "overhangs_projection", "red", "black", "", scaled(0.1f), 0.5f } } }); +#endif /* SLIC3R_DEBUG */ + + SupportGridPattern support_grid_pattern(&overhangs_projection, &trimming, grid_params); + tbb::task_group task_group_inner; + + std::pair out; + + // 1) Cache the slice of a support volume. The support volume is expanded by 1/2 of support material flow spacing + // to allow a placement of suppot zig-zag snake along the grid lines. + task_group_inner.run([&grid_params, &support_grid_pattern, &out +#ifdef SLIC3R_DEBUG + , &layer, layer_id, iRun, debug_name +#endif /* SLIC3R_DEBUG */ + ] { + out.first = support_grid_pattern.extract_support(grid_params.expansion_to_slice, true +#ifdef SLIC3R_DEBUG + , (std::string(debug_name) + "_support_area").c_str(), iRun, layer_id, layer.print_z +#endif // SLIC3R_DEBUG + ); +#ifdef SLIC3R_DEBUG + Slic3r::SVG::export_expolygons( + debug_out_path("support-layer_support_area-gridded-%s-%d-%lf.svg", debug_name, iRun, layer.print_z), + union_ex(out.first)); +#endif /* SLIC3R_DEBUG */ + }); + + // 2) Support polygons will be projected down. To keep the interface and base layers from growing, return a contour a tiny bit smaller than the grid cells. + task_group_inner.run([&grid_params, &support_grid_pattern, &out +#ifdef SLIC3R_DEBUG + , &layer, layer_id, &overhangs_projection, &trimming, iRun, debug_name +#endif /* SLIC3R_DEBUG */ + ] { + out.second = support_grid_pattern.extract_support(grid_params.expansion_to_propagate, true +#ifdef SLIC3R_DEBUG + , "support_projection", iRun, layer_id, layer.print_z +#endif // SLIC3R_DEBUG + ); +#ifdef SLIC3R_DEBUG + Slic3r::SVG::export_expolygons( + debug_out_path("support-projection_new-gridded-%d-%lf.svg", iRun, layer.print_z), + union_ex(out.second)); +#endif /* SLIC3R_DEBUG */ +#ifdef SLIC3R_DEBUG + SVG::export_expolygons(debug_out_path("support-projection_new-gridded-%d-%lf.svg", iRun, layer.print_z), + { { { union_ex(trimming) }, { "trimming", "gray", 0.5f } }, + { { union_safety_offset_ex(overhangs_projection) }, { "overhangs_projection", "blue", 0.5f } }, + { { union_safety_offset_ex(out.second) }, { "projection_new", "red", "black", "", scaled(0.1f), 0.5f } } }); +#endif /* SLIC3R_DEBUG */ + }); + + task_group_inner.wait(); + return out; +} + +// Generate bottom contact layers supporting the top contact layers. +// For a soluble interface material synchronize the layer heights with the object, +// otherwise set the layer height to a bridging flow of a support interface nozzle. +SupportGeneratorLayersPtr PrintObjectSupportMaterial::bottom_contact_layers_and_layer_support_areas( + const PrintObject &object, const SupportGeneratorLayersPtr &top_contacts, std::vector &buildplate_covered, + SupportGeneratorLayerStorage &layer_storage, std::vector &layer_support_areas) const +{ + if (top_contacts.empty()) + return SupportGeneratorLayersPtr(); + +#ifdef SLIC3R_DEBUG + static size_t s_iRun = 0; + size_t iRun = s_iRun ++; +#endif /* SLIC3R_DEBUG */ + + //FIXME higher expansion_to_slice here? why? + //const auto expansion_to_slice = m_support_material_flow.scaled_spacing() / 2 + 25; + const SupportGridParams grid_params(*m_object_config, m_support_params.support_material_flow); + const bool buildplate_only = ! buildplate_covered.empty(); + + // Allocate empty surface areas, one per object layer. + layer_support_areas.assign(object.total_layer_count(), Polygons()); + + // find object top surfaces + // we'll use them to clip our support and detect where does it stick + SupportGeneratorLayersPtr bottom_contacts; + + // There is some support to be built, if there are non-empty top surfaces detected. + // Sum of unsupported contact areas above the current layer.print_z. + Polygons overhangs_projection; + // Sum of unsupported enforcer contact areas above the current layer.print_z. + // Only used if "supports on build plate only" is enabled and both automatic and support enforcers are enabled. + Polygons enforcers_projection; + // Last top contact layer visited when collecting the projection of contact areas. + int contact_idx = int(top_contacts.size()) - 1; + for (int layer_id = int(object.total_layer_count()) - 2; layer_id >= 0; -- layer_id) { + BOOST_LOG_TRIVIAL(trace) << "Support generator - bottom_contact_layers - layer " << layer_id; + const Layer &layer = *object.get_layer(layer_id); + // Collect projections of all contact areas above or at the same level as this top surface. +#ifdef SLIC3R_DEBUG + Polygons polygons_new; + Polygons enforcers_new; +#endif // SLIC3R_DEBUG + for (; contact_idx >= 0 && top_contacts[contact_idx]->print_z > layer.print_z - EPSILON; -- contact_idx) { + SupportGeneratorLayer &top_contact = *top_contacts[contact_idx]; +#ifndef SLIC3R_DEBUG + Polygons polygons_new; + Polygons enforcers_new; +#endif // SLIC3R_DEBUG + // Contact surfaces are expanded away from the object, trimmed by the object. + // Use a slight positive offset to overlap the touching regions. +#if 0 + // Merge and collect the contact polygons. The contact polygons are inflated, but not extended into a grid form. + polygons_append(polygons_new, offset(*top_contact.contact_polygons, SCALED_EPSILON)); + if (top_contact.enforcer_polygons) + polygons_append(enforcers_new, offset(*top_contact.enforcer_polygons, SCALED_EPSILON)); +#else + // Consume the contact_polygons. The contact polygons are already expanded into a grid form, and they are a tiny bit smaller + // than the grid cells. + polygons_append(polygons_new, std::move(*top_contact.contact_polygons)); + if (top_contact.enforcer_polygons) + polygons_append(enforcers_new, std::move(*top_contact.enforcer_polygons)); +#endif + // These are the overhang surfaces. They are touching the object and they are not expanded away from the object. + // Use a slight positive offset to overlap the touching regions. + polygons_append(polygons_new, expand(*top_contact.overhang_polygons, float(SCALED_EPSILON))); + polygons_append(overhangs_projection, union_(polygons_new)); + polygons_append(enforcers_projection, enforcers_new); + } + if (overhangs_projection.empty() && enforcers_projection.empty()) + continue; + + // Overhangs_projection will be filled in asynchronously, move it away. + Polygons overhangs_projection_raw = union_(std::move(overhangs_projection)); + Polygons enforcers_projection_raw = union_(std::move(enforcers_projection)); + + tbb::task_group task_group; + const Polygons &overhangs_for_bottom_contacts = buildplate_only ? enforcers_projection_raw : overhangs_projection_raw; + if (! overhangs_for_bottom_contacts.empty()) + // Find the bottom contact layers above the top surfaces of this layer. + task_group.run([this, &object, &layer, &top_contacts, contact_idx, &layer_storage, &layer_support_areas, &bottom_contacts, &overhangs_for_bottom_contacts + #ifdef SLIC3R_DEBUG + , iRun, &polygons_new + #endif // SLIC3R_DEBUG + ] { + // Find the bottom contact layers above the top surfaces of this layer. + SupportGeneratorLayer *layer_new = detect_bottom_contacts( + m_slicing_params, m_support_params, object, layer, top_contacts, contact_idx, layer_storage, layer_support_areas, overhangs_for_bottom_contacts +#ifdef SLIC3R_DEBUG + , iRun, polygons_new +#endif // SLIC3R_DEBUG + ); + if (layer_new) + bottom_contacts.push_back(layer_new); + }); + + Polygons &layer_support_area = layer_support_areas[layer_id]; + Polygons *layer_buildplate_covered = buildplate_covered.empty() ? nullptr : &buildplate_covered[layer_id]; + // Filtering the propagated support columns to two extrusions, overlapping by maximum 20%. +// float column_propagation_filtering_radius = scaled(0.8 * 0.5 * (m_support_params.support_material_flow.spacing() + m_support_params.support_material_flow.width())); + task_group.run([&grid_params, &overhangs_projection, &overhangs_projection_raw, &layer, &layer_support_area, layer_buildplate_covered /* , column_propagation_filtering_radius */ +#ifdef SLIC3R_DEBUG + , iRun, layer_id +#endif /* SLIC3R_DEBUG */ + ] { + // buildplate_covered[layer_id] will be consumed here. + std::tie(layer_support_area, overhangs_projection) = project_support_to_grid(layer, grid_params, overhangs_projection_raw, layer_buildplate_covered +#ifdef SLIC3R_DEBUG + , iRun, layer_id, "general" +#endif /* SLIC3R_DEBUG */ + ); + // When propagating support areas downwards, stop propagating the support column if it becomes too thin to be printable. + //overhangs_projection = opening(overhangs_projection, column_propagation_filtering_radius); + }); + + Polygons layer_support_area_enforcers; + if (! enforcers_projection.empty()) + // Project the enforcers polygons downwards, don't trim them with the "buildplate only" polygons. + task_group.run([&grid_params, &enforcers_projection, &enforcers_projection_raw, &layer, &layer_support_area_enforcers +#ifdef SLIC3R_DEBUG + , iRun, layer_id +#endif /* SLIC3R_DEBUG */ + ]{ + std::tie(layer_support_area_enforcers, enforcers_projection) = project_support_to_grid(layer, grid_params, enforcers_projection_raw, nullptr +#ifdef SLIC3R_DEBUG + , iRun, layer_id, "enforcers" +#endif /* SLIC3R_DEBUG */ + ); + }); + + task_group.wait(); + + if (! layer_support_area_enforcers.empty()) { + if (layer_support_area.empty()) + layer_support_area = std::move(layer_support_area_enforcers); + else + layer_support_area = union_(layer_support_area, layer_support_area_enforcers); + } + } // over all layers downwards + + std::reverse(bottom_contacts.begin(), bottom_contacts.end()); + trim_support_layers_by_object(object, bottom_contacts, m_slicing_params.gap_support_object, m_slicing_params.gap_object_support, m_support_params.gap_xy); + return bottom_contacts; +} + +// Trim the top_contacts layers with the bottom_contacts layers if they overlap, so there would not be enough vertical space for both of them. +void PrintObjectSupportMaterial::trim_top_contacts_by_bottom_contacts( + const PrintObject &object, const SupportGeneratorLayersPtr &bottom_contacts, SupportGeneratorLayersPtr &top_contacts) const +{ + tbb::parallel_for(tbb::blocked_range(0, int(top_contacts.size())), + [&bottom_contacts, &top_contacts](const tbb::blocked_range& range) { + int idx_bottom_overlapping_first = -2; + // For all top contact layers, counting downwards due to the way idx_higher_or_equal caches the last index to avoid repeated binary search. + for (int idx_top = range.end() - 1; idx_top >= range.begin(); -- idx_top) { + SupportGeneratorLayer &layer_top = *top_contacts[idx_top]; + // Find the first bottom layer overlapping with layer_top. + idx_bottom_overlapping_first = idx_lower_or_equal(bottom_contacts, idx_bottom_overlapping_first, [&layer_top](const SupportGeneratorLayer *layer_bottom){ return layer_bottom->bottom_print_z() - EPSILON <= layer_top.bottom_z; }); + // For all top contact layers overlapping with the thick bottom contact layer: + for (int idx_bottom_overlapping = idx_bottom_overlapping_first; idx_bottom_overlapping >= 0; -- idx_bottom_overlapping) { + const SupportGeneratorLayer &layer_bottom = *bottom_contacts[idx_bottom_overlapping]; + assert(layer_bottom.bottom_print_z() - EPSILON <= layer_top.bottom_z); + if (layer_top.print_z < layer_bottom.print_z + EPSILON) { + // Layers overlap. Trim layer_top with layer_bottom. + layer_top.polygons = diff(layer_top.polygons, layer_bottom.polygons); + } else + break; + } + } + }); +} + +SupportGeneratorLayersPtr PrintObjectSupportMaterial::raft_and_intermediate_support_layers( + const PrintObject &object, + const SupportGeneratorLayersPtr &bottom_contacts, + const SupportGeneratorLayersPtr &top_contacts, + SupportGeneratorLayerStorage &layer_storage) const +{ + SupportGeneratorLayersPtr intermediate_layers; + + // Collect and sort the extremes (bottoms of the top contacts and tops of the bottom contacts). + SupportGeneratorLayersPtr extremes; + extremes.reserve(top_contacts.size() + bottom_contacts.size()); + for (size_t i = 0; i < top_contacts.size(); ++ i) + // Bottoms of the top contact layers. In case of non-soluble supports, + // the top contact layer thickness is not known yet. + extremes.push_back(top_contacts[i]); + for (size_t i = 0; i < bottom_contacts.size(); ++ i) + // Tops of the bottom contact layers. + extremes.push_back(bottom_contacts[i]); + if (extremes.empty()) + return intermediate_layers; + + auto layer_extreme_lower = [](const SupportGeneratorLayer *l1, const SupportGeneratorLayer *l2) { + coordf_t z1 = l1->extreme_z(); + coordf_t z2 = l2->extreme_z(); + // If the layers are aligned, return the top contact surface first. + return z1 < z2 || (z1 == z2 && l1->layer_type == SupporLayerType::TopContact && l2->layer_type == SupporLayerType::BottomContact); + }; + std::sort(extremes.begin(), extremes.end(), layer_extreme_lower); + + assert(extremes.empty() || + (extremes.front()->extreme_z() > m_slicing_params.raft_interface_top_z - EPSILON && + (m_slicing_params.raft_layers() == 1 || // only raft contact layer + extremes.front()->layer_type == SupporLayerType::TopContact || // first extreme is a top contact layer + extremes.front()->extreme_z() > m_slicing_params.first_print_layer_height - EPSILON))); + + bool synchronize = this->synchronize_layers(); + +#ifdef _DEBUG + // Verify that the extremes are separated by m_support_layer_height_min. + for (size_t i = 1; i < extremes.size(); ++ i) { + assert(extremes[i]->extreme_z() - extremes[i-1]->extreme_z() == 0. || + extremes[i]->extreme_z() - extremes[i-1]->extreme_z() > m_support_params.support_layer_height_min - EPSILON); + assert(extremes[i]->extreme_z() - extremes[i-1]->extreme_z() > 0. || + extremes[i]->layer_type == extremes[i-1]->layer_type || + (extremes[i]->layer_type == SupporLayerType::BottomContact && extremes[i - 1]->layer_type == SupporLayerType::TopContact)); + } +#endif + + // Generate intermediate layers. + // The first intermediate layer is the same as the 1st layer if there is no raft, + // or the bottom of the first intermediate layer is aligned with the bottom of the raft contact layer. + // Intermediate layers are always printed with a normal etrusion flow (non-bridging). + size_t idx_layer_object = 0; + size_t idx_extreme_first = 0; + if (! extremes.empty() && std::abs(extremes.front()->extreme_z() - m_slicing_params.raft_interface_top_z) < EPSILON) { + // This is a raft contact layer, its height has been decided in this->top_contact_layers(). + // Ignore this layer when calculating the intermediate support layers. + assert(extremes.front()->layer_type == SupporLayerType::TopContact); + ++ idx_extreme_first; + } + for (size_t idx_extreme = idx_extreme_first; idx_extreme < extremes.size(); ++ idx_extreme) { + SupportGeneratorLayer *extr2 = extremes[idx_extreme]; + coordf_t extr2z = extr2->extreme_z(); + if (std::abs(extr2z - m_slicing_params.first_print_layer_height) < EPSILON) { + // This is a bottom of a synchronized (or soluble) top contact layer, its height has been decided in this->top_contact_layers(). + assert(extr2->layer_type == SupporLayerType::TopContact); + assert(extr2->bottom_z == m_slicing_params.first_print_layer_height); + assert(extr2->print_z >= m_slicing_params.first_print_layer_height + m_support_params.support_layer_height_min - EPSILON); + if (intermediate_layers.empty() || intermediate_layers.back()->print_z < m_slicing_params.first_print_layer_height) { + SupportGeneratorLayer &layer_new = layer_storage.allocate_unguarded(SupporLayerType::Intermediate); + layer_new.bottom_z = 0.; + layer_new.print_z = m_slicing_params.first_print_layer_height; + layer_new.height = m_slicing_params.first_print_layer_height; + intermediate_layers.push_back(&layer_new); + } + continue; + } + assert(extr2z >= m_slicing_params.raft_interface_top_z + EPSILON); + assert(extr2z >= m_slicing_params.first_print_layer_height + EPSILON); + SupportGeneratorLayer *extr1 = (idx_extreme == idx_extreme_first) ? nullptr : extremes[idx_extreme - 1]; + // Fuse a support layer firmly to the raft top interface (not to the raft contacts). + coordf_t extr1z = (extr1 == nullptr) ? m_slicing_params.raft_interface_top_z : extr1->extreme_z(); + assert(extr2z >= extr1z); + assert(extr2z > extr1z || (extr1 != nullptr && extr2->layer_type == SupporLayerType::BottomContact)); + if (std::abs(extr1z) < EPSILON) { + // This layer interval starts with the 1st layer. Print the 1st layer using the prescribed 1st layer thickness. + // assert(! m_slicing_params.has_raft()); RaftingEdition: unclear where the issue is: assert fails with 1-layer raft & base supports + assert(intermediate_layers.empty() || intermediate_layers.back()->print_z <= m_slicing_params.first_print_layer_height); + // At this point only layers above first_print_layer_heigth + EPSILON are expected as the other cases were captured earlier. + assert(extr2z >= m_slicing_params.first_print_layer_height + EPSILON); + // Generate a new intermediate layer. + SupportGeneratorLayer &layer_new = layer_storage.allocate_unguarded(SupporLayerType::Intermediate); + layer_new.bottom_z = 0.; + layer_new.print_z = extr1z = m_slicing_params.first_print_layer_height; + layer_new.height = extr1z; + intermediate_layers.push_back(&layer_new); + // Continue printing the other layers up to extr2z. + } + coordf_t dist = extr2z - extr1z; + assert(dist >= 0.); + if (dist == 0.) + continue; + // The new layers shall be at least m_support_layer_height_min thick. + assert(dist >= m_support_params.support_layer_height_min - EPSILON); + if (synchronize) { + // Emit support layers synchronized with the object layers. + // Find the first object layer, which has its print_z in this support Z range. + while (idx_layer_object < object.layers().size() && object.layers()[idx_layer_object]->print_z < extr1z + EPSILON) + ++ idx_layer_object; + if (idx_layer_object == 0 && extr1z == m_slicing_params.raft_interface_top_z) { + // Insert one base support layer below the object. + SupportGeneratorLayer &layer_new = layer_storage.allocate_unguarded(SupporLayerType::Intermediate); + layer_new.print_z = m_slicing_params.object_print_z_min; + layer_new.bottom_z = m_slicing_params.raft_interface_top_z; + layer_new.height = layer_new.print_z - layer_new.bottom_z; + intermediate_layers.push_back(&layer_new); + } + // Emit all intermediate support layers synchronized with object layers up to extr2z. + for (; idx_layer_object < object.layers().size() && object.layers()[idx_layer_object]->print_z < extr2z + EPSILON; ++ idx_layer_object) { + SupportGeneratorLayer &layer_new = layer_storage.allocate_unguarded(SupporLayerType::Intermediate); + layer_new.print_z = object.layers()[idx_layer_object]->print_z; + layer_new.height = object.layers()[idx_layer_object]->height; + layer_new.bottom_z = (idx_layer_object > 0) ? object.layers()[idx_layer_object - 1]->print_z : (layer_new.print_z - layer_new.height); + assert(intermediate_layers.empty() || intermediate_layers.back()->print_z < layer_new.print_z + EPSILON); + intermediate_layers.push_back(&layer_new); + } + } else { + // Insert intermediate layers. + size_t n_layers_extra = size_t(ceil(dist / m_slicing_params.max_suport_layer_height)); + assert(n_layers_extra > 0); + coordf_t step = dist / coordf_t(n_layers_extra); + if (extr1 != nullptr && extr1->layer_type == SupporLayerType::TopContact && + extr1->print_z + m_support_params.support_layer_height_min > extr1->bottom_z + step) { + // The bottom extreme is a bottom of a top surface. Ensure that the gap + // between the 1st intermediate layer print_z and extr1->print_z is not too small. + assert(extr1->bottom_z + m_support_params.support_layer_height_min < extr1->print_z + EPSILON); + // Generate the first intermediate layer. + SupportGeneratorLayer &layer_new = layer_storage.allocate_unguarded(SupporLayerType::Intermediate); + layer_new.bottom_z = extr1->bottom_z; + layer_new.print_z = extr1z = extr1->print_z; + layer_new.height = extr1->height; + intermediate_layers.push_back(&layer_new); + dist = extr2z - extr1z; + n_layers_extra = size_t(ceil(dist / m_slicing_params.max_suport_layer_height)); + if (n_layers_extra == 0) + continue; + // Continue printing the other layers up to extr2z. + step = dist / coordf_t(n_layers_extra); + } + if (! m_slicing_params.soluble_interface && extr2->layer_type == SupporLayerType::TopContact) { + // This is a top interface layer, which does not have a height assigned yet. Do it now. + assert(extr2->height == 0.); + assert(extr1z > m_slicing_params.first_print_layer_height - EPSILON); + extr2->height = step; + extr2->bottom_z = extr2z = extr2->print_z - step; + if (-- n_layers_extra == 0) + continue; + } + coordf_t extr2z_large_steps = extr2z; + // Take the largest allowed step in the Z axis until extr2z_large_steps is reached. + for (size_t i = 0; i < n_layers_extra; ++ i) { + SupportGeneratorLayer &layer_new = layer_storage.allocate_unguarded(SupporLayerType::Intermediate); + if (i + 1 == n_layers_extra) { + // Last intermediate layer added. Align the last entered layer with extr2z_large_steps exactly. + layer_new.bottom_z = (i == 0) ? extr1z : intermediate_layers.back()->print_z; + layer_new.print_z = extr2z_large_steps; + layer_new.height = layer_new.print_z - layer_new.bottom_z; + } + else { + // Intermediate layer, not the last added. + layer_new.height = step; + layer_new.bottom_z = extr1z + i * step; + layer_new.print_z = layer_new.bottom_z + step; + } + assert(intermediate_layers.empty() || intermediate_layers.back()->print_z <= layer_new.print_z); + intermediate_layers.push_back(&layer_new); + } + } + } + +#ifdef _DEBUG + for (size_t i = 0; i < top_contacts.size(); ++i) + assert(top_contacts[i]->height > 0.); +#endif /* _DEBUG */ + + return intermediate_layers; +} + +// At this stage there shall be intermediate_layers allocated between bottom_contacts and top_contacts, but they have no polygons assigned. +// Also the bottom/top_contacts shall have a layer thickness assigned already. +void PrintObjectSupportMaterial::generate_base_layers( + const PrintObject &object, + const SupportGeneratorLayersPtr &bottom_contacts, + const SupportGeneratorLayersPtr &top_contacts, + SupportGeneratorLayersPtr &intermediate_layers, + const std::vector &layer_support_areas) const +{ +#ifdef SLIC3R_DEBUG + static int iRun = 0; +#endif /* SLIC3R_DEBUG */ + + if (top_contacts.empty()) + // No top contacts -> no intermediate layers will be produced. + return; + + BOOST_LOG_TRIVIAL(debug) << "PrintObjectSupportMaterial::generate_base_layers() in parallel - start"; + tbb::parallel_for( + tbb::blocked_range(0, intermediate_layers.size()), + [&object, &bottom_contacts, &top_contacts, &intermediate_layers, &layer_support_areas](const tbb::blocked_range& range) { + // index -2 means not initialized yet, -1 means intialized and decremented to 0 and then -1. + int idx_top_contact_above = -2; + int idx_bottom_contact_overlapping = -2; + int idx_object_layer_above = -2; + // Counting down due to the way idx_lower_or_equal caches indices to avoid repeated binary search over the complete sequence. + for (int idx_intermediate = int(range.end()) - 1; idx_intermediate >= int(range.begin()); -- idx_intermediate) + { + BOOST_LOG_TRIVIAL(trace) << "Support generator - generate_base_layers - creating layer " << + idx_intermediate << " of " << intermediate_layers.size(); + SupportGeneratorLayer &layer_intermediate = *intermediate_layers[idx_intermediate]; + // Layers must be sorted by print_z. + assert(idx_intermediate == 0 || layer_intermediate.print_z >= intermediate_layers[idx_intermediate - 1]->print_z); + + // Find a top_contact layer touching the layer_intermediate from above, if any, and collect its polygons into polygons_new. + // New polygons for layer_intermediate. + Polygons polygons_new; + + // Use the precomputed layer_support_areas. "idx_object_layer_above": above means above since the last iteration, not above after this call. + idx_object_layer_above = idx_lower_or_equal(object.layers().begin(), object.layers().end(), idx_object_layer_above, + [&layer_intermediate](const Layer* layer) { return layer->print_z <= layer_intermediate.print_z + EPSILON; }); + + // Polygons to trim polygons_new. + Polygons polygons_trimming; + + // Trimming the base layer with any overlapping top layer. + // Following cases are recognized: + // 1) top.bottom_z >= base.top_z -> No overlap, no trimming needed. + // 2) base.bottom_z >= top.print_z -> No overlap, no trimming needed. + // 3) base.print_z > top.print_z && base.bottom_z >= top.bottom_z -> Overlap, which will be solved inside generate_toolpaths() by reducing the base layer height where it overlaps the top layer. No trimming needed here. + // 4) base.print_z > top.bottom_z && base.bottom_z < top.bottom_z -> Base overlaps with top.bottom_z. This must not happen. + // 5) base.print_z <= top.print_z && base.bottom_z >= top.bottom_z -> Base is fully inside top. Trim base by top. + idx_top_contact_above = idx_lower_or_equal(top_contacts, idx_top_contact_above, + [&layer_intermediate](const SupportGeneratorLayer *layer){ return layer->bottom_z <= layer_intermediate.print_z - EPSILON; }); + // Collect all the top_contact layer intersecting with this layer. + for (int idx_top_contact_overlapping = idx_top_contact_above; idx_top_contact_overlapping >= 0; -- idx_top_contact_overlapping) { + SupportGeneratorLayer &layer_top_overlapping = *top_contacts[idx_top_contact_overlapping]; + if (layer_top_overlapping.print_z < layer_intermediate.bottom_z + EPSILON) + break; + // Base must not overlap with top.bottom_z. + assert(! (layer_intermediate.print_z > layer_top_overlapping.bottom_z + EPSILON && layer_intermediate.bottom_z < layer_top_overlapping.bottom_z - EPSILON)); + if (layer_intermediate.print_z <= layer_top_overlapping.print_z + EPSILON && layer_intermediate.bottom_z >= layer_top_overlapping.bottom_z - EPSILON) + // Base is fully inside top. Trim base by top. + polygons_append(polygons_trimming, layer_top_overlapping.polygons); + } + + if (idx_object_layer_above < 0) { + // layer_support_areas are synchronized with object layers and they contain projections of the contact layers above them. + // This intermediate layer is not above any object layer, thus there is no information in layer_support_areas about + // towers supporting contact layers intersecting the first object layer. Project these contact layers now. + polygons_new = layer_support_areas.front(); + double first_layer_z = object.layers().front()->print_z; + for (int i = idx_top_contact_above + 1; i < int(top_contacts.size()); ++ i) { + SupportGeneratorLayer &contacts = *top_contacts[i]; + if (contacts.print_z > first_layer_z + EPSILON) + break; + assert(contacts.bottom_z > layer_intermediate.print_z - EPSILON); + polygons_append(polygons_new, contacts.polygons); + } + } else + polygons_new = layer_support_areas[idx_object_layer_above]; + + // Trimming the base layer with any overlapping bottom layer. + // Following cases are recognized: + // 1) bottom.bottom_z >= base.top_z -> No overlap, no trimming needed. + // 2) base.bottom_z >= bottom.print_z -> No overlap, no trimming needed. + // 3) base.print_z > bottom.bottom_z && base.bottom_z < bottom.bottom_z -> Overlap, which will be solved inside generate_toolpaths() by reducing the bottom layer height where it overlaps the base layer. No trimming needed here. + // 4) base.print_z > bottom.print_z && base.bottom_z >= bottom.print_z -> Base overlaps with bottom.print_z. This must not happen. + // 5) base.print_z <= bottom.print_z && base.bottom_z >= bottom.bottom_z -> Base is fully inside top. Trim base by top. + idx_bottom_contact_overlapping = idx_lower_or_equal(bottom_contacts, idx_bottom_contact_overlapping, + [&layer_intermediate](const SupportGeneratorLayer *layer){ return layer->bottom_print_z() <= layer_intermediate.print_z - EPSILON; }); + // Collect all the bottom_contacts layer intersecting with this layer. + for (int i = idx_bottom_contact_overlapping; i >= 0; -- i) { + SupportGeneratorLayer &layer_bottom_overlapping = *bottom_contacts[i]; + if (layer_bottom_overlapping.print_z < layer_intermediate.bottom_print_z() + EPSILON) + break; + // Base must not overlap with bottom.top_z. + assert(! (layer_intermediate.print_z > layer_bottom_overlapping.print_z + EPSILON && layer_intermediate.bottom_z < layer_bottom_overlapping.print_z - EPSILON)); + if (layer_intermediate.print_z <= layer_bottom_overlapping.print_z + EPSILON && layer_intermediate.bottom_z >= layer_bottom_overlapping.bottom_print_z() - EPSILON) + // Base is fully inside bottom. Trim base by bottom. + polygons_append(polygons_trimming, layer_bottom_overlapping.polygons); + } + + #ifdef SLIC3R_DEBUG + { + BoundingBox bbox = get_extents(polygons_new); + bbox.merge(get_extents(polygons_trimming)); + ::Slic3r::SVG svg(debug_out_path("support-intermediate-layers-raw-%d-%lf.svg", iRun, layer_intermediate.print_z), bbox); + svg.draw(union_ex(polygons_new), "blue", 0.5f); + svg.draw(to_polylines(polygons_new), "blue"); + svg.draw(union_safety_offset_ex(polygons_trimming), "red", 0.5f); + svg.draw(to_polylines(polygons_trimming), "red"); + } + #endif /* SLIC3R_DEBUG */ + + // Trim the polygons, store them. + if (polygons_trimming.empty()) + layer_intermediate.polygons = std::move(polygons_new); + else + layer_intermediate.polygons = diff( + polygons_new, + polygons_trimming, + ApplySafetyOffset::Yes); // safety offset to merge the touching source polygons + layer_intermediate.layer_type = SupporLayerType::Base; + + #if 0 + // coordf_t fillet_radius_scaled = scale_(m_object_config->support_material_spacing); + // Fillet the base polygons and trim them again with the top, interface and contact layers. + $base->{$i} = diff( + offset2( + $base->{$i}, + $fillet_radius_scaled, + -$fillet_radius_scaled, + # Use a geometric offsetting for filleting. + JT_ROUND, + 0.2*$fillet_radius_scaled), + $trim_polygons, + false); // don't apply the safety offset. + } + #endif + } + }); + BOOST_LOG_TRIVIAL(debug) << "PrintObjectSupportMaterial::generate_base_layers() in parallel - end"; + +#ifdef SLIC3R_DEBUG + for (SupportGeneratorLayersPtr::const_iterator it = intermediate_layers.begin(); it != intermediate_layers.end(); ++it) + ::Slic3r::SVG::export_expolygons( + debug_out_path("support-intermediate-layers-untrimmed-%d-%lf.svg", iRun, (*it)->print_z), + union_ex((*it)->polygons)); + ++ iRun; +#endif /* SLIC3R_DEBUG */ + + this->trim_support_layers_by_object(object, intermediate_layers, m_slicing_params.gap_support_object, m_slicing_params.gap_object_support, m_support_params.gap_xy); +} + +void PrintObjectSupportMaterial::trim_support_layers_by_object( + const PrintObject &object, + SupportGeneratorLayersPtr &support_layers, + const coordf_t gap_extra_above, + const coordf_t gap_extra_below, + const coordf_t gap_xy) const +{ + const float gap_xy_scaled = float(scale_(gap_xy)); + + // Collect non-empty layers to be processed in parallel. + // This is a good idea as pulling a thread from a thread pool for an empty task is expensive. + SupportGeneratorLayersPtr nonempty_layers; + nonempty_layers.reserve(support_layers.size()); + for (size_t idx_layer = 0; idx_layer < support_layers.size(); ++ idx_layer) { + SupportGeneratorLayer *support_layer = support_layers[idx_layer]; + if (! support_layer->polygons.empty() && support_layer->print_z >= m_slicing_params.raft_contact_top_z + EPSILON) + // Non-empty support layer and not a raft layer. + nonempty_layers.push_back(support_layer); + } + + // For all intermediate support layers: + BOOST_LOG_TRIVIAL(debug) << "PrintObjectSupportMaterial::trim_support_layers_by_object() in parallel - start"; + tbb::parallel_for( + tbb::blocked_range(0, nonempty_layers.size()), + [this, &object, &nonempty_layers, gap_extra_above, gap_extra_below, gap_xy_scaled](const tbb::blocked_range& range) { + size_t idx_object_layer_overlapping = size_t(-1); + for (size_t idx_layer = range.begin(); idx_layer < range.end(); ++ idx_layer) { + SupportGeneratorLayer &support_layer = *nonempty_layers[idx_layer]; + // BOOST_LOG_TRIVIAL(trace) << "Support generator - trim_support_layers_by_object - trimmming non-empty layer " << idx_layer << " of " << nonempty_layers.size(); + assert(! support_layer.polygons.empty() && support_layer.print_z >= m_slicing_params.raft_contact_top_z + EPSILON); + // Find the overlapping object layers including the extra above / below gap. + coordf_t z_threshold = support_layer.bottom_print_z() - gap_extra_below + EPSILON; + idx_object_layer_overlapping = idx_higher_or_equal( + object.layers().begin(), object.layers().end(), idx_object_layer_overlapping, + [z_threshold](const Layer *layer){ return layer->print_z >= z_threshold; }); + // Collect all the object layers intersecting with this layer. + Polygons polygons_trimming; + size_t i = idx_object_layer_overlapping; + for (; i < object.layers().size(); ++ i) { + const Layer &object_layer = *object.layers()[i]; + if (object_layer.bottom_z() > support_layer.print_z + gap_extra_above - EPSILON) + break; + polygons_append(polygons_trimming, offset(object_layer.lslices, gap_xy_scaled, SUPPORT_SURFACES_OFFSET_PARAMETERS)); + } + if (! m_slicing_params.soluble_interface && m_object_config->thick_bridges) { + // Collect all bottom surfaces, which will be extruded with a bridging flow. + for (; i < object.layers().size(); ++ i) { + const Layer &object_layer = *object.layers()[i]; + bool some_region_overlaps = false; + for (LayerRegion *region : object_layer.regions()) { + coordf_t bridging_height = region->region().bridging_height_avg(*m_print_config); + if (object_layer.print_z - bridging_height > support_layer.print_z + gap_extra_above - EPSILON) + break; + some_region_overlaps = true; + polygons_append(polygons_trimming, + offset(region->fill_surfaces.filter_by_type(stBottomBridge), gap_xy_scaled, SUPPORT_SURFACES_OFFSET_PARAMETERS)); + if (region->region().config().detect_overhang_wall.value) + // Add bridging perimeters. + SupportMaterialInternal::collect_bridging_perimeter_areas(region->perimeters, gap_xy_scaled, polygons_trimming); + } + if (! some_region_overlaps) + break; + } + } + // $layer->slices contains the full shape of layer, thus including + // perimeter's width. $support contains the full shape of support + // material, thus including the width of its foremost extrusion. + // We leave a gap equal to a full extrusion width. + support_layer.polygons = diff(support_layer.polygons, polygons_trimming); + } + }); + BOOST_LOG_TRIVIAL(debug) << "PrintObjectSupportMaterial::trim_support_layers_by_object() in parallel - end"; +} + +/* +void PrintObjectSupportMaterial::clip_by_pillars( + const PrintObject &object, + LayersPtr &bottom_contacts, + LayersPtr &top_contacts, + LayersPtr &intermediate_contacts); + +{ + // this prevents supplying an empty point set to BoundingBox constructor + if (top_contacts.empty()) + return; + + coord_t pillar_size = scale_(PILLAR_SIZE); + coord_t pillar_spacing = scale_(PILLAR_SPACING); + + // A regular grid of pillars, filling the 2D bounding box. + Polygons grid; + { + // Rectangle with a side of 2.5x2.5mm. + Polygon pillar; + pillar.points.push_back(Point(0, 0)); + pillar.points.push_back(Point(pillar_size, 0)); + pillar.points.push_back(Point(pillar_size, pillar_size)); + pillar.points.push_back(Point(0, pillar_size)); + + // 2D bounding box of the projection of all contact polygons. + BoundingBox bbox; + for (LayersPtr::const_iterator it = top_contacts.begin(); it != top_contacts.end(); ++ it) + bbox.merge(get_extents((*it)->polygons)); + grid.reserve(size_t(ceil(bb.size()(0) / pillar_spacing)) * size_t(ceil(bb.size()(1) / pillar_spacing))); + for (coord_t x = bb.min(0); x <= bb.max(0) - pillar_size; x += pillar_spacing) { + for (coord_t y = bb.min(1); y <= bb.max(1) - pillar_size; y += pillar_spacing) { + grid.push_back(pillar); + for (size_t i = 0; i < pillar.points.size(); ++ i) + grid.back().points[i].translate(Point(x, y)); + } + } + } + + // add pillars to every layer + for my $i (0..n_support_z) { + $shape->[$i] = [ @$grid ]; + } + + // build capitals + for my $i (0..n_support_z) { + my $z = $support_z->[$i]; + + my $capitals = intersection( + $grid, + $contact->{$z} // [], + ); + + // work on one pillar at time (if any) to prevent the capitals from being merged + // but store the contact area supported by the capital because we need to make + // sure nothing is left + my $contact_supported_by_capitals = []; + foreach my $capital (@$capitals) { + // enlarge capital tops + $capital = offset([$capital], +($pillar_spacing - $pillar_size)/2); + push @$contact_supported_by_capitals, @$capital; + + for (my $j = $i-1; $j >= 0; $j--) { + my $jz = $support_z->[$j]; + $capital = offset($capital, -$self->interface_flow->scaled_width/2); + last if !@$capitals; + push @{ $shape->[$j] }, @$capital; + } + } + + // Capitals will not generally cover the whole contact area because there will be + // remainders. For now we handle this situation by projecting such unsupported + // areas to the ground, just like we would do with a normal support. + my $contact_not_supported_by_capitals = diff( + $contact->{$z} // [], + $contact_supported_by_capitals, + ); + if (@$contact_not_supported_by_capitals) { + for (my $j = $i-1; $j >= 0; $j--) { + push @{ $shape->[$j] }, @$contact_not_supported_by_capitals; + } + } + } +} + +sub clip_with_shape { + my ($self, $support, $shape) = @_; + + foreach my $i (keys %$support) { + // don't clip bottom layer with shape so that we + // can generate a continuous base flange + // also don't clip raft layers + next if $i == 0; + next if $i < $self->object_config->raft_layers; + $support->{$i} = intersection( + $support->{$i}, + $shape->[$i], + ); + } +} +*/ + +} // namespace Slic3r diff --git a/src/libslic3r/Support/SupportMaterial.hpp b/src/libslic3r/Support/SupportMaterial.hpp new file mode 100644 index 0000000000..1b421959ed --- /dev/null +++ b/src/libslic3r/Support/SupportMaterial.hpp @@ -0,0 +1,106 @@ +///|/ Copyright (c) Prusa Research 2016 - 2023 Vojtěch Bubník @bubnikv, Lukáš Matěna @lukasmatena +///|/ Copyright (c) Slic3r 2014 Alessandro Ranellucci @alranel +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +#ifndef slic3r_SupportMaterial_hpp_ +#define slic3r_SupportMaterial_hpp_ + +#include "../Flow.hpp" +#include "../PrintConfig.hpp" +#include "../Slicing.hpp" + +#include "SupportLayer.hpp" +#include "SupportParameters.hpp" + +namespace Slic3r { + +class PrintObject; + +// This class manages raft and supports for a single PrintObject. +// Instantiated by Slic3r::Print::Object->_support_material() +// This class is instantiated before the slicing starts as Object.pm will query +// the parameters of the raft to determine the 1st layer height and thickness. +class PrintObjectSupportMaterial +{ +public: + PrintObjectSupportMaterial(const PrintObject *object, const SlicingParameters &slicing_params); + + // Is raft enabled? + bool has_raft() const { return m_slicing_params.has_raft(); } + // Has any support? + bool has_support() const { return m_object_config->enable_support.value || m_object_config->enforce_support_layers; } + bool build_plate_only() const { return this->has_support() && m_object_config->support_on_build_plate_only.value; } + + bool synchronize_layers() const { return m_slicing_params.soluble_interface && m_print_config->independent_support_layer_height.value; } + bool has_contact_loops() const { return m_object_config->support_interface_loop_pattern.value; } + + // Generate support material for the object. + // New support layers will be added to the object, + // with extrusion paths and islands filled in for each support layer. + void generate(PrintObject &object); + +private: + using SupportGeneratorLayersPtr = FFFSupport::SupportGeneratorLayersPtr; + using SupportGeneratorLayerStorage = FFFSupport::SupportGeneratorLayerStorage; + using SupportParameters = FFFSupport::SupportParameters; + + std::vector buildplate_covered(const PrintObject &object) const; + + // Generate top contact layers supporting overhangs. + // For a soluble interface material synchronize the layer heights with the object, otherwise leave the layer height undefined. + // If supports over bed surface only are requested, don't generate contact layers over an object. + SupportGeneratorLayersPtr top_contact_layers(const PrintObject &object, const std::vector &buildplate_covered, SupportGeneratorLayerStorage &layer_storage) const; + + // Generate bottom contact layers supporting the top contact layers. + // For a soluble interface material synchronize the layer heights with the object, + // otherwise set the layer height to a bridging flow of a support interface nozzle. + SupportGeneratorLayersPtr bottom_contact_layers_and_layer_support_areas( + const PrintObject &object, const SupportGeneratorLayersPtr &top_contacts, std::vector &buildplate_covered, + SupportGeneratorLayerStorage &layer_storage, std::vector &layer_support_areas) const; + + // Trim the top_contacts layers with the bottom_contacts layers if they overlap, so there would not be enough vertical space for both of them. + void trim_top_contacts_by_bottom_contacts(const PrintObject &object, const SupportGeneratorLayersPtr &bottom_contacts, SupportGeneratorLayersPtr &top_contacts) const; + + // Generate raft layers and the intermediate support layers between the bottom contact and top contact surfaces. + SupportGeneratorLayersPtr raft_and_intermediate_support_layers( + const PrintObject &object, + const SupportGeneratorLayersPtr &bottom_contacts, + const SupportGeneratorLayersPtr &top_contacts, + SupportGeneratorLayerStorage &layer_storage) const; + + // Fill in the base layers with polygons. + void generate_base_layers( + const PrintObject &object, + const SupportGeneratorLayersPtr &bottom_contacts, + const SupportGeneratorLayersPtr &top_contacts, + SupportGeneratorLayersPtr &intermediate_layers, + const std::vector &layer_support_areas) const; + + // Trim support layers by an object to leave a defined gap between + // the support volume and the object. + void trim_support_layers_by_object( + const PrintObject &object, + SupportGeneratorLayersPtr &support_layers, + const coordf_t gap_extra_above, + const coordf_t gap_extra_below, + const coordf_t gap_xy) const; + +/* + void generate_pillars_shape(); + void clip_with_shape(); +*/ + + // Following objects are not owned by SupportMaterial class. + const PrintConfig *m_print_config; + const PrintObjectConfig *m_object_config; + // Pre-calculated parameters shared between the object slicer and the support generator, + // carrying information on a raft, 1st layer height, 1st object layer height, gap between the raft and object etc. + SlicingParameters m_slicing_params; + // Various precomputed support parameters to be shared with external functions. + SupportParameters m_support_params; +}; + +} // namespace Slic3r + +#endif /* slic3r_SupportMaterial_hpp_ */ diff --git a/src/libslic3r/Support/SupportParameters.cpp b/src/libslic3r/Support/SupportParameters.cpp new file mode 100644 index 0000000000..c4cf2bee1c --- /dev/null +++ b/src/libslic3r/Support/SupportParameters.cpp @@ -0,0 +1,148 @@ +///|/ Copyright (c) Prusa Research 2023 Vojtěch Bubník @bubnikv +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +#include "../Print.hpp" +#include "../PrintConfig.hpp" +#include "../Slicing.hpp" +#include "SupportParameters.hpp" + +namespace Slic3r::FFFSupport { + +SupportParameters::SupportParameters(const PrintObject &object) +{ + const PrintConfig &print_config = object.print()->config(); + const PrintObjectConfig &object_config = object.config(); + const SlicingParameters &slicing_params = object.slicing_parameters(); + + this->soluble_interface = slicing_params.soluble_interface; + this->soluble_interface_non_soluble_base = + // Zero z-gap between the overhangs and the support interface. + slicing_params.soluble_interface && + // Interface extruder soluble. + object_config.support_interface_filament.value > 0 && print_config.filament_soluble.get_at(object_config.support_interface_filament.value - 1) && + // Base extruder: Either "print with active extruder" not soluble. + (object_config.support_filament.value == 0 || ! print_config.filament_soluble.get_at(object_config.support_filament.value - 1)); + + { + int num_top_interface_layers = std::max(0, object_config.support_interface_top_layers.value); + int num_bottom_interface_layers = object_config.support_interface_bottom_layers < 0 ? + num_top_interface_layers : object_config.support_interface_bottom_layers; + this->has_top_contacts = num_top_interface_layers > 0; + this->has_bottom_contacts = num_bottom_interface_layers > 0; + this->num_top_interface_layers = this->has_top_contacts ? size_t(num_top_interface_layers - 1) : 0; + this->num_bottom_interface_layers = this->has_bottom_contacts ? size_t(num_bottom_interface_layers - 1) : 0; + if (this->soluble_interface_non_soluble_base) { + // Try to support soluble dense interfaces with non-soluble dense interfaces. + this->num_top_base_interface_layers = size_t(std::min(num_top_interface_layers / 2, 2)); + this->num_bottom_base_interface_layers = size_t(std::min(num_bottom_interface_layers / 2, 2)); + } else { + this->num_top_base_interface_layers = 0; + this->num_bottom_base_interface_layers = 0; + } + } + + this->first_layer_flow = Slic3r::support_material_1st_layer_flow(&object, float(slicing_params.first_print_layer_height)); + this->support_material_flow = Slic3r::support_material_flow(&object, float(slicing_params.layer_height)); + this->support_material_interface_flow = Slic3r::support_material_interface_flow(&object, float(slicing_params.layer_height)); + this->raft_interface_flow = support_material_interface_flow; + + // Calculate a minimum support layer height as a minimum over all extruders, but not smaller than 10um. + this->support_layer_height_min = scaled(0.01); + for (auto lh : print_config.min_layer_height.values) + this->support_layer_height_min = std::min(this->support_layer_height_min, std::max(0.01, lh)); + for (auto layer : object.layers()) + this->support_layer_height_min = std::min(this->support_layer_height_min, std::max(0.01, layer->height)); + + if (object_config.support_interface_top_layers.value == 0) { + // No interface layers allowed, print everything with the base support pattern. + this->support_material_interface_flow = this->support_material_flow; + } + + // Evaluate the XY gap between the object outer perimeters and the support structures. + // Evaluate the XY gap between the object outer perimeters and the support structures. + coordf_t external_perimeter_width = 0.; + coordf_t bridge_flow_ratio = 0; + for (size_t region_id = 0; region_id < object.num_printing_regions(); ++ region_id) { + const PrintRegion ®ion = object.printing_region(region_id); + external_perimeter_width = std::max(external_perimeter_width, coordf_t(region.flow(object, frExternalPerimeter, slicing_params.layer_height).width())); + bridge_flow_ratio += region.config().bridge_flow; + } + this->gap_xy = object_config.support_object_xy_distance;//.get_abs_value(external_perimeter_width); + bridge_flow_ratio /= object.num_printing_regions(); + + this->support_material_bottom_interface_flow = slicing_params.soluble_interface || ! object_config.thick_bridges ? + this->support_material_interface_flow.with_flow_ratio(bridge_flow_ratio) : + Flow::bridging_flow(bridge_flow_ratio * this->support_material_interface_flow.nozzle_diameter(), this->support_material_interface_flow.nozzle_diameter()); + + this->can_merge_support_regions = object_config.support_filament.value == object_config.support_interface_filament.value; + if (!this->can_merge_support_regions && (object_config.support_filament.value == 0 || object_config.support_interface_filament.value == 0)) { + // One of the support extruders is of "don't care" type. + auto object_extruders = object.object_extruders(); + if (object_extruders.size() == 1 && + *object_extruders.begin() == std::max(object_config.support_filament.value, object_config.support_interface_filament.value)) + // Object is printed with the same extruder as the support. + this->can_merge_support_regions = true; + } + + double interface_spacing = object_config.support_interface_spacing.value + this->support_material_interface_flow.spacing(); + this->interface_density = std::min(1., this->support_material_interface_flow.spacing() / interface_spacing); + double raft_interface_spacing = object_config.support_interface_spacing.value + this->raft_interface_flow.spacing(); + this->raft_interface_density = std::min(1., this->raft_interface_flow.spacing() / raft_interface_spacing); + double support_spacing = object_config.support_base_pattern_spacing.value + this->support_material_flow.spacing(); + this->support_density = std::min(1., this->support_material_flow.spacing() / support_spacing); + if (object_config.support_interface_top_layers.value == 0) { + // No interface layers allowed, print everything with the base support pattern. + this->interface_density = this->support_density; + } + + SupportMaterialPattern support_pattern = object_config.support_base_pattern; + this->with_sheath = false;//object_config.support_material_with_sheath; + this->base_fill_pattern = + support_pattern == smpHoneycomb ? ipHoneycomb : + this->support_density > 0.95 || this->with_sheath ? ipRectilinear : ipSupportBase; + this->interface_fill_pattern = (this->interface_density > 0.95 ? ipRectilinear : ipSupportBase); + this->raft_interface_fill_pattern = this->raft_interface_density > 0.95 ? ipRectilinear : ipSupportBase; + this->contact_fill_pattern = + (object_config.support_interface_pattern == smipAuto && slicing_params.soluble_interface) || + object_config.support_interface_pattern == smipConcentric ? + ipConcentric : + (this->interface_density > 0.95 ? ipRectilinear : ipSupportBase); + + this->base_angle = Geometry::deg2rad(float(object_config.support_angle.value)); + this->interface_angle = Geometry::deg2rad(float(object_config.support_angle.value + 90.)); + this->raft_angle_1st_layer = 0.f; + this->raft_angle_base = 0.f; + this->raft_angle_interface = 0.f; + if (slicing_params.base_raft_layers > 1) { + assert(slicing_params.raft_layers() >= 4); + // There are all raft layer types (1st layer, base, interface & contact layers) available. + this->raft_angle_1st_layer = this->interface_angle; + this->raft_angle_base = this->base_angle; + this->raft_angle_interface = this->interface_angle; + if ((slicing_params.interface_raft_layers & 1) == 0) + // Allign the 1st raft interface layer so that the object 1st layer is hatched perpendicularly to the raft contact interface. + this->raft_angle_interface += float(0.5 * M_PI); + } else if (slicing_params.base_raft_layers == 1 || slicing_params.interface_raft_layers > 1) { + assert(slicing_params.raft_layers() == 2 || slicing_params.raft_layers() == 3); + // 1st layer, interface & contact layers available. + this->raft_angle_1st_layer = this->base_angle; + this->raft_angle_interface = this->interface_angle + 0.5 * M_PI; + } else if (slicing_params.interface_raft_layers == 1) { + // Only the contact raft layer is non-empty, which will be printed as the 1st layer. + assert(slicing_params.base_raft_layers == 0); + assert(slicing_params.interface_raft_layers == 1); + assert(slicing_params.raft_layers() == 1); + this->raft_angle_1st_layer = float(0.5 * M_PI); + this->raft_angle_interface = this->raft_angle_1st_layer; + } else { + // No raft. + assert(slicing_params.base_raft_layers == 0); + assert(slicing_params.interface_raft_layers == 0); + assert(slicing_params.raft_layers() == 0); + } + + this->tree_branch_diameter_double_wall_area_scaled = 0.25 * sqr(scaled(object_config.tree_support_branch_diameter_double_wall.value)) * M_PI; +} + +} // namespace Slic3r diff --git a/src/libslic3r/Support/SupportParameters.hpp b/src/libslic3r/Support/SupportParameters.hpp new file mode 100644 index 0000000000..b042e7640f --- /dev/null +++ b/src/libslic3r/Support/SupportParameters.hpp @@ -0,0 +1,100 @@ +///|/ Copyright (c) Prusa Research 2023 Vojtěch Bubník @bubnikv +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +#ifndef slic3r_SupportParameters_hpp_ +#define slic3r_SupportParameters_hpp_ + +#include "../libslic3r.h" +#include "../Flow.hpp" + +namespace Slic3r { + +class PrintObject; +enum InfillPattern : int; + +namespace FFFSupport { + +struct SupportParameters { + SupportParameters(const PrintObject &object); + + // Both top / bottom contacts and interfaces are soluble. + bool soluble_interface; + // Support contact & interface are soluble, but support base is non-soluble. + bool soluble_interface_non_soluble_base; + + // Is there at least a top contact layer extruded above support base? + bool has_top_contacts; + // Is there at least a bottom contact layer extruded below support base? + bool has_bottom_contacts; + // Number of top interface layers without counting the contact layer. + size_t num_top_interface_layers; + // Number of bottom interface layers without counting the contact layer. + size_t num_bottom_interface_layers; + // Number of top base interface layers. Zero if not soluble_interface_non_soluble_base. + size_t num_top_base_interface_layers; + // Number of bottom base interface layers. Zero if not soluble_interface_non_soluble_base. + size_t num_bottom_base_interface_layers; + + bool has_contacts() const { return this->has_top_contacts || this->has_bottom_contacts; } + bool has_interfaces() const { return this->num_top_interface_layers + this->num_bottom_interface_layers > 0; } + bool has_base_interfaces() const { return this->num_top_base_interface_layers + this->num_bottom_base_interface_layers > 0; } + size_t num_top_interface_layers_only() const { return this->num_top_interface_layers - this->num_top_base_interface_layers; } + size_t num_bottom_interface_layers_only() const { return this->num_bottom_interface_layers - this->num_bottom_base_interface_layers; } + + // Flow at the 1st print layer. + Flow first_layer_flow; + // Flow at the support base (neither top, nor bottom interface). + // Also flow at the raft base with the exception of raft interface and contact layers. + Flow support_material_flow; + // Flow at the top interface and contact layers. + Flow support_material_interface_flow; + // Flow at the bottom interfaces and contacts. + Flow support_material_bottom_interface_flow; + // Flow at raft inteface & contact layers. + Flow raft_interface_flow; + // Is merging of regions allowed? Could the interface & base support regions be printed with the same extruder? + bool can_merge_support_regions; + + coordf_t support_layer_height_min; +// coordf_t support_layer_height_max; + + coordf_t gap_xy; + + float base_angle; + float interface_angle; + + // Density of the top / bottom interface and contact layers. + coordf_t interface_density; + // Density of the raft interface and contact layers. + coordf_t raft_interface_density; + // Density of the base support layers. + coordf_t support_density; + + // Pattern of the sparse infill including sparse raft layers. + InfillPattern base_fill_pattern; + // Pattern of the top / bottom interface and contact layers. + InfillPattern interface_fill_pattern; + // Pattern of the raft interface and contact layers. + InfillPattern raft_interface_fill_pattern; + // Pattern of the contact layers. + InfillPattern contact_fill_pattern; + // Shall the sparse (base) layers be printed with a single perimeter line (sheath) for robustness? + bool with_sheath; + // Branches of organic supports with area larger than this threshold will be extruded with double lines. + double tree_branch_diameter_double_wall_area_scaled; + + float raft_angle_1st_layer; + float raft_angle_base; + float raft_angle_interface; + + // Produce a raft interface angle for a given SupportLayer::interface_id() + float raft_interface_angle(size_t interface_id) const + { return this->raft_angle_interface + ((interface_id & 1) ? float(- M_PI / 4.) : float(+ M_PI / 4.)); } +}; + +} // namespace FFFSupport + +} // namespace Slic3r + +#endif /* slic3r_SupportParameters_hpp_ */ diff --git a/src/libslic3r/Support/TreeModelVolumes.cpp b/src/libslic3r/Support/TreeModelVolumes.cpp new file mode 100644 index 0000000000..2e14e81f49 --- /dev/null +++ b/src/libslic3r/Support/TreeModelVolumes.cpp @@ -0,0 +1,878 @@ +///|/ Copyright (c) Prusa Research 2022 - 2023 Vojtěch Bubník @bubnikv, Pavel Mikuš @Godrak +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +// Tree supports by Thomas Rahm, losely based on Tree Supports by CuraEngine. +// Original source of Thomas Rahm's tree supports: +// https://github.com/ThomasRahm/CuraEngine +// +// Original CuraEngine copyright: +// Copyright (c) 2021 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. + +#include "TreeModelVolumes.hpp" +#include "TreeSupportCommon.hpp" + +#include "../BuildVolume.hpp" +#include "../ClipperUtils.hpp" +#include "../Flow.hpp" +#include "../Layer.hpp" +#include "../Point.hpp" +#include "../Print.hpp" +#include "../PrintConfig.hpp" +#include "../Utils.hpp" +#include "../format.hpp" + +#include + +#include + +#include +#include + +namespace Slic3r::FFFTreeSupport +{ + +using namespace std::literals; + +// or warning +// had to use a define beacuse the macro processing inside macro BOOST_LOG_TRIVIAL() +#define error_level_not_in_cache error + +//FIXME Machine border is currently ignored. +static Polygons calculateMachineBorderCollision(Polygon machine_border) +{ + // Put a border of 1m around the print volume so that we don't collide. +#if 1 + //FIXME just returning no border will let tree support legs collide with print bed boundary + return {}; +#else + //FIXME offsetting by 1000mm easily overflows int32_tr coordinate. + Polygons out = offset(machine_border, scaled(1000.), jtMiter, 1.2); + machine_border.reverse(); // Makes the polygon negative so that we subtract the actual volume from the collision area. + out.emplace_back(std::move(machine_border)); + return out; +#endif +} + +TreeModelVolumes::TreeModelVolumes( + const PrintObject &print_object, + const BuildVolume &build_volume, + const coord_t max_move, const coord_t max_move_slow, size_t current_mesh_idx, +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + double progress_multiplier, double progress_offset, +#endif // SLIC3R_TREESUPPORTS_PROGRESS + const std::vector& additional_excluded_areas) : + // -2 to avoid rounding errors + m_max_move{ std::max(max_move - 2, 0) }, m_max_move_slow{ std::max(max_move_slow - 2, 0) }, +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + m_progress_multiplier{ progress_multiplier }, m_progress_offset{ progress_offset }, +#endif // SLIC3R_TREESUPPORTS_PROGRESS + m_machine_border{ calculateMachineBorderCollision(build_volume.polygon()) } +{ +#if 0 + std::unordered_map mesh_to_layeroutline_idx; + for (size_t mesh_idx = 0; mesh_idx < storage.meshes.size(); ++ mesh_idx) { + SliceMeshStorage mesh = storage.meshes[mesh_idx]; + bool added = false; + for (size_t idx = 0; idx < m_layer_outlines.size(); ++ idx) + if (TreeSupport::TreeSupportSettings(m_layer_outlines[idx].first) == TreeSupport::TreeSupportSettings(mesh.settings)) { + added = true; + mesh_to_layeroutline_idx[mesh_idx] = idx; + } + if (! added) { + mesh_to_layeroutline_idx[mesh_idx] = m_layer_outlines.size(); + m_layer_outlines.emplace_back(mesh.settings, std::vector(storage.support.supportLayers.size(), Polygons())); + } + } + for (size_t idx = 0; idx < m_layer_outlines.size(); ++ idx) { + tbb::parallel_for(tbb::blocked_range(0, m_layer_outlines[idx].second.size()), + [&](const tbb::blocked_range &range) { + for (const size_t layer_idx = range.begin(); layer_idx < range.end(); ++ layer_idx) + m_layer_outlines[idx].second[layer_idx] = union_(m_layer_outlines[idx].second[layer_idx]); + }); + } + m_current_outline_idx = mesh_to_layeroutline_idx[current_mesh_idx]; + +#else + { + m_anti_overhang = print_object.slice_support_blockers(); + TreeSupportMeshGroupSettings mesh_settings(print_object); + const TreeSupportSettings config{ mesh_settings, print_object.slicing_parameters() }; + m_current_min_xy_dist = config.xy_min_distance; + m_current_min_xy_dist_delta = config.xy_distance - m_current_min_xy_dist; + assert(m_current_min_xy_dist_delta >= 0); + m_increase_until_radius = config.increase_radius_until_radius; + m_radius_0 = config.getRadius(0); + m_raft_layers = config.raft_layers; + m_current_outline_idx = 0; + + m_layer_outlines.emplace_back(mesh_settings, std::vector{}); + std::vector &outlines = m_layer_outlines.front().second; + size_t num_raft_layers = m_raft_layers.size(); + size_t num_layers = print_object.layer_count() + num_raft_layers; + outlines.assign(num_layers, Polygons{}); + tbb::parallel_for(tbb::blocked_range(num_raft_layers, num_layers, std::min(1, std::max(16, num_layers / (8 * tbb::this_task_arena::max_concurrency())))), + [&](const tbb::blocked_range &range) { + for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++ layer_idx) + outlines[layer_idx] = polygons_simplify(to_polygons(print_object.get_layer(layer_idx - num_raft_layers)->lslices), mesh_settings.resolution, polygons_strictly_simple); + }); + } +#endif + + m_support_rests_on_model = false; + m_min_resolution = std::numeric_limits::max(); + for (auto data_pair : m_layer_outlines) { + m_support_rests_on_model |= ! data_pair.first.support_material_buildplate_only; + m_min_resolution = std::min(m_min_resolution, data_pair.first.resolution); + } + +#if 0 + for (size_t mesh_idx = 0; mesh_idx < storage.meshes.size(); mesh_idx++) { + SliceMeshStorage mesh = storage.meshes[mesh_idx]; + tbb::parallel_for(tbb::blocked_range(0, m_layer_outlines[mesh_to_layeroutline_idx[mesh_idx]].second.size()), + [&](const tbb::blocked_range &range) { + for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++ layer_idx) + if (layer_idx < mesh.layer_nr_max_filled_layer) { + Polygons outline = extractOutlineFromMesh(mesh, layer_idx); + append(m_layer_outlines[mesh_to_layeroutline_idx[mesh_idx]].second[layer_idx], outline); + } + }); + } + if (! additional_excluded_areas.empty()) { + tbb::parallel_for(tbb::blocked_range(0, m_anti_overhang.size()), + [&](const tbb::blocked_range &range) { + for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++ layer_idx) { + if (layer_idx < coord_t(additional_excluded_areas.size())) + append(m_anti_overhang[layer_idx], additional_excluded_areas[layer_idx]); + // if (SUPPORT_TREE_AVOID_SUPPORT_BLOCKER) + // append(m_anti_overhang[layer_idx], storage.support.supportLayers[layer_idx].anti_overhang); + //FIXME block wipe tower + // if (storage.primeTower.enabled) + // append(m_anti_overhang[layer_idx], layer_idx == 0 ? storage.primeTower.outer_poly_first_layer : storage.primeTower.outer_poly); + m_anti_overhang[layer_idx] = union_(m_anti_overhang[layer_idx]); + } + }); + } +#endif +} + +void TreeModelVolumes::precalculate(const PrintObject& print_object, const coord_t max_layer, std::function throw_on_cancel) +{ + auto t_start = std::chrono::high_resolution_clock::now(); + m_precalculated = true; + + // Get the config corresponding to one mesh that is in the current group. Which one has to be irrelevant. + // Not the prettiest way to do this, but it ensures some calculations that may be a bit more complex + // like inital layer diameter are only done in once. + TreeSupportSettings config(m_layer_outlines[m_current_outline_idx].first, print_object.slicing_parameters()); + + { + // calculate which radius each layer in the tip may have. + std::vector possible_tip_radiis; + for (size_t distance_to_top = 0; distance_to_top <= config.tip_layers; ++ distance_to_top) { + possible_tip_radiis.emplace_back(ceilRadius(config.getRadius(distance_to_top))); + possible_tip_radiis.emplace_back(ceilRadius(config.getRadius(distance_to_top) + m_current_min_xy_dist_delta)); + } + sort_remove_duplicates(possible_tip_radiis); + // It theoretically may happen in the tip, that the radius can change so much in-between 2 layers, + // that a ceil step is skipped (as in there is a radius r so that ceilRadius(radius(dtt)) radius_until_layer; + // while it is possible to calculate, up to which layer the avoidance should be calculated, this simulation is easier to understand, and does not need to be adjusted if something of the radius calculation is changed. + // Overhead with an assumed worst case of 6600 layers was about 2ms + for (LayerIndex distance_to_top = 0; distance_to_top <= max_layer; ++ distance_to_top) { + const LayerIndex current_layer = max_layer - distance_to_top; + auto update_radius_until_layer = [&radius_until_layer, current_layer](coord_t r) { + auto it = radius_until_layer.find(r); + if (it == radius_until_layer.end()) + radius_until_layer.emplace_hint(it, r, current_layer); + else + assert(it->second >= current_layer); + }; + // regular radius + update_radius_until_layer(ceilRadius(config.getRadius(distance_to_top, 0) + m_current_min_xy_dist_delta)); + // the maximum radius that the radius with the min_xy_dist can achieve + update_radius_until_layer(ceilRadius(config.getRadius(distance_to_top, 0))); + update_radius_until_layer(ceilRadius(config.recommendedMinRadius(current_layer) + m_current_min_xy_dist_delta)); + } + + throw_on_cancel(); + + // Copy to deque to use in parallel for later. + std::vector relevant_avoidance_radiis{ radius_until_layer.begin(), radius_until_layer.end() }; + + // Append additional radiis needed for collision. + // To calculate collision holefree for every radius, the collision of radius m_increase_until_radius will be required. + radius_until_layer[ceilRadius(m_increase_until_radius + m_current_min_xy_dist_delta)] = max_layer; + // Collision for radius 0 needs to be calculated everywhere, as it will be used to ensure valid xy_distance in drawAreas. + radius_until_layer[0] = max_layer; + if (m_current_min_xy_dist_delta != 0) + radius_until_layer[m_current_min_xy_dist_delta] = max_layer; + + // Now that required_avoidance_limit contains the maximum of ild and regular required radius just copy. + std::vector relevant_collision_radiis{ radius_until_layer.begin(), radius_until_layer.end() }; + + // Calculate the relevant collisions + calculateCollision(relevant_collision_radiis, throw_on_cancel); + + // calculate a separate Collisions with all holes removed. These are relevant for some avoidances that try to avoid holes (called safe) + std::vector relevant_hole_collision_radiis; + for (RadiusLayerPair key : relevant_avoidance_radiis) + if (key.first < m_increase_until_radius + m_current_min_xy_dist_delta) + relevant_hole_collision_radiis.emplace_back(key); + + // Calculate collisions without holes, built from regular collision + calculateCollisionHolefree(relevant_hole_collision_radiis, throw_on_cancel); + // Let placables be calculated from calculateAvoidance() for better parallelization. + if (m_support_rests_on_model) + calculatePlaceables(relevant_avoidance_radiis, throw_on_cancel); + + auto t_coll = std::chrono::high_resolution_clock::now(); + + // Calculate the relevant avoidances in parallel as far as possible + { + tbb::task_group task_group; + task_group.run([this, relevant_avoidance_radiis, throw_on_cancel]{ calculateAvoidance(relevant_avoidance_radiis, true, m_support_rests_on_model, throw_on_cancel); }); + task_group.run([this, relevant_avoidance_radiis, throw_on_cancel]{ calculateWallRestrictions(relevant_avoidance_radiis, throw_on_cancel); }); + task_group.wait(); + } + auto t_end = std::chrono::high_resolution_clock::now(); + auto dur_col = 0.001 * std::chrono::duration_cast(t_coll - t_start).count(); + auto dur_avo = 0.001 * std::chrono::duration_cast(t_end - t_coll).count(); + +// m_precalculated = true; + BOOST_LOG_TRIVIAL(info) << "Precalculating collision took" << dur_col << " ms. Precalculating avoidance took " << dur_avo << " ms."; + +#if 0 + // Paint caches into SVGs: + auto paint_cache_into_SVGs = [this](const RadiusLayerPolygonCache &cache, std::string_view name) { + const std::vector>> sorted = cache.sorted(); + static constexpr const std::string_view colors[] = { + "red", "green", "blue", "magenta", "orange" + }; + static constexpr const size_t num_colors = sizeof(colors) / sizeof(colors[0]); + for (size_t i = 0; i < sorted.size();) { + // Find range of cache items with the same layer index. + size_t j = i; + for (++ j; j < sorted.size() && sorted[i].first.second == sorted[j].first.second; ++ j) ; + // Collect expolygons in reverse order (largest to smallest). + std::vector> expolygons_with_attributes; + for (int k = int(j - 1); k >= int(i); -- k) { + std::string legend = format("radius-%1%", unscaled(sorted[k].first.first)); + expolygons_with_attributes.push_back({ union_ex(sorted[k].second), SVG::ExPolygonAttributes(legend, std::string(colors[(k - int(i)) % num_colors]), 1.) }); + SVG::export_expolygons(debug_out_path("treesupport_cache-%s-%d-%s.svg", name.data(), sorted[i].first.second, legend.c_str()), { expolygons_with_attributes.back() }); + } + // Render the range of per radius collision polygons into a common SVG. + SVG::export_expolygons(debug_out_path("treesupport_cache-%s-%d.svg", name.data(), sorted[i].first.second), expolygons_with_attributes); + i = j; + } + }; + paint_cache_into_SVGs(m_collision_cache, "collision_cache"); + paint_cache_into_SVGs(m_collision_cache_holefree, "collision_cache_holefree"); + paint_cache_into_SVGs(m_avoidance_cache, "avoidance_cache"); + paint_cache_into_SVGs(m_avoidance_cache_slow, "avoidance_cache_slow"); + paint_cache_into_SVGs(m_avoidance_cache_to_model, "avoidance_cache_to_model"); + paint_cache_into_SVGs(m_avoidance_cache_to_model_slow, "avoidance_cache_to_model_slow"); + paint_cache_into_SVGs(m_placeable_areas_cache, "placable_areas_cache"); + paint_cache_into_SVGs(m_avoidance_cache_holefree, "avoidance_cache_holefree"); + paint_cache_into_SVGs(m_avoidance_cache_holefree_to_model, "avoidance_cache_holefree_to_model"); + paint_cache_into_SVGs(m_wall_restrictions_cache, "wall_restrictions_cache"); + paint_cache_into_SVGs(m_wall_restrictions_cache_min, "wall_restrictions_cache_min"); +#endif +} + +const Polygons& TreeModelVolumes::getCollision(const coord_t orig_radius, LayerIndex layer_idx, bool min_xy_dist) const +{ + const coord_t radius = this->ceilRadius(orig_radius, min_xy_dist); + if (std::optional> result = m_collision_cache.getArea({ radius, layer_idx }); result) + return (*result).get(); + if (m_precalculated) { + BOOST_LOG_TRIVIAL(error_level_not_in_cache) << "Had to calculate collision at radius " << radius << " and layer " << layer_idx << ", but precalculate was called. Performance may suffer!"; + tree_supports_show_error("Not precalculated Collision requested."sv, false); + } + const_cast(this)->calculateCollision(radius, layer_idx, []{}); + return getCollision(orig_radius, layer_idx, min_xy_dist); +} + +// Get a collision area at a given layer for a radius that is a lower or equial to the key radius. +// It is expected that the collision area is precalculated for a given layer at least for the radius zero. +// Used for pushing tree supports away from object during the final Organic optimization step. +std::optional>> TreeModelVolumes::get_collision_lower_bound_area(LayerIndex layer_id, coord_t max_radius) const +{ + return m_collision_cache.get_lower_bound_area({ max_radius, layer_id }); +} + +// Private. Only called internally by calculateAvoidance() and calculateAvoidanceToModel(), radius is already snapped to grid. +const Polygons& TreeModelVolumes::getCollisionHolefree(coord_t radius, LayerIndex layer_idx) const +{ + assert(radius == this->ceilRadius(radius)); + assert(radius < m_increase_until_radius + m_current_min_xy_dist_delta); + if (std::optional> result = m_collision_cache_holefree.getArea({ radius, layer_idx }); result) + return (*result).get(); + if (m_precalculated) { + BOOST_LOG_TRIVIAL(error_level_not_in_cache) << "Had to calculate collision holefree at radius " << radius << " and layer " << layer_idx << ", but precalculate was called. Performance may suffer!"; + tree_supports_show_error("Not precalculated Holefree Collision requested."sv, false); + } + const_cast(this)->calculateCollisionHolefree({ radius, layer_idx }); + return getCollisionHolefree(radius, layer_idx); +} + +const Polygons& TreeModelVolumes::getAvoidance(const coord_t orig_radius, LayerIndex layer_idx, AvoidanceType type, bool to_model, bool min_xy_dist) const +{ + if (layer_idx == 0) // What on the layer directly above buildplate do i have to avoid to reach the buildplate ... + return getCollision(orig_radius, layer_idx, min_xy_dist); + + const coord_t radius = this->ceilRadius(orig_radius, min_xy_dist); + if (type == AvoidanceType::FastSafe && radius >= m_increase_until_radius + m_current_min_xy_dist_delta) + // no holes anymore by definition at this request + type = AvoidanceType::Fast; + + if (std::optional> result = + this->avoidance_cache(type, to_model).getArea({ radius, layer_idx }); + result) + return (*result).get(); + + if (m_precalculated) { + if (to_model) { + BOOST_LOG_TRIVIAL(error_level_not_in_cache) << "Had to calculate Avoidance to model at radius " << radius << " and layer " << layer_idx << ", but precalculate was called. Performance may suffer!"; + tree_supports_show_error("Not precalculated Avoidance(to model) requested."sv, false); + } else { + BOOST_LOG_TRIVIAL(error_level_not_in_cache) << "Had to calculate Avoidance at radius " << radius << " and layer " << layer_idx << ", but precalculate was called. Performance may suffer!"; + tree_supports_show_error("Not precalculated Avoidance(to buildplate) requested."sv, false); + } + } + const_cast(this)->calculateAvoidance({ radius, layer_idx }, ! to_model, to_model); + // Retrive failed and correct result was calculated. Now it has to be retrived. + return getAvoidance(orig_radius, layer_idx, type, to_model, min_xy_dist); +} + +const Polygons& TreeModelVolumes::getPlaceableAreas(const coord_t orig_radius, LayerIndex layer_idx, std::function throw_on_cancel) const +{ + const coord_t radius = ceilRadius(orig_radius); + if (std::optional> result = m_placeable_areas_cache.getArea({ radius, layer_idx }); result) + return (*result).get(); + if (m_precalculated) { + BOOST_LOG_TRIVIAL(error_level_not_in_cache) << "Had to calculate Placeable Areas at radius " << radius << " and layer " << layer_idx << ", but precalculate was called. Performance may suffer!"; + tree_supports_show_error(format("Not precalculated Placeable areas requested, radius %1%, layer %2%", radius, layer_idx), false); + } + if (orig_radius == 0) + // Placable areas for radius 0 are calculated in the general collision code. + return this->getCollision(0, layer_idx, true); + else + const_cast(this)->calculatePlaceables(radius, layer_idx, throw_on_cancel); + return getPlaceableAreas(orig_radius, layer_idx, throw_on_cancel); +} + +const Polygons& TreeModelVolumes::getWallRestriction(const coord_t orig_radius, LayerIndex layer_idx, bool min_xy_dist) const +{ + assert(layer_idx > 0); + if (layer_idx == 0) + // Should never be requested as there will be no going below layer 0 ..., + // but just to be sure some semi-sane catch. Alternative would be empty Polygon. + return getCollision(orig_radius, layer_idx, min_xy_dist); + + min_xy_dist &= m_current_min_xy_dist_delta > 0; + + const coord_t radius = ceilRadius(orig_radius); + if (std::optional> result = + (min_xy_dist ? m_wall_restrictions_cache_min : m_wall_restrictions_cache).getArea({ radius, layer_idx }); + result) + return (*result).get(); + if (m_precalculated) { + BOOST_LOG_TRIVIAL(error_level_not_in_cache) << "Had to calculate Wall restricions at radius " << radius << " and layer " << layer_idx << ", but precalculate was called. Performance may suffer!"; + tree_supports_show_error( + min_xy_dist ? + "Not precalculated Wall restriction of minimum xy distance requested )." : + "Not precalculated Wall restriction requested )."sv + , false); + } + const_cast(this)->calculateWallRestrictions({ radius, layer_idx }); + return getWallRestriction(orig_radius, layer_idx, min_xy_dist); // Retrieve failed and correct result was calculated. Now it has to be retrieved. +} + +void TreeModelVolumes::calculateCollision(const std::vector &keys, std::function throw_on_cancel) +{ + tbb::parallel_for(tbb::blocked_range(0, keys.size()), + [&](const tbb::blocked_range &range) { + for (size_t ikey = range.begin(); ikey != range.end(); ++ ikey) { + const LayerIndex radius = keys[ikey].first; + const size_t max_layer_idx = keys[ikey].second; + // recursive call to parallel_for. + calculateCollision(radius, max_layer_idx, throw_on_cancel); + } + }); +} + +// Calculate collisions and placable areas for radius and for layer 0 to max_layer_idx inclusive. +void TreeModelVolumes::calculateCollision(const coord_t radius, const LayerIndex max_layer_idx, std::function throw_on_cancel) +{ +// assert(radius == this->ceilRadius(radius)); + + // Process the outlines from least layers to most layers so that the final union will run over the longest vector. + std::vector layer_outline_indices(m_layer_outlines.size(), 0); + std::iota(layer_outline_indices.begin(), layer_outline_indices.end(), 0); + std::sort(layer_outline_indices.begin(), layer_outline_indices.end(), + [this](size_t i, size_t j) { return m_layer_outlines[i].second.size() < m_layer_outlines[j].second.size(); }); + + // Layer range for which the collisions will be calculated. + LayerPolygonCache data; + data.allocate(m_collision_cache.getMaxCalculatedLayer(radius) + 1, max_layer_idx + 1); + + const bool calculate_placable = m_support_rests_on_model && radius == 0; + LayerPolygonCache data_placeable; + if (calculate_placable) + data_placeable.allocate(data.begin(), data.end()); + + for (size_t outline_idx : layer_outline_indices) + if (const std::vector &outlines = m_layer_outlines[outline_idx].second; ! outlines.empty()) { + const TreeSupportMeshGroupSettings &settings = m_layer_outlines[outline_idx].first; + const coord_t layer_height = settings.layer_height; + const int z_distance_bottom_layers = int(round(double(settings.support_bottom_distance) / double(layer_height))); + const int z_distance_top_layers = int(round(double(settings.support_top_distance) / double(layer_height))); + const coord_t xy_distance = outline_idx == m_current_outline_idx ? m_current_min_xy_dist : + // technically this causes collision for the normal xy_distance to be larger by m_current_min_xy_dist_delta for all + // not currently processing meshes as this delta will be added at request time. + // avoiding this would require saving each collision for each outline_idx separately. + // and later for each avoidance... But avoidance calculation has to be for the whole scene and can NOT be done for each outline_idx separately and combined later. + // so avoiding this inaccuracy seems infeasible as it would require 2x the avoidance calculations => 0.5x the performance. + //FIXME support_xy_distance is not corrected for "soluble" flag, see TreeSupportSettings constructor. + settings.support_xy_distance; + + // 1) Calculate offsets of collision areas in parallel. + LayerPolygonCache collision_areas_offsetted; + collision_areas_offsetted.allocate( + std::max(0, data.begin() - z_distance_bottom_layers), + std::min(outlines.size(), data.end() + z_distance_top_layers)); + tbb::parallel_for(tbb::blocked_range(collision_areas_offsetted.begin(), collision_areas_offsetted.end()), + [&outlines, &machine_border = std::as_const(m_machine_border), offset_value = radius + xy_distance, &collision_areas_offsetted, &throw_on_cancel] + (const tbb::blocked_range &range) { + for (LayerIndex layer_idx = range.begin(); layer_idx != range.end(); ++ layer_idx) { + Polygons collision_areas = machine_border; + append(collision_areas, outlines[layer_idx]); + // jtRound is not needed here, as the overshoot can not cause errors in the algorithm, because no assumptions are made about the model. + // if a key does not exist when it is accessed it is added! + collision_areas_offsetted[layer_idx] = offset_value == 0 ? + union_(collision_areas) : + offset(union_ex(collision_areas), offset_value, ClipperLib::jtMiter, 1.2); + throw_on_cancel(); + } + }); + + // 2) Sum over top / bottom ranges. + const bool processing_last_mesh = outline_idx == layer_outline_indices.size(); + tbb::parallel_for(tbb::blocked_range(data.begin(), data.end()), + [&collision_areas_offsetted, &outlines, &machine_border = m_machine_border, &anti_overhang = m_anti_overhang, radius, + xy_distance, z_distance_bottom_layers, z_distance_top_layers, min_resolution = m_min_resolution, &data, processing_last_mesh, &throw_on_cancel] + (const tbb::blocked_range& range) { + for (LayerIndex layer_idx = range.begin(); layer_idx != range.end(); ++ layer_idx) { + Polygons collisions; + for (int i = - z_distance_bottom_layers; i <= 0; ++ i) + if (int j = layer_idx + i; collision_areas_offsetted.has(j)) + append(collisions, collision_areas_offsetted[j]); + for (int i = 1; i <= z_distance_top_layers; ++ i) + if (int j = layer_idx + i; j < int(outlines.size())) { + Polygons collision_areas_original = machine_border; + append(collision_areas_original, outlines[j]); + + // If just the collision (including the xy distance) of the layers above is accumulated, it leads to the + // following issue: + // Example: assuming the z distance is 2 layer + // + = xy_distance + // - = model + // o = overhang of the area two layers above that should result in tips on this layer + // + // +-----+ + // +-----+ + // +-----+ + // o +-----+ + // If just the collision above is accumulated the overhang will get overwritten by the xy_distance of the + // layer below the overhang... + // + // This only causes issues if the overhang area is thinner than xy_distance + // Just accumulating areas of the model above without the xy distance is also problematic, as then support + // may get closer to the model (on the diagonal downwards) than the user intended. Example (s = support): + // +-----+ + // +-----+ + // +-----+ + // s+-----+ + + // technically the calculation below is off by one layer, as the actual distance between plastic one layer + // down is 0 not layer height, as this layer is filled with said plastic. But otherwise a part of the + // overhang that is expected to be supported is overwritten by the remaining part of the xy distance of the + // layer below the to be supported area. + coord_t required_range_x = + (xy_distance - ((i - (z_distance_top_layers == 1 ? 0.5 : 0)) * xy_distance / z_distance_top_layers)); + // the conditional -0.5 ensures that plastic can never touch on the diagonal + // downward when the z_distance_top_layers = 1. It is assumed to be better to + // not support an overhang<90 degree than to risk fusing to it. + append(collisions, offset(union_ex(collision_areas_original), radius + required_range_x, ClipperLib::jtMiter, 1.2)); + } + collisions = processing_last_mesh && layer_idx < int(anti_overhang.size()) ? + union_(collisions, offset(union_ex(anti_overhang[layer_idx]), radius, ClipperLib::jtMiter, 1.2)) : + union_(collisions); + auto &dst = data[layer_idx]; + if (processing_last_mesh) { + if (! dst.empty()) + collisions = union_(collisions, dst); + dst = polygons_simplify(collisions, min_resolution, polygons_strictly_simple); + } else + append(dst, std::move(collisions)); + throw_on_cancel(); + } + }); + + // 3) Optionally calculate placables. + if (calculate_placable) { + // Now calculate the placable areas. + tbb::parallel_for(tbb::blocked_range(std::max(z_distance_bottom_layers + 1, data.begin()), data.end()), + [&collision_areas_offsetted, &outlines, &anti_overhang = m_anti_overhang, processing_last_mesh, + min_resolution = m_min_resolution, z_distance_bottom_layers, xy_distance, &data_placeable, &throw_on_cancel] + (const tbb::blocked_range& range) { + for (LayerIndex layer_idx = range.begin(); layer_idx != range.end(); ++ layer_idx) { + LayerIndex layer_idx_below = layer_idx - z_distance_bottom_layers - 1; + assert(layer_idx_below >= 0); + const Polygons ¤t = collision_areas_offsetted[layer_idx]; + const Polygons &below = outlines[layer_idx_below]; + Polygons placable = diff( + // Inflate the surface to sit on by the separation distance to increase chance of a support being placed on a sloped surface. + offset(below, xy_distance), + layer_idx_below < int(anti_overhang.size()) ? union_(current, anti_overhang[layer_idx_below]) : current); + auto &dst = data_placeable[layer_idx]; + if (processing_last_mesh) { + if (! dst.empty()) + placable = union_(placable, dst); + dst = polygons_simplify(placable, min_resolution, polygons_strictly_simple); + } else + append(dst, placable); + throw_on_cancel(); + } + }); + } else { + // Calculating just the collision areas. + } + } +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + { + std::lock_guard critical_section(*m_critical_progress); + if (m_precalculated && m_precalculation_progress < TREE_PROGRESS_PRECALC_COLL) { + m_precalculation_progress += TREE_PROGRESS_PRECALC_COLL / keys.size(); + Progress::messageProgress(Progress::Stage::SUPPORT, m_precalculation_progress * m_progress_multiplier + m_progress_offset, TREE_PROGRESS_TOTAL); + } + } +#endif + throw_on_cancel(); + m_collision_cache.insert(std::move(data), radius); + if (calculate_placable) + m_placeable_areas_cache.insert(std::move(data_placeable), radius); +} + +void TreeModelVolumes::calculateCollisionHolefree(const std::vector &keys, std::function throw_on_cancel) +{ + LayerIndex max_layer = 0; + for (long long unsigned int i = 0; i < keys.size(); i++) + max_layer = std::max(max_layer, keys[i].second); + + tbb::parallel_for(tbb::blocked_range(0, max_layer + 1, keys.size()), + [&](const tbb::blocked_range &range) { + std::vector> data; + data.reserve(range.size() * keys.size()); + for (LayerIndex layer_idx = range.begin(); layer_idx < range.end(); ++ layer_idx) { + for (RadiusLayerPair key : keys) + if (layer_idx <= key.second) { + // Logically increase the collision by m_increase_until_radius + coord_t radius = key.first; + assert(radius == this->ceilRadius(radius)); + assert(radius < m_increase_until_radius + m_current_min_xy_dist_delta); + coord_t increase_radius_ceil = ceilRadius(m_increase_until_radius, false) - radius; + assert(increase_radius_ceil > 0); + // this union is important as otherwise holes(in form of lines that will increase to holes in a later step) can get unioned onto the area. + data.emplace_back(RadiusLayerPair(radius, layer_idx), polygons_simplify( + offset(union_ex(this->getCollision(m_increase_until_radius, layer_idx, false)), + 5 - increase_radius_ceil, ClipperLib::jtRound, m_min_resolution), + m_min_resolution, polygons_strictly_simple)); + throw_on_cancel(); + } + } + m_collision_cache_holefree.insert(std::move(data)); + }); +} + +void TreeModelVolumes::calculateAvoidance(const std::vector &keys, bool to_build_plate, bool to_model, std::function throw_on_cancel) +{ + // For every RadiusLayer pair there are 3 avoidances that have to be calculated. + // Prepare tasks for parallelization. + struct AvoidanceTask { + AvoidanceType type; + coord_t radius; + LayerIndex max_required_layer; + bool to_model; + LayerIndex start_layer; + + bool slow() const { return this->type == AvoidanceType::Slow; } + bool holefree() const { return this->type == AvoidanceType::FastSafe; } + }; + + std::vector avoidance_tasks; + avoidance_tasks.reserve((int(to_build_plate) + int(to_model)) * keys.size() * size_t(AvoidanceType::Count)); + + for (int iter_idx = 0; iter_idx < 2 * int(keys.size()) * int(AvoidanceType::Count); ++ iter_idx) { + AvoidanceTask task{ + AvoidanceType(iter_idx % int(AvoidanceType::Count)), + keys[iter_idx / 6].first, // radius + keys[iter_idx / 6].second, // max_layer + ((iter_idx / 3) & 1) != 0 // to_model + }; + // Ensure start_layer is at least 1 as if no avoidance was calculated yet getMaxCalculatedLayer() returns -1. + task.start_layer = std::max(1, 1 + avoidance_cache(task.type, task.to_model).getMaxCalculatedLayer(task.radius)); + if (task.start_layer > task.max_required_layer) { + BOOST_LOG_TRIVIAL(debug) << "Calculation requested for value already calculated?"; + continue; + } + if ((task.to_model ? to_model : to_build_plate) && + (! task.holefree() || task.radius < m_increase_until_radius + m_current_min_xy_dist_delta)) + avoidance_tasks.emplace_back(task); + } + + throw_on_cancel(); + + tbb::parallel_for(tbb::blocked_range(0, avoidance_tasks.size(), 1), + [this, &avoidance_tasks, &throw_on_cancel](const tbb::blocked_range &range) { + for (size_t task_idx = range.begin(); task_idx < range.end(); ++ task_idx) { + const AvoidanceTask &task = avoidance_tasks[task_idx]; + assert(! task.holefree() || task.radius < m_increase_until_radius + m_current_min_xy_dist_delta); + if (task.to_model) + // ensuring Placeableareas are calculated + //FIXME pass throw_on_cancel + getPlaceableAreas(task.radius, task.max_required_layer, throw_on_cancel); + // The following loop propagating avoidance regions bottom up is inherently serial. + const bool collision_holefree = (task.slow() || task.holefree()) && task.radius < m_increase_until_radius + m_current_min_xy_dist_delta; + const float max_move = task.slow() ? m_max_move_slow : m_max_move; + // Limiting the offset step so that unioning the shrunk latest_avoidance with the current layer collisions + // will not create gaps in the resulting avoidance region letting a tree support branch tunneling through an object wall. + float move_step = 1.9 * std::max(task.radius, m_current_min_xy_dist); + int move_steps = round_up_divide(max_move, move_step); + assert(move_steps > 0); + float last_move_step = max_move - (move_steps - 1) * move_step; + if (last_move_step < scaled(0.05)) { + assert(move_steps > 1); + if (move_steps > 1) { + // Avoid taking a very short last step, stretch the other steps a bit instead. + move_step = max_move / (-- move_steps); + last_move_step = move_step; + } + } + // minDist as the delta was already added, also avoidance for layer 0 will return the collision. + Polygons latest_avoidance = getAvoidance(task.radius, task.start_layer - 1, task.type, task.to_model, true); + std::vector> data; + data.reserve(task.max_required_layer + 1 - task.start_layer); + for (LayerIndex layer_idx = task.start_layer; layer_idx <= task.max_required_layer; ++ layer_idx) { + // Merge current layer collisions with shrunk last_avoidance. + const Polygons ¤t_layer_collisions = collision_holefree ? getCollisionHolefree(task.radius, layer_idx) : getCollision(task.radius, layer_idx, true); + // For mildly steep branch angles only one step will be taken. + for (int istep = 0; istep < move_steps; ++ istep) + latest_avoidance = union_(current_layer_collisions, + offset(latest_avoidance, + istep + 1 == move_steps ? - last_move_step : - move_step, + ClipperLib::jtRound, m_min_resolution)); + if (task.to_model) + latest_avoidance = diff(latest_avoidance, getPlaceableAreas(task.radius, layer_idx, throw_on_cancel)); + latest_avoidance = polygons_simplify(latest_avoidance, m_min_resolution, polygons_strictly_simple); + data.emplace_back(RadiusLayerPair{task.radius, layer_idx}, latest_avoidance); + throw_on_cancel(); + } +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + { + std::lock_guard critical_section(*m_critical_progress); + if (m_precalculated && m_precalculation_progress < TREE_PROGRESS_PRECALC_COLL + TREE_PROGRESS_PRECALC_AVO) { + m_precalculation_progress += to_model ? + 0.4 * TREE_PROGRESS_PRECALC_AVO / (keys.size() * 3) : + m_support_rests_on_model ? 0.4 : 1 * TREE_PROGRESS_PRECALC_AVO / (keys.size() * 3); + Progress::messageProgress(Progress::Stage::SUPPORT, m_precalculation_progress * m_progress_multiplier + m_progress_offset, TREE_PROGRESS_TOTAL); + } + } +#endif + avoidance_cache(task.type, task.to_model).insert(std::move(data)); + } + }); +} + + +void TreeModelVolumes::calculatePlaceables(const std::vector &keys, std::function throw_on_cancel) +{ + tbb::parallel_for(tbb::blocked_range(0, keys.size()), + [&, keys](const tbb::blocked_range& range) { + for (size_t key_idx = range.begin(); key_idx < range.end(); ++ key_idx) + this->calculatePlaceables(keys[key_idx].first, keys[key_idx].second, throw_on_cancel); + }); +} + +void TreeModelVolumes::calculatePlaceables(const coord_t radius, const LayerIndex max_required_layer, std::function throw_on_cancel) +{ + LayerIndex start_layer = 1 + m_placeable_areas_cache.getMaxCalculatedLayer(radius); + if (start_layer > max_required_layer) { + BOOST_LOG_TRIVIAL(debug) << "Requested calculation for value already calculated ?"; + return; + } + + std::vector data(max_required_layer + 1 - start_layer, Polygons{}); + + if (start_layer == 0) + data[0] = diff(m_machine_border, getCollision(radius, 0, true)); + + tbb::parallel_for(tbb::blocked_range(std::max(1, start_layer), max_required_layer + 1), + [this, &data, radius, start_layer, &throw_on_cancel](const tbb::blocked_range& range) { + for (LayerIndex layer_idx = range.begin(); layer_idx < range.end(); ++ layer_idx) { + data[layer_idx - start_layer] = offset( + union_ex(getPlaceableAreas(0, layer_idx, throw_on_cancel)), + // As a placeable area is calculated by (collision of the layer below) - (collision of the current layer) and the collision is offset by xy_distance, + // it can happen that a small line is considered a flat area to place something onto, even though it is mostly + // xy_distance that cant support it. Making the area smaller by xy_distance fixes this. + - (radius + m_current_min_xy_dist + m_current_min_xy_dist_delta), + jtMiter, 1.2); + throw_on_cancel(); + } + }); +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + { + std::lock_guard critical_section(*m_critical_progress); + if (m_precalculated && m_precalculation_progress < TREE_PROGRESS_PRECALC_COLL + TREE_PROGRESS_PRECALC_AVO) { + m_precalculation_progress += 0.2 * TREE_PROGRESS_PRECALC_AVO / (keys.size()); + Progress::messageProgress(Progress::Stage::SUPPORT, m_precalculation_progress * m_progress_multiplier + m_progress_offset, TREE_PROGRESS_TOTAL); + } + } +#endif + m_placeable_areas_cache.insert(std::move(data), start_layer, radius); +} + +void TreeModelVolumes::calculateWallRestrictions(const std::vector &keys, std::function throw_on_cancel) +{ + // Wall restrictions are mainly important when they represent actual walls that are printed, and not "just" the configured z_distance, because technically valid placement is no excuse for moving through a wall. + // As they exist to prevent accidentially moving though a wall at high speed between layers like thie (x = wall,i = influence area,o= empty space,d = blocked area because of z distance) Assume maximum movement distance is two characters and maximum safe movement distance of one character + + /* Potential issue addressed by the wall restrictions: Influence area may lag through a wall + * layer z+1:iiiiiiiiiiioooo + * layer z+0:xxxxxiiiiiiiooo + * layer z-1:ooooixxxxxxxxxx + */ + + // The radius for the upper collission has to be 0 as otherwise one may not enter areas that may be forbidden on layer_idx but not one below (c = not an influence area even though it should ): + /* + * layer z+1:xxxxxiiiiiioo + * layer z+0:dddddiiiiiiio + * layer z-1:dddocdddddddd + */ + // Also there can not just the collision of the lower layer be used because if it were: + /* + * layer z+1:dddddiiiiiiiiiio + * layer z+0:xxxxxddddddddddc + * layer z-1:dddddxxxxxxxxxxc + */ + // Or of the upper layer be used because if it were: + /* + * layer z+1:dddddiiiiiiiiiio + * layer z+0:xxxxcddddddddddc + * layer z-1:ddddcxxxxxxxxxxc + */ + + // And just offseting with maximum movement distance (and not in multiple steps) could cause: + /* + * layer z: oxiiiiiiiiioo + * layer z-1: ixiiiiiiiiiii + */ + + tbb::parallel_for(tbb::blocked_range(0, keys.size()), + [&, keys](const tbb::blocked_range &range) { + for (size_t key_idx = range.begin(); key_idx < range.end(); ++ key_idx) { + const coord_t radius = keys[key_idx].first; + const LayerIndex max_required_layer = keys[key_idx].second; + const coord_t min_layer_bottom = std::max(1, m_wall_restrictions_cache.getMaxCalculatedLayer(radius)); + const size_t buffer_size = max_required_layer + 1 - min_layer_bottom; + std::vector data(buffer_size, Polygons{}); + std::vector data_min; + if (m_current_min_xy_dist_delta > 0) + data_min.assign(buffer_size, Polygons{}); + tbb::parallel_for(tbb::blocked_range(min_layer_bottom, max_required_layer + 1), + [this, &data, &data_min, radius, min_layer_bottom, &throw_on_cancel](const tbb::blocked_range &range) { + for (LayerIndex layer_idx = range.begin(); layer_idx < range.end(); ++ layer_idx) { + data[layer_idx - min_layer_bottom] = polygons_simplify( + // radius contains m_current_min_xy_dist_delta already if required + intersection(getCollision(0, layer_idx, false), getCollision(radius, layer_idx - 1, true)), + m_min_resolution, polygons_strictly_simple); + if (! data_min.empty()) + data_min[layer_idx - min_layer_bottom] = + polygons_simplify( + intersection(getCollision(0, layer_idx, true), getCollision(radius, layer_idx - 1, true)), + m_min_resolution, polygons_strictly_simple); + throw_on_cancel(); + } + }); + m_wall_restrictions_cache.insert(std::move(data), min_layer_bottom, radius); + if (! data_min.empty()) + m_wall_restrictions_cache_min.insert(std::move(data_min), min_layer_bottom, radius); + } + }); +} + +coord_t TreeModelVolumes::ceilRadius(const coord_t radius) const +{ + if (radius == 0) + return 0; + + coord_t out = m_radius_0; + if (radius > m_radius_0) { + // generate SUPPORT_TREE_PRE_EXPONENTIAL_STEPS of radiis before starting to exponentially increase them. + coord_t initial_radius_delta = SUPPORT_TREE_EXPONENTIAL_THRESHOLD - m_radius_0; + auto ignore = [this](coord_t r) { return std::binary_search(m_ignorable_radii.begin(), m_ignorable_radii.end(), r); }; + if (initial_radius_delta > SUPPORT_TREE_COLLISION_RESOLUTION) { + const int num_steps = round_up_divide(initial_radius_delta, SUPPORT_TREE_EXPONENTIAL_THRESHOLD); + const int stepsize = initial_radius_delta / num_steps; + out += stepsize; + for (auto step = 0; step < num_steps; ++ step) { + if (out >= radius && ! ignore(out)) + return out; + out += stepsize; + } + } else + out += SUPPORT_TREE_COLLISION_RESOLUTION; + while (out < radius || ignore(out)) { + assert(out * SUPPORT_TREE_EXPONENTIAL_FACTOR > out + SUPPORT_TREE_COLLISION_RESOLUTION); + out = out * SUPPORT_TREE_EXPONENTIAL_FACTOR; + } + } + return out; +} + +void TreeModelVolumes::RadiusLayerPolygonCache::allocate_layers(size_t num_layers) +{ + if (num_layers > m_data.size()) { + if (num_layers > m_data.capacity()) + reserve_power_of_2(m_data, num_layers); + m_data.resize(num_layers, {}); + } +} + +// For debugging purposes, sorted by layer index, then by radius. +std::vector>> TreeModelVolumes::RadiusLayerPolygonCache::sorted() const +{ + std::vector>> out; + for (auto &layer : m_data) { + auto layer_idx = LayerIndex(&layer - m_data.data()); + for (auto &radius_polygons : layer) + out.emplace_back(std::make_pair(radius_polygons.first, layer_idx), radius_polygons.second); + } + assert(std::is_sorted(out.begin(), out.end(), [](auto &l, auto &r){ return l.first.second < r.first.second || (l.first.second == r.first.second) && l.first.first < r.first.first; })); + return out; +} + +} // namespace Slic3r::FFFTreeSupport diff --git a/src/libslic3r/Support/TreeModelVolumes.hpp b/src/libslic3r/Support/TreeModelVolumes.hpp new file mode 100644 index 0000000000..57ca9fae7a --- /dev/null +++ b/src/libslic3r/Support/TreeModelVolumes.hpp @@ -0,0 +1,558 @@ +///|/ Copyright (c) Prusa Research 2022 - 2023 Vojtěch Bubník @bubnikv, Oleksandra Iushchenko @YuSanka +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +// Tree supports by Thomas Rahm, losely based on Tree Supports by CuraEngine. +// Original source of Thomas Rahm's tree supports: +// https://github.com/ThomasRahm/CuraEngine +// +// Original CuraEngine copyright: +// Copyright (c) 2021 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. + +#ifndef slic3r_TreeModelVolumes_hpp +#define slic3r_TreeModelVolumes_hpp + +#include +#include + +#include + +#include "TreeSupportCommon.hpp" + +#include "../Point.hpp" +#include "../Polygon.hpp" +#include "../PrintConfig.hpp" + +namespace Slic3r +{ + +class BuildVolume; +class PrintObject; + +namespace FFFTreeSupport +{ + +static constexpr const double SUPPORT_TREE_EXPONENTIAL_FACTOR = 1.5; +static constexpr const coord_t SUPPORT_TREE_EXPONENTIAL_THRESHOLD = scaled(1. * SUPPORT_TREE_EXPONENTIAL_FACTOR); +static constexpr const coord_t SUPPORT_TREE_COLLISION_RESOLUTION = scaled(0.5); +static constexpr const bool SUPPORT_TREE_AVOID_SUPPORT_BLOCKER = true; + +class TreeModelVolumes +{ +public: + TreeModelVolumes() = default; + explicit TreeModelVolumes(const PrintObject &print_object, const BuildVolume &build_volume, + coord_t max_move, coord_t max_move_slow, size_t current_mesh_idx, +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + double progress_multiplier, + double progress_offset, +#endif // SLIC3R_TREESUPPORTS_PROGRESS + const std::vector &additional_excluded_areas = {}); + TreeModelVolumes(TreeModelVolumes&&) = default; + TreeModelVolumes& operator=(TreeModelVolumes&&) = default; + + TreeModelVolumes(const TreeModelVolumes&) = delete; + TreeModelVolumes& operator=(const TreeModelVolumes&) = delete; + + void clear() { + this->clear_all_but_object_collision(); + m_collision_cache.clear(); + m_placeable_areas_cache.clear(); + } + void clear_all_but_object_collision() { + //m_collision_cache.clear_all_but_radius0(); + m_collision_cache_holefree.clear(); + m_avoidance_cache.clear(); + m_avoidance_cache_slow.clear(); + m_avoidance_cache_to_model.clear(); + m_avoidance_cache_to_model_slow.clear(); + m_placeable_areas_cache.clear_all_but_radius0(); + m_avoidance_cache_holefree.clear(); + m_avoidance_cache_holefree_to_model.clear(); + m_wall_restrictions_cache.clear(); + m_wall_restrictions_cache_min.clear(); + } + + enum class AvoidanceType : int8_t + { + Slow, + FastSafe, + Fast, + Count + }; + + /*! + * \brief Precalculate avoidances and collisions up to max_layer. + * + * Knowledge about branch angle is used to only calculate avoidances and collisions that may actually be needed. + * Not calling precalculate() will cause the class to lazily calculate avoidances and collisions as needed, which will be a lot slower on systems with more then one or two cores! + */ + void precalculate(const PrintObject& print_object, const coord_t max_layer, std::function throw_on_cancel); + + /*! + * \brief Provides the areas that have to be avoided by the tree's branches to prevent collision with the model on this layer. + * + * The result is a 2D area that would cause nodes of radius \p radius to + * collide with the model. + * + * \param radius The radius of the node of interest + * \param layer_idx The layer of interest + * \param min_xy_dist Is the minimum xy distance used. + * \return Polygons object + */ + const Polygons& getCollision(const coord_t radius, LayerIndex layer_idx, bool min_xy_dist) const; + + // Get a collision area at a given layer for a radius that is a lower or equial to the key radius. + // It is expected that the collision area is precalculated for a given layer at least for the radius zero. + // Used for pushing tree supports away from object during the final Organic optimization step. + std::optional>> get_collision_lower_bound_area(LayerIndex layer_id, coord_t max_radius) const; + + /*! + * \brief Provides the areas that have to be avoided by the tree's branches + * in order to reach the build plate. + * + * The result is a 2D area that would cause nodes of radius \p radius to + * collide with the model or be unable to reach the build platform. + * + * The input collision areas are inset by the maximum move distance and + * propagated upwards. + * + * \param radius The radius of the node of interest + * \param layer_idx The layer of interest + * \param type Is the propagation with the maximum move distance slow required. + * \param to_model Does the avoidance allow good connections with the model. + * \param min_xy_dist is the minimum xy distance used. + * \return Polygons object + */ + const Polygons& getAvoidance(coord_t radius, LayerIndex layer_idx, AvoidanceType type, bool to_model, bool min_xy_dist) const; + /*! + * \brief Provides the area represents all areas on the model where the branch does completely fit on the given layer. + * \param radius The radius of the node of interest + * \param layer_idx The layer of interest + * \return Polygons object + */ + const Polygons& getPlaceableAreas(coord_t radius, LayerIndex layer_idx, std::function throw_on_cancel) const; + /*! + * \brief Provides the area that represents the walls, as in the printed area, of the model. This is an abstract representation not equal with the outline. See calculateWallRestrictions for better description. + * \param radius The radius of the node of interest. + * \param layer_idx The layer of interest. + * \param min_xy_dist is the minimum xy distance used. + * \return Polygons object + */ + const Polygons& getWallRestriction(coord_t radius, LayerIndex layer_idx, bool min_xy_dist) const; + /*! + * \brief Round \p radius upwards to either a multiple of m_radius_sample_resolution or a exponentially increasing value + * + * It also adds the difference between the minimum xy distance and the regular one. + * + * \param radius The radius of the node of interest + * \param min_xy_dist is the minimum xy distance used. + * \return The rounded radius + */ + coord_t ceilRadius(const coord_t radius, const bool min_xy_dist) const { + assert(radius >= 0); + return min_xy_dist ? + this->ceilRadius(radius) : + // special case as if a radius 0 is requested it could be to ensure correct xy distance. As such it is beneficial if the collision is as close to the configured values as possible. + radius > 0 ? this->ceilRadius(radius + m_current_min_xy_dist_delta) : m_current_min_xy_dist_delta; + } + /*! + * \brief Round \p radius upwards to the maximum that would still round up to the same value as the provided one. + * + * \param radius The radius of the node of interest + * \param min_xy_dist is the minimum xy distance used. + * \return The maximum radius, resulting in the same rounding. + */ + coord_t getRadiusNextCeil(coord_t radius, bool min_xy_dist) const { + assert(radius > 0); + return min_xy_dist ? + this->ceilRadius(radius) : + this->ceilRadius(radius + m_current_min_xy_dist_delta) - m_current_min_xy_dist_delta; + } + +private: + // Caching polygons for a range of layers. + class LayerPolygonCache { + public: + void allocate(LayerIndex aidx_begin, LayerIndex aidx_end) { + m_idx_begin = aidx_begin; + m_idx_end = aidx_end; + m_polygons.assign(aidx_end - aidx_begin, {}); + } + + LayerIndex begin() const { return m_idx_begin; } + LayerIndex end() const { return m_idx_end; } + size_t size() const { return m_polygons.size(); } + + bool has(LayerIndex idx) const { return idx >= m_idx_begin && idx < m_idx_end; } + Polygons& operator[](LayerIndex idx) { assert(idx >= m_idx_begin && idx < m_idx_end); return m_polygons[idx - m_idx_begin]; } + std::vector& polygons_mutable() { return m_polygons; } + + private: + std::vector m_polygons; + LayerIndex m_idx_begin; + LayerIndex m_idx_end; + }; + + /*! + * \brief Convenience typedef for the keys to the caches + */ + using RadiusLayerPair = std::pair; + class RadiusLayerPolygonCache { + // Map from radius to Polygons. Cache of one layer collision regions. + using LayerData = std::map; + // Vector of layers, at each layer map of radius to Polygons. + // Reference to Polygons returned shall be stable to insertion. + using Layers = std::vector; + public: + RadiusLayerPolygonCache() = default; + RadiusLayerPolygonCache(RadiusLayerPolygonCache &&rhs) : m_data(std::move(rhs.m_data)) {} + RadiusLayerPolygonCache& operator=(RadiusLayerPolygonCache &&rhs) { m_data = std::move(rhs.m_data); return *this; } + + RadiusLayerPolygonCache(const RadiusLayerPolygonCache&) = delete; + RadiusLayerPolygonCache& operator=(const RadiusLayerPolygonCache&) = delete; + + void insert(std::vector> &&in) { + std::lock_guard guard(m_mutex); + for (auto &d : in) + this->get_allocate_layer_data(d.first.second).emplace(d.first.first, std::move(d.second)); + } + // by layer + void insert(std::vector> &&in, coord_t radius) { + std::lock_guard guard(m_mutex); + for (auto &d : in) + this->get_allocate_layer_data(d.first).emplace(radius, std::move(d.second)); + } + void insert(std::vector &&in, coord_t first_layer_idx, coord_t radius) { + std::lock_guard guard(m_mutex); + allocate_layers(first_layer_idx + in.size()); + for (auto &d : in) + m_data[first_layer_idx ++].emplace(radius, std::move(d)); + } + void insert(LayerPolygonCache &&in, coord_t radius) { + std::lock_guard guard(m_mutex); + LayerIndex i = in.begin(); + allocate_layers(i + LayerIndex(in.size())); + for (auto &d : in.polygons_mutable()) + m_data[i ++].emplace(radius, std::move(d)); + } + /*! + * \brief Checks a cache for a given RadiusLayerPair and returns it if it is found + * \param key RadiusLayerPair of the requested areas. The radius will be calculated up to the provided layer. + * \return A wrapped optional reference of the requested area (if it was found, an empty optional if nothing was found) + */ + std::optional> getArea(const TreeModelVolumes::RadiusLayerPair &key) const { + std::lock_guard guard(m_mutex); + if (key.second >= LayerIndex(m_data.size())) + return std::optional>{}; + const auto &layer = m_data[key.second]; + auto it = layer.find(key.first); + return it == layer.end() ? + std::optional>{} : std::optional>{ it->second }; + } + // Get a collision area at a given layer for a radius that is a lower or equial to the key radius. + std::optional>> get_lower_bound_area(const TreeModelVolumes::RadiusLayerPair &key) const { + std::lock_guard guard(m_mutex); + if (key.second >= LayerIndex(m_data.size())) + return {}; + const auto &layer = m_data[key.second]; + if (layer.empty()) + return {}; + auto it = layer.lower_bound(key.first); + if (it == layer.end() || it->first != key.first) { + if (it == layer.begin()) + return {}; + -- it; + } + return std::make_pair(it->first, std::reference_wrapper(it->second)); + } + /*! + * \brief Get the highest already calculated layer in the cache. + * \param radius The radius for which the highest already calculated layer has to be found. + * \param map The cache in which the lookup is performed. + * + * \return A wrapped optional reference of the requested area (if it was found, an empty optional if nothing was found) + */ + LayerIndex getMaxCalculatedLayer(coord_t radius) const { + std::lock_guard guard(m_mutex); + auto layer_idx = LayerIndex(m_data.size()) - 1; + for (; layer_idx > 0; -- layer_idx) + if (const auto &layer = m_data[layer_idx]; layer.find(radius) != layer.end()) + break; + // The placeable on model areas do not exist on layer 0, as there can not be model below it. As such it may be possible that layer 1 is available, but layer 0 does not exist. + return layer_idx == 0 ? -1 : layer_idx; + } + + // For debugging purposes, sorted by layer index, then by radius. + [[nodiscard]] std::vector>> sorted() const; + + void clear() { m_data.clear(); } + void clear_all_but_radius0() { + for (LayerData &l : m_data) { + auto begin = l.begin(); + auto end = l.end(); + if (begin != end && ++ begin != end) + l.erase(begin, end); + } + } + + private: + LayerData& get_allocate_layer_data(LayerIndex layer_idx) { + allocate_layers(layer_idx + 1); + return m_data[layer_idx]; + } + void allocate_layers(size_t num_layers); + + Layers m_data; + mutable std::mutex m_mutex; + }; + + + /*! + * \brief Provides the areas that have to be avoided by the tree's branches to prevent collision with the model on this layer. Holes are removed. + * + * The result is a 2D area that would cause nodes of given radius to + * collide with the model or be inside a hole. + * A Hole is defined as an area, in which a branch with m_increase_until_radius radius would collide with the wall. + * minimum xy distance is always used. + * \param radius The radius of the node of interest + * \param layer_idx The layer of interest + * \param min_xy_dist Is the minimum xy distance used. + * \return Polygons object + */ + const Polygons& getCollisionHolefree(coord_t radius, LayerIndex layer_idx) const; + + /*! + * \brief Round \p radius upwards to either a multiple of m_radius_sample_resolution or a exponentially increasing value + * + * \param radius The radius of the node of interest + */ + coord_t ceilRadius(const coord_t radius) const; + + /*! + * \brief Creates the areas that have to be avoided by the tree's branches to prevent collision with the model on this layer. + * + * The result is a 2D area that would cause nodes of given radius to + * collide with the model. Result is saved in the cache. + * \param keys RadiusLayerPairs of all requested areas. Every radius will be calculated up to the provided layer. + */ + void calculateCollision(const std::vector &keys, std::function throw_on_cancel); + void calculateCollision(const coord_t radius, const LayerIndex max_layer_idx, std::function throw_on_cancel); + /*! + * \brief Creates the areas that have to be avoided by the tree's branches to prevent collision with the model on this layer. Holes are removed. + * + * The result is a 2D area that would cause nodes of given radius to + * collide with the model or be inside a hole. Result is saved in the cache. + * A Hole is defined as an area, in which a branch with m_increase_until_radius radius would collide with the wall. + * \param keys RadiusLayerPairs of all requested areas. Every radius will be calculated up to the provided layer. + */ + void calculateCollisionHolefree(const std::vector &keys, std::function throw_on_cancel); + + /*! + * \brief Creates the areas that have to be avoided by the tree's branches to prevent collision with the model on this layer. Holes are removed. + * + * The result is a 2D area that would cause nodes of given radius to + * collide with the model or be inside a hole. Result is saved in the cache. + * A Hole is defined as an area, in which a branch with m_increase_until_radius radius would collide with the wall. + * \param key RadiusLayerPairs the requested areas. The radius will be calculated up to the provided layer. + */ + void calculateCollisionHolefree(RadiusLayerPair key) + { + calculateCollisionHolefree(std::vector{ RadiusLayerPair(key) }, []{}); + } + + /*! + * \brief Creates the areas that have to be avoided by the tree's branches to prevent collision with the model. + * + * The result is a 2D area that would cause nodes of radius \p radius to + * collide with the model. Result is saved in the cache. + * \param keys RadiusLayerPairs of all requested areas. Every radius will be calculated up to the provided layer. + */ + void calculateAvoidance(const std::vector &keys, bool to_build_plate, bool to_model, std::function throw_on_cancel); + + /*! + * \brief Creates the areas that have to be avoided by the tree's branches to prevent collision with the model. + * + * The result is a 2D area that would cause nodes of radius \p radius to + * collide with the model. Result is saved in the cache. + * \param key RadiusLayerPair of the requested areas. It will be calculated up to the provided layer. + */ + void calculateAvoidance(RadiusLayerPair key, bool to_build_plate, bool to_model) + { + calculateAvoidance(std::vector{ RadiusLayerPair(key) }, to_build_plate, to_model, []{}); + } + + /*! + * \brief Creates the areas where a branch of a given radius can be place on the model. + * Result is saved in the cache. + * \param key RadiusLayerPair of the requested areas. It will be calculated up to the provided layer. + */ + void calculatePlaceables(const coord_t radius, const LayerIndex max_required_layer, std::function throw_on_cancel); + + + /*! + * \brief Creates the areas where a branch of a given radius can be placed on the model. + * Result is saved in the cache. + * \param keys RadiusLayerPair of the requested areas. The radius will be calculated up to the provided layer. + */ + void calculatePlaceables(const std::vector &keys, std::function throw_on_cancel); + + /*! + * \brief Creates the areas that can not be passed when expanding an area downwards. As such these areas are an somewhat abstract representation of a wall (as in a printed object). + * + * These areas are at least xy_min_dist wide. When calculating it is always assumed that every wall is printed on top of another (as in has an overlap with the wall a layer below). Result is saved in the corresponding cache. + * + * \param keys RadiusLayerPairs of all requested areas. Every radius will be calculated up to the provided layer. + */ + void calculateWallRestrictions(const std::vector &keys, std::function throw_on_cancel); + + /*! + * \brief Creates the areas that can not be passed when expanding an area downwards. As such these areas are an somewhat abstract representation of a wall (as in a printed object). + * These areas are at least xy_min_dist wide. When calculating it is always assumed that every wall is printed on top of another (as in has an overlap with the wall a layer below). Result is saved in the corresponding cache. + * \param key RadiusLayerPair of the requested area. It well be will be calculated up to the provided layer. + */ + void calculateWallRestrictions(RadiusLayerPair key) + { + calculateWallRestrictions(std::vector{ RadiusLayerPair(key) }, []{}); + } + + /*! + * \brief The maximum distance that the center point of a tree branch may move in consecutive layers if it has to avoid the model. + */ + coord_t m_max_move; + /*! + * \brief The maximum distance that the centre-point of a tree branch may + * move in consecutive layers if it does not have to avoid the model + */ + coord_t m_max_move_slow; + /*! + * \brief The smallest maximum resolution for simplify + */ + coord_t m_min_resolution; + + bool m_precalculated = false; + /*! + * \brief The index to access the outline corresponding with the currently processing mesh + */ + size_t m_current_outline_idx; + /*! + * \brief The minimum required clearance between the model and the tree branches + */ + coord_t m_current_min_xy_dist; + /*! + * \brief The difference between the minimum required clearance between the model and the tree branches and the regular one. + */ + coord_t m_current_min_xy_dist_delta; + /*! + * \brief Does at least one mesh allow support to rest on a model. + */ + bool m_support_rests_on_model; +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + /*! + * \brief The progress of the precalculate function for communicating it to the progress bar. + */ + coord_t m_precalculation_progress = 0; + /*! + * \brief The progress multiplier of all values added progress bar. + * Required for the progress bar the behave as expected when areas have to be calculated multiple times + */ + double m_progress_multiplier; + /*! + * \brief The progress offset added to all values communicated to the progress bar. + * Required for the progress bar the behave as expected when areas have to be calculated multiple times + */ + double m_progress_offset; +#endif // SLIC3R_TREESUPPORTS_PROGRESS + /*! + * \brief Increase radius in the resulting drawn branches, even if the avoidance does not allow it. Will be cut later to still fit. + */ + coord_t m_increase_until_radius; + + /*! + * \brief Polygons representing the limits of the printable area of the + * machine + */ + Polygons m_machine_border; + /*! + * \brief Storage for layer outlines and the corresponding settings of the meshes grouped by meshes with identical setting. + */ + std::vector>> m_layer_outlines; + /*! + * \brief Storage for areas that should be avoided, like support blocker or previous generated trees. + */ + std::vector m_anti_overhang; + /*! + * \brief Radii that can be ignored by ceilRadius as they will never be requested, sorted. + */ + std::vector m_ignorable_radii; + + /*! + * \brief Smallest radius a branch can have. This is the radius of a SupportElement with DTT=0. + */ + coord_t m_radius_0; + + // Z heights of the raft layers (additional layers below the object, last raft layer aligned with the bottom of the first object layer). + std::vector m_raft_layers; + + /*! + * \brief Caches for the collision, avoidance and areas on the model where support can be placed safely + * at given radius and layer indices. + */ + RadiusLayerPolygonCache m_collision_cache; + RadiusLayerPolygonCache m_collision_cache_holefree; + RadiusLayerPolygonCache m_avoidance_cache; + RadiusLayerPolygonCache m_avoidance_cache_slow; + RadiusLayerPolygonCache m_avoidance_cache_to_model; + RadiusLayerPolygonCache m_avoidance_cache_to_model_slow; + RadiusLayerPolygonCache m_placeable_areas_cache; + + /*! + * \brief Caches to avoid holes smaller than the radius until which the radius is always increased, as they are free of holes. + * Also called safe avoidances, as they are safe regarding not running into holes. + */ + RadiusLayerPolygonCache m_avoidance_cache_holefree; + RadiusLayerPolygonCache m_avoidance_cache_holefree_to_model; + + RadiusLayerPolygonCache& avoidance_cache(const AvoidanceType type, const bool to_model) { + if (to_model) { + switch (type) { + case AvoidanceType::Fast: return m_avoidance_cache_to_model; + case AvoidanceType::Slow: return m_avoidance_cache_to_model_slow; + case AvoidanceType::Count: assert(false); + case AvoidanceType::FastSafe: return m_avoidance_cache_holefree_to_model; + } + } else { + switch (type) { + case AvoidanceType::Fast: return m_avoidance_cache; + case AvoidanceType::Slow: return m_avoidance_cache_slow; + case AvoidanceType::Count: assert(false); + case AvoidanceType::FastSafe: return m_avoidance_cache_holefree; + } + } + assert(false); + return m_avoidance_cache; + } + const RadiusLayerPolygonCache& avoidance_cache(const AvoidanceType type, const bool to_model) const { + return const_cast(this)->avoidance_cache(type, to_model); + } + + /*! + * \brief Caches to represent walls not allowed to be passed over. + */ + RadiusLayerPolygonCache m_wall_restrictions_cache; + + // A different cache for min_xy_dist as the maximal safe distance an influence area can be increased(guaranteed overlap of two walls in consecutive layer) + // is much smaller when min_xy_dist is used. This causes the area of the wall restriction to be thinner and as such just using the min_xy_dist wall + // restriction would be slower. + RadiusLayerPolygonCache m_wall_restrictions_cache_min; + +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + std::unique_ptr m_critical_progress { std::make_unique() }; +#endif // SLIC3R_TREESUPPORTS_PROGRESS +}; + +} // namespace FFFTreeSupport +} // namespace Slic3r + +#endif //slic3r_TreeModelVolumes_hpp diff --git a/src/libslic3r/Support/TreeSupport.cpp b/src/libslic3r/Support/TreeSupport.cpp new file mode 100644 index 0000000000..b119824c69 --- /dev/null +++ b/src/libslic3r/Support/TreeSupport.cpp @@ -0,0 +1,3637 @@ +///|/ Copyright (c) Prusa Research 2022 - 2023 Vojtěch Bubník @bubnikv, Lukáš Matěna @lukasmatena, Tomáš Mészáros @tamasmeszaros +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +// Tree supports by Thomas Rahm, losely based on Tree Supports by CuraEngine. +// Original source of Thomas Rahm's tree supports: +// https://github.com/ThomasRahm/CuraEngine +// +// Original CuraEngine copyright: +// Copyright (c) 2021 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. + +#include "TreeSupport.hpp" +#include "TreeSupportCommon.hpp" +#include "SupportCommon.hpp" +#include "OrganicSupport.hpp" + +#include "../AABBTreeIndirect.hpp" +#include "../BuildVolume.hpp" +#include "../ClipperUtils.hpp" +#include "../EdgeGrid.hpp" +#include "../Fill/Fill.hpp" +#include "../Layer.hpp" +#include "../Print.hpp" +#include "../MultiPoint.hpp" +#include "../Polygon.hpp" +#include "../Polyline.hpp" +#include "../MutablePolygon.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +// #define TREESUPPORT_DEBUG_SVG + +using namespace Slic3r::FFFSupport; + +namespace Slic3r +{ + +namespace FFFTreeSupport +{ + +enum class LineStatus +{ + INVALID, + TO_MODEL, + TO_MODEL_GRACIOUS, + TO_MODEL_GRACIOUS_SAFE, + TO_BP, + TO_BP_SAFE +}; + +using LineInformation = std::vector>; +using LineInformations = std::vector; +using namespace std::literals; + +static inline void validate_range(const Point &pt) +{ + static constexpr const int32_t hi = 65536 * 16384; + if (pt.x() > hi || pt.y() > hi || -pt.x() > hi || -pt.y() > hi) + throw ClipperLib::clipperException("Coordinate outside allowed range"); +} + +static inline void validate_range(const Points &points) +{ + for (const Point &p : points) + validate_range(p); +} + +static inline void validate_range(const MultiPoint &mp) +{ + validate_range(mp.points); +} + +static inline void validate_range(const Polygons &polygons) +{ + for (const Polygon &p : polygons) + validate_range(p); +} + +static inline void validate_range(const Polylines &polylines) +{ + for (const Polyline &p : polylines) + validate_range(p); +} + +static inline void validate_range(const LineInformation &lines) +{ + for (const auto& p : lines) + validate_range(p.first); +} + +static inline void validate_range(const LineInformations &lines) +{ + for (const LineInformation &l : lines) + validate_range(l); +} + +static inline void check_self_intersections(const Polygons &polygons, const std::string_view message) +{ +#ifdef TREE_SUPPORT_SHOW_ERRORS_WIN32 + if (!intersecting_edges(polygons).empty()) + ::MessageBoxA(nullptr, (std::string("TreeSupport infill self intersections: ") + std::string(message)).c_str(), "Bug detected!", MB_OK | MB_SYSTEMMODAL | MB_SETFOREGROUND | MB_ICONWARNING); +#endif // TREE_SUPPORT_SHOW_ERRORS_WIN32 +} +static inline void check_self_intersections(const ExPolygon &expoly, const std::string_view message) +{ +#ifdef TREE_SUPPORT_SHOW_ERRORS_WIN32 + check_self_intersections(to_polygons(expoly), message); +#endif // TREE_SUPPORT_SHOW_ERRORS_WIN32 +} + +static std::vector>> group_meshes(const Print &print, const std::vector &print_object_ids) +{ + std::vector>> grouped_meshes; + + //FIXME this is ugly, it does not belong here. + for (size_t object_id : print_object_ids) { + const PrintObject &print_object = *print.get_object(object_id); + const PrintObjectConfig &object_config = print_object.config(); + if (object_config.support_top_z_distance < EPSILON) + // || min_feature_size < scaled(0.1) that is the minimum line width + TreeSupportSettings::soluble = true; + } + + size_t largest_printed_mesh_idx = 0; + + // Group all meshes that can be processed together. NOTE this is different from mesh-groups! Only one setting object is needed per group, + // as different settings in the same group may only occur in the tip, which uses the original settings objects from the meshes. + for (size_t object_id : print_object_ids) { + const PrintObject &print_object = *print.get_object(object_id); +#ifndef NDEBUG + const PrintObjectConfig &object_config = print_object.config(); +#endif // NDEBUG + // Support must be enabled and set to Tree style. + assert(object_config.support_material || object_config.support_material_enforce_layers > 0); + assert(object_config.support_material_style == smsTree || object_config.support_material_style == smsOrganic); + + bool found_existing_group = false; + TreeSupportSettings next_settings{ TreeSupportMeshGroupSettings{ print_object }, print_object.slicing_parameters() }; + //FIXME for now only a single object per group is enabled. +#if 0 + for (size_t idx = 0; idx < grouped_meshes.size(); ++ idx) + if (next_settings == grouped_meshes[idx].first) { + found_existing_group = true; + grouped_meshes[idx].second.emplace_back(object_id); + // handle some settings that are only used for performance reasons. This ensures that a horrible set setting intended to improve performance can not reduce it drastically. + grouped_meshes[idx].first.performance_interface_skip_layers = std::min(grouped_meshes[idx].first.performance_interface_skip_layers, next_settings.performance_interface_skip_layers); + } +#endif + if (! found_existing_group) + grouped_meshes.emplace_back(next_settings, std::vector{ object_id }); + + // no need to do this per mesh group as adaptive layers and raft setting are not setable per mesh. + if (print.get_object(largest_printed_mesh_idx)->layers().back()->print_z < print_object.layers().back()->print_z) + largest_printed_mesh_idx = object_id; + } + +#if 0 + { + std::vector known_z(storage.meshes[largest_printed_mesh_idx].layers.size()); + for (size_t z = 0; z < storage.meshes[largest_printed_mesh_idx].layers.size(); z++) + known_z[z] = storage.meshes[largest_printed_mesh_idx].layers[z].printZ; + for (size_t idx = 0; idx < grouped_meshes.size(); ++ idx) + grouped_meshes[idx].first.setActualZ(known_z); + } +#endif + + return grouped_meshes; +} + +#if 0 +// todo remove as only for debugging relevant +[[nodiscard]] static std::string getPolygonAsString(const Polygons& poly) +{ + std::string ret; + for (auto path : poly) + for (Point p : path) { + if (ret != "") + ret += ","; + ret += "(" + std::to_string(p.x()) + "," + std::to_string(p.y()) + ")"; + } + return ret; +} +#endif + +[[nodiscard]] static const std::vector generate_overhangs(const TreeSupportSettings &settings, const PrintObject &print_object, std::function throw_on_cancel) +{ + const size_t num_raft_layers = settings.raft_layers.size(); + const size_t num_object_layers = print_object.layer_count(); + const size_t num_layers = num_object_layers + num_raft_layers; + std::vector out(num_layers, Polygons{}); + + const PrintConfig &print_config = print_object.print()->config(); + const PrintObjectConfig &config = print_object.config(); + const bool support_auto = config.enable_support.value && is_auto(config.support_type.value); + const int support_enforce_layers = config.enforce_support_layers.value; + std::vector enforcers_layers{ print_object.slice_support_enforcers() }; + std::vector blockers_layers{ print_object.slice_support_blockers() }; + print_object.project_and_append_custom_facets(false, EnforcerBlockerType::ENFORCER, enforcers_layers); + print_object.project_and_append_custom_facets(false, EnforcerBlockerType::BLOCKER, blockers_layers); + const int support_threshold = config.support_threshold_angle.value; + const bool support_threshold_auto = support_threshold == 0; + // +1 makes the threshold inclusive + double tan_threshold = support_threshold_auto ? 0. : tan(M_PI * double(support_threshold + 1) / 180.); + //FIXME this is a fudge constant! + auto enforcer_overhang_offset = scaled(config.tree_support_tip_diameter.value); + + size_t num_overhang_layers = support_auto ? num_object_layers : std::min(num_object_layers, std::max(size_t(support_enforce_layers), enforcers_layers.size())); + tbb::parallel_for(tbb::blocked_range(1, num_overhang_layers), + [&print_object, &config, &print_config, &enforcers_layers, &blockers_layers, + support_auto, support_enforce_layers, support_threshold_auto, tan_threshold, enforcer_overhang_offset, num_raft_layers, &throw_on_cancel, &out] + (const tbb::blocked_range &range) { + for (LayerIndex layer_id = range.begin(); layer_id < range.end(); ++ layer_id) { + const Layer ¤t_layer = *print_object.get_layer(layer_id); + const Layer &lower_layer = *print_object.get_layer(layer_id - 1); + // Full overhangs with zero lower_layer_offset and no blockers applied. + Polygons raw_overhangs; + bool raw_overhangs_calculated = false; + // Final overhangs. + Polygons overhangs; + // For how many layers full overhangs shall be supported. + const bool enforced_layer = layer_id < support_enforce_layers; + if (support_auto || enforced_layer) { + float lower_layer_offset; + if (enforced_layer) + lower_layer_offset = 0; + else if (support_threshold_auto) { + float external_perimeter_width = 0; + for (const LayerRegion *layerm : lower_layer.regions()) + external_perimeter_width += layerm->flow(frExternalPerimeter).scaled_width(); + external_perimeter_width /= lower_layer.region_count(); + lower_layer_offset = float(0.5 * external_perimeter_width); + } else + lower_layer_offset = scaled(lower_layer.height / tan_threshold); + overhangs = lower_layer_offset == 0 ? + diff(current_layer.lslices, lower_layer.lslices) : + diff(current_layer.lslices, offset(lower_layer.lslices, lower_layer_offset)); + if (lower_layer_offset == 0) { + raw_overhangs = overhangs; + raw_overhangs_calculated = true; + } + if (! (enforced_layer || blockers_layers.empty() || blockers_layers[layer_id].empty())) + overhangs = diff(overhangs, blockers_layers[layer_id], ApplySafetyOffset::Yes); + if (config.bridge_no_support) { + for (const LayerRegion *layerm : current_layer.regions()) + remove_bridges_from_contacts(print_config, lower_layer, *layerm, + float(layerm->flow(frExternalPerimeter).scaled_width()), overhangs); + } + } + //check_self_intersections(overhangs, "generate_overhangs1"); + if (! enforcers_layers.empty() && ! enforcers_layers[layer_id].empty()) { + // Has some support enforcers at this layer, apply them to the overhangs, don't apply the support threshold angle. + //enforcers_layers[layer_id] = union_(enforcers_layers[layer_id]); + //check_self_intersections(enforcers_layers[layer_id], "generate_overhangs - enforcers"); + //check_self_intersections(to_polygons(lower_layer.lslices), "generate_overhangs - lowerlayers"); + if (Polygons enforced_overhangs = intersection(raw_overhangs_calculated ? raw_overhangs : diff(current_layer.lslices, lower_layer.lslices), enforcers_layers[layer_id] /*, ApplySafetyOffset::Yes */); + ! enforced_overhangs.empty()) { + //FIXME this is a hack to make enforcers work on steep overhangs. + //check_self_intersections(enforced_overhangs, "generate_overhangs - enforced overhangs1"); + //Polygons enforced_overhangs_prev = enforced_overhangs; + //check_self_intersections(to_polygons(union_ex(enforced_overhangs)), "generate_overhangs - enforced overhangs11"); + //check_self_intersections(offset(union_ex(enforced_overhangs), + //FIXME enforcer_overhang_offset is a fudge constant! + enforced_overhangs = diff(offset(union_ex(enforced_overhangs), enforcer_overhang_offset), + lower_layer.lslices); +#ifdef TREESUPPORT_DEBUG_SVG +// if (! intersecting_edges(enforced_overhangs).empty()) + { + static int irun = 0; + SVG::export_expolygons(debug_out_path("treesupport-self-intersections-%d.svg", ++irun), + { { { current_layer.lslices }, { "current_layer.lslices", "yellow", 0.5f } }, + { { lower_layer.lslices }, { "lower_layer.lslices", "gray", 0.5f } }, + { { union_ex(enforced_overhangs) }, { "enforced_overhangs", "red", "black", "", scaled(0.1f), 0.5f } } }); + } +#endif // TREESUPPORT_DEBUG_SVG + //check_self_intersections(enforced_overhangs, "generate_overhangs - enforced overhangs2"); + overhangs = overhangs.empty() ? std::move(enforced_overhangs) : union_(overhangs, enforced_overhangs); + //check_self_intersections(overhangs, "generate_overhangs - enforcers"); + } + } + out[layer_id + num_raft_layers] = std::move(overhangs); + throw_on_cancel(); + } + }); + +#if 0 + if (num_raft_layers > 0) { + const Layer &first_layer = *print_object.get_layer(0); + // Final overhangs. + Polygons overhangs = + // Don't apply blockes on raft layer. + //(! blockers_layers.empty() && ! blockers_layers[layer_id].empty() ? + // diff(first_layer.lslices, blockers_layers[layer_id], ApplySafetyOffset::Yes) : + to_polygons(first_layer.lslices); +#if 0 + if (! enforcers_layers.empty() && ! enforcers_layers[layer_id].empty()) { + if (Polygons enforced_overhangs = intersection(first_layer.lslices, enforcers_layers[layer_id] /*, ApplySafetyOffset::Yes */); + ! enforced_overhangs.empty()) { + //FIXME this is a hack to make enforcers work on steep overhangs. + //FIXME enforcer_overhang_offset is a fudge constant! + enforced_overhangs = offset(union_ex(enforced_overhangs), enforcer_overhang_offset); + overhangs = overhangs.empty() ? std::move(enforced_overhangs) : union_(overhangs, enforced_overhangs); + } + } +#endif + out[num_raft_layers] = std::move(overhangs); + throw_on_cancel(); + } +#endif + + return out; +} + +/*! + * \brief Precalculates all avoidances, that could be required. + * + * \param storage[in] Background storage to access meshes. + * \param currently_processing_meshes[in] Indexes of all meshes that are processed in this iteration + */ +[[nodiscard]] static LayerIndex precalculate(const Print &print, const std::vector &overhangs, const TreeSupportSettings &config, const std::vector &object_ids, TreeModelVolumes &volumes, std::function throw_on_cancel) +{ + // calculate top most layer that is relevant for support + LayerIndex max_layer = 0; + for (size_t object_id : object_ids) { + const PrintObject &print_object = *print.get_object(object_id); + const int num_raft_layers = int(config.raft_layers.size()); + const int num_layers = int(print_object.layer_count()) + num_raft_layers; + int max_support_layer_id = 0; + for (int layer_id = std::max(num_raft_layers, 1); layer_id < num_layers; ++ layer_id) + if (! overhangs[layer_id].empty()) + max_support_layer_id = layer_id; + max_layer = std::max(max_support_layer_id - int(config.z_distance_top_layers), 0); + } + if (max_layer > 0) + // The actual precalculation happens in TreeModelVolumes. + volumes.precalculate(*print.get_object(object_ids.front()), max_layer, throw_on_cancel); + return max_layer; +} + +/*! + * \brief Converts a Polygons object representing a line into the internal format. + * + * \param polylines[in] The Polyline that will be converted. + * \param layer_idx[in] The current layer. + * \return All lines of the \p polylines object, with information for each point regarding in which avoidance it is currently valid in. + */ +// Called by generate_initial_areas() +[[nodiscard]] static LineInformations convert_lines_to_internal( + const TreeModelVolumes &volumes, const TreeSupportSettings &config, + const Polylines &polylines, LayerIndex layer_idx) +{ + const bool min_xy_dist = config.xy_distance > config.xy_min_distance; + + LineInformations result; + // Also checks if the position is valid, if it is NOT, it deletes that point + for (const Polyline &line : polylines) { + LineInformation res_line; + for (Point p : line) { + if (! contains(volumes.getAvoidance(config.getRadius(0), layer_idx, TreeModelVolumes::AvoidanceType::FastSafe, false, min_xy_dist), p)) + res_line.emplace_back(p, LineStatus::TO_BP_SAFE); + else if (! contains(volumes.getAvoidance(config.getRadius(0), layer_idx, TreeModelVolumes::AvoidanceType::Fast, false, min_xy_dist), p)) + res_line.emplace_back(p, LineStatus::TO_BP); + else if (config.support_rests_on_model && ! contains(volumes.getAvoidance(config.getRadius(0), layer_idx, TreeModelVolumes::AvoidanceType::FastSafe, true, min_xy_dist), p)) + res_line.emplace_back(p, LineStatus::TO_MODEL_GRACIOUS_SAFE); + else if (config.support_rests_on_model && ! contains(volumes.getAvoidance(config.getRadius(0), layer_idx, TreeModelVolumes::AvoidanceType::Fast, true, min_xy_dist), p)) + res_line.emplace_back(p, LineStatus::TO_MODEL_GRACIOUS); + else if (config.support_rests_on_model && ! contains(volumes.getCollision(config.getRadius(0), layer_idx, min_xy_dist), p)) + res_line.emplace_back(p, LineStatus::TO_MODEL); + else if (!res_line.empty()) { + result.emplace_back(res_line); + res_line.clear(); + } + } + if (!res_line.empty()) { + result.emplace_back(res_line); + res_line.clear(); + } + } + + validate_range(result); + return result; +} + +#if 0 +/*! + * \brief Converts lines in internal format into a Polygons object representing these lines. + * + * \param lines[in] The lines that will be converted. + * \return All lines of the \p lines object as a Polygons object. + */ +[[nodiscard]] static Polylines convert_internal_to_lines(LineInformations lines) +{ + Polylines result; + for (LineInformation line : lines) { + Polyline path; + for (auto point_data : line) + path.points.emplace_back(point_data.first); + result.emplace_back(std::move(path)); + } + validate_range(result); + return result; +} +#endif + +/*! + * \brief Evaluates if a point has to be added now. Required for a split_lines call in generate_initial_areas(). + * + * \param current_layer[in] The layer on which the point lies, point and its status. + * \return whether the point is valid. + */ +[[nodiscard]] static bool evaluate_point_for_next_layer_function( + const TreeModelVolumes &volumes, const TreeSupportSettings &config, + size_t current_layer, const std::pair &p) +{ + using AvoidanceType = TreeModelVolumes::AvoidanceType; + const bool min_xy_dist = config.xy_distance > config.xy_min_distance; + if (! contains(volumes.getAvoidance(config.getRadius(0), current_layer - 1, p.second == LineStatus::TO_BP_SAFE ? AvoidanceType::FastSafe : AvoidanceType::Fast, false, min_xy_dist), p.first)) + return true; + if (config.support_rests_on_model && (p.second != LineStatus::TO_BP && p.second != LineStatus::TO_BP_SAFE)) + return ! contains( + p.second == LineStatus::TO_MODEL_GRACIOUS || p.second == LineStatus::TO_MODEL_GRACIOUS_SAFE ? + volumes.getAvoidance(config.getRadius(0), current_layer - 1, p.second == LineStatus::TO_MODEL_GRACIOUS_SAFE ? AvoidanceType::FastSafe : AvoidanceType::Fast, true, min_xy_dist) : + volumes.getCollision(config.getRadius(0), current_layer - 1, min_xy_dist), + p.first); + return false; +} + +/*! + * \brief Evaluates which points of some lines are not valid one layer below and which are. Assumes all points are valid on the current layer. Validity is evaluated using supplied lambda. + * + * \param lines[in] The lines that have to be evaluated. + * \param evaluatePoint[in] The function used to evaluate the points. + * \return A pair with which points are still valid in the first slot and which are not in the second slot. + */ +template +[[nodiscard]] static std::pair split_lines(const LineInformations &lines, EvaluatePointFn evaluatePoint) +{ + // assumes all Points on the current line are valid + + LineInformations keep; + LineInformations set_free; + for (const std::vector> &line : lines) { + bool current_keep = true; + LineInformation resulting_line; + for (const std::pair &me : line) { + if (evaluatePoint(me) != current_keep) { + if (! resulting_line.empty()) + (current_keep ? &keep : &set_free)->emplace_back(std::move(resulting_line)); + current_keep = !current_keep; + } + resulting_line.emplace_back(me); + } + if (! resulting_line.empty()) + (current_keep ? &keep : &set_free)->emplace_back(std::move(resulting_line)); + } + validate_range(keep); + validate_range(set_free); + return std::pair>>, std::vector>>>(keep, set_free); +} + +// Ported from CURA's PolygonUtils::getNextPointWithDistance() +// Sample a next point at distance "dist" from start_pt on polyline segment (start_idx, start_idx + 1). +// Returns sample point and start index of its segment on polyline if such sample exists. +static std::optional> polyline_sample_next_point_at_distance(const Points &polyline, const Point &start_pt, size_t start_idx, double dist) +{ + const double dist2 = sqr(dist); + const auto dist2i = int64_t(dist2); + static constexpr const auto eps = scaled(0.01); + + for (size_t i = start_idx + 1; i < polyline.size(); ++ i) { + const Point p1 = polyline[i]; + if ((p1 - start_pt).cast().squaredNorm() >= dist2i) { + // The end point is outside the circle with center "start_pt" and radius "dist". + const Point p0 = polyline[i - 1]; + Vec2d v = (p1 - p0).cast(); + double l2v = v.squaredNorm(); + if (l2v < sqr(eps)) { + // Very short segment. + Point c = (p0 + p1) / 2; + if (std::abs((start_pt - c).cast().norm() - dist) < eps) + return std::pair{ c, i - 1 }; + else + continue; + } + Vec2d p0f = (start_pt - p0).cast(); + // Foot point of start_pt into v. + Vec2d foot_pt = v * (p0f.dot(v) / l2v); + // Vector from foot point of "start_pt" to "start_pt". + Vec2d xf = p0f - foot_pt; + // Squared distance of "start_pt" from the ray (p0, p1). + double l2_from_line = xf.squaredNorm(); + // Squared distance of an intersection point of a circle with center at the foot point. + if (double l2_intersection = dist2 - l2_from_line; + l2_intersection > - SCALED_EPSILON) { + // The ray (p0, p1) touches or intersects a circle centered at "start_pt" with radius "dist". + // Distance of the circle intersection point from the foot point. + l2_intersection = std::max(l2_intersection, 0.); + if ((v - foot_pt).cast().squaredNorm() >= l2_intersection) { + // Intersection of the circle with the segment (p0, p1) is on the right side (close to p1) from the foot point. + Point p = p0 + (foot_pt + v * sqrt(l2_intersection / l2v)).cast(); + validate_range(p); + return std::pair{ p, i - 1 }; + } + } + } + } + return {}; +} + +/*! + * \brief Eensures that every line segment is about distance in length. The resulting lines may differ from the original but all points are on the original + * + * \param input[in] The lines on which evenly spaced points should be placed. + * \param distance[in] The distance the points should be from each other. + * \param min_points[in] The amount of points that have to be placed. If not enough can be placed the distance will be reduced to place this many points. + * \return A Polygons object containing the evenly spaced points. Does not represent an area, more a collection of points on lines. + */ +[[nodiscard]] static Polylines ensure_maximum_distance_polyline(const Polylines &input, double distance, size_t min_points) +{ + Polylines result; + for (Polyline part : input) { + if (part.empty()) + continue; + + double len = length(part.points); + Polyline line; + double current_distance = std::max(distance, scaled(0.1)); + if (len < 2 * distance && min_points <= 1) + { + // Insert the opposite point of the first one. + //FIXME pretty expensive + Polyline pl(part); + pl.clip_end(len / 2); + line.points.emplace_back(pl.points.back()); + } + else + { + size_t optimal_end_index = part.size() - 1; + + if (part.front() == part.back()) { + size_t optimal_start_index = 0; + // If the polyline was a polygon, there is a high chance it was an overhang. Overhangs that are <60� tend to be very thin areas, so lets get the beginning and end of them and ensure that they are supported. + // The first point of the line will always be supported, so rotate the order of points in this polyline that one of the two corresponding points that are furthest from each other is in the beginning. + // The other will be manually added (optimal_end_index) + coord_t max_dist2_between_vertecies = 0; + for (size_t idx = 0; idx < part.size() - 1; ++ idx) { + for (size_t inner_idx = 0; inner_idx < part.size() - 1; inner_idx++) { + if ((part[idx] - part[inner_idx]).cast().squaredNorm() > max_dist2_between_vertecies) { + optimal_start_index = idx; + optimal_end_index = inner_idx; + max_dist2_between_vertecies = (part[idx] - part[inner_idx]).cast().squaredNorm(); + } + } + } + std::rotate(part.begin(), part.begin() + optimal_start_index, part.end() - 1); + part[part.size() - 1] = part[0]; // restore that property that this polyline ends where it started. + optimal_end_index = (part.size() + optimal_end_index - optimal_start_index - 1) % (part.size() - 1); + } + + while (line.size() < min_points && current_distance >= scaled(0.1)) + { + line.clear(); + Point current_point = part[0]; + line.points.emplace_back(part[0]); + if (min_points > 1 || (part[0] - part[optimal_end_index]).cast().norm() > current_distance) + line.points.emplace_back(part[optimal_end_index]); + size_t current_index = 0; + std::optional> next_point; + double next_distance = current_distance; + // Get points so that at least min_points are added and they each are current_distance away from each other. If that is impossible, decrease current_distance a bit. + // The input are lines, that means that the line from the last to the first vertex does not have to exist, so exclude all points that are on this line! + while ((next_point = polyline_sample_next_point_at_distance(part.points, current_point, current_index, next_distance))) { + // Not every point that is distance away, is valid, as it may be much closer to another point. This is especially the case when the overhang is very thin. + // So this ensures that the points are actually a certain distance from each other. + // This assurance is only made on a per polygon basis, as different but close polygon may not be able to use support below the other polygon. + double min_distance_to_existing_point = std::numeric_limits::max(); + for (Point p : line) + min_distance_to_existing_point = std::min(min_distance_to_existing_point, (p - next_point->first).cast().norm()); + if (min_distance_to_existing_point >= current_distance) { + // viable point was found. Add to possible result. + line.points.emplace_back(next_point->first); + current_point = next_point->first; + current_index = next_point->second; + next_distance = current_distance; + } else { + if (current_point == next_point->first) { + // In case a fixpoint is encountered, better aggressively overcompensate so the code does not become stuck here... + BOOST_LOG_TRIVIAL(warning) << "Tree Support: Encountered a fixpoint in polyline_sample_next_point_at_distance. This is expected to happen if the distance (currently " << next_distance << + ") is smaller than 100"; + tree_supports_show_error("Encountered issue while placing tips. Some tips may be missing."sv, true); + if (next_distance > 2 * current_distance) + // This case should never happen, but better safe than sorry. + break; + next_distance += current_distance; + continue; + } + // if the point was too close, the next possible viable point is at least distance-min_distance_to_existing_point away from the one that was just checked. + next_distance = std::max(current_distance - min_distance_to_existing_point, scaled(0.1)); + current_point = next_point->first; + current_index = next_point->second; + } + } + current_distance *= 0.9; + } + } + result.emplace_back(std::move(line)); + } + validate_range(result); + return result; +} + +/*! + * \brief Returns Polylines representing the (infill) lines that will result in slicing the given area + * + * \param area[in] The area that has to be filled with infill. + * \param roof[in] Whether the roofing or regular support settings should be used. + * \param layer_idx[in] The current layer index. + * \param support_infill_distance[in] The distance that should be between the infill lines. + * + * \return A Polygons object that represents the resulting infill lines. + */ +[[nodiscard]] static Polylines generate_support_infill_lines( + // Polygon to fill in with a zig-zag pattern supporting an overhang. + const Polygons &polygon, + const SupportParameters &support_params, + bool roof, LayerIndex layer_idx, coord_t support_infill_distance) +{ +#if 0 + Polygons gaps; + // as we effectivly use lines to place our supportPoints we may use the Infill class for it, while not made for it it works perfect + + const EFillMethod pattern = roof ? config.roof_pattern : config.support_pattern; + +// const bool zig_zaggify_infill = roof ? pattern == EFillMethod::ZIG_ZAG : config.zig_zaggify_support; + const bool connect_polygons = false; + constexpr coord_t support_roof_overlap = 0; + constexpr size_t infill_multiplier = 1; + constexpr coord_t outline_offset = 0; + const int support_shift = roof ? 0 : support_infill_distance / 2; + const size_t wall_line_count = include_walls && !roof ? config.support_wall_count : 0; + const Point infill_origin; + constexpr Polygons* perimeter_gaps = nullptr; + constexpr bool use_endpieces = true; + const bool connected_zigzags = roof ? false : config.connect_zigzags; + const size_t zag_skip_count = roof ? 0 : config.zag_skip_count; + constexpr coord_t pocket_size = 0; + std::vector angles = roof ? config.support_roof_angles : config.support_infill_angles; + std::vector toolpaths; + + const coord_t z = config.getActualZ(layer_idx); + int divisor = static_cast(angles.size()); + int index = ((layer_idx % divisor) + divisor) % divisor; + const AngleRadians fill_angle = angles[index]; + Infill roof_computation(pattern, true /* zig_zaggify_infill */, connect_polygons, polygon, + roof ? config.support_roof_line_width : config.support_line_width, support_infill_distance, support_roof_overlap, infill_multiplier, + fill_angle, z, support_shift, config.resolution, wall_line_count, infill_origin, + perimeter_gaps, connected_zigzags, use_endpieces, false /* skip_some_zags */, zag_skip_count, pocket_size); + Polygons polygons; + Polygons lines; + roof_computation.generate(toolpaths, polygons, lines, config.settings); + append(lines, to_polylines(polygons)); + return lines; +#else +// const bool connected_zigzags = roof ? false : config.connect_zigzags; +// const int support_shift = roof ? 0 : support_infill_distance / 2; + + const Flow &flow = roof ? support_params.support_material_interface_flow : support_params.support_material_flow; + std::unique_ptr filler = std::unique_ptr(Fill::new_from_type(roof ? support_params.interface_fill_pattern : support_params.base_fill_pattern)); + FillParams fill_params; + + filler->layer_id = layer_idx; + filler->spacing = flow.spacing(); + filler->angle = roof ? + //fixme support_layer.interface_id() instead of layer_idx + (support_params.interface_angle + (layer_idx & 1) ? float(- M_PI / 4.) : float(+ M_PI / 4.)) : + support_params.base_angle; + + fill_params.density = float(roof ? support_params.interface_density : scaled(filler->spacing) / (scaled(filler->spacing) + float(support_infill_distance))); + fill_params.dont_adjust = true; + + Polylines out; + for (ExPolygon &expoly : union_ex(polygon)) { + // The surface type does not matter. + assert(area(expoly) > 0.); +#ifdef TREE_SUPPORT_SHOW_ERRORS_WIN32 + if (area(expoly) <= 0.) + ::MessageBoxA(nullptr, "TreeSupport infill negative area", "Bug detected!", MB_OK | MB_SYSTEMMODAL | MB_SETFOREGROUND | MB_ICONWARNING); +#endif // TREE_SUPPORT_SHOW_ERRORS_WIN32 + assert(intersecting_edges(to_polygons(expoly)).empty()); + check_self_intersections(expoly, "generate_support_infill_lines"); + Surface surface(stInternal, std::move(expoly)); + try { + Polylines pl = filler->fill_surface(&surface, fill_params); + assert(pl.empty() || get_extents(surface.expolygon).inflated(SCALED_EPSILON).contains(get_extents(pl))); +#ifdef TREE_SUPPORT_SHOW_ERRORS_WIN32 + if (! pl.empty() && ! get_extents(surface.expolygon).inflated(SCALED_EPSILON).contains(get_extents(pl))) + ::MessageBoxA(nullptr, "TreeSupport infill failure", "Bug detected!", MB_OK | MB_SYSTEMMODAL | MB_SETFOREGROUND | MB_ICONWARNING); +#endif // TREE_SUPPORT_SHOW_ERRORS_WIN32 + append(out, std::move(pl)); + } catch (InfillFailedException &) { + } + } + validate_range(out); + return out; +#endif +} + +/*! + * \brief Unions two Polygons. Ensures that if the input is non empty that the output also will be non empty. + * \param first[in] The first Polygon. + * \param second[in] The second Polygon. + * \return The union of both Polygons + */ +[[nodiscard]] static Polygons safe_union(const Polygons first, const Polygons second = {}) +{ + // unionPolygons can slowly remove Polygons under certain circumstances, because of rounding issues (Polygons that have a thin area). + // This does not cause a problem when actually using it on large areas, but as influence areas (representing centerpoints) can be very thin, this does occur so this ugly workaround is needed + // Here is an example of a Polygons object that will loose vertices when unioning, and will be gone after a few times unionPolygons was called: + /* + Polygons example; + Polygon exampleInner; + exampleInner.add(Point(120410,83599));//A + exampleInner.add(Point(120384,83643));//B + exampleInner.add(Point(120399,83618));//C + exampleInner.add(Point(120414,83591));//D + exampleInner.add(Point(120423,83570));//E + exampleInner.add(Point(120419,83580));//F + example.add(exampleInner); + for(int i=0;i<10;i++){ + log("Iteration %d Example area: %f\n",i,area(example)); + example=example.unionPolygons(); + } +*/ + + Polygons result; + if (! first.empty() || ! second.empty()) { + result = union_(first, second); + if (result.empty()) { + BOOST_LOG_TRIVIAL(debug) << "Caught an area destroying union, enlarging areas a bit."; + // just take the few lines we have, and offset them a tiny bit. Needs to be offsetPolylines, as offset may aleady have problems with the area. + result = union_(offset(to_polylines(first), scaled(0.002), jtMiter, 1.2), offset(to_polylines(second), scaled(0.002), jtMiter, 1.2)); + } + } + + return result; +} + +/*! + * \brief Offsets (increases the area of) a polygons object in multiple steps to ensure that it does not lag through over a given obstacle. + * \param me[in] Polygons object that has to be offset. + * \param distance[in] The distance by which me should be offset. Expects values >=0. + * \param collision[in] The area representing obstacles. + * \param last_step_offset_without_check[in] The most it is allowed to offset in one step. + * \param min_amount_offset[in] How many steps have to be done at least. As this uses round offset this increases the amount of vertices, which may be required if Polygons get very small. Required as arcTolerance is not exposed in offset, which should result with a similar result. + * \return The resulting Polygons object. + */ +[[nodiscard]] static Polygons safe_offset_inc(const Polygons& me, coord_t distance, const Polygons& collision, coord_t safe_step_size, coord_t last_step_offset_without_check, size_t min_amount_offset) +{ + bool do_final_difference = last_step_offset_without_check == 0; + Polygons ret = safe_union(me); // ensure sane input + + // Trim the collision polygons with the region of interest for diff() efficiency. + Polygons collision_trimmed_buffer; + auto collision_trimmed = [&collision_trimmed_buffer, &collision, &ret, distance]() -> const Polygons& { + if (collision_trimmed_buffer.empty() && ! collision.empty()) + collision_trimmed_buffer = ClipperUtils::clip_clipper_polygons_with_subject_bbox(collision, get_extents(ret).inflated(std::max(0, distance) + SCALED_EPSILON)); + return collision_trimmed_buffer; + }; + + if (distance == 0) + return do_final_difference ? diff(ret, collision_trimmed()) : union_(ret); + if (safe_step_size < 0 || last_step_offset_without_check < 0) { + BOOST_LOG_TRIVIAL(error) << "Offset increase got invalid parameter!"; + tree_supports_show_error("Negative offset distance... How did you manage this ?"sv, true); + return do_final_difference ? diff(ret, collision_trimmed()) : union_(ret); + } + + coord_t step_size = safe_step_size; + int steps = distance > last_step_offset_without_check ? (distance - last_step_offset_without_check) / step_size : 0; + if (distance - steps * step_size > last_step_offset_without_check) { + if ((steps + 1) * step_size <= distance) + // This will be the case when last_step_offset_without_check >= safe_step_size + ++ steps; + else + do_final_difference = true; + } + if (steps + (distance < last_step_offset_without_check || (distance % step_size) != 0) < int(min_amount_offset) && min_amount_offset > 1) { + // yes one can add a bool as the standard specifies that a result from compare operators has to be 0 or 1 + // reduce the stepsize to ensure it is offset the required amount of times + step_size = distance / min_amount_offset; + if (step_size >= safe_step_size) { + // effectivly reduce last_step_offset_without_check + step_size = safe_step_size; + steps = min_amount_offset; + } else + steps = distance / step_size; + } + // offset in steps + for (int i = 0; i < steps; ++ i) { + ret = diff(offset(ret, step_size, ClipperLib::jtRound, scaled(0.01)), collision_trimmed()); + // ensure that if many offsets are done the performance does not suffer extremely by the new vertices of jtRound. + if (i % 10 == 7) + ret = polygons_simplify(ret, scaled(0.015), polygons_strictly_simple); + } + // offset the remainder + float last_offset = distance - steps * step_size; + if (last_offset > SCALED_EPSILON) + ret = offset(ret, distance - steps * step_size, ClipperLib::jtRound, scaled(0.01)); + ret = polygons_simplify(ret, scaled(0.015), polygons_strictly_simple); + + if (do_final_difference) + ret = diff(ret, collision_trimmed()); + return union_(ret); +} + +class RichInterfacePlacer : public InterfacePlacer { +public: + RichInterfacePlacer( + const InterfacePlacer &interface_placer, + const TreeModelVolumes &volumes, + bool force_tip_to_roof, + size_t num_support_layers, + std::vector &move_bounds) + : + InterfacePlacer(interface_placer), + volumes(volumes), force_tip_to_roof(force_tip_to_roof), move_bounds(move_bounds) + { + m_already_inserted.assign(num_support_layers, {}); + this->min_xy_dist = this->config.xy_distance > this->config.xy_min_distance; + } + const TreeModelVolumes &volumes; + // Radius of the tree tip is large enough to be covered by an interface. + const bool force_tip_to_roof; + bool min_xy_dist; + +public: + // called by sample_overhang_area() + void add_points_along_lines( + // Insert points (tree tips or top contact interfaces) along these lines. + LineInformations lines, + // Start at this layer. + LayerIndex insert_layer_idx, + // Insert this number of interface layers. + size_t roof_tip_layers, + // True if an interface is already generated above these lines. + size_t supports_roof_layers, + // The element tries to not move until this dtt is reached. + size_t dont_move_until) + { + validate_range(lines); + // Add tip area as roof (happens when minimum roof area > minimum tip area) if possible + size_t dtt_roof_tip; + for (dtt_roof_tip = 0; dtt_roof_tip < roof_tip_layers && insert_layer_idx - dtt_roof_tip >= 1; ++ dtt_roof_tip) { + size_t this_layer_idx = insert_layer_idx - dtt_roof_tip; + auto evaluateRoofWillGenerate = [&](const std::pair &p) { + //FIXME Vojtech: The circle is just shifted, it has a known size, the infill should fit all the time! + #if 0 + Polygon roof_circle; + for (Point corner : base_circle) + roof_circle.points.emplace_back(p.first + corner * config.min_radius); + return !generate_support_infill_lines({ roof_circle }, config, true, insert_layer_idx - dtt_roof_tip, config.support_roof_line_distance).empty(); + #else + return true; + #endif + }; + + { + std::pair split = + // keep all lines that are still valid on the next layer + split_lines(lines, [this, this_layer_idx](const std::pair &p) + { return evaluate_point_for_next_layer_function(volumes, config, this_layer_idx, p); }); + LineInformations points = std::move(split.second); + // Not all roofs are guaranteed to actually generate lines, so filter these out and add them as points. + split = split_lines(split.first, evaluateRoofWillGenerate); + lines = std::move(split.first); + append(points, split.second); + // add all points that would not be valid + for (const LineInformation &line : points) + for (const std::pair &point_data : line) + add_point_as_influence_area(point_data, this_layer_idx, + // don't move until + roof_tip_layers - dtt_roof_tip, + // supports roof + dtt_roof_tip + supports_roof_layers > 0, + // disable ovalization + false); + } + + // add all tips as roof to the roof storage + Polygons new_roofs; + for (const LineInformation &line : lines) + //FIXME sweep the tip radius along the line? + for (const std::pair &p : line) { + Polygon roof_circle{ m_base_circle }; + roof_circle.scale(config.min_radius / m_base_radius); + roof_circle.translate(p.first); + new_roofs.emplace_back(std::move(roof_circle)); + } + this->add_roof(std::move(new_roofs), this_layer_idx, dtt_roof_tip + supports_roof_layers); + } + + for (const LineInformation &line : lines) { + // If a line consists of enough tips, the assumption is that it is not a single tip, but part of a simulated support pattern. + // Ovalisation should be disabled for these to improve the quality of the lines when tip_diameter=line_width + bool disable_ovalistation = config.min_radius < 3 * config.support_line_width && roof_tip_layers == 0 && dtt_roof_tip == 0 && line.size() > 5; + for (const std::pair &point_data : line) + add_point_as_influence_area(point_data, insert_layer_idx - dtt_roof_tip, + // don't move until + dont_move_until > dtt_roof_tip ? dont_move_until - dtt_roof_tip : 0, + // supports roof + dtt_roof_tip + supports_roof_layers > 0, + disable_ovalistation); + } + } + +private: + // called by this->add_points_along_lines() + void add_point_as_influence_area(std::pair p, LayerIndex insert_layer, size_t dont_move_until, bool roof, bool skip_ovalisation) + { + bool to_bp = p.second == LineStatus::TO_BP || p.second == LineStatus::TO_BP_SAFE; + bool gracious = to_bp || p.second == LineStatus::TO_MODEL_GRACIOUS || p.second == LineStatus::TO_MODEL_GRACIOUS_SAFE; + bool safe_radius = p.second == LineStatus::TO_BP_SAFE || p.second == LineStatus::TO_MODEL_GRACIOUS_SAFE; + if (! config.support_rests_on_model && ! to_bp) { + BOOST_LOG_TRIVIAL(warning) << "Tried to add an invalid support point"; + tree_supports_show_error("Unable to add tip. Some overhang may not be supported correctly."sv, true); + return; + } + Polygons circle{ m_base_circle }; + circle.front().translate(p.first); + { + Point hash_pos = p.first / ((config.min_radius + 1) / 10); + std::lock_guard critical_section_movebounds(m_mutex_movebounds); + if (!m_already_inserted[insert_layer].count(hash_pos)) { + // normalize the point a bit to also catch points which are so close that inserting it would achieve nothing + m_already_inserted[insert_layer].emplace(hash_pos); + static constexpr const size_t dtt = 0; + SupportElementState state; + state.target_height = insert_layer; + state.target_position = p.first; + state.next_position = p.first; + state.layer_idx = insert_layer; + state.effective_radius_height = dtt; + state.to_buildplate = to_bp; + state.distance_to_top = dtt; + state.result_on_layer = p.first; + assert(state.result_on_layer_is_set()); + state.increased_to_model_radius = 0; + state.to_model_gracious = gracious; + state.elephant_foot_increases = 0; + state.use_min_xy_dist = min_xy_dist; + state.supports_roof = roof; + state.dont_move_until = dont_move_until; + state.can_use_safe_radius = safe_radius; + state.missing_roof_layers = force_tip_to_roof ? dont_move_until : 0; + state.skip_ovalisation = skip_ovalisation; + move_bounds[insert_layer].emplace_back(state, std::move(circle)); + } + } + } + + // Outputs + std::vector &move_bounds; + + // Temps + static constexpr const auto m_base_radius = scaled(0.01); + const Polygon m_base_circle { make_circle(m_base_radius, SUPPORT_TREE_CIRCLE_RESOLUTION) }; + + // Mutexes, guards + std::mutex m_mutex_movebounds; + std::vector> m_already_inserted; +}; + +int generate_raft_contact( + const PrintObject &print_object, + const TreeSupportSettings &config, + InterfacePlacer &interface_placer) +{ + int raft_contact_layer_idx = -1; + if (print_object.has_raft() && print_object.layer_count() > 0) { + // Produce raft contact layer outside of the tree support loop, so that no trees will be generated for the raft contact layer. + // Raft layers supporting raft contact interface will be produced by the classic raft generator. + // Find the raft contact layer. + raft_contact_layer_idx = int(config.raft_layers.size()) - 1; + while (raft_contact_layer_idx > 0 && config.raft_layers[raft_contact_layer_idx] > print_object.slicing_parameters().raft_contact_top_z + EPSILON) + -- raft_contact_layer_idx; + // Create the raft contact layer. + const ExPolygons &lslices = print_object.get_layer(0)->lslices; + double expansion = print_object.config().raft_expansion.value; + interface_placer.add_roof_unguarded(expansion > 0 ? expand(lslices, scaled(expansion)) : to_polygons(lslices), raft_contact_layer_idx, 0); + } + return raft_contact_layer_idx; +} + +void finalize_raft_contact( + const PrintObject &print_object, + const int raft_contact_layer_idx, + SupportGeneratorLayersPtr &top_contacts, + std::vector &move_bounds) +{ + if (raft_contact_layer_idx >= 0) { + const size_t first_tree_layer = print_object.slicing_parameters().raft_layers() - 1; + // Remove tree tips that start below the raft contact, + // remove interface layers below the raft contact. + for (size_t i = 0; i < first_tree_layer; ++i) { + top_contacts[i] = nullptr; + move_bounds[i].clear(); + } + if (raft_contact_layer_idx >= 0 && print_object.config().raft_expansion.value > 0) { + // If any tips at first_tree_layer now are completely inside the expanded raft layer, remove them as well before they are propagated to the ground. + Polygons &raft_polygons = top_contacts[raft_contact_layer_idx]->polygons; + EdgeGrid::Grid grid(get_extents(raft_polygons).inflated(SCALED_EPSILON)); + grid.create(raft_polygons, Polylines{}, coord_t(scale_(10.))); + SupportElements &first_layer_move_bounds = move_bounds[first_tree_layer]; + double threshold = scaled(print_object.config().raft_expansion.value) * 2.; + first_layer_move_bounds.erase(std::remove_if(first_layer_move_bounds.begin(), first_layer_move_bounds.end(), + [&grid, threshold](const SupportElement &el) { + coordf_t dist; + if (grid.signed_distance_edges(el.state.result_on_layer, threshold, dist)) { + assert(std::abs(dist) < threshold + SCALED_EPSILON); + // Support point is inside the expanded raft, remove it. + return dist < - 0.; + } + return false; + }), first_layer_move_bounds.end()); + #if 0 + // Remove the remaining tips from the raft: Closing operation on tip circles. + if (! first_layer_move_bounds.empty()) { + const double eps = 0.1; + // All tips supporting this layer are expected to have the same radius. + double radius = support_element_radius(config, first_layer_move_bounds.front()); + // Connect the tips with the following closing radius. + double closing_distance = radius; + Polygon circle = make_circle(radius + closing_distance, eps); + Polygons circles; + circles.reserve(first_layer_move_bounds.size()); + for (const SupportElement &el : first_layer_move_bounds) { + circles.emplace_back(circle); + circles.back().translate(el.state.result_on_layer); + } + raft_polygons = diff(raft_polygons, offset(union_(circles), - closing_distance)); + } + #endif + } + } +} + +// Called by generate_initial_areas(), used in parallel by multiple layers. +// Produce +// 1) Maximum num_support_roof_layers roof (top interface & contact) layers. +// 2) Tree tips supporting either the roof layers or the object itself. +// num_support_roof_layers should always be respected: +// If num_support_roof_layers contact layers could not be produced, then the tree tip +// is augmented with SupportElementState::missing_roof_layers +// and the top "missing_roof_layers" of such particular tree tips are supposed to be coverted to +// roofs aka interface layers by the tool path generator. +void sample_overhang_area( + // Area to support + Polygons &&overhang_area, + // If true, then the overhang_area is likely large and wide, thus it is worth to try + // to cover it with continuous interfaces supported by zig-zag patterned tree tips. + const bool large_horizontal_roof, + // Index of the top suport layer generated by this function. + const size_t layer_idx, + // Maximum number of roof (contact, interface) layers between the overhang and tree tips to be generated. + const size_t num_support_roof_layers, + // + const coord_t connect_length, + // Configuration classes + const TreeSupportMeshGroupSettings &mesh_group_settings, + // Configuration & Output + RichInterfacePlacer &interface_placer) +{ + // Assumption is that roof will support roof further up to avoid a lot of unnecessary branches. Each layer down it is checked whether the roof area + // is still large enough to be a roof and aborted as soon as it is not. This part was already reworked a few times, and there could be an argument + // made to change it again if there are actual issues encountered regarding supporting roofs. + // Main problem is that some patterns change each layer, so just calculating points and checking if they are still valid an layer below is not useful, + // as the pattern may be different one layer below. Same with calculating which points are now no longer being generated as result from + // a decreasing roof, as there is no guarantee that a line will be above these points. Implementing a separate roof support behavior + // for each pattern harms maintainability as it very well could be >100 LOC + auto generate_roof_lines = [&interface_placer, &mesh_group_settings](const Polygons &area, LayerIndex layer_idx) -> Polylines { + return generate_support_infill_lines(area, interface_placer.support_parameters, true, layer_idx, mesh_group_settings.support_roof_line_distance); + }; + + LineInformations overhang_lines; + // Track how many top contact / interface layers were already generated. + size_t dtt_roof = 0; + size_t layer_generation_dtt = 0; + + if (large_horizontal_roof) { + assert(num_support_roof_layers > 0); + // Sometimes roofs could be empty as the pattern does not generate lines if the area is narrow enough (i am looking at you, concentric infill). + // To catch these cases the added roofs are saved to be evaluated later. + std::vector added_roofs(num_support_roof_layers); + Polygons last_overhang = overhang_area; + for (dtt_roof = 0; dtt_roof < num_support_roof_layers && layer_idx - dtt_roof >= 1; ++ dtt_roof) { + // here the roof is handled. If roof can not be added the branches will try to not move instead + Polygons forbidden_next; + { + const bool min_xy_dist = interface_placer.config.xy_distance > interface_placer.config.xy_min_distance; + const Polygons &forbidden_next_raw = interface_placer.config.support_rests_on_model ? + interface_placer.volumes.getCollision(interface_placer.config.getRadius(0), layer_idx - (dtt_roof + 1), min_xy_dist) : + interface_placer.volumes.getAvoidance(interface_placer.config.getRadius(0), layer_idx - (dtt_roof + 1), TreeModelVolumes::AvoidanceType::Fast, false, min_xy_dist); + // prevent rounding errors down the line + //FIXME maybe use SafetyOffset::Yes at the following diff() instead? + forbidden_next = offset(union_ex(forbidden_next_raw), scaled(0.005), jtMiter, 1.2); + } + Polygons overhang_area_next = diff(overhang_area, forbidden_next); + if (area(overhang_area_next) < mesh_group_settings.minimum_roof_area) { + // Next layer down the roof area would be to small so we have to insert our roof support here. + if (dtt_roof > 0) { + size_t dtt_before = dtt_roof - 1; + // Produce support head points supporting an interface layer: First produce the interface lines, then sample them. + overhang_lines = split_lines( + convert_lines_to_internal(interface_placer.volumes, interface_placer.config, + ensure_maximum_distance_polyline(generate_roof_lines(last_overhang, layer_idx - dtt_before), connect_length, 1), layer_idx - dtt_before), + [&interface_placer, layer_idx, dtt_before](const std::pair &p) + { return evaluate_point_for_next_layer_function(interface_placer.volumes, interface_placer.config, layer_idx - dtt_before, p); }) + .first; + } + break; + } + added_roofs[dtt_roof] = overhang_area; + last_overhang = std::move(overhang_area); + overhang_area = std::move(overhang_area_next); + } + + layer_generation_dtt = std::max(dtt_roof, size_t(1)) - 1; // 1 inside max and -1 outside to avoid underflow. layer_generation_dtt=dtt_roof-1 if dtt_roof!=0; + // if the roof should be valid, check that the area does generate lines. This is NOT guaranteed. + if (overhang_lines.empty() && dtt_roof != 0 && generate_roof_lines(overhang_area, layer_idx - layer_generation_dtt).empty()) + for (size_t idx = 0; idx < dtt_roof; idx++) { + // check for every roof area that it has resulting lines. Remember idx 1 means the 2. layer of roof => higher idx == lower layer + if (generate_roof_lines(added_roofs[idx], layer_idx - idx).empty()) { + dtt_roof = idx; + layer_generation_dtt = std::max(dtt_roof, size_t(1)) - 1; + break; + } + } + added_roofs.erase(added_roofs.begin() + dtt_roof, added_roofs.end()); + interface_placer.add_roofs(std::move(added_roofs), layer_idx); + } + + if (overhang_lines.empty()) { + // support_line_width to form a line here as otherwise most will be unsupported. Technically this violates branch distance, but not only is this the only reasonable choice, + // but it ensures consistant behaviour as some infill patterns generate each line segment as its own polyline part causing a similar line forming behaviour. + // This is not doen when a roof is above as the roof will support the model and the trees only need to support the roof + bool supports_roof = dtt_roof > 0; + bool continuous_tips = ! supports_roof && large_horizontal_roof; + Polylines polylines = ensure_maximum_distance_polyline( + generate_support_infill_lines(overhang_area, interface_placer.support_parameters, supports_roof, layer_idx - layer_generation_dtt, + supports_roof ? mesh_group_settings.support_roof_line_distance : mesh_group_settings.support_tree_branch_distance), + continuous_tips ? interface_placer.config.min_radius / 2 : connect_length, 1); + size_t point_count = 0; + for (const Polyline &poly : polylines) + point_count += poly.size(); + const size_t min_support_points = std::max(coord_t(1), std::min(coord_t(3), coord_t(total_length(overhang_area) / connect_length))); + if (point_count <= min_support_points) { + // add the outer wall (of the overhang) to ensure it is correct supported instead. Try placing the support points in a way that they fully support the outer wall, instead of just the with half of the the support line width. + // I assume that even small overhangs are over one line width wide, so lets try to place the support points in a way that the full support area generated from them + // will support the overhang (if this is not done it may only be half). This WILL NOT be the case when supporting an angle of about < 60� so there is a fallback, + // as some support is better than none. + Polygons reduced_overhang_area = offset(union_ex(overhang_area), - interface_placer.config.support_line_width / 2.2, jtMiter, 1.2); + polylines = ensure_maximum_distance_polyline( + to_polylines( + ! reduced_overhang_area.empty() && + area(offset(diff_ex(overhang_area, reduced_overhang_area), std::max(interface_placer.config.support_line_width, connect_length), jtMiter, 1.2)) < sqr(scaled(0.001)) ? + reduced_overhang_area : + overhang_area), + connect_length, min_support_points); + } + overhang_lines = convert_lines_to_internal(interface_placer.volumes, interface_placer.config, polylines, layer_idx - dtt_roof); + } + + assert(dtt_roof <= layer_idx); + if (dtt_roof >= layer_idx && large_horizontal_roof) + // Reached buildplate when generating contact, interface and base interface layers. + interface_placer.add_roof_build_plate(std::move(overhang_area), dtt_roof); + else { + // normal trees have to be generated + const bool roof_enabled = num_support_roof_layers > 0; + interface_placer.add_points_along_lines( + // Sample along these lines + overhang_lines, + // First layer index to insert the tree tips or interfaces. + layer_idx - dtt_roof, + // Remaining roof tip layers. + interface_placer.force_tip_to_roof ? num_support_roof_layers - dtt_roof : 0, + // Supports roof already? How many roof layers were already produced above these tips? + dtt_roof, + // Don't move until the following distance to top is reached. + roof_enabled ? num_support_roof_layers - dtt_roof : 0); + } +} + +/*! + * \brief Creates the initial influence areas (that can later be propagated down) by placing them below the overhang. + * + * Generates Points where the Model should be supported and creates the areas where these points have to be placed. + * + * \param mesh[in] The mesh that is currently processed. + * \param move_bounds[out] Storage for the influence areas. + * \param storage[in] Background storage, required for adding roofs. + */ +static void generate_initial_areas( + const PrintObject &print_object, + const TreeModelVolumes &volumes, + const TreeSupportSettings &config, + const std::vector &overhangs, + std::vector &move_bounds, + InterfacePlacer &interface_placer, + std::function throw_on_cancel) +{ + using AvoidanceType = TreeModelVolumes::AvoidanceType; + TreeSupportMeshGroupSettings mesh_group_settings(print_object); + + // To ensure z_distance_top_layers are left empty between the overhang (zeroth empty layer), the support has to be added z_distance_top_layers+1 layers below + const size_t z_distance_delta = config.z_distance_top_layers + 1; + + const bool min_xy_dist = config.xy_distance > config.xy_min_distance; + +#if 0 + if (mesh.overhang_areas.size() <= z_distance_delta) + return; +#endif + + const coord_t connect_length = (config.support_line_width * 100. / mesh_group_settings.support_tree_top_rate) + std::max(2. * config.min_radius - 1.0 * config.support_line_width, 0.0); + // As r*r=x*x+y*y (circle equation): If a circle with center at (0,0) the top most point is at (0,r) as in y=r. + // This calculates how far one has to move on the x-axis so that y=r-support_line_width/2. + // In other words how far does one need to move on the x-axis to be support_line_width/2 away from the circle line. + // As a circle is round this length is identical for every axis as long as the 90 degrees angle between both remains. + const coord_t circle_length_to_half_linewidth_change = config.min_radius < config.support_line_width ? + config.min_radius / 2 : + scale_(sqrt(sqr(unscale(config.min_radius)) - sqr(unscale(config.min_radius - config.support_line_width / 2)))); + // Extra support offset to compensate for larger tip radiis. Also outset a bit more when z overwrites xy, because supporting something with a part of a support line is better than not supporting it at all. + //FIXME Vojtech: This is not sufficient for support enforcers to work. + //FIXME There is no account for the support overhang angle. + //FIXME There is no account for the width of the collision regions. + const coord_t extra_outset = std::max(coord_t(0), config.min_radius - config.support_line_width / 2) + (min_xy_dist ? config.support_line_width / 2 : 0) + //FIXME this is a heuristic value for support enforcers to work. +// + 10 * config.support_line_width; + ; + const size_t num_support_roof_layers = mesh_group_settings.support_roof_layers; + const bool roof_enabled = num_support_roof_layers > 0; + const bool force_tip_to_roof = roof_enabled && (interface_placer.support_parameters.soluble_interface || sqr(config.min_radius) * M_PI > mesh_group_settings.minimum_roof_area); + // cap for how much layer below the overhang a new support point may be added, as other than with regular support every new inserted point + // may cause extra material and time cost. Could also be an user setting or differently calculated. Idea is that if an overhang + // does not turn valid in double the amount of layers a slope of support angle would take to travel xy_distance, nothing reasonable will come from it. + // The 2*z_distance_delta is only a catch for when the support angle is very high. + // Used only if not min_xy_dist. + coord_t max_overhang_insert_lag = 0; + if (config.z_distance_top_layers > 0) { + max_overhang_insert_lag = 2 * config.z_distance_top_layers; + if (mesh_group_settings.support_angle > EPSILON && mesh_group_settings.support_angle < 0.5 * M_PI - EPSILON) { + //FIXME mesh_group_settings.support_angle does not apply to enforcers and also it does not apply to automatic support angle (by half the external perimeter width). + //used by max_overhang_insert_lag, only if not min_xy_dist. + const auto max_overhang_speed = coord_t(tan(mesh_group_settings.support_angle) * config.layer_height); + max_overhang_insert_lag = std::max(max_overhang_insert_lag, round_up_divide(config.xy_distance, max_overhang_speed / 2)); + } + } + + size_t num_support_layers; + int raft_contact_layer_idx; + // Layers with their overhang regions. + std::vector> raw_overhangs; + + { + const size_t num_raft_layers = config.raft_layers.size(); + const size_t first_support_layer = std::max(int(num_raft_layers) - int(z_distance_delta), 1); + num_support_layers = size_t(std::max(0, int(print_object.layer_count()) + int(num_raft_layers) - int(z_distance_delta))); + raft_contact_layer_idx = generate_raft_contact(print_object, config, interface_placer); + // Enumerate layers for which the support tips may be generated from overhangs above. + raw_overhangs.reserve(num_support_layers - first_support_layer); + for (size_t layer_idx = first_support_layer; layer_idx < num_support_layers; ++ layer_idx) + if (const size_t overhang_idx = layer_idx + z_distance_delta; ! overhangs[overhang_idx].empty()) + raw_overhangs.push_back({ layer_idx, &overhangs[overhang_idx] }); + } + + RichInterfacePlacer rich_interface_placer{ interface_placer, volumes, force_tip_to_roof, num_support_layers, move_bounds }; + + tbb::parallel_for(tbb::blocked_range(0, raw_overhangs.size()), + [&volumes, &config, &raw_overhangs, &mesh_group_settings, + min_xy_dist, roof_enabled, num_support_roof_layers, extra_outset, circle_length_to_half_linewidth_change, connect_length, + &rich_interface_placer, &throw_on_cancel](const tbb::blocked_range &range) { + for (size_t raw_overhang_idx = range.begin(); raw_overhang_idx < range.end(); ++ raw_overhang_idx) { + size_t layer_idx = raw_overhangs[raw_overhang_idx].first; + const Polygons &overhang_raw = *raw_overhangs[raw_overhang_idx].second; + + // take the least restrictive avoidance possible + Polygons relevant_forbidden; + { + const Polygons &relevant_forbidden_raw = config.support_rests_on_model ? + volumes.getCollision(config.getRadius(0), layer_idx, min_xy_dist) : + volumes.getAvoidance(config.getRadius(0), layer_idx, AvoidanceType::Fast, false, min_xy_dist); + // prevent rounding errors down the line, points placed directly on the line of the forbidden area may not be added otherwise. + relevant_forbidden = offset(union_ex(relevant_forbidden_raw), scaled(0.005), jtMiter, 1.2); + } + + // every overhang has saved if a roof should be generated for it. This can NOT be done in the for loop as an area may NOT have a roof + // even if it is larger than the minimum_roof_area when it is only larger because of the support horizontal expansion and + // it would not have a roof if the overhang is offset by support roof horizontal expansion instead. (At least this is the current behavior of the regular support) + Polygons overhang_regular; + { + // When support_offset = 0 safe_offset_inc will only be the difference between overhang_raw and relevant_forbidden, that has to be calculated anyway. + overhang_regular = safe_offset_inc(overhang_raw, mesh_group_settings.support_offset, relevant_forbidden, config.min_radius * 1.75 + config.xy_min_distance, 0, 1); + //check_self_intersections(overhang_regular, "overhang_regular1"); + + // offset ensures that areas that could be supported by a part of a support line, are not considered unsupported overhang + Polygons remaining_overhang = intersection( + diff(mesh_group_settings.support_offset == 0 ? + overhang_raw : + offset(union_ex(overhang_raw), mesh_group_settings.support_offset, jtMiter, 1.2), + offset(union_ex(overhang_regular), config.support_line_width * 0.5, jtMiter, 1.2)), + relevant_forbidden); + + // Offset the area to compensate for large tip radiis. Offset happens in multiple steps to ensure the tip is as close to the original overhang as possible. + //+config.support_line_width / 80 to avoid calculating very small (useless) offsets because of rounding errors. + //FIXME likely a better approach would be to find correspondences between the full overhang and the trimmed overhang + // and if there is no correspondence, project the missing points to the clipping curve. + for (coord_t extra_total_offset_acc = 0; ! remaining_overhang.empty() && extra_total_offset_acc + config.support_line_width / 8 < extra_outset; ) { + const coord_t offset_current_step = std::min( + extra_total_offset_acc + 2 * config.support_line_width > config.min_radius ? + config.support_line_width / 8 : + circle_length_to_half_linewidth_change, + extra_outset - extra_total_offset_acc); + extra_total_offset_acc += offset_current_step; + const Polygons &raw_collision = volumes.getCollision(0, layer_idx, true); + const coord_t offset_step = config.xy_min_distance + config.support_line_width; + // Reducing the remaining overhang by the areas already supported. + //FIXME 1.5 * extra_total_offset_acc seems to be too much, it may remove some remaining overhang without being supported at all. + remaining_overhang = diff(remaining_overhang, safe_offset_inc(overhang_regular, 1.5 * extra_total_offset_acc, raw_collision, offset_step, 0, 1)); + // Extending the overhangs by the inflated remaining overhangs. + overhang_regular = union_(overhang_regular, diff(safe_offset_inc(remaining_overhang, extra_total_offset_acc, raw_collision, offset_step, 0, 1), relevant_forbidden)); + //check_self_intersections(overhang_regular, "overhang_regular2"); + } +#if 0 + // If the xy distance overrides the z distance, some support needs to be inserted further down. + //=> Analyze which support points do not fit on this layer and check if they will fit a few layers down (while adding them an infinite amount of layers down would technically be closer the the setting description, it would not produce reasonable results. ) + if (! min_xy_dist) { + LineInformations overhang_lines; + { + //Vojtech: Generate support heads at support_tree_branch_distance spacing by producing a zig-zag infill at support_tree_branch_distance spacing, + // which is then resmapled + // support_line_width to form a line here as otherwise most will be unsupported. Technically this violates branch distance, + // mbut not only is this the only reasonable choice, but it ensures consistent behavior as some infill patterns generate + // each line segment as its own polyline part causing a similar line forming behavior. Also it is assumed that + // the area that is valid a layer below is to small for support roof. + Polylines polylines = ensure_maximum_distance_polyline( + generate_support_infill_lines(remaining_overhang, support_params, false, layer_idx, mesh_group_settings.support_tree_branch_distance), + config.min_radius, 1); + if (polylines.size() <= 3) + // add the outer wall to ensure it is correct supported instead + polylines = ensure_maximum_distance_polyline(to_polylines(remaining_overhang), connect_length, 3); + for (const auto &line : polylines) { + LineInformation res_line; + for (Point p : line) + res_line.emplace_back(p, LineStatus::INVALID); + overhang_lines.emplace_back(res_line); + } + validate_range(overhang_lines); + } + for (size_t lag_ctr = 1; lag_ctr <= max_overhang_insert_lag && !overhang_lines.empty() && layer_idx - coord_t(lag_ctr) >= 1; lag_ctr++) { + // get least restricted avoidance for layer_idx-lag_ctr + const Polygons &relevant_forbidden_below = config.support_rests_on_model ? + volumes.getCollision(config.getRadius(0), layer_idx - lag_ctr, min_xy_dist) : + volumes.getAvoidance(config.getRadius(0), layer_idx - lag_ctr, AvoidanceType::Fast, false, min_xy_dist); + // it is not required to offset the forbidden area here as the points wont change: If points here are not inside the forbidden area neither will they be later when placing these points, as these are the same points. + auto evaluatePoint = [&](std::pair p) { return contains(relevant_forbidden_below, p.first); }; + + std::pair split = split_lines(overhang_lines, evaluatePoint); // keep all lines that are invalid + overhang_lines = split.first; + // Set all now valid lines to their correct LineStatus. Easiest way is to just discard Avoidance information for each point and evaluate them again. + LineInformations fresh_valid_points = convert_lines_to_internal(volumes, config, convert_internal_to_lines(split.second), layer_idx - lag_ctr); + validate_range(fresh_valid_points); + + rich_interface_placer.add_points_along_lines(fresh_valid_points, (force_tip_to_roof && lag_ctr <= num_support_roof_layers) ? num_support_roof_layers : 0, layer_idx - lag_ctr, false, roof_enabled ? num_support_roof_layers : 0); + } + } +#endif + } + + throw_on_cancel(); + + if (roof_enabled) { + // Try to support the overhangs by dense interfaces for num_support_roof_layers, cover the bottom most interface with tree tips. + static constexpr const coord_t support_roof_offset = 0; + Polygons overhang_roofs = safe_offset_inc(overhang_raw, support_roof_offset, relevant_forbidden, config.min_radius * 2 + config.xy_min_distance, 0, 1); + if (mesh_group_settings.minimum_support_area > 0) + remove_small(overhang_roofs, mesh_group_settings.minimum_roof_area); + overhang_regular = diff(overhang_regular, overhang_roofs, ApplySafetyOffset::Yes); + //check_self_intersections(overhang_regular, "overhang_regular3"); + for (ExPolygon &roof_part : union_ex(overhang_roofs)) { + sample_overhang_area(to_polygons(std::move(roof_part)), true, layer_idx, num_support_roof_layers, connect_length, + mesh_group_settings, rich_interface_placer); + throw_on_cancel(); + } + } + // Either the roof is not enabled, then these are all the overhangs to be supported, + // or roof is enabled and these are the thin overhangs at object slopes (not horizontal overhangs). + if (mesh_group_settings.minimum_support_area > 0) + remove_small(overhang_regular, mesh_group_settings.minimum_support_area); + for (ExPolygon &support_part : union_ex(overhang_regular)) { + sample_overhang_area(to_polygons(std::move(support_part)), + false, layer_idx, num_support_roof_layers, connect_length, + mesh_group_settings, rich_interface_placer); + throw_on_cancel(); + } + } + }); + + finalize_raft_contact(print_object, raft_contact_layer_idx, interface_placer.top_contacts_mutable(), move_bounds); +} + +static unsigned int move_inside(const Polygons &polygons, Point &from, int distance = 0, int64_t maxDist2 = std::numeric_limits::max()) +{ + Point ret = from; + double bestDist2 = std::numeric_limits::max(); + auto bestPoly = static_cast(-1); + bool is_already_on_correct_side_of_boundary = false; // whether [from] is already on the right side of the boundary + for (unsigned int poly_idx = 0; poly_idx < polygons.size(); ++ poly_idx) { + const Polygon &poly = polygons[poly_idx]; + if (poly.size() < 2) + continue; + Point p0 = poly[poly.size() - 2]; + Point p1 = poly.back(); + // because we compare with vSize2 here (no division by zero), we also need to compare by vSize2 inside the loop + // to avoid integer rounding edge cases + bool projected_p_beyond_prev_segment = (p1 - p0).cast().dot((from - p0).cast()) >= (p1 - p0).cast().squaredNorm(); + for (const Point& p2 : poly) { + // X = A + Normal(B-A) * (((B-A) dot (P-A)) / VSize(B-A)); + // = A + (B-A) * ((B-A) dot (P-A)) / VSize2(B-A); + // X = P projected on AB + const Point& a = p1; + const Point& b = p2; + const Point& p = from; + auto ab = (b - a).cast(); + auto ap = (p - a).cast(); + int64_t ab_length2 = ab.squaredNorm(); + if (ab_length2 <= 0) { //A = B, i.e. the input polygon had two adjacent points on top of each other. + p1 = p2; //Skip only one of the points. + continue; + } + int64_t dot_prod = ab.dot(ap); + if (dot_prod <= 0) { // x is projected to before ab + if (projected_p_beyond_prev_segment) { + // case which looks like: > . + projected_p_beyond_prev_segment = false; + Point& x = p1; + + auto dist2 = (x - p).cast().squaredNorm(); + if (dist2 < bestDist2) { + bestDist2 = dist2; + bestPoly = poly_idx; + if (distance == 0) + ret = x; + else { + Vec2d abd = ab.cast(); + Vec2d p1p2 = (p1 - p0).cast(); + double lab = abd.norm(); + double lp1p2 = p1p2.norm(); + // inward direction irrespective of sign of [distance] + auto inward_dir = perp(abd * (scaled(10.0) / lab) + p1p2 * (scaled(10.0) / lp1p2)); + // MM2INT(10.0) to retain precision for the eventual normalization + ret = x + (inward_dir * (distance / inward_dir.norm())).cast(); + is_already_on_correct_side_of_boundary = inward_dir.dot((p - x).cast()) * distance >= 0; + } + } + } else { + projected_p_beyond_prev_segment = false; + p0 = p1; + p1 = p2; + continue; + } + } else if (dot_prod >= ab_length2) { + // x is projected to beyond ab + projected_p_beyond_prev_segment = true; + p0 = p1; + p1 = p2; + continue; + } else { + // x is projected to a point properly on the line segment (not onto a vertex). The case which looks like | . + projected_p_beyond_prev_segment = false; + Point x = a + (ab.cast() * (double(dot_prod) / double(ab_length2))).cast(); + auto dist2 = (p - x).cast().squaredNorm(); + if (dist2 < bestDist2) { + bestDist2 = dist2; + bestPoly = poly_idx; + if (distance == 0) + ret = x; + else { + Vec2d abd = ab.cast(); + Vec2d inward_dir = perp(abd * (distance / abd.norm())); // inward or outward depending on the sign of [distance] + ret = x + inward_dir.cast(); + is_already_on_correct_side_of_boundary = inward_dir.dot((p - x).cast()) >= 0; + } + } + } + p0 = p1; + p1 = p2; + } + } + // when the best point is already inside and we're moving inside, or when the best point is already outside and we're moving outside + if (is_already_on_correct_side_of_boundary) { + if (bestDist2 < distance * distance) + from = ret; + else { + // from = from; // original point stays unaltered. It is already inside by enough distance + } + return bestPoly; + } else if (bestDist2 < maxDist2) { + from = ret; + return bestPoly; + } + return -1; +} + +static Point move_inside_if_outside(const Polygons &polygons, Point from, int distance = 0, int64_t maxDist2 = std::numeric_limits::max()) +{ + if (! contains(polygons, from)) + move_inside(polygons, from); + return from; +} + +/*! + * \brief Checks if an influence area contains a valid subsection and returns the corresponding metadata and the new Influence area. + * + * Calculates an influence areas of the layer below, based on the influence area of one element on the current layer. + * Increases every influence area by maximum_move_distance_slow. If this is not enough, as in we would change our gracious or to_buildplate status the influence areas are instead increased by maximum_move_distance_slow. + * Also ensures that increasing the radius of a branch, does not cause it to change its status (like to_buildplate ). If this were the case, the radius is not increased instead. + * + * Warning: The used format inside this is different as the SupportElement does not have a valid area member. Instead this area is saved as value of the dictionary. This was done to avoid not needed heap allocations. + * + * \param settings[in] Which settings have to be used to check validity. + * \param layer_idx[in] Number of the current layer. + * \param parent[in] The metadata of the parents influence area. + * \param relevant_offset[in] The maximal possible influence area. No guarantee regarding validity with current layer collision required, as it is ensured in-function! + * \param to_bp_data[out] The part of the Influence area that can reach the buildplate. + * \param to_model_data[out] The part of the Influence area that do not have to reach the buildplate. This has overlap with new_layer_data. + * \param increased[out] Area than can reach all further up support points. No assurance is made that the buildplate or the model can be reached in accordance to the user-supplied settings. + * \param overspeed[in] How much should the already offset area be offset again. Usually this is 0. + * \param mergelayer[in] Will the merge method be called on this layer. This information is required as some calculation can be avoided if they are not required for merging. + * \return A valid support element for the next layer regarding the calculated influence areas. Empty if no influence are can be created using the supplied influence area and settings. + */ +[[nodiscard]] static std::optional increase_single_area( + const TreeModelVolumes &volumes, + const TreeSupportSettings &config, + const AreaIncreaseSettings &settings, + const LayerIndex layer_idx, + const SupportElement &parent, + const Polygons &relevant_offset, + Polygons &to_bp_data, + Polygons &to_model_data, + Polygons &increased, + const coord_t overspeed, + const bool mergelayer) +{ + SupportElementState current_elem{ SupportElementState::propagate_down(parent.state) }; + Polygons check_layer_data; + if (settings.increase_radius) + current_elem.effective_radius_height += 1; + coord_t radius = support_element_collision_radius(config, current_elem); + + if (settings.move) { + increased = relevant_offset; + if (overspeed > 0) { + const coord_t safe_movement_distance = + (current_elem.use_min_xy_dist ? config.xy_min_distance : config.xy_distance) + + (std::min(config.z_distance_top_layers, config.z_distance_bottom_layers) > 0 ? config.min_feature_size : 0); + // The difference to ensure that the result not only conforms to wall_restriction, but collision/avoidance is done later. + // The higher last_safe_step_movement_distance comes exactly from the fact that the collision will be subtracted later. + increased = safe_offset_inc(increased, overspeed, volumes.getWallRestriction(support_element_collision_radius(config, parent.state), layer_idx, parent.state.use_min_xy_dist), + safe_movement_distance, safe_movement_distance + radius, 1); + } + if (settings.no_error && settings.move) + // as ClipperLib::jtRound has to be used for offsets this simplify is VERY important for performance. + polygons_simplify(increased, scaled(0.025), polygons_strictly_simple); + } else + // if no movement is done the areas keep parent area as no move == offset(0) + increased = parent.influence_area; + + if (mergelayer || current_elem.to_buildplate) { + to_bp_data = safe_union(diff_clipped(increased, volumes.getAvoidance(radius, layer_idx - 1, settings.type, false, settings.use_min_distance))); + if (! current_elem.to_buildplate && area(to_bp_data) > tiny_area_threshold) { + // mostly happening in the tip, but with merges one should check every time, just to be sure. + current_elem.to_buildplate = true; // sometimes nodes that can reach the buildplate are marked as cant reach, tainting subtrees. This corrects it. + BOOST_LOG_TRIVIAL(debug) << "Corrected taint leading to a wrong to model value on layer " << layer_idx - 1 << " targeting " << + current_elem.target_height << " with radius " << radius; + } + } + if (config.support_rests_on_model) { + if (mergelayer || current_elem.to_model_gracious) + to_model_data = safe_union(diff_clipped(increased, volumes.getAvoidance(radius, layer_idx - 1, settings.type, true, settings.use_min_distance))); + + if (!current_elem.to_model_gracious) { + if (mergelayer && area(to_model_data) >= tiny_area_threshold) { + current_elem.to_model_gracious = true; + BOOST_LOG_TRIVIAL(debug) << "Corrected taint leading to a wrong non gracious value on layer " << layer_idx - 1 << " targeting " << + current_elem.target_height << " with radius " << radius; + } else + // Cannot route to gracious areas. Push the tree away from object and route it down anyways. + to_model_data = safe_union(diff_clipped(increased, volumes.getCollision(radius, layer_idx - 1, settings.use_min_distance))); + } + } + + check_layer_data = current_elem.to_buildplate ? to_bp_data : to_model_data; + + if (settings.increase_radius && area(check_layer_data) > tiny_area_threshold) { + auto validWithRadius = [&](coord_t next_radius) { + if (volumes.ceilRadius(next_radius, settings.use_min_distance) <= volumes.ceilRadius(radius, settings.use_min_distance)) + return true; + + Polygons to_bp_data_2; + if (current_elem.to_buildplate) + // regular union as output will not be used later => this area should always be a subset of the safe_union one (i think) + to_bp_data_2 = diff_clipped(increased, volumes.getAvoidance(next_radius, layer_idx - 1, settings.type, false, settings.use_min_distance)); + Polygons to_model_data_2; + if (config.support_rests_on_model && !current_elem.to_buildplate) + to_model_data_2 = diff_clipped(increased, + current_elem.to_model_gracious ? + volumes.getAvoidance(next_radius, layer_idx - 1, settings.type, true, settings.use_min_distance) : + volumes.getCollision(next_radius, layer_idx - 1, settings.use_min_distance)); + Polygons check_layer_data_2 = current_elem.to_buildplate ? to_bp_data_2 : to_model_data_2; + return area(check_layer_data_2) > tiny_area_threshold; + }; + coord_t ceil_radius_before = volumes.ceilRadius(radius, settings.use_min_distance); + + if (support_element_collision_radius(config, current_elem) < config.increase_radius_until_radius && support_element_collision_radius(config, current_elem) < support_element_radius(config, current_elem)) { + coord_t target_radius = std::min(support_element_radius(config, current_elem), config.increase_radius_until_radius); + coord_t current_ceil_radius = volumes.getRadiusNextCeil(radius, settings.use_min_distance); + + while (current_ceil_radius < target_radius && validWithRadius(volumes.getRadiusNextCeil(current_ceil_radius + 1, settings.use_min_distance))) + current_ceil_radius = volumes.getRadiusNextCeil(current_ceil_radius + 1, settings.use_min_distance); + size_t resulting_eff_dtt = current_elem.effective_radius_height; + while (resulting_eff_dtt + 1 < current_elem.distance_to_top && + config.getRadius(resulting_eff_dtt + 1, current_elem.elephant_foot_increases) <= current_ceil_radius && + config.getRadius(resulting_eff_dtt + 1, current_elem.elephant_foot_increases) <= support_element_radius(config, current_elem)) + ++ resulting_eff_dtt; + current_elem.effective_radius_height = resulting_eff_dtt; + } + radius = support_element_collision_radius(config, current_elem); + + const coord_t foot_radius_increase = std::max(config.bp_radius_increase_per_layer - config.branch_radius_increase_per_layer, 0.0); + // Is nearly all of the time 1, but sometimes an increase of 1 could cause the radius to become bigger than recommendedMinRadius, + // which could cause the radius to become bigger than precalculated. + double planned_foot_increase = std::min(1.0, double(config.recommendedMinRadius(layer_idx - 1) - support_element_radius(config, current_elem)) / foot_radius_increase); +//FIXME + bool increase_bp_foot = planned_foot_increase > 0 && current_elem.to_buildplate; +// bool increase_bp_foot = false; + + if (increase_bp_foot && support_element_radius(config, current_elem) >= config.branch_radius && support_element_radius(config, current_elem) >= config.increase_radius_until_radius) + if (validWithRadius(config.getRadius(current_elem.effective_radius_height, current_elem.elephant_foot_increases + planned_foot_increase))) { + current_elem.elephant_foot_increases += planned_foot_increase; + radius = support_element_collision_radius(config, current_elem); + } + + if (ceil_radius_before != volumes.ceilRadius(radius, settings.use_min_distance)) { + if (current_elem.to_buildplate) + to_bp_data = safe_union(diff_clipped(increased, volumes.getAvoidance(radius, layer_idx - 1, settings.type, false, settings.use_min_distance))); + if (config.support_rests_on_model && (!current_elem.to_buildplate || mergelayer)) + to_model_data = safe_union(diff_clipped(increased, + current_elem.to_model_gracious ? + volumes.getAvoidance(radius, layer_idx - 1, settings.type, true, settings.use_min_distance) : + volumes.getCollision(radius, layer_idx - 1, settings.use_min_distance) + )); + check_layer_data = current_elem.to_buildplate ? to_bp_data : to_model_data; + if (area(check_layer_data) < tiny_area_threshold) { + BOOST_LOG_TRIVIAL(error) << "Lost area by doing catch up from " << ceil_radius_before << " to radius " << + volumes.ceilRadius(support_element_collision_radius(config, current_elem), settings.use_min_distance); + tree_supports_show_error("Area lost catching up radius. May not cause visible malformation."sv, true); + } + } + } + + return area(check_layer_data) > tiny_area_threshold ? std::optional(current_elem) : std::optional(); +} + +struct SupportElementInfluenceAreas { + // All influence areas: both to build plate and model. + Polygons influence_areas; + // Influence areas just to build plate. + Polygons to_bp_areas; + // Influence areas just to model. + Polygons to_model_areas; + + void clear() { + this->influence_areas.clear(); + this->to_bp_areas.clear(); + this->to_model_areas.clear(); + } +}; + +struct SupportElementMerging { + SupportElementState state; + /*! + * \brief All elements in the layer above the current one that are supported by this element + */ + SupportElement::ParentIndices parents; + + SupportElementInfluenceAreas areas; + // Bounding box of all influence areas. + Eigen::AlignedBox bbox_data; + + const Eigen::AlignedBox& bbox() const { return bbox_data;} + const Point centroid() const { return (bbox_data.min() + bbox_data.max()) / 2; } + void set_bbox(const BoundingBox& abbox) + { Point eps { coord_t(SCALED_EPSILON), coord_t(SCALED_EPSILON) }; bbox_data = { abbox.min - eps, abbox.max + eps }; } + + // Called by the AABBTree builder to get an index into the vector of source elements. + // Not needed, thus zero is returned. + static size_t idx() { return 0; } +}; + +/*! + * \brief Increases influence areas as far as required. + * + * Calculates influence areas of the layer below, based on the influence areas of the current layer. + * Increases every influence area by maximum_move_distance_slow. If this is not enough, as in it would change the gracious or to_buildplate status, the influence areas are instead increased by maximum_move_distance. + * Also ensures that increasing the radius of a branch, does not cause it to change its status (like to_buildplate ). If this were the case, the radius is not increased instead. + * + * Warning: The used format inside this is different as the SupportElement does not have a valid area member. Instead this area is saved as value of the dictionary. This was done to avoid not needed heap allocations. + * + * \param to_bp_areas[out] Influence areas that can reach the buildplate + * \param to_model_areas[out] Influence areas that do not have to reach the buildplate. This has overlap with new_layer_data, as areas that can reach the buildplate are also considered valid areas to the model. + * This redundancy is required if a to_buildplate influence area is allowed to merge with a to model influence area. + * \param influence_areas[out] Area than can reach all further up support points. No assurance is made that the buildplate or the model can be reached in accordance to the user-supplied settings. + * \param bypass_merge_areas[out] Influence areas ready to be added to the layer below that do not need merging. + * \param last_layer[in] Influence areas of the current layer. + * \param layer_idx[in] Number of the current layer. + * \param mergelayer[in] Will the merge method be called on this layer. This information is required as some calculation can be avoided if they are not required for merging. + */ +static void increase_areas_one_layer( + const TreeModelVolumes &volumes, + const TreeSupportSettings &config, + // New areas at the layer below layer_idx + std::vector &merging_areas, + // Layer above merging_areas. + const LayerIndex layer_idx, + // Layer elements above merging_areas. + SupportElements &layer_elements, + // If false, the merging_areas will not be merged for performance reasons. + const bool mergelayer, + std::function throw_on_cancel) +{ + using AvoidanceType = TreeModelVolumes::AvoidanceType; + + tbb::parallel_for(tbb::blocked_range(0, merging_areas.size(), 1), + [&](const tbb::blocked_range &range) { + for (size_t merging_area_idx = range.begin(); merging_area_idx < range.end(); ++ merging_area_idx) { + SupportElementMerging &merging_area = merging_areas[merging_area_idx]; + assert(merging_area.parents.size() == 1); + SupportElement &parent = layer_elements[merging_area.parents.front()]; + SupportElementState elem = SupportElementState::propagate_down(parent.state); + const Polygons &wall_restriction = + // Abstract representation of the model outline. If an influence area would move through it, it could teleport through a wall. + volumes.getWallRestriction(support_element_collision_radius(config, parent.state), layer_idx, parent.state.use_min_xy_dist); + +#ifdef TREESUPPORT_DEBUG_SVG + SVG::export_expolygons(debug_out_path("treesupport-increase_areas_one_layer-%d-%ld.svg", layer_idx, int(merging_area_idx)), + { { { union_ex(wall_restriction) }, { "wall_restricrictions", "gray", 0.5f } }, + { { union_ex(parent.influence_area) }, { "parent", "red", "black", "", scaled(0.1f), 0.5f } } }); +#endif // TREESUPPORT_DEBUG_SVG + + Polygons to_bp_data, to_model_data; + coord_t radius = support_element_collision_radius(config, elem); + + // When the radius increases, the outer "support wall" of the branch will have been moved farther away from the center (as this is the definition of radius). + // As it is not specified that the support_tree_angle has to be one of the center of the branch, it is here seen as the smaller angle of the outer wall of the branch, to the outer wall of the same branch one layer above. + // As the branch may have become larger the distance between these 2 walls is smaller than the distance of the center points. + // These extra distance is added to the movement distance possible for this layer. + + coord_t extra_speed = 5; // The extra speed is added to both movement distances. Also move 5 microns faster than allowed to avoid rounding errors, this may cause issues at VERY VERY small layer heights. + coord_t extra_slow_speed = 0; // Only added to the slow movement distance. + const coord_t ceiled_parent_radius = volumes.ceilRadius(support_element_collision_radius(config, parent.state), parent.state.use_min_xy_dist); + coord_t projected_radius_increased = config.getRadius(parent.state.effective_radius_height + 1, parent.state.elephant_foot_increases); + coord_t projected_radius_delta = projected_radius_increased - support_element_collision_radius(config, parent.state); + + // When z distance is more than one layer up and down the Collision used to calculate the wall restriction will always include the wall (and not just the xy_min_distance) of the layer above and below like this (d = blocked area because of z distance): + /* + * layer z+1:dddddiiiiiioooo + * layer z+0:xxxxxdddddddddd + * layer z-1:dddddxxxxxxxxxx + * For more detailed visualisation see calculateWallRestrictions + */ + const coord_t safe_movement_distance = + (elem.use_min_xy_dist ? config.xy_min_distance : config.xy_distance) + + (std::min(config.z_distance_top_layers, config.z_distance_bottom_layers) > 0 ? config.min_feature_size : 0); + if (ceiled_parent_radius == volumes.ceilRadius(projected_radius_increased, parent.state.use_min_xy_dist) || + projected_radius_increased < config.increase_radius_until_radius) + // If it is guaranteed possible to increase the radius, the maximum movement speed can be increased, as it is assumed that the maximum movement speed is the one of the slower moving wall + extra_speed += projected_radius_delta; + else + // if a guaranteed radius increase is not possible, only increase the slow speed + // Ensure that the slow movement distance can not become larger than the fast one. + extra_slow_speed += std::min(projected_radius_delta, (config.maximum_move_distance + extra_speed) - (config.maximum_move_distance_slow + extra_slow_speed)); + + if (config.layer_start_bp_radius > layer_idx && + config.recommendedMinRadius(layer_idx - 1) < config.getRadius(elem.effective_radius_height + 1, elem.elephant_foot_increases)) { + // can guarantee elephant foot radius increase + if (ceiled_parent_radius == volumes.ceilRadius(config.getRadius(parent.state.effective_radius_height + 1, parent.state.elephant_foot_increases + 1), parent.state.use_min_xy_dist)) + extra_speed += config.bp_radius_increase_per_layer; + else + extra_slow_speed += std::min(coord_t(config.bp_radius_increase_per_layer), + config.maximum_move_distance - (config.maximum_move_distance_slow + extra_slow_speed)); + } + + const coord_t fast_speed = config.maximum_move_distance + extra_speed; + const coord_t slow_speed = config.maximum_move_distance_slow + extra_speed + extra_slow_speed; + + Polygons offset_slow, offset_fast; + + bool add = false; + bool bypass_merge = false; + constexpr bool increase_radius = true, no_error = true, use_min_radius = true, move = true; // aliases for better readability + + // Determine in which order configurations are checked if they result in a valid influence area. Check will stop if a valid area is found + std::vector order; + auto insertSetting = [&](AreaIncreaseSettings settings, bool back) { + if (std::find(order.begin(), order.end(), settings) == order.end()) { + if (back) + order.emplace_back(settings); + else + order.insert(order.begin(), settings); + } + }; + + const bool parent_moved_slow = elem.last_area_increase.increase_speed < config.maximum_move_distance; + const bool avoidance_speed_mismatch = parent_moved_slow && elem.last_area_increase.type != AvoidanceType::Slow; + if (elem.last_area_increase.move && elem.last_area_increase.no_error && elem.can_use_safe_radius && !mergelayer && + !avoidance_speed_mismatch && (elem.distance_to_top >= config.tip_layers || parent_moved_slow)) { + // assume that the avoidance type that was best for the parent is best for me. Makes this function about 7% faster. + insertSetting({ elem.last_area_increase.type, elem.last_area_increase.increase_speed < config.maximum_move_distance ? slow_speed : fast_speed, + increase_radius, elem.last_area_increase.no_error, !use_min_radius, elem.last_area_increase.move }, true); + insertSetting({ elem.last_area_increase.type, elem.last_area_increase.increase_speed < config.maximum_move_distance ? slow_speed : fast_speed, + !increase_radius, elem.last_area_increase.no_error, !use_min_radius, elem.last_area_increase.move }, true); + } + // branch may still go though a hole, so a check has to be done whether the hole was already passed, and the regular avoidance can be used. + if (!elem.can_use_safe_radius) { + // if the radius until which it is always increased can not be guaranteed, move fast. This is to avoid holes smaller than the real branch radius. + // This does not guarantee the avoidance of such holes, but ensures they are avoided if possible. + // order.emplace_back(AvoidanceType::Slow,!increase_radius,no_error,!use_min_radius,move); + insertSetting({ AvoidanceType::Slow, slow_speed, increase_radius, no_error, !use_min_radius, !move }, true); // did we go through the hole + // in many cases the definition of hole is overly restrictive, so to avoid unnecessary fast movement in the tip, it is ignored there for a bit. + // This CAN cause a branch to go though a hole it otherwise may have avoided. + if (elem.distance_to_top < round_up_divide(config.tip_layers, size_t(2))) + insertSetting({ AvoidanceType::Fast, slow_speed, increase_radius, no_error, !use_min_radius, !move }, true); + insertSetting({ AvoidanceType::FastSafe, fast_speed, increase_radius, no_error, !use_min_radius, !move }, true); // did we manage to avoid the hole + insertSetting({ AvoidanceType::FastSafe, fast_speed, !increase_radius, no_error, !use_min_radius, move }, true); + insertSetting({ AvoidanceType::Fast, fast_speed, !increase_radius, no_error, !use_min_radius, move }, true); + } else { + insertSetting({ AvoidanceType::Slow, slow_speed, increase_radius, no_error, !use_min_radius, move }, true); + // while moving fast to be able to increase the radius (b) may seems preferable (over a) this can cause the a sudden skip in movement, + // which looks similar to a layer shift and can reduce stability. + // as such idx have chosen to only use the user setting for radius increases as a friendly recommendation. + insertSetting({ AvoidanceType::Slow, slow_speed, !increase_radius, no_error, !use_min_radius, move }, true); // a + if (elem.distance_to_top < config.tip_layers) + insertSetting({ AvoidanceType::FastSafe, slow_speed, increase_radius, no_error, !use_min_radius, move }, true); + insertSetting({ AvoidanceType::FastSafe, fast_speed, increase_radius, no_error, !use_min_radius, move }, true); // b + insertSetting({ AvoidanceType::FastSafe, fast_speed, !increase_radius, no_error, !use_min_radius, move }, true); + } + + if (elem.use_min_xy_dist) { + std::vector new_order; + // if the branch currently has to use min_xy_dist check if the configuration would also be valid + // with the regular xy_distance before checking with use_min_radius (Only happens when Support Distance priority is z overrides xy ) + for (AreaIncreaseSettings settings : order) { + new_order.emplace_back(settings); + new_order.push_back({ settings.type, settings.increase_speed, settings.increase_radius, settings.no_error, use_min_radius, settings.move }); + } + order = new_order; + } + if (elem.to_buildplate || (elem.to_model_gracious && intersection(parent.influence_area, volumes.getPlaceableAreas(radius, layer_idx, throw_on_cancel)).empty())) { + // error case + // it is normal that we wont be able to find a new area at some point in time if we wont be able to reach layer 0 aka have to connect with the model + insertSetting({ AvoidanceType::Fast, fast_speed, !increase_radius, !no_error, elem.use_min_xy_dist, move }, true); + } + if (elem.distance_to_top < elem.dont_move_until && elem.can_use_safe_radius) // only do not move when holes would be avoided in every case. + // Only do not move when already in a no hole avoidance with the regular xy distance. + insertSetting({ AvoidanceType::Slow, 0, increase_radius, no_error, !use_min_radius, !move }, false); + + Polygons inc_wo_collision; + // Check whether it is faster to calculate the area increased with the fast speed independently from the slow area, or time could be saved by reusing the slow area to calculate the fast one. + // Calculated by comparing the steps saved when calcualting idependently with the saved steps when not. + bool offset_independant_faster = radius / safe_movement_distance - int(config.maximum_move_distance + extra_speed < radius + safe_movement_distance) > + round_up_divide((extra_speed + extra_slow_speed + config.maximum_move_distance_slow), safe_movement_distance); + for (const AreaIncreaseSettings &settings : order) { + if (settings.move) { + if (offset_slow.empty() && (settings.increase_speed == slow_speed || ! offset_independant_faster)) { + // offsetting in 2 steps makes our offsetted area rounder preventing (rounding) errors created by to pointy areas. At this point one can see that the Polygons class + // was never made for precision in the single digit micron range. + offset_slow = safe_offset_inc(parent.influence_area, extra_speed + extra_slow_speed + config.maximum_move_distance_slow, + wall_restriction, safe_movement_distance, offset_independant_faster ? safe_movement_distance + radius : 0, 2); +#ifdef TREESUPPORT_DEBUG_SVG + SVG::export_expolygons(debug_out_path("treesupport-increase_areas_one_layer-slow-%d-%ld.svg", layer_idx, int(merging_area_idx)), + { { { union_ex(wall_restriction) }, { "wall_restricrictions", "gray", 0.5f } }, + { { union_ex(offset_slow) }, { "offset_slow", "red", "black", "", scaled(0.1f), 0.5f } } }); +#endif // TREESUPPORT_DEBUG_SVG + } + if (offset_fast.empty() && settings.increase_speed != slow_speed) { + if (offset_independant_faster) + offset_fast = safe_offset_inc(parent.influence_area, extra_speed + config.maximum_move_distance, + wall_restriction, safe_movement_distance, offset_independant_faster ? safe_movement_distance + radius : 0, 1); + else { + const coord_t delta_slow_fast = config.maximum_move_distance - (config.maximum_move_distance_slow + extra_slow_speed); + offset_fast = safe_offset_inc(offset_slow, delta_slow_fast, wall_restriction, safe_movement_distance, safe_movement_distance + radius, offset_independant_faster ? 2 : 1); + } +#ifdef TREESUPPORT_DEBUG_SVG + SVG::export_expolygons(debug_out_path("treesupport-increase_areas_one_layer-fast-%d-%ld.svg", layer_idx, int(merging_area_idx)), + { { { union_ex(wall_restriction) }, { "wall_restricrictions", "gray", 0.5f } }, + { { union_ex(offset_fast) }, { "offset_fast", "red", "black", "", scaled(0.1f), 0.5f } } }); +#endif // TREESUPPORT_DEBUG_SVG + } + } + std::optional result; + inc_wo_collision.clear(); + if (!settings.no_error) { + // ERROR CASE + // if the area becomes for whatever reason something that clipper sees as a line, offset would stop working, so ensure that even if if wrongly would be a line, it still actually has an area that can be increased + Polygons lines_offset = offset(to_polylines(parent.influence_area), scaled(0.005), jtMiter, 1.2); + Polygons base_error_area = union_(parent.influence_area, lines_offset); + result = increase_single_area(volumes, config, settings, layer_idx, parent, + base_error_area, to_bp_data, to_model_data, inc_wo_collision, (config.maximum_move_distance + extra_speed) * 1.5, mergelayer); +#ifdef TREE_SUPPORT_SHOW_ERRORS + BOOST_LOG_TRIVIAL(error) +#else // TREE_SUPPORT_SHOW_ERRORS + BOOST_LOG_TRIVIAL(warning) +#endif // TREE_SUPPORT_SHOW_ERRORS + << "Influence area could not be increased! Data about the Influence area: " + "Radius: " << radius << " at layer: " << layer_idx - 1 << " NextTarget: " << elem.layer_idx << " Distance to top: " << elem.distance_to_top << + " Elephant foot increases " << elem.elephant_foot_increases << " use_min_xy_dist " << elem.use_min_xy_dist << " to buildplate " << elem.to_buildplate << + " gracious " << elem.to_model_gracious << " safe " << elem.can_use_safe_radius << " until move " << elem.dont_move_until << " \n " + "Parent " << &parent << ": Radius: " << support_element_collision_radius(config, parent.state) << " at layer: " << layer_idx << " NextTarget: " << parent.state.layer_idx << + " Distance to top: " << parent.state.distance_to_top << " Elephant foot increases " << parent.state.elephant_foot_increases << " use_min_xy_dist " << parent.state.use_min_xy_dist << + " to buildplate " << parent.state.to_buildplate << " gracious " << parent.state.to_model_gracious << " safe " << parent.state.can_use_safe_radius << " until move " << parent.state.dont_move_until; + tree_supports_show_error("Potentially lost branch!"sv, true); +#ifdef TREE_SUPPORTS_TRACK_LOST + if (result) + result->lost = true; +#endif // TREE_SUPPORTS_TRACK_LOST + } else + result = increase_single_area(volumes, config, settings, layer_idx, parent, + settings.increase_speed == slow_speed ? offset_slow : offset_fast, to_bp_data, to_model_data, inc_wo_collision, 0, mergelayer); + + if (result) { + elem = *result; + radius = support_element_collision_radius(config, elem); + elem.last_area_increase = settings; + add = true; + // do not merge if the branch should not move or the priority has to be to get farther away from the model. + bypass_merge = !settings.move || (settings.use_min_distance && elem.distance_to_top < config.tip_layers); + if (settings.move) + elem.dont_move_until = 0; + else + elem.result_on_layer = parent.state.result_on_layer; + + elem.can_use_safe_radius = settings.type != AvoidanceType::Fast; + + if (!settings.use_min_distance) + elem.use_min_xy_dist = false; + if (!settings.no_error) +#ifdef TREE_SUPPORT_SHOW_ERRORS + BOOST_LOG_TRIVIAL(error) +#else // TREE_SUPPORT_SHOW_ERRORS + BOOST_LOG_TRIVIAL(info) +#endif // TREE_SUPPORT_SHOW_ERRORS + << "Trying to keep area by moving faster than intended: Success"; + break; + } else if (!settings.no_error) + BOOST_LOG_TRIVIAL(error) << "Trying to keep area by moving faster than intended: FAILURE! WRONG BRANCHES LIKLY!"; + } + + if (add) { + // Union seems useless, but some rounding errors somewhere can cause to_bp_data to be slightly bigger than it should be. + assert(! inc_wo_collision.empty() || ! to_bp_data.empty() || ! to_model_data.empty()); + Polygons max_influence_area = safe_union( + diff_clipped(inc_wo_collision, volumes.getCollision(radius, layer_idx - 1, elem.use_min_xy_dist)), + safe_union(to_bp_data, to_model_data)); + merging_area.state = elem; + assert(!max_influence_area.empty()); + merging_area.set_bbox(get_extents(max_influence_area)); + merging_area.areas.influence_areas = std::move(max_influence_area); + if (! bypass_merge) { + if (elem.to_buildplate) + merging_area.areas.to_bp_areas = std::move(to_bp_data); + if (config.support_rests_on_model) + merging_area.areas.to_model_areas = std::move(to_model_data); + } + } else { + // If the bottom most point of a branch is set, later functions will assume that the position is valid, and ignore it. + // But as branches connecting with the model that are to small have to be culled, the bottom most point has to be not set. + // A point can be set on the top most tip layer (maybe more if it should not move for a few layers). + parent.state.result_on_layer_reset(); + parent.state.to_model_gracious = false; +#ifdef TREE_SUPPORTS_TRACK_LOST + parent.state.verylost = true; +#endif // TREE_SUPPORTS_TRACK_LOST + } + + throw_on_cancel(); + } + }, tbb::simple_partitioner()); +} + +[[nodiscard]] static SupportElementState merge_support_element_states( + const SupportElementState &first, const SupportElementState &second, const Point &next_position, const coord_t layer_idx, + const TreeSupportSettings &config) +{ + SupportElementState out; + out.next_position = next_position; + out.layer_idx = layer_idx; + out.use_min_xy_dist = first.use_min_xy_dist || second.use_min_xy_dist; + out.supports_roof = first.supports_roof || second.supports_roof; + out.dont_move_until = std::max(first.dont_move_until, second.dont_move_until); + out.can_use_safe_radius = first.can_use_safe_radius || second.can_use_safe_radius; + out.missing_roof_layers = std::min(first.missing_roof_layers, second.missing_roof_layers); + out.skip_ovalisation = false; + if (first.target_height > second.target_height) { + out.target_height = first.target_height; + out.target_position = first.target_position; + } else { + out.target_height = second.target_height; + out.target_position = second.target_position; + } + out.effective_radius_height = std::max(first.effective_radius_height, second.effective_radius_height); + out.distance_to_top = std::max(first.distance_to_top, second.distance_to_top); + + out.to_buildplate = first.to_buildplate && second.to_buildplate; + out.to_model_gracious = first.to_model_gracious && second.to_model_gracious; // valid as we do not merge non-gracious with gracious + + out.elephant_foot_increases = 0; + if (config.bp_radius_increase_per_layer > 0) { + coord_t foot_increase_radius = std::abs(std::max(support_element_collision_radius(config, second), support_element_collision_radius(config, first)) - support_element_collision_radius(config, out)); + // elephant_foot_increases has to be recalculated, as when a smaller tree with a larger elephant_foot_increases merge with a larger branch + // the elephant_foot_increases may have to be lower as otherwise the radius suddenly increases. This results often in a non integer value. + out.elephant_foot_increases = foot_increase_radius / (config.bp_radius_increase_per_layer - config.branch_radius_increase_per_layer); + } + + // set last settings to the best out of both parents. If this is wrong, it will only cause a small performance penalty instead of weird behavior. + out.last_area_increase = { + std::min(first.last_area_increase.type, second.last_area_increase.type), + std::min(first.last_area_increase.increase_speed, second.last_area_increase.increase_speed), + first.last_area_increase.increase_radius || second.last_area_increase.increase_radius, + first.last_area_increase.no_error || second.last_area_increase.no_error, + first.last_area_increase.use_min_distance && second.last_area_increase.use_min_distance, + first.last_area_increase.move || second.last_area_increase.move }; + + return out; +} + +static bool merge_influence_areas_two_elements( + const TreeModelVolumes &volumes, const TreeSupportSettings &config, const LayerIndex layer_idx, + SupportElementMerging &dst, SupportElementMerging &src) +{ + // Don't merge gracious with a non gracious area as bad placement could negatively impact reliability of the whole subtree. + const bool merging_gracious_and_non_gracious = dst.state.to_model_gracious != src.state.to_model_gracious; + // Could cause some issues with the increase of one area, as it is assumed that if the smaller is increased + // by the delta to the larger it is engulfed by it already. But because a different collision + // may be removed from the in draw_area() generated circles, this assumption could be wrong. + const bool merging_min_and_regular_xy = dst.state.use_min_xy_dist != src.state.use_min_xy_dist; + + if (merging_gracious_and_non_gracious || merging_min_and_regular_xy) + return false; + + const bool dst_radius_bigger = support_element_collision_radius(config, dst.state) > support_element_collision_radius(config, src.state); + const SupportElementMerging &smaller_rad = dst_radius_bigger ? src : dst; + const SupportElementMerging &bigger_rad = dst_radius_bigger ? dst : src; + const coord_t real_radius_delta = std::abs(support_element_radius(config, bigger_rad.state) - support_element_radius(config, smaller_rad.state)); + { + // Testing intersection of bounding boxes. + // Expand the smaller radius branch bounding box to match the lambda intersect_small_with_bigger() below. + // Because the lambda intersect_small_with_bigger() applies a rounded offset, a snug offset of the bounding box + // is sufficient. On the other side, if a mitered offset was used by the lambda, + // the bounding box expansion would have to account for the mitered extension of the sharp corners. + Eigen::AlignedBox smaller_bbox = smaller_rad.bbox(); + smaller_bbox.min() -= Point{ real_radius_delta, real_radius_delta }; + smaller_bbox.max() += Point{ real_radius_delta, real_radius_delta }; + if (! smaller_bbox.intersects(bigger_rad.bbox())) + return false; + } + + // Accumulator of a radius increase of a "to model" branch by merging in a "to build plate" branch. + coord_t increased_to_model_radius = 0; + const bool merging_to_bp = dst.state.to_buildplate && src.state.to_buildplate; + if (! merging_to_bp) { + // Get the real radius increase as the user does not care for the collision model. + if (dst.state.to_buildplate != src.state.to_buildplate) { + // Merging a "to build plate" branch with a "to model" branch. + // Don't allow merging a thick "to build plate" branch into a thinner "to model" branch. + const coord_t rdst = support_element_radius(config, dst.state); + const coord_t rsrc = support_element_radius(config, src.state); + if (dst.state.to_buildplate) { + if (rsrc < rdst) + increased_to_model_radius = src.state.increased_to_model_radius + rdst - rsrc; + } else { + if (rsrc > rdst) + increased_to_model_radius = dst.state.increased_to_model_radius + rsrc - rdst; + } + if (increased_to_model_radius > config.max_to_model_radius_increase) + return false; + } + // if a merge could place a stable branch on unstable ground, would be increasing the radius further + // than allowed to when merging to model and to_bp trees or would merge to model before it is known + // they will even been drawn the merge is skipped + if (! dst.state.supports_roof && ! src.state.supports_roof && + std::max(src.state.distance_to_top, dst.state.distance_to_top) < config.min_dtt_to_model) + return false; + } + + // Area of the bigger radius is used to ensure correct placement regarding the relevant avoidance, + // so if that would change an invalid area may be created. + if (! bigger_rad.state.can_use_safe_radius && smaller_rad.state.can_use_safe_radius) + return false; + + // the bigger radius is used to verify that the area is still valid after the increase with the delta. + // If there were a point where the big influence area could be valid with can_use_safe_radius + // the element would already be can_use_safe_radius. + // the smaller radius, which gets increased by delta may reach into the area where use_min_xy_dist is no longer required. + const bool use_min_radius = bigger_rad.state.use_min_xy_dist && smaller_rad.state.use_min_xy_dist; + + // The idea is that the influence area with the smaller collision radius is increased by the radius difference. + // If this area has any intersections with the influence area of the larger collision radius, a branch (of the larger collision radius) placed in this intersection, has already engulfed the branch of the smaller collision radius. + // Because of this a merge may happen even if the influence areas (that represent possible center points of branches) do not intersect yet. + // Remember that collision radius <= real radius as otherwise this assumption would be false. + const coord_t smaller_collision_radius = support_element_collision_radius(config, smaller_rad.state); + const Polygons &collision = volumes.getCollision(smaller_collision_radius, layer_idx - 1, use_min_radius); + auto intersect_small_with_bigger = [real_radius_delta, smaller_collision_radius, &collision, &config](const Polygons &small, const Polygons &bigger) { + return intersection( + safe_offset_inc( + small, real_radius_delta, collision, + // -3 avoids possible rounding errors + 2 * (config.xy_distance + smaller_collision_radius - 3), 0, 0), + bigger); + }; +//#define TREES_MERGE_RATHER_LATER + Polygons intersect = +#ifdef TREES_MERGE_RATHER_LATER + intersection( +#else + intersect_small_with_bigger( +#endif + merging_to_bp ? smaller_rad.areas.to_bp_areas : smaller_rad.areas.to_model_areas, + merging_to_bp ? bigger_rad.areas.to_bp_areas : bigger_rad.areas.to_model_areas); + + // dont use empty as a line is not empty, but for this use-case it very well may be (and would be one layer down as union does not keep lines) + // check if the overlap is large enough (Small ares tend to attract rounding errors in clipper). + if (area(intersect) <= tiny_area_threshold) + return false; + + // While 0.025 was guessed as enough, i did not have reason to change it. + if (area(offset(intersect, scaled(-0.025), jtMiter, 1.2)) <= tiny_area_threshold) + return false; + +#ifdef TREES_MERGE_RATHER_LATER + intersect = + intersect_small_with_bigger( + merging_to_bp ? smaller_rad.areas.to_bp_areas : smaller_rad.areas.to_model_areas, + merging_to_bp ? bigger_rad.areas.to_bp_areas : bigger_rad.areas.to_model_areas); +#endif + + // Do the actual merge now that the branches are confirmed to be able to intersect. + // calculate which point is closest to the point of the last merge (or tip center if no merge above it has happened) + // used at the end to estimate where to best place the branch on the bottom most layer + // could be replaced with a random point inside the new area + Point new_pos = move_inside_if_outside(intersect, dst.state.next_position); + + SupportElementState new_state = merge_support_element_states(dst.state, src.state, new_pos, layer_idx - 1, config); + new_state.increased_to_model_radius = increased_to_model_radius == 0 ? + // increased_to_model_radius was not set yet. Propagate maximum. + std::max(dst.state.increased_to_model_radius, src.state.increased_to_model_radius) : + increased_to_model_radius; + + // Rather unioning with "intersect" due to some rounding errors. + Polygons influence_areas = safe_union( + intersect_small_with_bigger(smaller_rad.areas.influence_areas, bigger_rad.areas.influence_areas), + intersect); + + Polygons to_model_areas; + if (merging_to_bp && config.support_rests_on_model) + to_model_areas = new_state.to_model_gracious ? + // Rather unioning with "intersect" due to some rounding errors. + safe_union( + intersect_small_with_bigger(smaller_rad.areas.to_model_areas, bigger_rad.areas.to_model_areas), + intersect) : + influence_areas; + + dst.parents.insert(dst.parents.end(), src.parents.begin(), src.parents.end()); + dst.state = new_state; + dst.areas.influence_areas = std::move(influence_areas); + dst.areas.to_bp_areas.clear(); + dst.areas.to_model_areas.clear(); + if (merging_to_bp) { + dst.areas.to_bp_areas = std::move(intersect); + if (config.support_rests_on_model) + dst.areas.to_model_areas = std::move(to_model_areas); + } else + dst.areas.to_model_areas = std::move(intersect); + // Update the bounding box. + BoundingBox bbox(get_extents(dst.areas.influence_areas)); + bbox.merge(get_extents(dst.areas.to_bp_areas)); + bbox.merge(get_extents(dst.areas.to_model_areas)); + dst.set_bbox(bbox); + // Clear the source data. + src.areas.clear(); + src.parents.clear(); + return true; +} + +/*! + * \brief Merges Influence Areas if possible. + * + * Branches which do overlap have to be merged. This helper merges all elements in input with the elements into reduced_new_layer. + * Elements in input_aabb are merged together if possible, while elements reduced_new_layer_aabb are not checked against each other. + * + * \param reduced_aabb[in,out] The already processed elements. + * \param input_aabb[in] Not yet processed elements + * \param to_bp_areas[in] The Elements of the current Layer that will reach the buildplate. Value is the influence area where the center of a circle of support may be placed. + * \param to_model_areas[in] The Elements of the current Layer that do not have to reach the buildplate. Also contains main as every element that can reach the buildplate is not forced to. + * Value is the influence area where the center of a circle of support may be placed. + * \param influence_areas[in] The influence areas without avoidance removed. + * \param insert_bp_areas[out] Elements to be inserted into the main dictionary after the Helper terminates. + * \param insert_model_areas[out] Elements to be inserted into the secondary dictionary after the Helper terminates. + * \param insert_influence[out] Elements to be inserted into the dictionary containing the largest possibly valid influence area (ignoring if the area may not be there because of avoidance) + * \param erase[out] Elements that should be deleted from the above dictionaries. + * \param layer_idx[in] The Index of the current Layer. + */ + +static SupportElementMerging* merge_influence_areas_leaves( + const TreeModelVolumes &volumes, const TreeSupportSettings &config, const LayerIndex layer_idx, + SupportElementMerging * const dst_begin, SupportElementMerging *dst_end) +{ + // Merging at the lowest level of the AABB tree. Checking one against each other, O(n^2). + assert(dst_begin < dst_end); + for (SupportElementMerging *i = dst_begin; i + 1 < dst_end;) { + for (SupportElementMerging *j = i + 1; j != dst_end;) + if (merge_influence_areas_two_elements(volumes, config, layer_idx, *i, *j)) { + // i was merged with j, j is empty. + if (j != -- dst_end) + *j = std::move(*dst_end); + goto merged; + } else + ++ j; + // not merged + ++ i; + merged: + ; + } + return dst_end; +} + +static SupportElementMerging* merge_influence_areas_two_sets( + const TreeModelVolumes &volumes, const TreeSupportSettings &config, const LayerIndex layer_idx, + SupportElementMerging * const dst_begin, SupportElementMerging * dst_end, + SupportElementMerging * src_begin, SupportElementMerging * const src_end) +{ + // Merging src into dst. + // Areas of src should not overlap with areas of another elements of src. + // Areas of dst should not overlap with areas of another elements of dst. + // The memory from dst_begin to src_end is reserved for the merging operation, + // src follows dst. + assert(src_begin < src_end); + assert(dst_begin < dst_end); + assert(dst_end <= src_begin); + for (SupportElementMerging *src = src_begin; src != src_end; ++ src) { + SupportElementMerging *dst = dst_begin; + SupportElementMerging *merged = nullptr; + for (; dst != dst_end; ++ dst) + if (merge_influence_areas_two_elements(volumes, config, layer_idx, *dst, *src)) { + merged = dst ++; + if (src != src_begin) + // Compactify src. + *src = std::move(*src_begin); + ++ src_begin; + break; + } + for (; dst != dst_end;) + if (merge_influence_areas_two_elements(volumes, config, layer_idx, *merged, *dst)) { + // Compactify dst. + if (dst != -- dst_end) + *dst = std::move(*dst_end); + } else + ++ dst; + } + // Compactify src elements that were not merged with dst to the end of dst. + assert(dst_end <= src_begin); + if (dst_end == src_begin) + dst_end = src_end; + else + while (src_begin != src_end) + *dst_end ++ = std::move(*src_begin ++); + + return dst_end; +} + +/*! + * \brief Merges Influence Areas at one layer if possible. + * + * Branches which do overlap have to be merged. This manages the helper and uses a divide and conquer approach to parallelize this problem. This parallelization can at most accelerate the merging by a factor of 2. + * + * \param to_bp_areas[in] The Elements of the current Layer that will reach the buildplate. + * Value is the influence area where the center of a circle of support may be placed. + * \param to_model_areas[in] The Elements of the current Layer that do not have to reach the buildplate. Also contains main as every element that can reach the buildplate is not forced to. + * Value is the influence area where the center of a circle of support may be placed. + * \param influence_areas[in] The Elements of the current Layer without avoidances removed. This is the largest possible influence area for this layer. + * Value is the influence area where the center of a circle of support may be placed. + * \param layer_idx[in] The current layer. + */ +static void merge_influence_areas( + const TreeModelVolumes &volumes, + const TreeSupportSettings &config, + const LayerIndex layer_idx, + std::vector &influence_areas, + std::function throw_on_cancel) +{ + const size_t input_size = influence_areas.size(); + if (input_size == 0) + return; + + // Merging by divide & conquer. + // The majority of time is consumed by Clipper polygon operations, intersection is accelerated by bounding boxes. + // Sorting input into an AABB tree helps to perform most of the intersections at first iterations, + // thus reducing computation when merging larger subtrees. + // The actual merge logic is found in merge_influence_areas_two_sets. + + // Build an AABB tree over the influence areas. + //FIXME A full tree does not need to be built, the lowest level branches will be always bucketed. + // However the additional time consumed is negligible. + AABBTreeIndirect::Tree<2, coord_t> tree; + // Sort influence_areas in place. + tree.build_modify_input(influence_areas); + + throw_on_cancel(); + + // Prepare the initial buckets as ranges of influence areas. The initial buckets contain power of 2 influence areas to follow + // the branching of the AABB tree. + // Vectors of ranges of influence areas, following the branching of the AABB tree: + std::vector> buckets; + // Initial number of buckets for 1st round of merging. + size_t num_buckets_initial; + { + // How many buckets per first merge iteration? + const size_t num_threads = tbb::this_task_arena::max_concurrency(); + // 4 buckets per thread if possible, + const size_t num_buckets_min = (input_size + 2) / 4; + // 2 buckets per thread otherwise. + const size_t num_buckets_max = input_size / 2; + num_buckets_initial = num_buckets_min >= num_threads ? num_buckets_min : num_buckets_max; + const size_t bucket_size = num_buckets_min >= num_threads ? 4 : 2; + // Fill in the buckets. + SupportElementMerging *it = influence_areas.data(); + // Reserve one more bucket to keep a single influence area which will not be merged in the first iteration. + buckets.reserve(num_buckets_initial + 1); + for (size_t i = 0; i < num_buckets_initial; ++ i, it += bucket_size) + buckets.emplace_back(std::make_pair(it, it + bucket_size)); + SupportElementMerging *it_end = influence_areas.data() + influence_areas.size(); + if (buckets.back().second >= it_end) { + // Last bucket is less than size 4, but bigger than size 1. + buckets.back().second = std::min(buckets.back().second, it_end); + } else { + // Last bucket is size 1, it will not be merged in the first iteration. + assert(it + 1 == it_end); + buckets.emplace_back(std::make_pair(it, it_end)); + } + } + + // 1st merge iteration, merge one with each other. + tbb::parallel_for(tbb::blocked_range(0, num_buckets_initial), + [&](const tbb::blocked_range &range) { + for (size_t idx = range.begin(); idx < range.end(); ++ idx) { + // Merge bucket_count adjacent to each other, merging uneven bucket numbers into even buckets + buckets[idx].second = merge_influence_areas_leaves(volumes, config, layer_idx, buckets[idx].first, buckets[idx].second); + throw_on_cancel(); + } + }); + + // Further merge iterations, merging one AABB subtree with another one, hopefully minimizing intersections between the elements + // of each of the subtree. + while (buckets.size() > 1) { + tbb::parallel_for(tbb::blocked_range(0, buckets.size() / 2), + [&](const tbb::blocked_range &range) { + for (size_t idx = range.begin(); idx < range.end(); ++ idx) { + const size_t bucket_pair_idx = idx * 2; + // Merge bucket_count adjacent to each other, merging uneven bucket numbers into even buckets + buckets[bucket_pair_idx].second = merge_influence_areas_two_sets(volumes, config, layer_idx, + buckets[bucket_pair_idx].first, buckets[bucket_pair_idx].second, + buckets[bucket_pair_idx + 1].first, buckets[bucket_pair_idx + 1].second); + throw_on_cancel(); + } + }); + // Remove odd buckets, which were merged into even buckets. + size_t new_size = (buckets.size() + 1) / 2; + for (size_t i = 1; i < new_size; ++ i) + buckets[i] = std::move(buckets[i * 2]); + buckets.erase(buckets.begin() + new_size, buckets.end()); + } +} + +/*! + * \brief Propagates influence downwards, and merges overlapping ones. + * + * \param move_bounds[in,out] All currently existing influence areas + */ +static void create_layer_pathing(const TreeModelVolumes &volumes, const TreeSupportSettings &config, std::vector &move_bounds, std::function throw_on_cancel) +{ +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + const double data_size_inverse = 1 / double(move_bounds.size()); + double progress_total = TREE_PROGRESS_PRECALC_AVO + TREE_PROGRESS_PRECALC_COLL + TREE_PROGRESS_GENERATE_NODES; +#endif // SLIC3R_TREESUPPORTS_PROGRESS + + auto dur_inc = std::chrono::duration_values::zero(); + auto dur_total = std::chrono::duration_values::zero(); + + LayerIndex last_merge_layer_idx = move_bounds.size(); + bool new_element = false; + + // Ensures at least one merge operation per 3mm height, 50 layers, 1 mm movement of slow speed or 5mm movement of fast speed (whatever is lowest). Values were guessed. + size_t max_merge_every_x_layers = std::min(std::min(5000 / (std::max(config.maximum_move_distance, coord_t(100))), 1000 / std::max(config.maximum_move_distance_slow, coord_t(20))), 3000 / config.layer_height); + size_t merge_every_x_layers = 1; + // Calculate the influence areas for each layer below (Top down) + // This is done by first increasing the influence area by the allowed movement distance, and merging them with other influence areas if possible + for (int layer_idx = int(move_bounds.size()) - 1; layer_idx > 0; -- layer_idx) + if (SupportElements &prev_layer = move_bounds[layer_idx]; ! prev_layer.empty()) { + // merging is expensive and only parallelized to a max speedup of 2. As such it may be useful in some cases to only merge every few layers to improve performance. + bool had_new_element = new_element; + const bool merge_this_layer = had_new_element || size_t(last_merge_layer_idx - layer_idx) >= merge_every_x_layers; + if (had_new_element) + merge_every_x_layers = 1; + const auto ta = std::chrono::high_resolution_clock::now(); + + // ### Increase the influence areas by the allowed movement distance + std::vector influence_areas; + influence_areas.reserve(prev_layer.size()); + for (int32_t element_idx = 0; element_idx < int32_t(prev_layer.size()); ++ element_idx) { + SupportElement &el = prev_layer[element_idx]; + assert(!el.influence_area.empty()); + SupportElement::ParentIndices parents; + parents.emplace_back(element_idx); + influence_areas.push_back({ el.state, parents }); + } + increase_areas_one_layer(volumes, config, influence_areas, layer_idx, prev_layer, merge_this_layer, throw_on_cancel); + + // Place already fully constructed elements to the output, remove them from influence_areas. + SupportElements &this_layer = move_bounds[layer_idx - 1]; + influence_areas.erase(std::remove_if(influence_areas.begin(), influence_areas.end(), + [&this_layer, layer_idx](SupportElementMerging &elem) { + if (elem.areas.influence_areas.empty()) + // This area was removed completely due to collisions. + return true; + if (elem.areas.to_bp_areas.empty() && elem.areas.to_model_areas.empty()) { + if (area(elem.areas.influence_areas) < tiny_area_threshold) { + BOOST_LOG_TRIVIAL(error) << "Insert Error of Influence area bypass on layer " << layer_idx - 1; + tree_supports_show_error("Insert error of area after bypassing merge.\n"sv, true); + } + // Move the area to output. + this_layer.emplace_back(elem.state, std::move(elem.parents), std::move(elem.areas.influence_areas)); + return true; + } + // Keep the area. + return false; + }), + influence_areas.end()); + + dur_inc += std::chrono::high_resolution_clock::now() - ta; + new_element = ! move_bounds[layer_idx - 1].empty(); + if (merge_this_layer) { + bool reduced_by_merging = false; + if (size_t count_before_merge = influence_areas.size(); count_before_merge > 1) { + // ### Calculate which influence areas overlap, and merge them into a new influence area (simplified: an intersection of influence areas that have such an intersection) + merge_influence_areas(volumes, config, layer_idx, influence_areas, throw_on_cancel); + reduced_by_merging = count_before_merge > influence_areas.size(); + } + last_merge_layer_idx = layer_idx; + if (! reduced_by_merging && ! had_new_element) + merge_every_x_layers = std::min(max_merge_every_x_layers, merge_every_x_layers + 1); + } + + dur_total += std::chrono::high_resolution_clock::now() - ta; + + // Save calculated elements to output, and allocate Polygons on heap, as they will not be changed again. + for (SupportElementMerging &elem : influence_areas) + if (! elem.areas.influence_areas.empty()) { + Polygons new_area = safe_union(elem.areas.influence_areas); + if (area(new_area) < tiny_area_threshold) { + BOOST_LOG_TRIVIAL(error) << "Insert Error of Influence area on layer " << layer_idx - 1 << ". Origin of " << elem.parents.size() << " areas. Was to bp " << elem.state.to_buildplate; + tree_supports_show_error("Insert error of area after merge.\n"sv, true); + } + this_layer.emplace_back(elem.state, std::move(elem.parents), std::move(new_area)); + } + + #ifdef SLIC3R_TREESUPPORTS_PROGRESS + progress_total += data_size_inverse * TREE_PROGRESS_AREA_CALC; + Progress::messageProgress(Progress::Stage::SUPPORT, progress_total * m_progress_multiplier + m_progress_offset, TREE_PROGRESS_TOTAL); + #endif + throw_on_cancel(); + } + + BOOST_LOG_TRIVIAL(info) << "Time spent with creating influence areas' subtasks: Increasing areas " << dur_inc.count() / 1000000 << + " ms merging areas: " << (dur_total - dur_inc).count() / 1000000 << " ms"; +} + +/*! + * \brief Sets the result_on_layer for all parents based on the SupportElement supplied. + * + * \param elem[in] The SupportElements, which parent's position should be determined. + */ +static void set_points_on_areas(const SupportElement &elem, SupportElements *layer_above) +{ + assert(!elem.state.deleted); + assert(layer_above != nullptr || elem.parents.empty()); + + // Based on the branch center point of the current layer, the point on the next (further up) layer is calculated. + if (! elem.state.result_on_layer_is_set()) { + BOOST_LOG_TRIVIAL(error) << "Uninitialized support element"; + tree_supports_show_error("Uninitialized support element. A branch may be missing.\n"sv, true); + return; + } + + if (layer_above) + for (int32_t next_elem_idx : elem.parents) { + assert(next_elem_idx >= 0); + SupportElement &next_elem = (*layer_above)[next_elem_idx]; + assert(! next_elem.state.deleted); + // if the value was set somewhere else it it kept. This happens when a branch tries not to move after being unable to create a roof. + if (! next_elem.state.result_on_layer_is_set()) { + // Move inside has edgecases (see tests) so DONT use Polygons.inside to confirm correct move, Error with distance 0 is <= 1 + // it is not required to check if how far this move moved a point as is can be larger than maximum_movement_distance. + // While this seems like a problem it may for example occur after merges. + next_elem.state.result_on_layer = move_inside_if_outside(next_elem.influence_area, elem.state.result_on_layer); + // do not call recursive because then amount of layers would be restricted by the stack size + } + // Mark the parent element as accessed from a valid child element. + next_elem.state.marked = true; + } +} + +static void set_to_model_contact_simple(SupportElement &elem) +{ + const Point best = move_inside_if_outside(elem.influence_area, elem.state.next_position); + elem.state.result_on_layer = best; + BOOST_LOG_TRIVIAL(debug) << "Added NON gracious Support On Model Point (" << best.x() << "," << best.y() << "). The current layer is " << elem.state.layer_idx; +} + +/*! + * \brief Get the best point to connect to the model and set the result_on_layer of the relevant SupportElement accordingly. + * + * \param move_bounds[in,out] All currently existing influence areas + * \param first_elem[in,out] SupportElement that did not have its result_on_layer set meaning that it does not have a child element. + * \param layer_idx[in] The current layer. + */ +static void set_to_model_contact_to_model_gracious( + const TreeModelVolumes &volumes, + const TreeSupportSettings &config, + std::vector &move_bounds, + SupportElement &first_elem, + std::function throw_on_cancel) +{ + SupportElement *last_successfull_layer = nullptr; + + // check for every layer upwards, up to the point where this influence area was created (either by initial insert or merge) if the branch could be placed on it, and highest up layer index. + { + SupportElement *elem = &first_elem; + for (LayerIndex layer_check = elem->state.layer_idx; + ! intersection(elem->influence_area, volumes.getPlaceableAreas(support_element_collision_radius(config, elem->state), layer_check, throw_on_cancel)).empty(); + elem = &move_bounds[++ layer_check][elem->parents.front()]) { + assert(elem->state.layer_idx == layer_check); + assert(! elem->state.deleted); + assert(elem->state.to_model_gracious); + last_successfull_layer = elem; + if (elem->parents.size() != 1) + // Reached merge point. + break; + } + } + + // Could not find valid placement, even though it should exist => error handling + if (last_successfull_layer == nullptr) { + BOOST_LOG_TRIVIAL(warning) << "No valid placement found for to model gracious element on layer " << first_elem.state.layer_idx; + tree_supports_show_error("Could not fine valid placement on model! Just placing it down anyway. Could cause floating branches."sv, true); + first_elem.state.to_model_gracious = false; + set_to_model_contact_simple(first_elem); + } else { + // Found a gracious area above first_elem. Remove all below last_successfull_layer. + { + LayerIndex parent_layer_idx = first_elem.state.layer_idx; + for (SupportElement *elem = &first_elem; elem != last_successfull_layer; elem = &move_bounds[++ parent_layer_idx][elem->parents.front()]) { + assert(! elem->state.deleted); + elem->state.deleted = true; + } + } + // Guess a point inside the influence area, in which the branch will be placed in. + const Point best = move_inside_if_outside(last_successfull_layer->influence_area, last_successfull_layer->state.next_position); + last_successfull_layer->state.result_on_layer = best; + BOOST_LOG_TRIVIAL(debug) << "Added gracious Support On Model Point (" << best.x() << "," << best.y() << "). The current layer is " << last_successfull_layer; + } +} + +// Remove elements marked as "deleted", update indices to parents. +static void remove_deleted_elements(std::vector &move_bounds) +{ + std::vector map_parents; + std::vector map_current; + for (LayerIndex layer_idx = LayerIndex(move_bounds.size()) - 1; layer_idx >= 0; -- layer_idx) { + SupportElements &layer = move_bounds[layer_idx]; + map_current.clear(); + for (int32_t i = 0; i < int32_t(layer.size());) { + SupportElement &element = layer[i]; + if (element.state.deleted) { + if (map_current.empty()) { + // Initialize with identity map. + map_current.assign(layer.size(), 0); + std::iota(map_current.begin(), map_current.end(), 0); + } + // Delete all "deleted" elements from the end of the layer vector. + while (i < int32_t(layer.size()) && layer.back().state.deleted) { + layer.pop_back(); + // Mark as deleted in the map. + map_current[layer.size()] = -1; + } + assert(i == layer.size() || i + 1 < layer.size()); + if (i + 1 < int32_t(layer.size())) { + element = std::move(layer.back()); + layer.pop_back(); + // Mark the current element as deleted. + map_current[i] = -1; + // Mark the moved element as moved to index i. + map_current[layer.size()] = i; + } + } else { + // Current element is not deleted. Update its parent indices. + if (! map_parents.empty()) + for (int32_t &parent_idx : element.parents) + parent_idx = map_parents[parent_idx]; + ++ i; + } + } + std::swap(map_current, map_parents); + } +} + +/*! + * \brief Set the result_on_layer point for all influence areas + * + * \param move_bounds[in,out] All currently existing influence areas + */ +static void create_nodes_from_area( + const TreeModelVolumes &volumes, + const TreeSupportSettings &config, + std::vector &move_bounds, + std::function throw_on_cancel) +{ + // Initialize points on layer 0, with a "random" point in the influence area. + // Point is chosen based on an inaccurate estimate where the branches will split into two, but every point inside the influence area would produce a valid result. + { + SupportElements *layer_above = move_bounds.size() > 1 ? &move_bounds[1] : nullptr; + if (layer_above) { + for (SupportElement &elem : *layer_above) + elem.state.marked = false; + } + for (SupportElement &init : move_bounds.front()) { + init.state.result_on_layer = move_inside_if_outside(init.influence_area, init.state.next_position); + // Also set the parent nodes, as these will be required for the first iteration of the loop below and mark the parent nodes. + set_points_on_areas(init, layer_above); + } + } + + throw_on_cancel(); + + for (LayerIndex layer_idx = 1; layer_idx < LayerIndex(move_bounds.size()); ++ layer_idx) { + auto &layer = move_bounds[layer_idx]; + auto *layer_above = layer_idx + 1 < LayerIndex(move_bounds.size()) ? &move_bounds[layer_idx + 1] : nullptr; + if (layer_above) + for (SupportElement &elem : *layer_above) + elem.state.marked = false; + for (SupportElement &elem : layer) { + assert(! elem.state.deleted); + assert(elem.state.layer_idx == layer_idx); + // check if the resulting center point is not yet set + if (! elem.state.result_on_layer_is_set()) { + if (elem.state.to_buildplate || (elem.state.distance_to_top < config.min_dtt_to_model && ! elem.state.supports_roof)) { + if (elem.state.to_buildplate) { + BOOST_LOG_TRIVIAL(error) << "Uninitialized Influence area targeting " << elem.state.target_position.x() << "," << elem.state.target_position.y() << ") " + "at target_height: " << elem.state.target_height << " layer: " << layer_idx; + tree_supports_show_error("Uninitialized support element! A branch could be missing or exist partially."sv, true); + } + // we dont need to remove yet the parents as they will have a lower dtt and also no result_on_layer set + elem.state.deleted = true; + } else { + // set the point where the branch will be placed on the model + if (elem.state.to_model_gracious) + set_to_model_contact_to_model_gracious(volumes, config, move_bounds, elem, throw_on_cancel); + else + set_to_model_contact_simple(elem); + } + } + if (! elem.state.deleted && ! elem.state.marked && elem.state.target_height == layer_idx) + // Just a tip surface with no supporting element. + elem.state.deleted = true; + if (elem.state.deleted) { + for (int32_t parent_idx : elem.parents) + // When the roof was not able to generate downwards enough, the top elements may have not moved, and have result_on_layer already set. + // As this branch needs to be removed => all parents result_on_layer have to be invalidated. + (*layer_above)[parent_idx].state.result_on_layer_reset(); + } + if (! elem.state.deleted) { + // Element is valid now setting points in the layer above and mark the parent nodes. + set_points_on_areas(elem, layer_above); + } + } + throw_on_cancel(); + } + +#ifndef NDEBUG + // Verify the tree connectivity including the branch slopes. + for (LayerIndex layer_idx = 0; layer_idx + 1 < LayerIndex(move_bounds.size()); ++ layer_idx) { + auto &layer = move_bounds[layer_idx]; + auto &above = move_bounds[layer_idx + 1]; + for (SupportElement &elem : layer) + if (! elem.state.deleted) { + for (int32_t iparent : elem.parents) { + SupportElement &parent = above[iparent]; + assert(! parent.state.deleted); + assert(elem.state.result_on_layer_is_set() == parent.state.result_on_layer_is_set()); + if (elem.state.result_on_layer_is_set()) { + double radius_increase = support_element_radius(config, elem) - support_element_radius(config, parent); + assert(radius_increase >= 0); + double shift = (elem.state.result_on_layer - parent.state.result_on_layer).cast().norm(); + //FIXME this assert fails a lot. Is it correct? +// assert(shift < radius_increase + 2. * config.maximum_move_distance_slow); + } + } + } + } +#endif // NDEBUG + + remove_deleted_elements(move_bounds); + +#ifndef NDEBUG + // Verify the tree connectivity including the branch slopes. + for (LayerIndex layer_idx = 0; layer_idx + 1 < LayerIndex(move_bounds.size()); ++ layer_idx) { + auto &layer = move_bounds[layer_idx]; + auto &above = move_bounds[layer_idx + 1]; + for (SupportElement &elem : layer) { + assert(! elem.state.deleted); + for (int32_t iparent : elem.parents) { + SupportElement &parent = above[iparent]; + assert(! parent.state.deleted); + assert(elem.state.result_on_layer_is_set() == parent.state.result_on_layer_is_set()); + if (elem.state.result_on_layer_is_set()) { + double radius_increase = support_element_radius(config, elem) - support_element_radius(config, parent); + assert(radius_increase >= 0); + double shift = (elem.state.result_on_layer - parent.state.result_on_layer).cast().norm(); + //FIXME this assert fails a lot. Is it correct? +// assert(shift < radius_increase + 2. * config.maximum_move_distance_slow); + } + } + } + } +#endif // NDEBUG +} + +// For producing circular / elliptical areas from SupportElements (one DrawArea per one SupportElement) +// and for smoothing those areas along the tree branches. +struct DrawArea +{ + // Element to be processed. + SupportElement *element; + // Element below, if there is such an element. nullptr if element is a root of a tree. + SupportElement *child_element; + // Polygons to be extruded for this element. + Polygons polygons; +}; + +/*! + * \brief Draws circles around result_on_layer points of the influence areas + * + * \param linear_data[in] All currently existing influence areas with the layer they are on + * \param layer_tree_polygons[out] Resulting branch areas with the layerindex they appear on. layer_tree_polygons.size() has to be at least linear_data.size() as each Influence area in linear_data will save have at least one (that's why it's a vector) corresponding branch area in layer_tree_polygons. + * \param inverse_tree_order[in] A mapping that returns the child of every influence area. + */ +static void generate_branch_areas( + const TreeModelVolumes &volumes, + const TreeSupportSettings &config, + const std::vector &move_bounds, + std::vector &linear_data, + std::function throw_on_cancel) +{ +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + double progress_total = TREE_PROGRESS_PRECALC_AVO + TREE_PROGRESS_PRECALC_COLL + TREE_PROGRESS_GENERATE_NODES + TREE_PROGRESS_AREA_CALC; + constexpr int progress_report_steps = 10; + const size_t progress_inserts_check_interval = linear_data.size() / progress_report_steps; + std::mutex critical_sections; +#endif // SLIC3R_TREESUPPORTS_PROGRESS + + // Pre-generate a circle with correct diameter so that we don't have to recompute those (co)sines every time. + const Polygon branch_circle = make_circle(config.branch_radius, SUPPORT_TREE_CIRCLE_RESOLUTION); + + tbb::parallel_for(tbb::blocked_range(0, linear_data.size()), + [&volumes, &config, &move_bounds, &linear_data, &branch_circle, &throw_on_cancel](const tbb::blocked_range &range) { + for (size_t idx = range.begin(); idx < range.end(); ++ idx) { + DrawArea &draw_area = linear_data[idx]; + const LayerIndex layer_idx = draw_area.element->state.layer_idx; + const coord_t radius = support_element_radius(config, *draw_area.element); + bool parent_uses_min = false; + + // Calculate multiple ovalized circles, to connect with every parent and child. Also generate regular circle for the current layer. Merge all these into one area. + std::vector> movement_directions{ std::pair(Point(0, 0), radius) }; + if (! draw_area.element->state.skip_ovalisation) { + if (draw_area.child_element != nullptr) { + const Point movement = draw_area.child_element->state.result_on_layer - draw_area.element->state.result_on_layer; + movement_directions.emplace_back(movement, radius); + } + const SupportElements *layer_above = layer_idx + 1 < LayerIndex(move_bounds.size()) ? &move_bounds[layer_idx + 1] : nullptr; + for (int32_t parent_idx : draw_area.element->parents) { + const SupportElement &parent = (*layer_above)[parent_idx]; + const Point movement = parent.state.result_on_layer - draw_area.element->state.result_on_layer; + //FIXME why max(..., config.support_line_width)? + movement_directions.emplace_back(movement, std::max(support_element_radius(config, parent), config.support_line_width)); + parent_uses_min |= parent.state.use_min_xy_dist; + } + } + + const Polygons &collision = volumes.getCollision(0, layer_idx, parent_uses_min || draw_area.element->state.use_min_xy_dist); + auto generateArea = [&collision, &draw_area, &branch_circle, branch_radius = config.branch_radius, support_line_width = config.support_line_width, &movement_directions] + (coord_t aoffset, double &max_speed) { + Polygons poly; + max_speed = 0; + for (std::pair movement : movement_directions) { + max_speed = std::max(max_speed, movement.first.cast().norm()); + + // Visualization: https://jsfiddle.net/0zvcq39L/2/ + // Ovalizes the circle to an ellipse, that contains both old center and new target position. + double used_scale = (movement.second + aoffset) / (1.0 * branch_radius); + Point center_position = draw_area.element->state.result_on_layer + movement.first / 2; + const double moveX = movement.first.x() / (used_scale * branch_radius); + const double moveY = movement.first.y() / (used_scale * branch_radius); + const double vsize_inv = 0.5 / (0.01 + std::sqrt(moveX * moveX + moveY * moveY)); + + double matrix[] = { + used_scale * (1 + moveX * moveX * vsize_inv), + used_scale * (0 + moveX * moveY * vsize_inv), + used_scale * (0 + moveX * moveY * vsize_inv), + used_scale * (1 + moveY * moveY * vsize_inv), + }; + Polygon circle; + for (Point vertex : branch_circle) + circle.points.emplace_back(center_position + Point(matrix[0] * vertex.x() + matrix[1] * vertex.y(), matrix[2] * vertex.x() + matrix[3] * vertex.y())); + poly.emplace_back(std::move(circle)); + } + + // There seem to be some rounding errors, causing a branch to be a tiny bit further away from the model that it has to be. + // This can cause the tip to be slightly further away front the overhang (x/y wise) than optimal. This fixes it, and for every other part, 0.05mm will not be noticed. + poly = diff_clipped(offset(union_(poly), std::min(coord_t(50), support_line_width / 4), jtMiter, 1.2), collision); + return poly; + }; + + // Ensure branch area will not overlap with model/collision. This can happen because of e.g. ovalization or increase_until_radius. + double max_speed; + Polygons polygons = generateArea(0, max_speed); + const bool fast_relative_movement = max_speed > radius * 0.75; + + if (fast_relative_movement || support_element_radius(config, *draw_area.element) - support_element_collision_radius(config, draw_area.element->state) > config.support_line_width) { + // Simulate the path the nozzle will take on the outermost wall. + // If multiple parts exist, the outer line will not go all around the support part potentially causing support material to be printed mid air. + ExPolygons nozzle_path = offset_ex(polygons, - config.support_line_width / 2); + if (nozzle_path.size() > 1) { + // Just try to make the area a tiny bit larger. + polygons = generateArea(config.support_line_width / 2, max_speed); + nozzle_path = offset_ex(polygons, -config.support_line_width / 2); + // If larger area did not fix the problem, all parts off the nozzle path that do not contain the center point are removed, hoping for the best. + if (nozzle_path.size() > 1) { + ExPolygons polygons_with_correct_center; + for (ExPolygon &part : nozzle_path) { + bool drop = false; + if (! part.contains(draw_area.element->state.result_on_layer)) { + // try a fuzzy inside as sometimes the point should be on the border, but is not because of rounding errors... + Point pt = draw_area.element->state.result_on_layer; + move_inside(to_polygons(part), pt, 0); + drop = (draw_area.element->state.result_on_layer - pt).cast().norm() >= scaled(0.025); + } + if (! drop) + polygons_with_correct_center.emplace_back(std::move(part)); + } + // Increase the area again, to ensure the nozzle path when calculated later is very similar to the one assumed above. + assert(contains(polygons, draw_area.element->state.result_on_layer)); + polygons = diff_clipped(offset(polygons_with_correct_center, config.support_line_width / 2, jtMiter, 1.2), + //FIXME Vojtech: Clipping may split the region into multiple pieces again, reversing the fixing effort. + collision); + } + } + } + + draw_area.polygons = std::move(polygons); + +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + if (idx % progress_inserts_check_interval == 0) { + std::lock_guard critical_section_progress(critical_sections); + progress_total += TREE_PROGRESS_GENERATE_BRANCH_AREAS / progress_report_steps; + Progress::messageProgress(Progress::Stage::SUPPORT, progress_total * m_progress_multiplier + m_progress_offset, TREE_PROGRESS_TOTAL); + } +#endif + throw_on_cancel(); + } + }); +} + +/*! + * \brief Applies some smoothing to the outer wall, intended to smooth out sudden jumps as they can happen when a branch moves though a hole. + * + * \param layer_tree_polygons[in,out] Resulting branch areas with the layerindex they appear on. + */ +static void smooth_branch_areas( + const TreeSupportSettings &config, + std::vector &move_bounds, + std::vector &linear_data, + const std::vector &linear_data_layers, + std::function throw_on_cancel) +{ +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + double progress_total = TREE_PROGRESS_PRECALC_AVO + TREE_PROGRESS_PRECALC_COLL + TREE_PROGRESS_GENERATE_NODES + TREE_PROGRESS_AREA_CALC + TREE_PROGRESS_GENERATE_BRANCH_AREAS; +#endif // SLIC3R_TREESUPPORTS_PROGRESS + + const coord_t max_radius_change_per_layer = 1 + config.support_line_width / 2; // this is the upper limit a radius may change per layer. +1 to avoid rounding errors + + // smooth upwards + for (LayerIndex layer_idx = 0; layer_idx < LayerIndex(move_bounds.size()) - 1; ++ layer_idx) { + const size_t processing_base = linear_data_layers[layer_idx]; + const size_t processing_base_above = linear_data_layers[layer_idx + 1]; + const SupportElements &layer_above = move_bounds[layer_idx + 1]; + tbb::parallel_for(tbb::blocked_range(0, processing_base_above - processing_base), + [&](const tbb::blocked_range &range) { + for (size_t processing_idx = range.begin(); processing_idx < range.end(); ++ processing_idx) { + DrawArea &draw_area = linear_data[processing_base + processing_idx]; + assert(draw_area.element->state.layer_idx == layer_idx); + double max_outer_wall_distance = 0; + bool do_something = false; + for (int32_t parent_idx : draw_area.element->parents) { + const SupportElement &parent = layer_above[parent_idx]; + assert(parent.state.layer_idx == layer_idx + 1); + if (support_element_radius(config, parent) != support_element_collision_radius(config, parent)) { + do_something = true; + max_outer_wall_distance = std::max(max_outer_wall_distance, + (draw_area.element->state.result_on_layer - parent.state.result_on_layer).cast().norm() - (support_element_radius(config, *draw_area.element) - support_element_radius(config, parent))); + } + } + max_outer_wall_distance += max_radius_change_per_layer; // As this change is a bit larger than what usually appears, lost radius can be slowly reclaimed over the layers. + if (do_something) { + assert(contains(draw_area.polygons, draw_area.element->state.result_on_layer)); + Polygons max_allowed_area = offset(draw_area.polygons, float(max_outer_wall_distance), jtMiter, 1.2); + for (int32_t parent_idx : draw_area.element->parents) { + const SupportElement &parent = layer_above[parent_idx]; +#ifndef NDEBUG + assert(parent.state.layer_idx == layer_idx + 1); + assert(contains(linear_data[processing_base_above + parent_idx].polygons, parent.state.result_on_layer)); + double radius_increase = support_element_radius(config, *draw_area.element) - support_element_radius(config, parent); + assert(radius_increase >= 0); + double shift = (draw_area.element->state.result_on_layer - parent.state.result_on_layer).cast().norm(); + assert(shift < radius_increase + 2. * config.maximum_move_distance_slow); +#endif // NDEBUG + if (support_element_radius(config, parent) != support_element_collision_radius(config, parent)) { + // No other element on this layer than the current one may be connected to &parent, + // thus it is safe to update parent's DrawArea directly. + Polygons &dst = linear_data[processing_base_above + parent_idx].polygons; +// Polygons orig = dst; + if (! dst.empty()) { + dst = intersection(dst, max_allowed_area); +#if 0 + if (dst.empty()) { + static int irun = 0; + SVG::export_expolygons(debug_out_path("treesupport-extrude_areas-smooth-error-%d.svg", irun ++), + { { { union_ex(max_allowed_area) }, { "max_allowed_area", "yellow", 0.5f } }, + { { union_ex(orig) }, { "orig", "red", "black", "", scaled(0.1f), 0.5f } } }); + ::MessageBoxA(nullptr, "TreeSupport smoothing bug", "Bug detected!", MB_OK | MB_SYSTEMMODAL | MB_SETFOREGROUND | MB_ICONWARNING); + } +#endif + } + } + } + } + throw_on_cancel(); + } + }); + } + +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + progress_total += TREE_PROGRESS_SMOOTH_BRANCH_AREAS / 2; + Progress::messageProgress(Progress::Stage::SUPPORT, progress_total * m_progress_multiplier + m_progress_offset, TREE_PROGRESS_TOTAL); // It is just assumed that both smoothing loops together are one third of the time spent in this function. This was guessed. As the whole function is only 10%, and the smoothing is hard to predict a progress report in the loop may be not useful. +#endif + + // smooth downwards + for (auto& element : move_bounds.back()) + element.state.marked = false; + for (int layer_idx = int(move_bounds.size()) - 2; layer_idx >= 0; -- layer_idx) { + const size_t processing_base = linear_data_layers[layer_idx]; + const size_t processing_base_above = linear_data_layers[layer_idx + 1]; + const SupportElements &layer_above = move_bounds[layer_idx + 1]; + tbb::parallel_for(tbb::blocked_range(0, processing_base_above - processing_base), + [&](const tbb::blocked_range &range) { + for (size_t processing_idx = range.begin(); processing_idx < range.end(); ++ processing_idx) { + DrawArea &draw_area = linear_data[processing_base + processing_idx]; + bool do_something = false; + Polygons max_allowed_area; + for (int32_t parent_idx : draw_area.element->parents) { + const SupportElement &parent = layer_above[parent_idx]; + coord_t max_outer_line_increase = max_radius_change_per_layer; + Polygons result = offset(linear_data[processing_base_above + parent_idx].polygons, max_outer_line_increase, jtMiter, 1.2); + Point direction = draw_area.element->state.result_on_layer - parent.state.result_on_layer; + // move the polygons object + for (auto &outer : result) + for (Point& p : outer) + p += direction; + append(max_allowed_area, std::move(result)); + do_something = do_something || parent.state.marked || support_element_collision_radius(config, parent) != support_element_radius(config, parent); + } + if (do_something) { + // Trim the current drawing areas with max_allowed_area. + Polygons result = intersection(max_allowed_area, draw_area.polygons); + if (area(result) < area(draw_area.polygons)) { + // Mark parent as modified to propagate down. + draw_area.element->state.marked = true; + draw_area.polygons = std::move(result); + } + } + throw_on_cancel(); + } + }); + } + +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + progress_total += TREE_PROGRESS_SMOOTH_BRANCH_AREAS / 2; + Progress::messageProgress(Progress::Stage::SUPPORT, progress_total * m_progress_multiplier + m_progress_offset, TREE_PROGRESS_TOTAL); +#endif +} + +/*! + * \brief Drop down areas that do rest non-gracefully on the model to ensure the branch actually rests on something. + * + * \param layer_tree_polygons[in] Resulting branch areas with the layerindex they appear on. + * \param linear_data[in] All currently existing influence areas with the layer they are on + * \param dropped_down_areas[out] Areas that have to be added to support all non-graceful areas. + * \param inverse_tree_order[in] A mapping that returns the child of every influence area. + */ +static void drop_non_gracious_areas( + const TreeModelVolumes &volumes, + const std::vector &linear_data, + std::vector &support_layer_storage, + std::function throw_on_cancel) +{ + std::vector>> dropped_down_areas(linear_data.size()); + tbb::parallel_for(tbb::blocked_range(0, linear_data.size()), + [&](const tbb::blocked_range &range) { + for (size_t idx = range.begin(); idx < range.end(); ++ idx) { + // If a element has no child, it connects to whatever is below as no support further down for it will exist. + if (const DrawArea &draw_element = linear_data[idx]; ! draw_element.element->state.to_model_gracious && draw_element.child_element == nullptr) { + Polygons rest_support; + const LayerIndex layer_idx_first = draw_element.element->state.layer_idx - 1; + for (LayerIndex layer_idx = layer_idx_first; area(rest_support) > tiny_area_threshold && layer_idx >= 0; -- layer_idx) { + rest_support = diff_clipped(layer_idx == layer_idx_first ? draw_element.polygons : rest_support, volumes.getCollision(0, layer_idx, false)); + dropped_down_areas[idx].emplace_back(layer_idx, rest_support); + } + } + throw_on_cancel(); + } + }); + + for (coord_t i = 0; i < static_cast(dropped_down_areas.size()); i++) + for (std::pair &pair : dropped_down_areas[i]) + append(support_layer_storage[pair.first], std::move(pair.second)); +} + +/*! + * \brief Generates Support Floor, ensures Support Roof can not cut of branches, and saves the branches as support to storage + * + * \param support_layer_storage[in] Areas where support should be generated. + * \param support_roof_storage[in] Areas where support was replaced with roof. + * \param storage[in,out] The storage where the support should be stored. + */ +static void finalize_interface_and_support_areas( + const PrintObject &print_object, + const TreeModelVolumes &volumes, + const TreeSupportSettings &config, + const std::vector &overhangs, + std::vector &support_layer_storage, + std::vector &support_roof_storage, + + SupportGeneratorLayersPtr &bottom_contacts, + SupportGeneratorLayersPtr &top_contacts, + SupportGeneratorLayersPtr &intermediate_layers, + SupportGeneratorLayerStorage &layer_storage, + + std::function throw_on_cancel) +{ + assert(std::all_of(bottom_contacts.begin(), bottom_contacts.end(), [](auto *p) { return p == nullptr; })); +// assert(std::all_of(top_contacts.begin(), top_contacts.end(), [](auto* p) { return p == nullptr; })); + assert(std::all_of(intermediate_layers.begin(), intermediate_layers.end(), [](auto* p) { return p == nullptr; })); + + InterfacePreference interface_pref = config.interface_preference; // InterfacePreference::InterfaceAreaOverwritesSupport; + +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + double progress_total = TREE_PROGRESS_PRECALC_AVO + TREE_PROGRESS_PRECALC_COLL + TREE_PROGRESS_GENERATE_NODES + TREE_PROGRESS_AREA_CALC + TREE_PROGRESS_GENERATE_BRANCH_AREAS + TREE_PROGRESS_SMOOTH_BRANCH_AREAS; +#endif // SLIC3R_TREESUPPORTS_PROGRESS + + // Iterate over the generated circles in parallel and clean them up. Also add support floor. + tbb::parallel_for(tbb::blocked_range(0, support_layer_storage.size()), + [&](const tbb::blocked_range &range) { + for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++ layer_idx) { + // Subtract support lines of the branches from the roof + SupportGeneratorLayer *support_roof = top_contacts[layer_idx]; + Polygons support_roof_polygons; + + if (Polygons &src = support_roof_storage[layer_idx]; ! src.empty()) { + if (support_roof != nullptr && ! support_roof->polygons.empty()) { + support_roof_polygons = union_(src, support_roof->polygons); + support_roof->polygons.clear(); + } else + support_roof_polygons = std::move(src); + } else if (support_roof != nullptr) { + support_roof_polygons = std::move(support_roof->polygons); + support_roof->polygons.clear(); + } + + assert(intermediate_layers[layer_idx] == nullptr); + Polygons base_layer_polygons = std::move(support_layer_storage[layer_idx]); + + if (! base_layer_polygons.empty()) { + // Most of the time in this function is this union call. Can take 300+ ms when a lot of areas are to be unioned. + base_layer_polygons = smooth_outward(union_(base_layer_polygons), config.support_line_width); //FIXME was .smooth(50); + //smooth_outward(closing(std::move(bottom), closing_distance + minimum_island_radius, closing_distance, SUPPORT_SURFACES_OFFSET_PARAMETERS), smoothing_distance) : + // simplify a bit, to ensure the output does not contain outrageous amounts of vertices. Should not be necessary, just a precaution. + base_layer_polygons = polygons_simplify(base_layer_polygons, std::min(scaled(0.03), double(config.resolution)), polygons_strictly_simple); + } + + if (! support_roof_polygons.empty() && ! base_layer_polygons.empty()) { +// if (area(intersection(base_layer_polygons, support_roof_polygons)) > tiny_area_threshold) + { + switch (interface_pref) { + case InterfacePreference::InterfaceAreaOverwritesSupport: + base_layer_polygons = diff(base_layer_polygons, support_roof_polygons); + break; + case InterfacePreference::SupportAreaOverwritesInterface: + support_roof_polygons = diff(support_roof_polygons, base_layer_polygons); + break; + //FIXME + #if 1 + case InterfacePreference::InterfaceLinesOverwriteSupport: + case InterfacePreference::SupportLinesOverwriteInterface: + assert(false); + [[fallthrough]]; + #else + case InterfacePreference::InterfaceLinesOverwriteSupport: + { + // Hatch the support roof interfaces, offset them by their line width and subtract them from support base. + Polygons interface_lines = offset(to_polylines( + generate_support_infill_lines(support_roof->polygons, true, layer_idx, config.support_roof_line_distance)), + config.support_roof_line_width / 2); + base_layer_polygons = diff(base_layer_polygons, interface_lines); + break; + } + case InterfacePreference::SupportLinesOverwriteInterface: + { + // Hatch the support roof interfaces, offset them by their line width and subtract them from support base. + Polygons tree_lines = union_(offset(to_polylines( + generate_support_infill_lines(base_layer_polygons, false, layer_idx, config.support_line_distance, true)), + config.support_line_width / 2)); + // do not draw roof where the tree is. I prefer it this way as otherwise the roof may cut of a branch from its support below. + support_roof->polygons = diff(support_roof->polygons, tree_lines); + break; + } + #endif + case InterfacePreference::Nothing: + break; + } + } + } + + // Subtract support floors from the support area and add them to the support floor instead. + if (config.support_bottom_layers > 0 && ! base_layer_polygons.empty()) { + SupportGeneratorLayer*& support_bottom = bottom_contacts[layer_idx]; + Polygons layer_outset = diff_clipped( + config.support_bottom_offset > 0 ? offset(base_layer_polygons, config.support_bottom_offset, jtMiter, 1.2) : base_layer_polygons, + volumes.getCollision(0, layer_idx, false)); + Polygons floor_layer; + size_t layers_below = 0; + while (layers_below <= config.support_bottom_layers) { + // one sample at 0 layers below, another at config.support_bottom_layers. In-between samples at config.performance_interface_skip_layers distance from each other. + const size_t sample_layer = static_cast(std::max(0, (static_cast(layer_idx) - static_cast(layers_below)) - static_cast(config.z_distance_bottom_layers))); + //FIXME subtract the wipe tower + append(floor_layer, intersection(layer_outset, overhangs[sample_layer])); + if (layers_below < config.support_bottom_layers) + layers_below = std::min(layers_below + 1, config.support_bottom_layers); + else + break; + } + if (! floor_layer.empty()) { + if (support_bottom == nullptr) + support_bottom = &layer_allocate(layer_storage, SupporLayerType::BottomContact, print_object.slicing_parameters(), config, layer_idx); + support_bottom->polygons = union_(floor_layer, support_bottom->polygons); + base_layer_polygons = diff_clipped(base_layer_polygons, offset(support_bottom->polygons, scaled(0.01), jtMiter, 1.2)); // Subtract the support floor from the normal support. + } + } + + if (! support_roof_polygons.empty()) { + if (support_roof == nullptr) + support_roof = top_contacts[layer_idx] = &layer_allocate(layer_storage, SupporLayerType::TopContact, print_object.slicing_parameters(), config, layer_idx); + support_roof->polygons = union_(support_roof_polygons); + } + if (! base_layer_polygons.empty()) { + SupportGeneratorLayer *base_layer = intermediate_layers[layer_idx] = &layer_allocate(layer_storage, SupporLayerType::Base, print_object.slicing_parameters(), config, layer_idx); + base_layer->polygons = union_(base_layer_polygons); + } + +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + { + std::lock_guard critical_section_progress(critical_sections); + progress_total += TREE_PROGRESS_FINALIZE_BRANCH_AREAS / support_layer_storage.size(); + Progress::messageProgress(Progress::Stage::SUPPORT, progress_total * m_progress_multiplier + m_progress_offset, TREE_PROGRESS_TOTAL); + } +#endif +#if 0 + { + std::lock_guard lock(critical_sections); + if (!storage.support.supportLayers[layer_idx].support_infill_parts.empty() || !storage.support.supportLayers[layer_idx].support_roof.empty()) + storage.support.layer_nr_max_filled_layer = std::max(storage.support.layer_nr_max_filled_layer, static_cast(layer_idx)); + } +#endif + throw_on_cancel(); + } + }); +} + +/*! + * \brief Draws circles around result_on_layer points of the influence areas and applies some post processing. + * + * \param move_bounds[in] All currently existing influence areas + * \param storage[in,out] The storage where the support should be stored. + */ +static void draw_areas( + PrintObject &print_object, + const TreeModelVolumes &volumes, + const TreeSupportSettings &config, + const std::vector &overhangs, + std::vector &move_bounds, + + SupportGeneratorLayersPtr &bottom_contacts, + SupportGeneratorLayersPtr &top_contacts, + SupportGeneratorLayersPtr &intermediate_layers, + SupportGeneratorLayerStorage &layer_storage, + std::function throw_on_cancel) +{ + std::vector support_layer_storage(move_bounds.size()); + std::vector support_roof_storage(move_bounds.size()); + // All SupportElements are put into a layer independent storage to improve parallelization. + std::vector linear_data; + std::vector linear_data_layers; + { + std::vector> map_downwards_old; + std::vector> map_downwards_new; + for (LayerIndex layer_idx = 0; layer_idx < LayerIndex(move_bounds.size()); ++ layer_idx) { + SupportElements *layer_above = layer_idx + 1 < LayerIndex(move_bounds.size()) ? &move_bounds[layer_idx + 1] : nullptr; + map_downwards_new.clear(); + linear_data_layers.emplace_back(linear_data.size()); + std::sort(map_downwards_old.begin(), map_downwards_old.end(), [](auto &l, auto &r) { return l.first < r.first; }); + for (SupportElement &elem : move_bounds[layer_idx]) { + SupportElement *child = nullptr; + if (layer_idx > 0) { + auto it = std::lower_bound(map_downwards_old.begin(), map_downwards_old.end(), &elem, [](auto &l, const SupportElement *r) { return l.first < r; }); + if (it != map_downwards_old.end() && it->first == &elem) { + child = it->second; + // Only one link points to a node above from below. + assert(! (++ it != map_downwards_old.end() && it->first == &elem)); + } + assert(child ? child->state.result_on_layer_is_set() : elem.state.target_height > layer_idx); + } + for (int32_t parent_idx : elem.parents) { + SupportElement &parent = (*layer_above)[parent_idx]; + if (parent.state.result_on_layer_is_set()) + map_downwards_new.emplace_back(&parent, &elem); + } + linear_data.push_back({ &elem, child }); + } + std::swap(map_downwards_old, map_downwards_new); + } + linear_data_layers.emplace_back(linear_data.size()); + } + + throw_on_cancel(); + +#ifndef NDEBUG + for (size_t i = 0; i < move_bounds.size(); ++ i) { + size_t begin = linear_data_layers[i]; + size_t end = linear_data_layers[i + 1]; + for (size_t j = begin; j < end; ++ j) + assert(linear_data[j].element == &move_bounds[i][j - begin]); + } +#endif // NDEBUG + + auto t_start = std::chrono::high_resolution_clock::now(); + // Generate the circles that will be the branches. + generate_branch_areas(volumes, config, move_bounds, linear_data, throw_on_cancel); + +#if 0 + assert(linear_data_layers.size() == move_bounds.size() + 1); + for (const auto &draw_area : linear_data) + assert(contains(draw_area.polygons, draw_area.element->state.result_on_layer)); + for (size_t i = 0; i < move_bounds.size(); ++ i) { + size_t begin = linear_data_layers[i]; + size_t end = linear_data_layers[i + 1]; + for (size_t j = begin; j < end; ++ j) { + const auto &draw_area = linear_data[j]; + assert(draw_area.element == &move_bounds[i][j - begin]); + assert(contains(draw_area.polygons, draw_area.element->state.result_on_layer)); + } + } +#endif + +#if 0 + for (size_t area_layer_idx = 0; area_layer_idx + 1 < linear_data_layers.size(); ++ area_layer_idx) { + size_t begin = linear_data_layers[area_layer_idx]; + size_t end = linear_data_layers[area_layer_idx + 1]; + Polygons polygons; + for (size_t area_idx = begin; area_idx < end; ++ area_idx) { + DrawArea &area = linear_data[area_idx]; + append(polygons, area.polygons); + } + SVG::export_expolygons(debug_out_path("treesupport-extrude_areas-raw-%d.svg", area_layer_idx), + { { { union_ex(polygons) }, { "parent", "red", "black", "", scaled(0.1f), 0.5f } } }); + } +#endif + + auto t_generate = std::chrono::high_resolution_clock::now(); + // In some edgecases a branch may go though a hole, where the regular radius does not fit. This can result in an apparent jump in branch radius. As such this cases need to be caught and smoothed out. + smooth_branch_areas(config, move_bounds, linear_data, linear_data_layers, throw_on_cancel); + +#if 0 + for (size_t area_layer_idx = 0; area_layer_idx + 1 < linear_data_layers.size(); ++area_layer_idx) { + size_t begin = linear_data_layers[area_layer_idx]; + size_t end = linear_data_layers[area_layer_idx + 1]; + Polygons polygons; + for (size_t area_idx = begin; area_idx < end; ++area_idx) { + DrawArea& area = linear_data[area_idx]; + append(polygons, area.polygons); + } + SVG::export_expolygons(debug_out_path("treesupport-extrude_areas-smooth-%d.svg", area_layer_idx), + { { { union_ex(polygons) }, { "parent", "red", "black", "", scaled(0.1f), 0.5f } } }); + } +#endif + + auto t_smooth = std::chrono::high_resolution_clock::now(); + // drop down all trees that connect non gracefully with the model + drop_non_gracious_areas(volumes, linear_data, support_layer_storage, throw_on_cancel); + auto t_drop = std::chrono::high_resolution_clock::now(); + + // Single threaded combining all support areas to the right layers. + { + auto begin = linear_data.begin(); + for (LayerIndex layer_idx = 0; layer_idx < LayerIndex(move_bounds.size()); ++ layer_idx) { + size_t cnt_roofs = 0; + size_t cnt_layers = 0; + auto end = begin; + for (; end != linear_data.end() && end->element->state.layer_idx == layer_idx; ++ end) + ++ (end->element->state.missing_roof_layers > end->element->state.distance_to_top ? cnt_roofs : cnt_layers); + auto &this_roofs = support_roof_storage[layer_idx]; + auto &this_layers = support_layer_storage[layer_idx]; + this_roofs.reserve(this_roofs.size() + cnt_roofs); + this_layers.reserve(this_layers.size() + cnt_layers); + for (auto it = begin; it != end; ++ it) + std::move(std::begin(it->polygons), std::end(it->polygons), std::back_inserter(it->element->state.missing_roof_layers > it->element->state.distance_to_top ? this_roofs : this_layers)); + begin = end; + } + } + + finalize_interface_and_support_areas(print_object, volumes, config, overhangs, support_layer_storage, support_roof_storage, + bottom_contacts, top_contacts, intermediate_layers, layer_storage, throw_on_cancel); + auto t_end = std::chrono::high_resolution_clock::now(); + + auto dur_gen_tips = 0.001 * std::chrono::duration_cast(t_generate - t_start).count(); + auto dur_smooth = 0.001 * std::chrono::duration_cast(t_smooth - t_generate).count(); + auto dur_drop = 0.001 * std::chrono::duration_cast(t_drop - t_smooth).count(); + auto dur_finalize = 0.001 * std::chrono::duration_cast(t_end - t_drop).count(); + + BOOST_LOG_TRIVIAL(info) << + "Time used for drawing subfuctions: generate_branch_areas: " << dur_gen_tips << " ms " + "smooth_branch_areas: " << dur_smooth << " ms " + "drop_non_gracious_areas: " << dur_drop << " ms " + "finalize_interface_and_support_areas " << dur_finalize << " ms"; +} + +extern bool g_showed_critical_error; +extern bool g_showed_performance_warning; + +/*! + * \brief Create the areas that need support. + * + * These areas are stored inside the given SliceDataStorage object. + * \param storage The data storage where the mesh data is gotten from and + * where the resulting support areas are stored. + */ +static void generate_support_areas(Print &print, const BuildVolume &build_volume, const std::vector &print_object_ids, std::function throw_on_cancel) +{ + g_showed_critical_error = false; + g_showed_performance_warning = false; + + // Settings with the indexes of meshes that use these settings. + std::vector>> grouped_meshes = group_meshes(print, print_object_ids); + if (grouped_meshes.empty()) + return; + + size_t counter = 0; + + // Process every mesh group. These groups can not be processed parallel, as the processing in each group is parallelized, and nested parallelization is disables and slow. + for (std::pair> &processing : grouped_meshes) + { + // process each combination of meshes + // this struct is used to easy retrieve setting. No other function except those in TreeModelVolumes and generate_initial_areas() have knowledge of the existence of multiple meshes being processed. + //FIXME this is a copy + // Contains config settings to avoid loading them in every function. This was done to improve readability of the code. + const TreeSupportSettings &config = processing.first; + BOOST_LOG_TRIVIAL(info) << "Processing support tree mesh group " << counter + 1 << " of " << grouped_meshes.size() << " containing " << grouped_meshes[counter].second.size() << " meshes."; + auto t_start = std::chrono::high_resolution_clock::now(); +#if 0 + std::vector exclude(num_support_layers); + // get all already existing support areas and exclude them + tbb::parallel_for(tbb::blocked_range(0, num_support_layers), + [&](const tbb::blocked_range &range) { + for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++ layer_idx) { + Polygons exlude_at_layer; + append(exlude_at_layer, storage.support.supportLayers[layer_idx].support_bottom); + append(exlude_at_layer, storage.support.supportLayers[layer_idx].support_roof); + for (auto part : storage.support.supportLayers[layer_idx].support_infill_parts) + append(exlude_at_layer, part.outline); + exclude[layer_idx] = union_(exlude_at_layer); + } + }); +#endif +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + m_progress_multiplier = 1.0 / double(grouped_meshes.size()); + m_progress_offset = counter == 0 ? 0 : TREE_PROGRESS_TOTAL * (double(counter) * m_progress_multiplier); +#endif // SLIC3R_TREESUPPORT_PROGRESS + PrintObject &print_object = *print.get_object(processing.second.front()); + // Generator for model collision, avoidance and internal guide volumes. + TreeModelVolumes volumes{ print_object, build_volume, config.maximum_move_distance, config.maximum_move_distance_slow, processing.second.front(), +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + m_progress_multiplier, m_progress_offset, +#endif // SLIC3R_TREESUPPORTS_PROGRESS + /* additional_excluded_areas */{} }; + + //FIXME generating overhangs just for the furst mesh of the group. + assert(processing.second.size() == 1); + std::vector overhangs = generate_overhangs(config, *print.get_object(processing.second.front()), throw_on_cancel); + + // ### Precalculate avoidances, collision etc. + size_t num_support_layers = precalculate(print, overhangs, processing.first, processing.second, volumes, throw_on_cancel); + bool has_support = num_support_layers > 0; + bool has_raft = config.raft_layers.size() > 0; + num_support_layers = std::max(num_support_layers, config.raft_layers.size()); + + SupportParameters support_params(print_object); + support_params.with_sheath = true; +// Don't override the support density of tree supports, as the support density is used for raft. +// The trees will have the density zeroed in tree_supports_generate_paths() +// support_params.support_density = 0; + + SupportGeneratorLayerStorage layer_storage; + SupportGeneratorLayersPtr top_contacts; + SupportGeneratorLayersPtr bottom_contacts; + SupportGeneratorLayersPtr interface_layers; + SupportGeneratorLayersPtr base_interface_layers; + SupportGeneratorLayersPtr intermediate_layers(num_support_layers, nullptr); + if (support_params.has_top_contacts || has_raft) + top_contacts.assign(num_support_layers, nullptr); + if (support_params.has_bottom_contacts) + bottom_contacts.assign(num_support_layers, nullptr); + if (support_params.has_interfaces() || has_raft) + interface_layers.assign(num_support_layers, nullptr); + if (support_params.has_base_interfaces() || has_raft) + base_interface_layers.assign(num_support_layers, nullptr); + + auto remove_undefined_layers = [&bottom_contacts, &top_contacts, &interface_layers, &base_interface_layers, &intermediate_layers]() { + auto doit = [](SupportGeneratorLayersPtr& layers) { + layers.erase(std::remove_if(layers.begin(), layers.end(), [](const SupportGeneratorLayer* ptr) { return ptr == nullptr; }), layers.end()); + }; + doit(bottom_contacts); + doit(top_contacts); + doit(interface_layers); + doit(base_interface_layers); + doit(intermediate_layers); + }; + + InterfacePlacer interface_placer{ + print_object.slicing_parameters(), support_params, config, + // Outputs + layer_storage, top_contacts, interface_layers, base_interface_layers }; + + if (has_support) { + auto t_precalc = std::chrono::high_resolution_clock::now(); + + // value is the area where support may be placed. As this is calculated in CreateLayerPathing it is saved and reused in draw_areas + std::vector move_bounds(num_support_layers); + + // ### Place tips of the support tree + for (size_t mesh_idx : processing.second) + generate_initial_areas(*print.get_object(mesh_idx), volumes, config, overhangs, + move_bounds, interface_placer, throw_on_cancel); + auto t_gen = std::chrono::high_resolution_clock::now(); + + #ifdef TREESUPPORT_DEBUG_SVG + for (size_t layer_idx = 0; layer_idx < move_bounds.size(); ++layer_idx) { + Polygons polys; + for (auto& area : move_bounds[layer_idx]) + append(polys, area.influence_area); + if (auto begin = move_bounds[layer_idx].begin(); begin != move_bounds[layer_idx].end()) + SVG::export_expolygons(debug_out_path("treesupport-initial_areas-%d.svg", layer_idx), + { { { union_ex(volumes.getWallRestriction(support_element_collision_radius(config, begin->state), layer_idx, begin->state.use_min_xy_dist)) }, + { "wall_restricrictions", "gray", 0.5f } }, + { { union_ex(polys) }, { "parent", "red", "black", "", scaled(0.1f), 0.5f } } }); + } + #endif // TREESUPPORT_DEBUG_SVG + + // ### Propagate the influence areas downwards. This is an inherently serial operation. + create_layer_pathing(volumes, config, move_bounds, throw_on_cancel); + auto t_path = std::chrono::high_resolution_clock::now(); + + // ### Set a point in each influence area + create_nodes_from_area(volumes, config, move_bounds, throw_on_cancel); + auto t_place = std::chrono::high_resolution_clock::now(); + + // ### draw these points as circles + + if (print_object.config().support_style.value != smsOrganic) + draw_areas(*print.get_object(processing.second.front()), volumes, config, overhangs, move_bounds, + bottom_contacts, top_contacts, intermediate_layers, layer_storage, throw_on_cancel); + else { + assert(print_object.config().support_material_style == smsOrganic); + organic_draw_branches( + *print.get_object(processing.second.front()), volumes, config, move_bounds, + bottom_contacts, top_contacts, interface_placer, intermediate_layers, layer_storage, + throw_on_cancel); + } + + remove_undefined_layers(); + + std::tie(interface_layers, base_interface_layers) = generate_interface_layers(print_object.config(), support_params, + bottom_contacts, top_contacts, interface_layers, base_interface_layers, intermediate_layers, layer_storage); + + auto t_draw = std::chrono::high_resolution_clock::now(); + auto dur_pre_gen = 0.001 * std::chrono::duration_cast(t_precalc - t_start).count(); + auto dur_gen = 0.001 * std::chrono::duration_cast(t_gen - t_precalc).count(); + auto dur_path = 0.001 * std::chrono::duration_cast(t_path - t_gen).count(); + auto dur_place = 0.001 * std::chrono::duration_cast(t_place - t_path).count(); + auto dur_draw = 0.001 * std::chrono::duration_cast(t_draw - t_place).count(); + auto dur_total = 0.001 * std::chrono::duration_cast(t_draw - t_start).count(); + BOOST_LOG_TRIVIAL(info) << + "Total time used creating Tree support for the currently grouped meshes: " << dur_total << " ms. " + "Different subtasks:\nCalculating Avoidance: " << dur_pre_gen << " ms " + "Creating inital influence areas: " << dur_gen << " ms " + "Influence area creation: " << dur_path << "ms " + "Placement of Points in InfluenceAreas: " << dur_place << "ms " + "Drawing result as support " << dur_draw << " ms"; + // if (config.branch_radius==2121) + // BOOST_LOG_TRIVIAL(error) << "Why ask questions when you already know the answer twice.\n (This is not a real bug, please dont report it.)"; + + move_bounds.clear(); + } else if (generate_raft_contact(print_object, config, interface_placer) >= 0) { + remove_undefined_layers(); + } else + // No raft. + continue; + + // Produce the support G-code. + // Used by both classic and tree supports. + SupportGeneratorLayersPtr raft_layers = generate_raft_base(print_object, support_params, print_object.slicing_parameters(), + top_contacts, interface_layers, base_interface_layers, intermediate_layers, layer_storage); +#if 1 //#ifdef SLIC3R_DEBUG + SupportGeneratorLayersPtr layers_sorted = +#endif // SLIC3R_DEBUG + generate_support_layers(print_object, raft_layers, bottom_contacts, top_contacts, intermediate_layers, interface_layers, base_interface_layers); + // Don't fill in the tree supports, make them hollow with just a single sheath line. + generate_support_toolpaths(print_object.support_layers(), print_object.config(), support_params, print_object.slicing_parameters(), + raft_layers, bottom_contacts, top_contacts, intermediate_layers, interface_layers, base_interface_layers); + + #if 0 +//#ifdef SLIC3R_DEBUG + { + static int iRun = 0; + ++ iRun; + size_t layer_id = 0; + for (int i = 0; i < int(layers_sorted.size());) { + // Find the last layer with roughly the same print_z, find the minimum layer height of all. + // Due to the floating point inaccuracies, the print_z may not be the same even if in theory they should. + int j = i + 1; + coordf_t zmax = layers_sorted[i]->print_z + EPSILON; + bool empty = layers_sorted[i]->polygons.empty(); + for (; j < layers_sorted.size() && layers_sorted[j]->print_z <= zmax; ++j) + if (!layers_sorted[j]->polygons.empty()) + empty = false; + if (!empty) { + export_print_z_polygons_to_svg( + debug_out_path("support-%d-%lf.svg", iRun, layers_sorted[i]->print_z).c_str(), + layers_sorted.data() + i, j - i); + export_print_z_polygons_and_extrusions_to_svg( + debug_out_path("support-w-fills-%d-%lf.svg", iRun, layers_sorted[i]->print_z).c_str(), + layers_sorted.data() + i, j - i, + *print_object.support_layers()[layer_id]); + ++layer_id; + } + i = j; + } + } +#endif /* SLIC3R_DEBUG */ + + ++ counter; + } + +// storage.support.generated = true; +} + +} // namespace FFFTreeSupport + +void fff_tree_support_generate(PrintObject &print_object, std::function throw_on_cancel) +{ + size_t idx = 0; + for (const PrintObject *po : print_object.print()->objects()) { + if (po == &print_object) + break; + ++idx; + } + FFFTreeSupport::generate_support_areas(*print_object.print(), + BuildVolume(Pointfs{ Vec2d{ -300., -300. }, Vec2d{ -300., +300. }, Vec2d{ +300., +300. }, Vec2d{ +300., -300. } }, 0.), { idx }, + throw_on_cancel); +} + +} // namespace Slic3r diff --git a/src/libslic3r/Support/TreeSupport.hpp b/src/libslic3r/Support/TreeSupport.hpp new file mode 100644 index 0000000000..76387146f7 --- /dev/null +++ b/src/libslic3r/Support/TreeSupport.hpp @@ -0,0 +1,303 @@ +///|/ Copyright (c) Prusa Research 2022 - 2023 Vojtěch Bubník @bubnikv +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +// Tree supports by Thomas Rahm, losely based on Tree Supports by CuraEngine. +// Original source of Thomas Rahm's tree supports: +// https://github.com/ThomasRahm/CuraEngine +// +// Original CuraEngine copyright: +// Copyright (c) 2021 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. + +#ifndef slic3r_TreeSupport_hpp +#define slic3r_TreeSupport_hpp + +#include "SupportLayer.hpp" +#include "TreeModelVolumes.hpp" +#include "TreeSupportCommon.hpp" + +#include "../BoundingBox.hpp" +#include "../Point.hpp" +#include "../Utils.hpp" + +#include + + +// #define TREE_SUPPORT_SHOW_ERRORS + +#ifdef SLIC3R_TREESUPPORTS_PROGRESS + // The various stages of the process can be weighted differently in the progress bar. + // These weights are obtained experimentally using a small sample size. Sensible weights can differ drastically based on the assumed default settings and model. + #define TREE_PROGRESS_TOTAL 10000 + #define TREE_PROGRESS_PRECALC_COLL TREE_PROGRESS_TOTAL * 0.1 + #define TREE_PROGRESS_PRECALC_AVO TREE_PROGRESS_TOTAL * 0.4 + #define TREE_PROGRESS_GENERATE_NODES TREE_PROGRESS_TOTAL * 0.1 + #define TREE_PROGRESS_AREA_CALC TREE_PROGRESS_TOTAL * 0.3 + #define TREE_PROGRESS_DRAW_AREAS TREE_PROGRESS_TOTAL * 0.1 + #define TREE_PROGRESS_GENERATE_BRANCH_AREAS TREE_PROGRESS_DRAW_AREAS / 3 + #define TREE_PROGRESS_SMOOTH_BRANCH_AREAS TREE_PROGRESS_DRAW_AREAS / 3 + #define TREE_PROGRESS_FINALIZE_BRANCH_AREAS TREE_PROGRESS_DRAW_AREAS / 3 +#endif // SLIC3R_TREESUPPORTS_PROGRESS + +namespace Slic3r +{ + +// Forward declarations +class Print; +class PrintObject; +struct SlicingParameters; + +namespace FFFTreeSupport +{ + +// The number of vertices in each circle. +static constexpr const size_t SUPPORT_TREE_CIRCLE_RESOLUTION = 25; + +struct AreaIncreaseSettings +{ + AreaIncreaseSettings( + TreeModelVolumes::AvoidanceType type = TreeModelVolumes::AvoidanceType::Fast, coord_t increase_speed = 0, + bool increase_radius = false, bool no_error = false, bool use_min_distance = false, bool move = false) : + increase_speed{ increase_speed }, type{ type }, increase_radius{ increase_radius }, no_error{ no_error }, use_min_distance{ use_min_distance }, move{ move } {} + + coord_t increase_speed; + // Packing for smaller memory footprint of SupportElementState && SupportElementMerging + TreeModelVolumes::AvoidanceType type; + bool increase_radius : 1; + bool no_error : 1; + bool use_min_distance : 1; + bool move : 1; + bool operator==(const AreaIncreaseSettings& other) const + { + return type == other.type && + increase_speed == other.increase_speed && + increase_radius == other.increase_radius && + no_error == other.no_error && + use_min_distance == other.use_min_distance && + move == other.move; + } +}; + +#define TREE_SUPPORTS_TRACK_LOST + +// C++17 does not support in place initializers of bit values, thus a constructor zeroing the bits is provided. +struct SupportElementStateBits { + SupportElementStateBits() : + to_buildplate(false), + to_model_gracious(false), + use_min_xy_dist(false), + supports_roof(false), + can_use_safe_radius(false), + skip_ovalisation(false), +#ifdef TREE_SUPPORTS_TRACK_LOST + lost(false), + verylost(false), +#endif // TREE_SUPPORTS_TRACK_LOST + deleted(false), + marked(false) + {} + + /*! + * \brief The element trys to reach the buildplate + */ + bool to_buildplate : 1; + + /*! + * \brief Will the branch be able to rest completely on a flat surface, be it buildplate or model ? + */ + bool to_model_gracious : 1; + + /*! + * \brief Whether the min_xy_distance can be used to get avoidance or similar. Will only be true if support_xy_overrides_z=Z overrides X/Y. + */ + bool use_min_xy_dist : 1; + + /*! + * \brief True if this Element or any parent (element above) provides support to a support roof. + */ + bool supports_roof : 1; + + /*! + * \brief An influence area is considered safe when it can use the holefree avoidance <=> It will not have to encounter holes on its way downward. + */ + bool can_use_safe_radius : 1; + + /*! + * \brief Skip the ovalisation to parent and children when generating the final circles. + */ + bool skip_ovalisation : 1; + +#ifdef TREE_SUPPORTS_TRACK_LOST + // Likely a lost branch, debugging information. + bool lost : 1; + bool verylost : 1; +#endif // TREE_SUPPORTS_TRACK_LOST + + // Not valid anymore, to be deleted. + bool deleted : 1; + + // General purpose flag marking a visited element. + bool marked : 1; +}; + +struct SupportElementState : public SupportElementStateBits +{ + /*! + * \brief The layer this support elements wants reach + */ + LayerIndex target_height; + + /*! + * \brief The position this support elements wants to support on layer=target_height + */ + Point target_position; + + /*! + * \brief The next position this support elements wants to reach. NOTE: This is mainly a suggestion regarding direction inside the influence area. + */ + Point next_position; + + /*! + * \brief The next height this support elements wants to reach + */ + LayerIndex layer_idx; + + /*! + * \brief The Effective distance to top of this element regarding radius increases and collision calculations. + */ + uint32_t effective_radius_height; + + /*! + * \brief The amount of layers this element is below the topmost layer of this branch. + */ + uint32_t distance_to_top; + + /*! + * \brief The resulting center point around which a circle will be drawn later. + * Will be set by setPointsOnAreas + */ + Point result_on_layer { std::numeric_limits::max(), std::numeric_limits::max() }; + bool result_on_layer_is_set() const { return this->result_on_layer != Point{ std::numeric_limits::max(), std::numeric_limits::max() }; } + void result_on_layer_reset() { this->result_on_layer = Point{ std::numeric_limits::max(), std::numeric_limits::max() }; } + /*! + * \brief The amount of extra radius we got from merging branches that could have reached the buildplate, but merged with ones that can not. + */ + coord_t increased_to_model_radius; // how much to model we increased only relevant for merging + + /*! + * \brief Counter about the times the elephant foot was increased. Can be fractions for merge reasons. + */ + double elephant_foot_increases; + + /*! + * \brief The element tries to not move until this dtt is reached, is set to 0 if the element had to move. + */ + uint32_t dont_move_until; + + /*! + * \brief Settings used to increase the influence area to its current state. + */ + AreaIncreaseSettings last_area_increase; + + /*! + * \brief Amount of roof layers that were not yet added, because the branch needed to move. + */ + uint32_t missing_roof_layers; + + // called by increase_single_area() and increaseAreas() + [[nodiscard]] static SupportElementState propagate_down(const SupportElementState &src) + { + SupportElementState dst{ src }; + ++ dst.distance_to_top; + -- dst.layer_idx; + // set to invalid as we are a new node on a new layer + dst.result_on_layer_reset(); + dst.skip_ovalisation = false; + return dst; + } + + [[nodiscard]] bool locked() const { return this->distance_to_top < this->dont_move_until; } +}; + +/*! + * \brief Get the Distance to top regarding the real radius this part will have. This is different from distance_to_top, which is can be used to calculate the top most layer of the branch. + * \param elem[in] The SupportElement one wants to know the effectiveDTT + * \return The Effective DTT. + */ +[[nodiscard]] inline size_t getEffectiveDTT(const TreeSupportSettings &settings, const SupportElementState &elem) +{ + return elem.effective_radius_height < settings.increase_radius_until_layer ? + (elem.distance_to_top < settings.increase_radius_until_layer ? elem.distance_to_top : settings.increase_radius_until_layer) : + elem.effective_radius_height; +} + +/*! + * \brief Get the Radius, that this element will have. + * \param elem[in] The Element. + * \return The radius the element has. + */ +[[nodiscard]] inline coord_t support_element_radius(const TreeSupportSettings &settings, const SupportElementState &elem) +{ + return settings.getRadius(getEffectiveDTT(settings, elem), elem.elephant_foot_increases); +} + +/*! + * \brief Get the collision Radius of this Element. This can be smaller then the actual radius, as the drawAreas will cut off areas that may collide with the model. + * \param elem[in] The Element. + * \return The collision radius the element has. + */ +[[nodiscard]] inline coord_t support_element_collision_radius(const TreeSupportSettings &settings, const SupportElementState &elem) +{ + return settings.getRadius(elem.effective_radius_height, elem.elephant_foot_increases); +} + +struct SupportElement +{ + using ParentIndices = +#ifdef NDEBUG + // To reduce memory allocation in release mode. + boost::container::small_vector; +#else // NDEBUG + // To ease debugging. + std::vector; +#endif // NDEBUG + +// SupportElement(const SupportElementState &state) : SupportElementState(state) {} + SupportElement(const SupportElementState &state, Polygons &&influence_area) : state(state), influence_area(std::move(influence_area)) {} + SupportElement(const SupportElementState &state, ParentIndices &&parents, Polygons &&influence_area) : + state(state), parents(std::move(parents)), influence_area(std::move(influence_area)) {} + + SupportElementState state; + + /*! + * \brief All elements in the layer above the current one that are supported by this element + */ + ParentIndices parents; + + /*! + * \brief The resulting influence area. + * Will only be set in the results of createLayerPathing, and will be nullptr inside! + */ + Polygons influence_area; +}; + +using SupportElements = std::deque; + +[[nodiscard]] inline coord_t support_element_radius(const TreeSupportSettings &settings, const SupportElement &elem) +{ + return support_element_radius(settings, elem.state); +} + +[[nodiscard]] inline coord_t support_element_collision_radius(const TreeSupportSettings &settings, const SupportElement &elem) +{ + return support_element_collision_radius(settings, elem.state); +} + +} // namespace FFFTreeSupport + +void fff_tree_support_generate(PrintObject &print_object, std::function throw_on_cancel = []{}); + +} // namespace Slic3r + +#endif /* slic3r_TreeSupport_hpp */ diff --git a/src/libslic3r/Support/TreeSupportCommon.cpp b/src/libslic3r/Support/TreeSupportCommon.cpp new file mode 100644 index 0000000000..b7789dfce7 --- /dev/null +++ b/src/libslic3r/Support/TreeSupportCommon.cpp @@ -0,0 +1,196 @@ +///|/ Copyright (c) Prusa Research 2023 Vojtěch Bubník @bubnikv +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +// Tree supports by Thomas Rahm, losely based on Tree Supports by CuraEngine. +// Original source of Thomas Rahm's tree supports: +// https://github.com/ThomasRahm/CuraEngine +// +// Original CuraEngine copyright: +// Copyright (c) 2021 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. + +#include "TreeSupportCommon.hpp" + +namespace Slic3r::FFFTreeSupport { + +TreeSupportMeshGroupSettings::TreeSupportMeshGroupSettings(const PrintObject &print_object) +{ + const PrintConfig &print_config = print_object.print()->config(); + const PrintObjectConfig &config = print_object.config(); + const SlicingParameters &slicing_params = print_object.slicing_parameters(); +// const std::vector printing_extruders = print_object.object_extruders(); + + // Support must be enabled and set to Tree style. + assert(config.support_material || config.support_material_enforce_layers > 0); + assert(config.support_material_style == smsTree || config.support_material_style == smsOrganic); + + // Calculate maximum external perimeter width over all printing regions, taking into account the default layer height. + coordf_t external_perimeter_width = 0.; + for (size_t region_id = 0; region_id < print_object.num_printing_regions(); ++ region_id) { + const PrintRegion ®ion = print_object.printing_region(region_id); + external_perimeter_width = std::max(external_perimeter_width, region.flow(print_object, frExternalPerimeter, config.layer_height).width()); + } + + this->layer_height = scaled(config.layer_height.value); + this->resolution = scaled(print_config.resolution.value); + // Arache feature + this->min_feature_size = scaled(config.min_feature_size.value); + // +1 makes the threshold inclusive + this->support_angle = 0.5 * M_PI - std::clamp((config.support_threshold_angle + 1) * M_PI / 180., 0., 0.5 * M_PI); + this->support_line_width = support_material_flow(&print_object, config.layer_height).scaled_width(); + this->support_roof_line_width = support_material_interface_flow(&print_object, config.layer_height).scaled_width(); + //FIXME add it to SlicingParameters and reuse in both tree and normal supports? + this->support_bottom_enable = config.support_interface_top_layers.value > 0 && config.support_interface_bottom_layers.value != 0; + this->support_bottom_height = this->support_bottom_enable ? + (config.support_interface_bottom_layers.value > 0 ? + config.support_interface_bottom_layers.value : + config.support_interface_top_layers.value) * this->layer_height : + 0; + this->support_material_buildplate_only = config.support_on_build_plate_only; + this->support_xy_distance = scaled(config.support_object_xy_distance.value); + // Separation of interfaces, it is likely smaller than support_xy_distance. + this->support_xy_distance_overhang = std::min(this->support_xy_distance, scaled(0.5 * external_perimeter_width)); + this->support_top_distance = scaled(slicing_params.gap_support_object); + this->support_bottom_distance = scaled(slicing_params.gap_object_support); +// this->support_interface_skip_height = +// this->support_infill_angles = + this->support_roof_enable = config.support_interface_top_layers.value > 0; + this->support_roof_layers = this->support_roof_enable ? config.support_interface_top_layers.value : 0; + this->support_floor_enable = config.support_interface_top_layers.value > 0 && config.support_interface_bottom_layers.value > 0; + this->support_floor_layers = this->support_floor_enable ? config.support_interface_bottom_layers.value : 0; +// this->minimum_roof_area = +// this->support_roof_angles = + this->support_roof_pattern = config.support_interface_pattern; + this->support_pattern = config.support_base_pattern; + this->support_line_spacing = scaled(config.support_base_pattern_spacing.value); +// this->support_bottom_offset = +// this->support_wall_count = config.support_material_with_sheath ? 1 : 0; + this->support_wall_count = 1; + this->support_roof_line_distance = scaled(config.support_interface_spacing.value) + this->support_roof_line_width; +// this->minimum_support_area = +// this->minimum_bottom_area = +// this->support_offset = + this->support_tree_branch_distance = scaled(config.tree_support_branch_distance.value); + this->support_tree_angle = std::clamp(config.tree_support_branch_angle * M_PI / 180., 0., 0.5 * M_PI - EPSILON); + this->support_tree_angle_slow = std::clamp(config.tree_support_angle_slow * M_PI / 180., 0., this->support_tree_angle - EPSILON); + this->support_tree_branch_diameter = scaled(config.tree_support_branch_diameter.value); + this->support_tree_branch_diameter_angle = std::clamp(config.tree_support_branch_diameter_angle * M_PI / 180., 0., 0.5 * M_PI - EPSILON); + this->support_tree_top_rate = config.tree_support_top_rate.value; // percent +// this->support_tree_tip_diameter = this->support_line_width; + this->support_tree_tip_diameter = std::clamp(scaled(config.tree_support_tip_diameter.value), 0, this->support_tree_branch_diameter); +} + +TreeSupportSettings::TreeSupportSettings(const TreeSupportMeshGroupSettings &mesh_group_settings, const SlicingParameters &slicing_params) + : support_line_width(mesh_group_settings.support_line_width), + layer_height(mesh_group_settings.layer_height), + branch_radius(mesh_group_settings.support_tree_branch_diameter / 2), + min_radius(mesh_group_settings.support_tree_tip_diameter / 2), // The actual radius is 50 microns larger as the resulting branches will be increased by 50 microns to avoid rounding errors effectively increasing the xydistance + maximum_move_distance((mesh_group_settings.support_tree_angle < M_PI / 2.) ? (coord_t)(tan(mesh_group_settings.support_tree_angle) * layer_height) : std::numeric_limits::max()), + maximum_move_distance_slow((mesh_group_settings.support_tree_angle_slow < M_PI / 2.) ? (coord_t)(tan(mesh_group_settings.support_tree_angle_slow) * layer_height) : std::numeric_limits::max()), + support_bottom_layers(mesh_group_settings.support_bottom_enable ? (mesh_group_settings.support_bottom_height + layer_height / 2) / layer_height : 0), + // Ensure lines always stack nicely even if layer height is large. + tip_layers(std::max((branch_radius - min_radius) / (support_line_width / 3), branch_radius / layer_height)), + branch_radius_increase_per_layer(tan(mesh_group_settings.support_tree_branch_diameter_angle) * layer_height), + max_to_model_radius_increase(mesh_group_settings.support_tree_max_diameter_increase_by_merges_when_support_to_model / 2), + min_dtt_to_model(round_up_divide(mesh_group_settings.support_tree_min_height_to_model, layer_height)), + increase_radius_until_radius(mesh_group_settings.support_tree_branch_diameter / 2), + increase_radius_until_layer(increase_radius_until_radius <= branch_radius ? tip_layers * (increase_radius_until_radius / branch_radius) : (increase_radius_until_radius - branch_radius) / branch_radius_increase_per_layer), + support_rests_on_model(! mesh_group_settings.support_material_buildplate_only), + xy_distance(mesh_group_settings.support_xy_distance), + xy_min_distance(std::min(mesh_group_settings.support_xy_distance, mesh_group_settings.support_xy_distance_overhang)), + bp_radius(mesh_group_settings.support_tree_bp_diameter / 2), + // Increase by half a line overlap, but not faster than 40 degrees angle (0 degrees means zero increase in radius). + bp_radius_increase_per_layer(std::min(tan(0.7) * layer_height, 0.5 * support_line_width)), + z_distance_bottom_layers(size_t(round(double(mesh_group_settings.support_bottom_distance) / double(layer_height)))), + z_distance_top_layers(size_t(round(double(mesh_group_settings.support_top_distance) / double(layer_height)))), +// support_infill_angles(mesh_group_settings.support_infill_angles), + support_roof_angles(mesh_group_settings.support_roof_angles), + roof_pattern(mesh_group_settings.support_roof_pattern), + support_pattern(mesh_group_settings.support_pattern), + support_roof_line_width(mesh_group_settings.support_roof_line_width), + support_line_spacing(mesh_group_settings.support_line_spacing), + support_bottom_offset(mesh_group_settings.support_bottom_offset), + support_wall_count(mesh_group_settings.support_wall_count), + resolution(mesh_group_settings.resolution), + support_roof_line_distance(mesh_group_settings.support_roof_line_distance), // in the end the actual infill has to be calculated to subtract interface from support areas according to interface_preference. + settings(mesh_group_settings), + min_feature_size(mesh_group_settings.min_feature_size) +{ + // At least one tip layer must be defined. + assert(tip_layers > 0); + + layer_start_bp_radius = (bp_radius - branch_radius) / bp_radius_increase_per_layer; + + if (TreeSupportSettings::soluble) { + // safeOffsetInc can only work in steps of the size xy_min_distance in the worst case => xy_min_distance has to be a bit larger than 0 in this worst case and should be large enough for performance to not suffer extremely + // When for all meshes the z bottom and top distance is more than one layer though the worst case is xy_min_distance + min_feature_size + // This is not the best solution, but the only one to ensure areas can not lag though walls at high maximum_move_distance. + xy_min_distance = std::max(xy_min_distance, scaled(0.1)); + xy_distance = std::max(xy_distance, xy_min_distance); + } + +// const std::unordered_map interface_map = { { "support_area_overwrite_interface_area", InterfacePreference::SupportAreaOverwritesInterface }, { "interface_area_overwrite_support_area", InterfacePreference::InterfaceAreaOverwritesSupport }, { "support_lines_overwrite_interface_area", InterfacePreference::SupportLinesOverwriteInterface }, { "interface_lines_overwrite_support_area", InterfacePreference::InterfaceLinesOverwriteSupport }, { "nothing", InterfacePreference::Nothing } }; +// interface_preference = interface_map.at(mesh_group_settings.get("support_interface_priority")); +//FIXME this was the default +// interface_preference = InterfacePreference::SupportLinesOverwriteInterface; + //interface_preference = InterfacePreference::SupportAreaOverwritesInterface; + interface_preference = InterfacePreference::InterfaceAreaOverwritesSupport; + + if (slicing_params.raft_layers() > 0) { + // Fill in raft_layers with the heights of the layers below the first object layer. + // First layer + double z = slicing_params.first_print_layer_height; + this->raft_layers.emplace_back(z); + // Raft base layers + for (size_t i = 1; i < slicing_params.base_raft_layers; ++ i) { + z += slicing_params.base_raft_layer_height; + this->raft_layers.emplace_back(z); + } + // Raft interface layers + for (size_t i = 0; i + 1 < slicing_params.interface_raft_layers; ++ i) { + z += slicing_params.interface_raft_layer_height; + this->raft_layers.emplace_back(z); + } + // Raft contact layer + if (slicing_params.raft_layers() > 1) { + z = slicing_params.raft_contact_top_z; + this->raft_layers.emplace_back(z); + } + if (double dist_to_go = slicing_params.object_print_z_min - z; dist_to_go > EPSILON) { + // Layers between the raft contacts and bottom of the object. + auto nsteps = int(ceil(dist_to_go / slicing_params.max_suport_layer_height)); + double step = dist_to_go / nsteps; + for (int i = 0; i < nsteps; ++ i) { + z += step; + this->raft_layers.emplace_back(z); + } + } + } +} + +#if defined(TREE_SUPPORT_SHOW_ERRORS) && defined(_WIN32) + #define TREE_SUPPORT_SHOW_ERRORS_WIN32 + #include +#endif + +// Shared with generate_support_areas() +bool g_showed_critical_error = false; +bool g_showed_performance_warning = false; + +void tree_supports_show_error(std::string_view message, bool critical) +{ // todo Remove! ONLY FOR PUBLIC BETA!! + printf("Error: %s, critical: %d\n", message.data(), int(critical)); +#ifdef TREE_SUPPORT_SHOW_ERRORS_WIN32 + static bool showed_critical = false; + static bool showed_performance = false; + auto bugtype = std::string(critical ? " This is a critical bug. It may cause missing or malformed branches.\n" : "This bug should only decrease performance.\n"); + bool show = (critical && !g_showed_critical_error) || (!critical && !g_showed_performance_warning); + (critical ? g_showed_critical_error : g_showed_performance_warning) = true; + if (show) + MessageBoxA(nullptr, std::string("TreeSupport_2 MOD detected an error while generating the tree support.\nPlease report this back to me with profile and model.\nRevision 5.0\n" + std::string(message) + "\n" + bugtype).c_str(), + "Bug detected!", MB_OK | MB_SYSTEMMODAL | MB_SETFOREGROUND | MB_ICONWARNING); +#endif // TREE_SUPPORT_SHOW_ERRORS_WIN32 +} + +} // namespace Slic3r::FFFTreeSupport \ No newline at end of file diff --git a/src/libslic3r/Support/TreeSupportCommon.hpp b/src/libslic3r/Support/TreeSupportCommon.hpp new file mode 100644 index 0000000000..52cfe48522 --- /dev/null +++ b/src/libslic3r/Support/TreeSupportCommon.hpp @@ -0,0 +1,595 @@ +///|/ Copyright (c) Prusa Research 2023 Vojtěch Bubník @bubnikv +///|/ +///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher +///|/ +// Tree supports by Thomas Rahm, losely based on Tree Supports by CuraEngine. +// Original source of Thomas Rahm's tree supports: +// https://github.com/ThomasRahm/CuraEngine +// +// Original CuraEngine copyright: +// Copyright (c) 2021 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. + +#ifndef slic3r_TreeSupportCommon_hpp +#define slic3r_TreeSupportCommon_hpp + +#include "../libslic3r.h" +#include "../Polygon.hpp" +#include "SupportCommon.hpp" + +#include + +using namespace Slic3r::FFFSupport; + +namespace Slic3r +{ + +namespace FFFTreeSupport +{ + +using LayerIndex = int; + +enum class InterfacePreference +{ + InterfaceAreaOverwritesSupport, + SupportAreaOverwritesInterface, + InterfaceLinesOverwriteSupport, + SupportLinesOverwriteInterface, + Nothing +}; + +struct TreeSupportMeshGroupSettings { + TreeSupportMeshGroupSettings() = default; + explicit TreeSupportMeshGroupSettings(const PrintObject &print_object); + +/*********************************************************************/ +/* Print parameters, not support specific: */ +/*********************************************************************/ + coord_t layer_height { scaled(0.15) }; + // Maximum Deviation (meshfix_maximum_deviation) + // The maximum deviation allowed when reducing the resolution for the Maximum Resolution setting. If you increase this, + // the print will be less accurate, but the g-code will be smaller. Maximum Deviation is a limit for Maximum Resolution, + // so if the two conflict the Maximum Deviation will always be held true. + coord_t resolution { scaled(0.025) }; + // Minimum Feature Size (aka minimum line width) - Arachne specific + // Minimum thickness of thin features. Model features that are thinner than this value will not be printed, while features thicker + // than the Minimum Feature Size will be widened to the Minimum Wall Line Width. + coord_t min_feature_size { scaled(0.1) }; + +/*********************************************************************/ +/* General support parameters: */ +/*********************************************************************/ + + // Support Overhang Angle + // The minimum angle of overhangs for which support is added. At a value of 0° all overhangs are supported, 90° will not provide any support. + double support_angle { 50. * M_PI / 180. }; + // Support Line Width + // Width of a single support structure line. + coord_t support_line_width { scaled(0.4) }; + // Support Roof Line Width: Width of a single support roof line. + coord_t support_roof_line_width { scaled(0.4) }; + // Enable Support Floor (aka bottom interfaces) + // Generate a dense slab of material between the bottom of the support and the model. This will create a skin between the model and support. + bool support_bottom_enable { false }; + // Support Floor Thickness + // The thickness of the support floors. This controls the number of dense layers that are printed on top of places of a model on which support rests. + coord_t support_bottom_height { scaled(1.) }; + bool support_material_buildplate_only { false }; + // Support X/Y Distance + // Distance of the support structure from the print in the X/Y directions. + // minimum: 0, maximum warning: 1.5 * machine_nozzle_tip_outer_diameter + coord_t support_xy_distance { scaled(0.7) }; + // Minimum Support X/Y Distance + // Distance of the support structure from the overhang in the X/Y directions. + // minimum_value: 0, minimum warning": support_xy_distance - support_line_width * 2, maximum warning: support_xy_distance + coord_t support_xy_distance_overhang { scaled(0.2) }; + // Support Top Distance + // Distance from the top of the support to the print. + coord_t support_top_distance { scaled(0.1) }; + // Support Bottom Distance + // Distance from the print to the bottom of the support. + coord_t support_bottom_distance { scaled(0.1) }; + //FIXME likely not needed, optimization for clipping of interface layers + // When checking where there's model above and below the support, take steps of the given height. Lower values will slice slower, while higher values + // may cause normal support to be printed in some places where there should have been support interface. + coord_t support_interface_skip_height { scaled(0.3) }; + // Support Infill Line Directions + // A list of integer line directions to use. Elements from the list are used sequentially as the layers progress and when the end + // of the list is reached, it starts at the beginning again. The list items are separated by commas and the whole list is contained + // in square brackets. Default is an empty list which means use the default angle 0 degrees. +// std::vector support_infill_angles {}; + // Enable Support Roof + // Generate a dense slab of material between the top of support and the model. This will create a skin between the model and support. + bool support_roof_enable { false }; + // Support Roof Thickness + // The thickness of the support roofs. This controls the amount of dense layers at the top of the support on which the model rests. + coord_t support_roof_layers { 2 }; + bool support_floor_enable { false }; + coord_t support_floor_layers { 2 }; + // Minimum Support Roof Area + // Minimum area size for the roofs of the support. Polygons which have an area smaller than this value will be printed as normal support. + double minimum_roof_area { scaled(scaled(1.)) }; + // A list of integer line directions to use. Elements from the list are used sequentially as the layers progress + // and when the end of the list is reached, it starts at the beginning again. The list items are separated + // by commas and the whole list is contained in square brackets. Default is an empty list which means + // use the default angles (alternates between 45 and 135 degrees if interfaces are quite thick or 90 degrees). + std::vector support_roof_angles {}; + // Support Roof Pattern (aka top interface) + // The pattern with which the roofs of the support are printed. + SupportMaterialInterfacePattern support_roof_pattern { smipAuto }; + // Support Pattern + // The pattern of the support structures of the print. The different options available result in sturdy or easy to remove support. + SupportMaterialPattern support_pattern { smpRectilinear }; + // Support Line Distance + // Distance between the printed support structure lines. This setting is calculated by the support density. + coord_t support_line_spacing { scaled(2.66 - 0.4) }; + // Support Floor Horizontal Expansion + // Amount of offset applied to the floors of the support. + coord_t support_bottom_offset { scaled(0.) }; + // Support Wall Line Count + // The number of walls with which to surround support infill. Adding a wall can make support print more reliably + // and can support overhangs better, but increases print time and material used. + // tree: 1, zig-zag: 0, concentric: 1 + int support_wall_count { 1 }; + // Support Roof Line Distance + // Distance between the printed support roof lines. This setting is calculated by the Support Roof Density, but can be adjusted separately. + coord_t support_roof_line_distance { scaled(0.4) }; + // Minimum Support Area + // Minimum area size for support polygons. Polygons which have an area smaller than this value will not be generated. + coord_t minimum_support_area { scaled(0.) }; + // Minimum Support Floor Area + // Minimum area size for the floors of the support. Polygons which have an area smaller than this value will be printed as normal support. + coord_t minimum_bottom_area { scaled(1.0) }; + // Support Horizontal Expansion + // Amount of offset applied to all support polygons in each layer. Positive values can smooth out the support areas and result in more sturdy support. + coord_t support_offset { scaled(0.) }; + +/*********************************************************************/ +/* Parameters for the Cura tree supports implementation: */ +/*********************************************************************/ + + // Tree Support Maximum Branch Angle + // The maximum angle of the branches, when the branches have to avoid the model. Use a lower angle to make them more vertical and more stable. Use a higher angle to be able to have more reach. + // minimum: 0, minimum warning: 20, maximum: 89, maximum warning": 85 + double support_tree_angle { 60. * M_PI / 180. }; + // Tree Support Branch Diameter Angle + // The angle of the branches' diameter as they gradually become thicker towards the bottom. An angle of 0 will cause the branches to have uniform thickness over their length. + // A bit of an angle can increase stability of the tree support. + // minimum: 0, maximum: 89.9999, maximum warning: 15 + double support_tree_branch_diameter_angle { 5. * M_PI / 180. }; + // Tree Support Branch Distance + // How far apart the branches need to be when they touch the model. Making this distance small will cause + // the tree support to touch the model at more points, causing better overhang but making support harder to remove. + coord_t support_tree_branch_distance { scaled(1.) }; + // Tree Support Branch Diameter + // The diameter of the thinnest branches of tree support. Thicker branches are more sturdy. Branches towards the base will be thicker than this. + // minimum: 0.001, minimum warning: support_line_width * 2 + coord_t support_tree_branch_diameter { scaled(2.) }; + +/*********************************************************************/ +/* Parameters new to the Thomas Rahm's tree supports implementation: */ +/*********************************************************************/ + + // Tree Support Preferred Branch Angle + // The preferred angle of the branches, when they do not have to avoid the model. Use a lower angle to make them more vertical and more stable. Use a higher angle for branches to merge faster. + // minimum: 0, minimum warning: 10, maximum: support_tree_angle, maximum warning: support_tree_angle-1 + double support_tree_angle_slow { 50. * M_PI / 180. }; + // Tree Support Diameter Increase To Model + // The most the diameter of a branch that has to connect to the model may increase by merging with branches that could reach the buildplate. + // Increasing this reduces print time, but increases the area of support that rests on model + // minimum: 0 + coord_t support_tree_max_diameter_increase_by_merges_when_support_to_model { scaled(1.0) }; + // Tree Support Minimum Height To Model + // How tall a branch has to be if it is placed on the model. Prevents small blobs of support. This setting is ignored when a branch is supporting a support roof. + // minimum: 0, maximum warning: 5 + coord_t support_tree_min_height_to_model { scaled(1.0) }; + // Tree Support Inital Layer Diameter + // Diameter every branch tries to achieve when reaching the buildplate. Improves bed adhesion. + // minimum: 0, maximum warning: 20 + coord_t support_tree_bp_diameter { scaled(7.5) }; + // Tree Support Branch Density + // Adjusts the density of the support structure used to generate the tips of the branches. A higher value results in better overhangs, + // but the supports are harder to remove. Use Support Roof for very high values or ensure support density is similarly high at the top. + // -> + // Adjusts the density of the support structure used to generate the tips of the branches. + // A higher value results in better overhangs but the supports are harder to remove, thus it is recommended to enable top support interfaces + // instead of a high branch density value if dense interfaces are needed. + // 5%-35% + double support_tree_top_rate { 15. }; + // Tree Support Tip Diameter + // The diameter of the top of the tip of the branches of tree support. + // minimum: min_wall_line_width, minimum warning: min_wall_line_width+0.05, maximum_value: support_tree_branch_diameter, value: support_line_width + coord_t support_tree_tip_diameter { scaled(0.4) }; + + // Support Interface Priority + // How support interface and support will interact when they overlap. Currently only implemented for support roof. + //enum support_interface_priority { support_lines_overwrite_interface_area }; +}; + +/*! + * \brief This struct contains settings used in the tree support. Thanks to this most functions do not need to know of meshes etc. Also makes the code shorter. + */ +struct TreeSupportSettings +{ +public: + TreeSupportSettings() = default; // required for the definition of the config variable in the TreeSupportGenerator class. + explicit TreeSupportSettings(const TreeSupportMeshGroupSettings &mesh_group_settings, const SlicingParameters &slicing_params); + + // some static variables dependent on other meshes that are not currently processed. + // Has to be static because TreeSupportConfig will be used in TreeModelVolumes as this reduces redundancy. + inline static bool soluble = false; + /*! + * \brief Width of a single line of support. + */ + coord_t support_line_width; + /*! + * \brief Height of a single layer + */ + coord_t layer_height; + /*! + * \brief Radius of a branch when it has left the tip. + */ + coord_t branch_radius; + /*! + * \brief smallest allowed radius, required to ensure that even at DTT 0 every circle will still be printed + */ + coord_t min_radius; + /*! + * \brief How far an influence area may move outward every layer at most. + */ + coord_t maximum_move_distance; + /*! + * \brief How far every influence area will move outward every layer if possible. + */ + coord_t maximum_move_distance_slow; + /*! + * \brief Amount of bottom layers. 0 if disabled. + */ + size_t support_bottom_layers; + /*! + * \brief Amount of effectiveDTT increases are required to reach branch radius. + */ + size_t tip_layers; + /*! + * \brief How much a branch radius increases with each layer to guarantee the prescribed tree widening. + */ + double branch_radius_increase_per_layer; + /*! + * \brief How much a branch resting on the model may grow in radius by merging with branches that can reach the buildplate. + */ + coord_t max_to_model_radius_increase; + /*! + * \brief If smaller (in layers) than that, all branches to model will be deleted + */ + size_t min_dtt_to_model; + /*! + * \brief Increase radius in the resulting drawn branches, even if the avoidance does not allow it. Will be cut later to still fit. + */ + coord_t increase_radius_until_radius; + /*! + * \brief Same as increase_radius_until_radius, but contains the DTT at which the radius will be reached. + */ + size_t increase_radius_until_layer; + /*! + * \brief True if the branches may connect to the model. + */ + bool support_rests_on_model; + /*! + * \brief How far should support be from the model. + */ + coord_t xy_distance; + /*! + * \brief A minimum radius a tree trunk should expand to at the buildplate if possible. + */ + coord_t bp_radius; + /*! + * \brief The layer index at which an increase in radius may be required to reach the bp_radius. + */ + LayerIndex layer_start_bp_radius; + /*! + * \brief How much one is allowed to increase the tree branch radius close to print bed to reach the required bp_radius at layer 0. + * Note that this radius increase will not happen in the tip, to ensure the tip is structurally sound. + */ + double bp_radius_increase_per_layer; + /*! + * \brief minimum xy_distance. Only relevant when Z overrides XY, otherwise equal to xy_distance- + */ + coord_t xy_min_distance; + /*! + * \brief Amount of layers distance required the top of the support to the model + */ + size_t z_distance_top_layers; + /*! + * \brief Amount of layers distance required from the top of the model to the bottom of a support structure. + */ + size_t z_distance_bottom_layers; + /*! + * \brief User specified angles for the support infill. + */ +// std::vector support_infill_angles; + /*! + * \brief User specified angles for the support roof infill. + */ + std::vector support_roof_angles; + /*! + * \brief Pattern used in the support roof. May contain non relevant data if support roof is disabled. + */ + SupportMaterialInterfacePattern roof_pattern; + /*! + * \brief Pattern used in the support infill. + */ + SupportMaterialPattern support_pattern; + /*! + * \brief Line width of the support roof. + */ + coord_t support_roof_line_width; + /*! + * \brief Distance between support infill lines. + */ + coord_t support_line_spacing; + /*! + * \brief Offset applied to the support floor area. + */ + coord_t support_bottom_offset; + /* + * \brief Amount of walls the support area will have. + */ + int support_wall_count; + /* + * \brief Maximum allowed deviation when simplifying. + */ + coord_t resolution; + /* + * \brief Distance between the lines of the roof. + */ + coord_t support_roof_line_distance; + /* + * \brief How overlaps of an interface area with a support area should be handled. + */ + InterfacePreference interface_preference; + + /* + * \brief The infill class wants a settings object. This one will be the correct one for all settings it uses. + */ + TreeSupportMeshGroupSettings settings; + + /* + * \brief Minimum thickness of any model features. + */ + coord_t min_feature_size; + + // Extra raft layers below the object. + std::vector raft_layers; + +public: + bool operator==(const TreeSupportSettings& other) const + { + return branch_radius == other.branch_radius && tip_layers == other.tip_layers && branch_radius_increase_per_layer == other.branch_radius_increase_per_layer && layer_start_bp_radius == other.layer_start_bp_radius && bp_radius == other.bp_radius && + // as a recalculation of the collision areas is required to set a new min_radius. + bp_radius_increase_per_layer == other.bp_radius_increase_per_layer && min_radius == other.min_radius && xy_min_distance == other.xy_min_distance && + xy_distance - xy_min_distance == other.xy_distance - other.xy_min_distance && // if the delta of xy_min_distance and xy_distance is different the collision areas have to be recalculated. + support_rests_on_model == other.support_rests_on_model && increase_radius_until_layer == other.increase_radius_until_layer && min_dtt_to_model == other.min_dtt_to_model && max_to_model_radius_increase == other.max_to_model_radius_increase && maximum_move_distance == other.maximum_move_distance && maximum_move_distance_slow == other.maximum_move_distance_slow && z_distance_bottom_layers == other.z_distance_bottom_layers && support_line_width == other.support_line_width && + support_line_spacing == other.support_line_spacing && support_roof_line_width == other.support_roof_line_width && // can not be set on a per-mesh basis currently, so code to enable processing different roof line width in the same iteration seems useless. + support_bottom_offset == other.support_bottom_offset && support_wall_count == other.support_wall_count && support_pattern == other.support_pattern && roof_pattern == other.roof_pattern && // can not be set on a per-mesh basis currently, so code to enable processing different roof patterns in the same iteration seems useless. + support_roof_angles == other.support_roof_angles && + //support_infill_angles == other.support_infill_angles && + increase_radius_until_radius == other.increase_radius_until_radius && support_bottom_layers == other.support_bottom_layers && layer_height == other.layer_height && z_distance_top_layers == other.z_distance_top_layers && resolution == other.resolution && // Infill generation depends on deviation and resolution. + support_roof_line_distance == other.support_roof_line_distance && interface_preference == other.interface_preference + && min_feature_size == other.min_feature_size // interface_preference should be identical to ensure the tree will correctly interact with the roof. + // The infill class now wants the settings object and reads a lot of settings, and as the infill class is used to calculate support roof lines for interface-preference. Not all of these may be required to be identical, but as I am not sure, better safe than sorry +#if 0 + && (interface_preference == InterfacePreference::InterfaceAreaOverwritesSupport || interface_preference == InterfacePreference::SupportAreaOverwritesInterface + // Perimeter generator parameters + || + (settings.get("fill_outline_gaps") == other.settings.get("fill_outline_gaps") && + settings.get("min_bead_width") == other.settings.get("min_bead_width") && + settings.get("wall_transition_angle") == other.settings.get("wall_transition_angle") && + settings.get("wall_transition_length") == other.settings.get("wall_transition_length") && + settings.get("wall_split_middle_threshold") == other.settings.get("wall_split_middle_threshold") && + settings.get("wall_add_middle_threshold") == other.settings.get("wall_add_middle_threshold") && + settings.get("wall_distribution_count") == other.settings.get("wall_distribution_count") && + settings.get("wall_transition_filter_distance") == other.settings.get("wall_transition_filter_distance") && + settings.get("wall_transition_filter_deviation") == other.settings.get("wall_transition_filter_deviation") && + settings.get("wall_line_width_x") == other.settings.get("wall_line_width_x") && + settings.get("meshfix_maximum_extrusion_area_deviation") == other.settings.get("meshfix_maximum_extrusion_area_deviation")) + ) +#endif + && raft_layers == other.raft_layers + ; + } + + /*! + * \brief Get the Radius part will have based on numeric values. + * \param distance_to_top[in] The effective distance_to_top of the element + * \param elephant_foot_increases[in] The elephant_foot_increases of the element. + * \return The radius an element with these attributes would have. + */ + [[nodiscard]] inline coord_t getRadius(size_t distance_to_top, const double elephant_foot_increases = 0) const + { + return (distance_to_top <= tip_layers ? min_radius + (branch_radius - min_radius) * distance_to_top / tip_layers : // tip + branch_radius + // base + (distance_to_top - tip_layers) * branch_radius_increase_per_layer) + + // gradual increase + elephant_foot_increases * (std::max(bp_radius_increase_per_layer - branch_radius_increase_per_layer, 0.0)); + } + + /*! + * \brief Get the Radius an element should at least have at a given layer. + * \param layer_idx[in] The layer. + * \return The radius every element should aim to achieve. + */ + [[nodiscard]] inline coord_t recommendedMinRadius(LayerIndex layer_idx) const + { + double num_layers_widened = layer_start_bp_radius - layer_idx; + return num_layers_widened > 0 ? branch_radius + num_layers_widened * bp_radius_increase_per_layer : 0; + } + +#if 0 + /*! + * \brief Return on which z in microns the layer will be printed. Used only for support infill line generation. + * \param layer_idx[in] The layer. + * \return The radius every element should aim to achieve. + */ + [[nodiscard]] inline coord_t getActualZ(LayerIndex layer_idx) + { + return layer_idx < coord_t(known_z.size()) ? known_z[layer_idx] : (layer_idx - known_z.size()) * layer_height + known_z.size() ? known_z.back() : 0; + } + + /*! + * \brief Set the z every Layer is printed at. Required for getActualZ to work + * \param z[in] The z every LayerIndex is printed. Vector is used as a map with the index of each element being the corresponding LayerIndex + * \return The radius every element should aim to achieve. + */ + void setActualZ(std::vector& z) + { + known_z = z; + } +#endif + +private: +// std::vector known_z; +}; + +static constexpr const bool polygons_strictly_simple = false; + +static constexpr const auto tiny_area_threshold = sqr(scaled(0.001)); + +void tree_supports_show_error(std::string_view message, bool critical); + +inline double layer_z(const SlicingParameters &slicing_params, const TreeSupportSettings &config, const size_t layer_idx) +{ + return layer_idx >= config.raft_layers.size() ? + slicing_params.object_print_z_min + slicing_params.first_object_layer_height + (layer_idx - config.raft_layers.size()) * slicing_params.layer_height : + config.raft_layers[layer_idx]; +} +// Lowest collision layer +inline LayerIndex layer_idx_ceil(const SlicingParameters &slicing_params, const TreeSupportSettings &config, const double z) +{ + return + LayerIndex(config.raft_layers.size()) + + std::max(0, ceil((z - slicing_params.object_print_z_min - slicing_params.first_object_layer_height) / slicing_params.layer_height)); +} +// Highest collision layer +inline LayerIndex layer_idx_floor(const SlicingParameters &slicing_params, const TreeSupportSettings &config, const double z) +{ + return + LayerIndex(config.raft_layers.size()) + + std::max(0, floor((z - slicing_params.object_print_z_min - slicing_params.first_object_layer_height) / slicing_params.layer_height)); +} + +inline SupportGeneratorLayer& layer_initialize( + SupportGeneratorLayer &layer_new, + const SlicingParameters &slicing_params, + const TreeSupportSettings &config, + const size_t layer_idx) +{ + layer_new.print_z = layer_z(slicing_params, config, layer_idx); + layer_new.bottom_z = layer_idx > 0 ? layer_z(slicing_params, config, layer_idx - 1) : 0; + layer_new.height = layer_new.print_z - layer_new.bottom_z; + return layer_new; +} + +// Using the std::deque as an allocator. +inline SupportGeneratorLayer& layer_allocate_unguarded( + SupportGeneratorLayerStorage &layer_storage, + SupporLayerType layer_type, + const SlicingParameters &slicing_params, + const TreeSupportSettings &config, + size_t layer_idx) +{ + SupportGeneratorLayer &layer = layer_storage.allocate_unguarded(layer_type); + return layer_initialize(layer, slicing_params, config, layer_idx); +} + +inline SupportGeneratorLayer& layer_allocate( + SupportGeneratorLayerStorage &layer_storage, + SupporLayerType layer_type, + const SlicingParameters &slicing_params, + const TreeSupportSettings &config, + size_t layer_idx) +{ + SupportGeneratorLayer &layer = layer_storage.allocate(layer_type); + return layer_initialize(layer, slicing_params, config, layer_idx); +} + +// Used by generate_initial_areas() in parallel by multiple layers. +class InterfacePlacer { +public: + InterfacePlacer( + const SlicingParameters &slicing_parameters, + const SupportParameters &support_parameters, + const TreeSupportSettings &config, + SupportGeneratorLayerStorage &layer_storage, + SupportGeneratorLayersPtr &top_contacts, + SupportGeneratorLayersPtr &top_interfaces, + SupportGeneratorLayersPtr &top_base_interfaces) + : + slicing_parameters(slicing_parameters), support_parameters(support_parameters), config(config), + layer_storage(layer_storage), top_contacts(top_contacts), top_interfaces(top_interfaces), top_base_interfaces(top_base_interfaces) + {} + InterfacePlacer(const InterfacePlacer& rhs) : + slicing_parameters(rhs.slicing_parameters), support_parameters(rhs.support_parameters), config(rhs.config), + layer_storage(rhs.layer_storage), top_contacts(rhs.top_contacts), top_interfaces(rhs.top_interfaces), top_base_interfaces(rhs.top_base_interfaces) + {} + + const SlicingParameters &slicing_parameters; + const SupportParameters &support_parameters; + const TreeSupportSettings &config; + SupportGeneratorLayersPtr& top_contacts_mutable() { return this->top_contacts; } + +public: + // Insert the contact layer and some of the inteface and base interface layers below. + void add_roofs(std::vector &&new_roofs, const size_t insert_layer_idx) + { + if (! new_roofs.empty()) { + std::lock_guard lock(m_mutex_layer_storage); + for (size_t idx = 0; idx < new_roofs.size(); ++ idx) + if (! new_roofs[idx].empty()) + add_roof_unguarded(std::move(new_roofs[idx]), insert_layer_idx - idx, idx); + } + } + + void add_roof(Polygons &&new_roof, const size_t insert_layer_idx, const size_t dtt_tip) + { + std::lock_guard lock(m_mutex_layer_storage); + add_roof_unguarded(std::move(new_roof), insert_layer_idx, dtt_tip); + } + + // called by sample_overhang_area() + void add_roof_build_plate(Polygons &&overhang_areas, size_t dtt_roof) + { + std::lock_guard lock(m_mutex_layer_storage); + this->add_roof_unguarded(std::move(overhang_areas), 0, std::min(dtt_roof, this->support_parameters.num_top_interface_layers)); + } + + void add_roof_unguarded(Polygons &&new_roofs, const size_t insert_layer_idx, const size_t dtt_roof) + { + assert(support_parameters.has_top_contacts); + assert(dtt_roof <= support_parameters.num_top_interface_layers); + SupportGeneratorLayersPtr &layers = + dtt_roof == 0 ? this->top_contacts : + dtt_roof <= support_parameters.num_top_interface_layers_only() ? this->top_interfaces : this->top_base_interfaces; + SupportGeneratorLayer*& l = layers[insert_layer_idx]; + if (l == nullptr) + l = &layer_allocate_unguarded(layer_storage, dtt_roof == 0 ? SupporLayerType::TopContact : SupporLayerType::TopInterface, + slicing_parameters, config, insert_layer_idx); + // will be unioned in finalize_interface_and_support_areas() + append(l->polygons, std::move(new_roofs)); + } + +private: + // Outputs + SupportGeneratorLayerStorage &layer_storage; + SupportGeneratorLayersPtr &top_contacts; + SupportGeneratorLayersPtr &top_interfaces; + SupportGeneratorLayersPtr &top_base_interfaces; + + // Mutexes, guards + std::mutex m_mutex_layer_storage; +}; + +} // namespace FFFTreeSupport + +} // namespace Slic3r + +#endif // slic3r_TreeSupportCommon_hpp \ No newline at end of file diff --git a/src/libslic3r/Utils.hpp b/src/libslic3r/Utils.hpp index 47a809a749..73004621e1 100644 --- a/src/libslic3r/Utils.hpp +++ b/src/libslic3r/Utils.hpp @@ -282,6 +282,10 @@ template size_t next_highest_power_of_2(T v, return next_highest_power_of_2(uint32_t(v)); } +template void reserve_power_of_2(VectorType &vector, size_t n) { + vector.reserve(next_highest_power_of_2(n)); +} + template inline INDEX_TYPE prev_idx_modulo(INDEX_TYPE idx, const INDEX_TYPE count) { @@ -298,6 +302,14 @@ inline INDEX_TYPE next_idx_modulo(INDEX_TYPE idx, const INDEX_TYPE count) return idx; } + +// Return dividend divided by divisor rounded to the nearest integer +template +inline INDEX_TYPE round_up_divide(const INDEX_TYPE dividend, const INDEX_TYPE divisor) +{ + return (dividend + divisor - 1) / divisor; +} + template inline typename CONTAINER_TYPE::size_type prev_idx_modulo(typename CONTAINER_TYPE::size_type idx, const CONTAINER_TYPE &container) { diff --git a/src/slic3r/GUI/ConfigManipulation.cpp b/src/slic3r/GUI/ConfigManipulation.cpp index f42e923f38..88e1cf1d94 100644 --- a/src/slic3r/GUI/ConfigManipulation.cpp +++ b/src/slic3r/GUI/ConfigManipulation.cpp @@ -404,7 +404,7 @@ void ConfigManipulation::update_print_fff_config(DynamicPrintConfig* config, con auto support_type = config->opt_enum("support_type"); auto support_style = config->opt_enum("support_style"); std::set enum_set_normal = {0, 1, 2}; - std::set enum_set_tree = {0, 3, 4, 5}; + std::set enum_set_tree = {0, 3, 4, 5, 6}; auto & set = is_tree(support_type) ? enum_set_tree : enum_set_normal; if (set.find(support_style) == set.end()) { DynamicPrintConfig new_conf = *config; @@ -595,18 +595,22 @@ void ConfigManipulation::toggle_print_fff_options(DynamicPrintConfig *config, co //toggle_field("support_closing_radius", have_support_material && support_style == smsSnug); bool support_is_tree = config->opt_bool("enable_support") && is_tree(support_type); - for (auto el : {"tree_support_branch_angle", "tree_support_wall_count", "tree_support_branch_distance", - "tree_support_branch_diameter", "tree_support_adaptive_layer_height", "tree_support_auto_brim", "tree_support_brim_width"}) - toggle_field(el, support_is_tree); - - // hide tree support settings when normal is selected - for (auto el : {"tree_support_branch_angle", "tree_support_wall_count", "tree_support_branch_distance", - "tree_support_branch_diameter", "max_bridge_length", "tree_support_adaptive_layer_height", "tree_support_auto_brim", "tree_support_brim_width"}) + bool support_is_normal_tree = support_is_tree && support_style != smsOrganic; + bool support_is_organic = support_is_tree && !support_is_normal_tree; + // settings shared by normal and organic trees + for (auto el : {"tree_support_branch_angle", "tree_support_branch_distance", "tree_support_branch_diameter" }) toggle_line(el, support_is_tree); + // settings specific to normal trees + for (auto el : {"tree_support_wall_count", "tree_support_auto_brim", "tree_support_brim_width", "tree_support_adaptive_layer_height"}) + toggle_line(el, support_is_normal_tree); + // settings specific to organic trees + for (auto el : {"tree_support_angle_slow","tree_support_tip_diameter", "tree_support_top_rate", "tree_support_branch_diameter_angle", "tree_support_branch_diameter_double_wall"}) + toggle_line(el, support_is_organic); toggle_field("tree_support_brim_width", support_is_tree && !config->opt_bool("tree_support_auto_brim")); - // tree support use max_bridge_length instead of bridge_no_support - toggle_line("bridge_no_support", !support_is_tree); + // non-organic tree support use max_bridge_length instead of bridge_no_support + toggle_line("max_bridge_length", support_is_normal_tree); + toggle_line("bridge_no_support", !support_is_normal_tree); for (auto el : { "support_interface_spacing", "support_interface_filament", "support_interface_loop_pattern", "support_bottom_interface_spacing" }) @@ -625,8 +629,10 @@ void ConfigManipulation::toggle_print_fff_options(DynamicPrintConfig *config, co toggle_field("support_filament", have_support_material || have_skirt); toggle_line("raft_contact_distance", have_raft && !have_support_soluble); + + // Orca: Raft, grid, snug and organic supports use these two parameters to control the size & density of the "brim"/flange for (auto el : { "raft_first_layer_expansion", "raft_first_layer_density"}) - toggle_line(el, have_raft); + toggle_field(el, have_support_material && !support_is_normal_tree); bool has_ironing = (config->opt_enum("ironing_type") != IroningType::NoIroning); for (auto el : { "ironing_flow", "ironing_spacing", "ironing_speed" }) diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 3b290fde85..8f47e508e5 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -1420,7 +1420,8 @@ void Tab::on_value_change(const std::string& opt_key, const boost::any& value) } // BBS set support style to default when support type changes - if (opt_key == "support_type") { + // Orca: do this only in simple mode + if (opt_key == "support_type" && m_mode == comSimple) { DynamicPrintConfig new_conf = *m_config; new_conf.set_key_value("support_style", new ConfigOptionEnum(smsDefault)); m_config_manipulation.apply(m_config, &new_conf); @@ -2003,6 +2004,8 @@ void TabPrint::build() optgroup->append_single_option_line("support_type", "support#support-types"); optgroup->append_single_option_line("support_style", "support#support-styles"); optgroup->append_single_option_line("support_threshold_angle", "support#threshold-angle"); + optgroup->append_single_option_line("raft_first_layer_density"); + optgroup->append_single_option_line("raft_first_layer_expansion"); optgroup->append_single_option_line("support_on_build_plate_only"); optgroup->append_single_option_line("support_critical_regions_only"); optgroup->append_single_option_line("support_remove_small_overhang"); @@ -2011,8 +2014,6 @@ void TabPrint::build() optgroup = page->new_optgroup(L("Raft"), L"param_raft"); optgroup->append_single_option_line("raft_layers"); optgroup->append_single_option_line("raft_contact_distance"); - optgroup->append_single_option_line("raft_first_layer_density"); - optgroup->append_single_option_line("raft_first_layer_expansion"); optgroup = page->new_optgroup(L("Support filament"), L"param_support_filament"); optgroup->append_single_option_line("support_filament", "support#support-filament"); @@ -2022,9 +2023,14 @@ void TabPrint::build() //BBS optgroup = page->new_optgroup(L("Advanced"), L"param_advanced"); + optgroup->append_single_option_line("tree_support_tip_diameter"); optgroup->append_single_option_line("tree_support_branch_distance", "support#tree-support-only-options"); + optgroup->append_single_option_line("tree_support_top_rate"); optgroup->append_single_option_line("tree_support_branch_diameter", "support#tree-support-only-options"); + optgroup->append_single_option_line("tree_support_branch_diameter_angle"); optgroup->append_single_option_line("tree_support_branch_angle", "support#tree-support-only-options"); + optgroup->append_single_option_line("tree_support_angle_slow"); + optgroup->append_single_option_line("tree_support_branch_diameter_double_wall"); optgroup->append_single_option_line("tree_support_wall_count"); optgroup->append_single_option_line("tree_support_adaptive_layer_height"); optgroup->append_single_option_line("tree_support_auto_brim"); @@ -2165,7 +2171,7 @@ void TabPrint::toggle_options() if (auto choice = dynamic_cast(field)) { auto def = print_config_def.get("support_style"); std::vector enum_set_normal = {0, 1, 2}; - std::vector enum_set_tree = {0, 3, 4, 5}; + std::vector enum_set_tree = {0, 3, 4, 5, 6}; auto & set = is_tree(support_type) ? enum_set_tree : enum_set_normal; auto & opt = const_cast(field->m_opt); auto cb = dynamic_cast(choice->window);