From 333a9be86e707fbbd09fc137c21b4fa0feccddc1 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Thu, 16 Jul 2026 11:01:15 +0100 Subject: [PATCH] Add multi-nozzle exclusion volume travel routing --- src/libslic3r/CMakeLists.txt | 2 + src/libslic3r/GCode.cpp | 122 +++- src/libslic3r/GCode.hpp | 18 +- .../GCode/ExclusionVolumeTravelAvoidance.cpp | 592 ++++++++++++++++++ .../GCode/ExclusionVolumeTravelAvoidance.hpp | 79 +++ 5 files changed, 802 insertions(+), 11 deletions(-) create mode 100644 src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp create mode 100644 src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp diff --git a/src/libslic3r/CMakeLists.txt b/src/libslic3r/CMakeLists.txt index af1ef8e4db..ce3fd8476c 100644 --- a/src/libslic3r/CMakeLists.txt +++ b/src/libslic3r/CMakeLists.txt @@ -234,6 +234,8 @@ set(lisbslic3r_sources GCode/CoolingBuffer.hpp GCode/ExclusionVolumePathCheck.cpp GCode/ExclusionVolumePathCheck.hpp + GCode/ExclusionVolumeTravelAvoidance.cpp + GCode/ExclusionVolumeTravelAvoidance.hpp GCode/TimelapsePosPicker.cpp GCode/TimelapsePosPicker.hpp GCode.cpp diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index 23f7a47188..f31c0ed2c5 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -2435,6 +2435,8 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessorResult* resu // BBS m_curr_print = print; m_skirt_group_done.clear(); + m_pending_start_gcode_position.reset(); + m_exclusion_volume_travel_avoidance.init(print->config(), print->get_plate_origin()); GCodeWriter::full_gcode_comment = print->config().gcode_comments; CNumericLocalesSetter locales_setter; @@ -3776,6 +3778,17 @@ void GCode::_do_export(Print& print, GCodeOutputStream &file, ThumbnailsGenerato file.write(this->set_extruder(initial_extruder_id, 0.)); } + // Direct output writes are parsed synchronously. Preserve the startup + // endpoint before the generator establishes its first model-space point, + // so that first travel can be planned from the position the G-code actually + // left the machine at rather than the default last_pos value. + GCodeProcessor::PositionState startup_position = m_processor.get_current_position(); + const Vec2f plate_offset = m_writer.get_xy_offset(); + startup_position.position.x() += plate_offset.x(); + startup_position.position.y() += plate_offset.y(); + m_pending_start_gcode_position = !m_last_pos_defined && startup_position.has_known_xy() ? + std::optional(startup_position) : std::nullopt; + this->m_objsWithBrim.clear(); m_brim_done = false; @@ -8888,10 +8901,17 @@ std::string GCode::_encode_label_ids_to_base64(std::vector ids) // This method accepts &point in print coordinates. std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string comment, double z/* = DBL_MAX*/) { + const std::optional start_gcode_position = + !m_exclusion_volume_travel_avoidance.empty() && !m_last_pos_defined && + !m_writer.is_current_position_clear() && m_pending_start_gcode_position.has_value() ? + m_pending_start_gcode_position : std::nullopt; + /* Define the travel move as a line between current position and the taget point. This is expressed in print coordinates, so it will need to be translated by this->origin in order to get G-code coordinates. */ - Polyline travel { this->last_pos(), point }; + const Point travel_start = start_gcode_position ? + this->gcode_to_point(to_2d(start_gcode_position->position)) : this->last_pos(); + Polyline travel { travel_start, point }; // check whether a straight travel move would need retraction LiftType lift_type = LiftType::SpiralLift; @@ -8901,6 +8921,57 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string // Save state of use_external_mp_once for the case that will be needed to call twice m_avoid_crossing_perimeters.travel_to. const bool used_external_mp_once = m_avoid_crossing_perimeters.used_external_mp_once(); std::string gcode; + bool exclusion_volume_travel_rerouted = false; + + const auto active_extruder_id = [this]() { + if (m_writer.filament() == nullptr) + return -1; + const size_t id = m_writer.filament()->extruder_id(); + return id < m_config.nozzle_diameter.size() ? int(id) : -1; + }; + const auto to_gcode_point = [this](const Point &local_point) { + const Vec2d point = this->point_to_gcode(local_point); + return Point(scale_(point.x()), scale_(point.y())); + }; + const auto to_local_point = [this](const Point &gcode_point) { + return this->gcode_to_point(unscaled(gcode_point)); + }; + const auto to_gcode_polyline = [&to_gcode_point](const Polyline &local_path) { + Polyline result; + result.points.reserve(local_path.points.size()); + for (const Point &local_point : local_path.points) + result.append(to_gcode_point(local_point)); + return result; + }; + const auto to_local_polyline = [&to_local_point](const Polyline &gcode_path) { + Polyline result; + result.points.reserve(gcode_path.points.size()); + for (const Point &gcode_point : gcode_path.points) + result.append(to_local_point(gcode_point)); + return result; + }; + const auto nominal_writer_z = [this]() { + return m_writer.get_position().z() - m_writer.get_zhop(); + }; + const auto route_around_exclusion_volumes = [&]( + Polyline &path, + const std::optional &start_z_override) { + if (m_exclusion_volume_travel_avoidance.empty() || path.size() < 2) + return false; + + const double target_z = z == DBL_MAX ? m_nominal_z : z; + const ExclusionVolumeTravelAvoidance::Result result = + m_exclusion_volume_travel_avoidance.route( + to_gcode_polyline(path), + start_z_override.value_or(nominal_writer_z()), + target_z, + active_extruder_id()); + if (!result.rerouted()) + return false; + + path = to_local_polyline(result.path); + return true; + }; // Orca: we don't need to optimize the Klipper as only set once double jerk_to_set = 0.0; @@ -8965,6 +9036,14 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string //if (needs_retraction && m_layer_index > 1) exit(0); } + const std::optional start_gcode_z = + start_gcode_position && start_gcode_position->has_known_z() ? + std::optional(start_gcode_position->position.z()) : std::nullopt; + if (route_around_exclusion_volumes(travel, start_gcode_z)) { + exclusion_volume_travel_rerouted = true; + needs_retraction = this->needs_retraction(travel, role, lift_type); + } + // Re-allow reduce_crossing_wall for the next travel moves m_avoid_crossing_perimeters.reset_once_modifiers(); @@ -8980,15 +9059,22 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string // When "Wipe while retracting" is enabled, then extruder moves to another position, and travel from this position can cross perimeters. // Because of it, it is necessary to call avoid crossing perimeters again with new starting point after calling retraction() // FIXME Lukas H.: Try to predict if this second calling of avoid crossing perimeters will be needed or not. It could save computations. - if (last_post_before_retract != this->last_pos() && m_config.reduce_crossing_wall) { - // If in the previous call of m_avoid_crossing_perimeters.travel_to was use_external_mp_once set to true restore this value for next call. - if (used_external_mp_once) - m_avoid_crossing_perimeters.use_external_mp_once(); - travel = m_avoid_crossing_perimeters.travel_to(*this, point); - // If state of use_external_mp_once was changed reset it to right value. - if (used_external_mp_once) - m_avoid_crossing_perimeters.reset_once_modifiers(); + if (last_post_before_retract != this->last_pos()) { + travel = Polyline { this->last_pos(), point }; + if (m_config.reduce_crossing_wall) { + // If in the previous call of m_avoid_crossing_perimeters.travel_to was use_external_mp_once set to true restore this value for next call. + if (used_external_mp_once) + m_avoid_crossing_perimeters.use_external_mp_once(); + travel = m_avoid_crossing_perimeters.travel_to(*this, point); + // If state of use_external_mp_once was changed reset it to right value. + if (used_external_mp_once) + m_avoid_crossing_perimeters.reset_once_modifiers(); + } } + + exclusion_volume_travel_rerouted = + route_around_exclusion_volumes(travel, std::nullopt) || + (last_post_before_retract == this->last_pos() && exclusion_volume_travel_rerouted); } else { // Reset the wipe path when traveling, so one would not wipe along an old path. m_wipe.reset_path(); @@ -9020,6 +9106,24 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string Vec3d dest3d(dest2d(0), dest2d(1), z == DBL_MAX ? m_nominal_z : z); gcode += m_writer.travel_to_xyz(dest3d, comment, m_need_change_layer_lift_z); m_need_change_layer_lift_z = false; + } else if (exclusion_volume_travel_rerouted && z != DBL_MAX) { + // Preserve the original sloped-Z move over the longer detour. + // The router activates every volume touched by the complete Z + // range, so this interpolation remains conservative. + const double start_z = m_writer.get_position().z(); + const double total_length = std::max(travel.length(), 1.0); + double traveled = 0.0; + for (size_t i = 1; i < travel.size(); ++i) { + traveled += (travel.points[i] - travel.points[i - 1]).cast().norm(); + const Vec2d dest2d = this->point_to_gcode(travel.points[i]); + const Vec3d dest3d( + dest2d.x(), + dest2d.y(), + start_z + (z - start_z) * std::min(1.0, traveled / total_length)); + gcode += m_writer.travel_to_xyz(dest3d, comment, i == 1 && m_need_change_layer_lift_z); + if (i == 1) + m_need_change_layer_lift_z = false; + } } else { // Extra movements emitted by avoid_crossing_perimeters, lift the z to normal height at the beginning, then apply the z // ratio at the last point diff --git a/src/libslic3r/GCode.hpp b/src/libslic3r/GCode.hpp index 990bf0fee7..acc6a56a0e 100644 --- a/src/libslic3r/GCode.hpp +++ b/src/libslic3r/GCode.hpp @@ -10,6 +10,7 @@ #include "PrintConfig.hpp" #include "GCode/AvoidCrossingPerimeters.hpp" #include "GCode/CoolingBuffer.hpp" +#include "GCode/ExclusionVolumeTravelAvoidance.hpp" #include "GCode/FanMover.hpp" #include "GCode/RetractWhenCrossingPerimeters.hpp" #include "GCode/SpiralVase.hpp" @@ -413,8 +414,16 @@ private: size_t get_extruder_id(unsigned int filament_id) const; void update_placeholder_parser_with_variant_params(); - void set_last_pos(const Point &pos) { m_last_pos = Point3(pos, 0); m_last_pos_defined = true; } - void set_last_pos(const Point3 &pos) { m_last_pos = pos; m_last_pos_defined = true; } + void set_last_pos(const Point &pos) { + m_last_pos = Point3(pos, 0); + m_last_pos_defined = true; + m_pending_start_gcode_position.reset(); + } + void set_last_pos(const Point3 &pos) { + m_last_pos = pos; + m_last_pos_defined = true; + m_pending_start_gcode_position.reset(); + } bool last_pos_defined() const { return m_last_pos_defined; } void set_extruders(const std::vector &extruder_ids); std::string preamble(); @@ -622,6 +631,7 @@ private: OozePrevention m_ooze_prevention; Wipe m_wipe; AvoidCrossingPerimeters m_avoid_crossing_perimeters; + ExclusionVolumeTravelAvoidance m_exclusion_volume_travel_avoidance; RetractWhenCrossingPerimeters m_retract_when_crossing_perimeters; TimelapsePosPicker m_timelapse_pos_picker; @@ -739,6 +749,10 @@ private: // Processor GCodeProcessor m_processor; + // Command-space endpoint after startup G-code. The processor sees direct + // file writes synchronously, while the generator has not established its + // first model-space point yet. + std::optional m_pending_start_gcode_position; //some post-processing on the file, with their data class std::unique_ptr m_fan_mover; diff --git a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp new file mode 100644 index 0000000000..3a7f308f49 --- /dev/null +++ b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp @@ -0,0 +1,592 @@ +#include "ExclusionVolumeTravelAvoidance.hpp" + +#include "libslic3r/ClipperUtils.hpp" +#include "libslic3r/Line.hpp" +#include "libslic3r/Polygon.hpp" + +#include +#include +#include +#include + +namespace Slic3r { + +namespace { + +constexpr double Z_EPSILON_MM = 1e-6; +constexpr double T_EPSILON = 1e-9; +constexpr size_t MAX_REROUTE_ITERATIONS = 16; + +struct SegmentIntersection +{ + double t { 0.0 }; + Point point; + size_t edge_idx { 0 }; +}; + +double boundary_epsilon() +{ + return std::max(SCALED_EPSILON, scale_(0.005)); +} + +bool z_ranges_overlap(double a_min, double a_max, double b_min, double b_max) +{ + return a_max >= b_min - Z_EPSILON_MM && a_min <= b_max + Z_EPSILON_MM; +} + +bool line_intersection_t( + const Point &a, + const Point &b, + const Point &c, + const Point &d, + double &t, + Point &intersection) +{ + const Vec2d p = a.cast(); + const Vec2d r = (b - a).cast(); + const Vec2d q = c.cast(); + const Vec2d s = (d - c).cast(); + const double denominator = cross2(r, s); + if (std::abs(denominator) < T_EPSILON) + return false; + + const Vec2d qp = q - p; + const double candidate_t = cross2(qp, s) / denominator; + const double u = cross2(qp, r) / denominator; + if (candidate_t < -T_EPSILON || candidate_t > 1.0 + T_EPSILON || + u < -T_EPSILON || u > 1.0 + T_EPSILON) + return false; + + t = std::clamp(candidate_t, 0.0, 1.0); + intersection = (p + t * r).cast(); + return true; +} + +template +void for_each_expolygon_contour(const ExPolygon &expolygon, Fn &&fn) +{ + fn(expolygon.contour); + for (const Polygon &hole : expolygon.holes) + fn(hole); +} + +void add_unique_param(std::vector ¶ms, double t) +{ + const double clamped = std::clamp(t, 0.0, 1.0); + if (std::none_of(params.begin(), params.end(), [clamped](double value) { + return std::abs(value - clamped) < T_EPSILON; + })) + params.emplace_back(clamped); +} + +std::vector contour_intersections( + const Point &a, + const Point &b, + const Polygon &polygon) +{ + std::vector intersections; + if (polygon.points.size() < 2) + return intersections; + + intersections.reserve(4); + for (size_t edge_idx = 0; edge_idx < polygon.points.size(); ++edge_idx) { + const Point &c = polygon.points[edge_idx]; + const Point &d = polygon.points[(edge_idx + 1) % polygon.points.size()]; + double t = 0.0; + Point point; + if (line_intersection_t(a, b, c, d, t, point) && + std::none_of(intersections.begin(), intersections.end(), [t](const SegmentIntersection &other) { + return std::abs(other.t - t) < T_EPSILON; + })) + intersections.push_back({ t, point, edge_idx }); + } + + std::sort(intersections.begin(), intersections.end(), [](const SegmentIntersection &lhs, const SegmentIntersection &rhs) { + return lhs.t < rhs.t; + }); + return intersections; +} + +bool point_in_expolygons(const ExPolygons &expolygons, const Point &point, bool border_result) +{ + return std::any_of(expolygons.begin(), expolygons.end(), [&point, border_result](const ExPolygon &expolygon) { + return expolygon.contains(point, border_result); + }); +} + +bool point_on_expolygon_boundary(const ExPolygon &expolygon, const Point &point) +{ + const double epsilon = boundary_epsilon(); + if (expolygon.contour.on_boundary(point, epsilon)) + return true; + return std::any_of(expolygon.holes.begin(), expolygon.holes.end(), [&point, epsilon](const Polygon &hole) { + return hole.on_boundary(point, epsilon); + }); +} + +bool point_on_expolygons_boundary(const ExPolygons &expolygons, const Point &point) +{ + return std::any_of(expolygons.begin(), expolygons.end(), [&point](const ExPolygon &expolygon) { + return point_on_expolygon_boundary(expolygon, point); + }); +} + +bool point_in_expolygons_interior(const ExPolygons &expolygons, const Point &point) +{ + return point_in_expolygons(expolygons, point, false) && + !point_on_expolygons_boundary(expolygons, point); +} + +std::vector boundary_params_for_segment( + const Point &a, + const Point &b, + const ExPolygons &expolygons) +{ + std::vector params { 0.0, 1.0 }; + for (const ExPolygon &expolygon : expolygons) { + for_each_expolygon_contour(expolygon, [&](const Polygon &contour) { + for (const SegmentIntersection &intersection : contour_intersections(a, b, contour)) + add_unique_param(params, intersection.t); + }); + } + std::sort(params.begin(), params.end()); + return params; +} + +Point interpolate(const Point &a, const Point &b, double t) +{ + return (a.cast() + t * (b - a).cast()).cast(); +} + +bool segment_enters_expolygons_interior( + const Point &a, + const Point &b, + const ExPolygons &expolygons) +{ + if (expolygons.empty()) + return false; + if (point_in_expolygons_interior(expolygons, a) || point_in_expolygons_interior(expolygons, b)) + return true; + + const std::vector params = boundary_params_for_segment(a, b, expolygons); + for (size_t idx = 1; idx < params.size(); ++idx) { + const double low = params[idx - 1]; + const double high = params[idx]; + if (high - low < T_EPSILON) + continue; + if (point_in_expolygons_interior(expolygons, interpolate(a, b, 0.5 * (low + high)))) + return true; + } + return false; +} + +std::optional first_interior_param_for_segment( + const Point &a, + const Point &b, + const ExPolygons &expolygons) +{ + if (expolygons.empty()) + return std::nullopt; + if (point_in_expolygons_interior(expolygons, a)) + return 0.0; + + const std::vector params = boundary_params_for_segment(a, b, expolygons); + for (size_t idx = 1; idx < params.size(); ++idx) { + const double low = params[idx - 1]; + const double high = params[idx]; + if (high - low < T_EPSILON) + continue; + if (point_in_expolygons_interior(expolygons, interpolate(a, b, 0.5 * (low + high)))) + return low; + } + + return point_in_expolygons_interior(expolygons, b) ? std::optional(1.0) : std::nullopt; +} + +bool segment_inside_bed(const Point &a, const Point &b, const ExPolygons &valid_bed) +{ + if (valid_bed.empty()) + return true; + if (!point_in_expolygons(valid_bed, a, true) || !point_in_expolygons(valid_bed, b, true)) + return false; + + const std::vector params = boundary_params_for_segment(a, b, valid_bed); + for (size_t idx = 1; idx < params.size(); ++idx) { + const double low = params[idx - 1]; + const double high = params[idx]; + if (high - low < T_EPSILON) + continue; + if (!point_in_expolygons(valid_bed, interpolate(a, b, 0.5 * (low + high)), false)) + return false; + } + return true; +} + +double polyline_length(const Polyline &polyline) +{ + double length = 0.0; + for (size_t idx = 1; idx < polyline.points.size(); ++idx) + length += (polyline.points[idx] - polyline.points[idx - 1]).cast().norm(); + return length; +} + +bool points_near(const Point &lhs, const Point &rhs) +{ + const double epsilon = boundary_epsilon(); + return (lhs - rhs).cast().squaredNorm() <= epsilon * epsilon; +} + +bool replacement_matches_original_segment(const Polyline &replacement, const Point &a, const Point &b) +{ + return replacement.points.size() == 2 && + points_near(replacement.points.front(), a) && points_near(replacement.points.back(), b); +} + +void append_point(Points &points, const Point &point) +{ + if (points.empty() || points.back() != point) + points.emplace_back(point); +} + +Polyline make_forward_detour( + const Point &a, + const Point &b, + const Polygon &contour, + const SegmentIntersection &entry, + const SegmentIntersection &exit) +{ + Points points; + append_point(points, a); + append_point(points, entry.point); + + const size_t count = contour.points.size(); + for (size_t idx = (entry.edge_idx + 1) % count; idx != (exit.edge_idx + 1) % count; idx = (idx + 1) % count) + append_point(points, contour.points[idx]); + + append_point(points, exit.point); + append_point(points, b); + return Polyline(std::move(points)); +} + +Polyline make_backward_detour( + const Point &a, + const Point &b, + const Polygon &contour, + const SegmentIntersection &entry, + const SegmentIntersection &exit) +{ + Points points; + append_point(points, a); + append_point(points, entry.point); + + const size_t count = contour.points.size(); + const size_t last_vertex = (exit.edge_idx + 1) % count; + for (size_t idx = entry.edge_idx;; idx = idx == 0 ? count - 1 : idx - 1) { + append_point(points, contour.points[idx]); + if (idx == last_vertex) + break; + } + + append_point(points, exit.point); + append_point(points, b); + return Polyline(std::move(points)); +} + +bool polyline_inside_bed(const Polyline &polyline, const ExPolygons &valid_bed) +{ + for (size_t idx = 1; idx < polyline.points.size(); ++idx) + if (!segment_inside_bed(polyline.points[idx - 1], polyline.points[idx], valid_bed)) + return false; + return true; +} + +bool polyline_intersects_obstacles(const Polyline &polyline, const ExPolygons &obstacles) +{ + for (size_t idx = 1; idx < polyline.points.size(); ++idx) + if (segment_enters_expolygons_interior(polyline.points[idx - 1], polyline.points[idx], obstacles)) + return true; + return false; +} + +std::optional first_intersected_obstacle( + const Point &a, + const Point &b, + const ExPolygons &obstacles) +{ + std::optional best_idx; + double best_t = std::numeric_limits::infinity(); + for (size_t idx = 0; idx < obstacles.size(); ++idx) { + const ExPolygons single { obstacles[idx] }; + if (const std::optional t = first_interior_param_for_segment(a, b, single); t && *t < best_t) { + best_t = *t; + best_idx = idx; + } + } + return best_idx; +} + +std::optional detour_around_obstacle( + const Point &a, + const Point &b, + const ExPolygon &obstacle, + const ExPolygons &obstacles, + const ExPolygons &valid_bed) +{ + const std::vector intersections = contour_intersections(a, b, obstacle.contour); + if (intersections.size() < 2) + return std::nullopt; + + const SegmentIntersection &entry = intersections.front(); + const SegmentIntersection &exit = intersections.back(); + const Polyline forward = make_forward_detour(a, b, obstacle.contour, entry, exit); + const Polyline backward = make_backward_detour(a, b, obstacle.contour, entry, exit); + + const bool forward_bed_valid = polyline_inside_bed(forward, valid_bed); + const bool backward_bed_valid = polyline_inside_bed(backward, valid_bed); + const bool forward_clear = forward_bed_valid && !polyline_intersects_obstacles(forward, obstacles); + const bool backward_clear = backward_bed_valid && !polyline_intersects_obstacles(backward, obstacles); + + if (forward_clear || backward_clear) { + if (forward_clear && !backward_clear) + return forward; + if (!forward_clear && backward_clear) + return backward; + return polyline_length(forward) <= polyline_length(backward) ? forward : backward; + } + + // If another obstacle blocks both immediate choices, retain the valid local + // detour and let the outer repair loop address the next crossing. + if (!forward_bed_valid && !backward_bed_valid) + return std::nullopt; + if (forward_bed_valid && !backward_bed_valid) + return forward; + if (!forward_bed_valid && backward_bed_valid) + return backward; + return polyline_length(forward) <= polyline_length(backward) ? forward : backward; +} + +void replace_segment(Polyline &path, size_t segment_idx, const Polyline &replacement) +{ + Points points; + points.reserve(path.points.size() + replacement.points.size()); + for (size_t idx = 0; idx < segment_idx; ++idx) + append_point(points, path.points[idx]); + for (const Point &point : replacement.points) + append_point(points, point); + for (size_t idx = segment_idx + 2; idx < path.points.size(); ++idx) + append_point(points, path.points[idx]); + path.points = std::move(points); +} + +Polyline simplify_path(const Polyline &path, const ExPolygons &obstacles, const ExPolygons &valid_bed) +{ + if (path.points.size() <= 2) + return path; + + Points simplified; + simplified.reserve(path.points.size()); + size_t current = 0; + append_point(simplified, path.points.front()); + while (current + 1 < path.points.size()) { + size_t next = path.points.size() - 1; + for (; next > current + 1; --next) { + if (segment_inside_bed(path.points[current], path.points[next], valid_bed) && + !segment_enters_expolygons_interior(path.points[current], path.points[next], obstacles)) + break; + } + append_point(simplified, path.points[next]); + current = next; + } + return Polyline(std::move(simplified)); +} + +} // namespace + +void ExclusionVolumeTravelAvoidance::init(const PrintConfig &config, const Vec3d &plate_origin) +{ + clear(); + + std::vector> regions_by_extruder = + get_bed_excluded_regions_by_extruder(config); + m_spaces.resize(regions_by_extruder.size()); + + const Polygon base_bed_shape(get_bed_shape(config)); + const Vec2d plate_xy = plate_origin.head<2>(); + for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { + RoutingSpace &space = m_spaces[extruder_id]; + space.regions = std::move(regions_by_extruder[extruder_id]); + + const Vec2d extruder_offset = extruder_id < config.extruder_offset.values.size() ? + config.extruder_offset.values[extruder_id] : Vec2d::Zero(); + // Resolved regions are in nozzle/model space. The generator routes in + // emitted G-code space (model - active nozzle offset), before the writer + // subtracts the plate origin, so transform both obstacles and bed alike. + const Vec2d translation_mm = plate_xy - extruder_offset; + const Point translation = scaled(translation_mm); + for (BedExcludeRegion ®ion : space.regions) + region.polygon.translate(translation); + + space.bed_shape = base_bed_shape; + space.bed_shape.translate(translation); + space.bed_shape.make_counter_clockwise(); + } + + double max_nozzle_diameter = 0.0; + for (double diameter : config.nozzle_diameter.values) + max_nozzle_diameter = std::max(max_nozzle_diameter, diameter); + + // This is a numerical/perimeter-walk clearance, not a hidden toolhead + // footprint. The exact configured volume remains Stage 2's source of truth. + const coord_t minimum_clearance = static_cast(SCALED_EPSILON); + const coord_t configured_clearance = + static_cast(scale_(std::max(0.05, 0.1 * max_nozzle_diameter))); + m_clearance = std::max(minimum_clearance, configured_clearance); +} + +void ExclusionVolumeTravelAvoidance::clear() +{ + m_spaces.clear(); + m_clearance = static_cast(SCALED_EPSILON); +} + +bool ExclusionVolumeTravelAvoidance::empty() const +{ + return std::all_of(m_spaces.begin(), m_spaces.end(), [](const RoutingSpace &space) { + return space.regions.empty(); + }); +} + +std::optional +ExclusionVolumeTravelAvoidance::active_obstacles( + const RoutingSpace &space, + double z_min, + double z_max) const +{ + Polygons active_polygons; + active_polygons.reserve(space.regions.size()); + for (const BedExcludeRegion ®ion : space.regions) + if (z_ranges_overlap(z_min, z_max, region.z_min, region.z_max)) + active_polygons.emplace_back(region.polygon); + + if (active_polygons.empty()) + return std::nullopt; + + ActiveObstacles active; + active.obstacles = union_ex(expand(active_polygons, float(m_clearance))); + if (space.bed_shape.points.size() >= 3) { + active.valid_bed = offset_ex(space.bed_shape, -float(m_clearance)); + if (active.valid_bed.empty()) + active.valid_bed = union_ex(Polygons { space.bed_shape }); + } + return active; +} + +ExclusionVolumeTravelAvoidance::Result ExclusionVolumeTravelAvoidance::route( + const Polyline &travel, + double start_z, + double end_z, + int extruder_id) const +{ + Result result; + result.path = travel; + if (travel.points.size() < 2) + return result; + if (extruder_id < 0 || size_t(extruder_id) >= m_spaces.size()) { + result.status = Status::Failed; + result.detail = Detail::UnknownExtruder; + return result; + } + + const RoutingSpace &space = m_spaces[size_t(extruder_id)]; + if (space.regions.empty()) { + result.detail = Detail::NoActiveObstacles; + return result; + } + + const double z_min = std::min(start_z, end_z); + const double z_max = std::max(start_z, end_z); + const std::optional active = active_obstacles(space, z_min, z_max); + if (!active || active->obstacles.empty()) { + result.detail = Detail::NoActiveObstacles; + return result; + } + result.active_obstacles = active->obstacles.size(); + + const Point &start = travel.points.front(); + const Point &end = travel.points.back(); + const std::optional start_obstacles = active_obstacles(space, start_z, start_z); + const std::optional end_obstacles = active_obstacles(space, end_z, end_z); + if ((start_obstacles && point_in_expolygons_interior(start_obstacles->obstacles, start)) || + (end_obstacles && point_in_expolygons_interior(end_obstacles->obstacles, end))) { + result.status = Status::EndpointInside; + result.detail = Detail::EndpointInside; + return result; + } + + bool needs_reroute = false; + for (size_t idx = 1; idx < travel.points.size(); ++idx) { + if (segment_enters_expolygons_interior(travel.points[idx - 1], travel.points[idx], active->obstacles)) { + needs_reroute = true; + break; + } + } + if (!needs_reroute) { + result.detail = Detail::NoIntersection; + return result; + } + + Polyline path = travel; + bool rerouted = false; + for (size_t iteration = 0; iteration < MAX_REROUTE_ITERATIONS; ++iteration) { + result.iterations = iteration + 1; + bool changed = false; + for (size_t segment_idx = 0; segment_idx + 1 < path.points.size(); ++segment_idx) { + const Point &a = path.points[segment_idx]; + const Point &b = path.points[segment_idx + 1]; + if (!segment_inside_bed(a, b, active->valid_bed)) { + result.status = Status::Failed; + result.detail = Detail::SegmentOutsideBed; + return result; + } + + const std::optional obstacle_idx = first_intersected_obstacle(a, b, active->obstacles); + if (!obstacle_idx) + continue; + + const std::optional detour = detour_around_obstacle( + a, b, active->obstacles[*obstacle_idx], active->obstacles, active->valid_bed); + if (!detour) { + result.status = Status::Failed; + result.detail = Detail::DetourFailed; + return result; + } + if (replacement_matches_original_segment(*detour, a, b)) + continue; + + replace_segment(path, segment_idx, *detour); + changed = true; + rerouted = true; + break; + } + + if (!changed) { + path = simplify_path(path, active->obstacles, active->valid_bed); + if (!polyline_inside_bed(path, active->valid_bed) || + polyline_intersects_obstacles(path, active->obstacles)) { + result.status = Status::Failed; + result.detail = Detail::FinalPathInvalid; + return result; + } + result.path = std::move(path); + result.status = rerouted ? Status::Rerouted : Status::Unchanged; + result.detail = rerouted ? Detail::None : Detail::NoIntersection; + return result; + } + } + + result.status = Status::Failed; + result.detail = Detail::IterationLimit; + return result; +} + +} // namespace Slic3r diff --git a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp new file mode 100644 index 0000000000..27b3318039 --- /dev/null +++ b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp @@ -0,0 +1,79 @@ +#pragma once + +#include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Polyline.hpp" +#include "libslic3r/PrintConfig.hpp" + +#include +#include +#include + +namespace Slic3r { + +class ExclusionVolumeTravelAvoidance +{ +public: + enum class Status : unsigned char + { + Unchanged, + Rerouted, + EndpointInside, + Failed + }; + + enum class Detail : unsigned char + { + None, + UnknownExtruder, + NoActiveObstacles, + NoIntersection, + EndpointInside, + SegmentOutsideBed, + DetourFailed, + FinalPathInvalid, + IterationLimit + }; + + struct Result + { + Status status { Status::Unchanged }; + Detail detail { Detail::None }; + Polyline path; + size_t active_obstacles { 0 }; + size_t iterations { 0 }; + + bool rerouted() const { return status == Status::Rerouted; } + }; + + void init(const PrintConfig &config, const Vec3d &plate_origin); + void clear(); + + bool empty() const; + + // Input and output are scaled XY points in the active nozzle's generated + // G-code coordinates before GCodeWriter subtracts the plate offset. + Result route(const Polyline &travel, double start_z, double end_z, int extruder_id) const; + +private: + struct RoutingSpace + { + std::vector regions; + Polygon bed_shape; + }; + + struct ActiveObstacles + { + ExPolygons obstacles; + ExPolygons valid_bed; + }; + + std::optional active_obstacles( + const RoutingSpace &space, + double z_min, + double z_max) const; + + std::vector m_spaces; + coord_t m_clearance { 0 }; +}; + +} // namespace Slic3r