diff --git a/deps_src/libnest2d/include/libnest2d/nester.hpp b/deps_src/libnest2d/include/libnest2d/nester.hpp index 13281c389b..f1852478d2 100644 --- a/deps_src/libnest2d/include/libnest2d/nester.hpp +++ b/deps_src/libnest2d/include/libnest2d/nester.hpp @@ -78,6 +78,12 @@ public: std::vector extrude_ids; int filament_temp_type = -1; // -1 means unset. otherwise should be {0,1,2} double height{ 0 }; + double z_min{ 0 }; + double z_max{ 0 }; + bool has_z_range{ false }; + bool is_bed_exclusion{ false }; + std::vector bed_exclusion_extruder_ids; + int bed_exclusion_extruder_id{ -1 }; double print_temp{ 0 }; double bed_temp{ 0 }; double vitrify_temp{ 0 }; // vitrify temperature diff --git a/deps_src/libnest2d/include/libnest2d/placers/nfpplacer.hpp b/deps_src/libnest2d/include/libnest2d/placers/nfpplacer.hpp index ba015b0faa..f41e9ade61 100644 --- a/deps_src/libnest2d/include/libnest2d/placers/nfpplacer.hpp +++ b/deps_src/libnest2d/include/libnest2d/placers/nfpplacer.hpp @@ -123,6 +123,10 @@ struct NfpPConfig { std::function on_preload; + // Return false when a packed item does not constrain this candidate. + // By default every pair participates in the 2D collision calculation. + std::function&, const _Item&)> should_check_collision; + //BBS: sort function for selector std::function& i1, _Item& i2)> sortfunc; //BBS: excluded region for V4 bed @@ -579,7 +583,14 @@ private: { using namespace nfp; - Shapes nfps(items_.size()); + std::vector collision_items; + collision_items.reserve(items_.size()); + for (Item &item : items_) { + if (!config_.should_check_collision || config_.should_check_collision(trsh, item)) + collision_items.emplace_back(&item); + } + + Shapes nfps(collision_items.size()); // ///////////////////////////////////////////////////////////////////// // TODO: this is a workaround and should be solved in Item with mutexes @@ -590,21 +601,21 @@ private: trsh.rightmostTopVertex(); trsh.leftmostBottomVertex(); - for(Item& itm : items_) { - itm.transformedShape(); - itm.referenceVertex(); - itm.rightmostTopVertex(); - itm.leftmostBottomVertex(); + for (Item *item : collision_items) { + item->transformedShape(); + item->referenceVertex(); + item->rightmostTopVertex(); + item->leftmostBottomVertex(); } // ///////////////////////////////////////////////////////////////////// - __parallel::enumerate(items_.begin(), items_.end(), - [&nfps, &trsh](const Item& sh, size_t n) + __parallel::enumerate(collision_items.begin(), collision_items.end(), + [&nfps, &trsh](Item *const &sh, size_t n) { - auto& fixedp = sh.transformedShape(); + auto& fixedp = sh->transformedShape(); auto& orbp = trsh.transformedShape(); auto subnfp_r = noFitPolygon(fixedp, orbp); - correctNfpPosition(subnfp_r, sh, trsh); + correctNfpPosition(subnfp_r, *sh, trsh); nfps[n] = subnfp_r.first; }); diff --git a/docs/HLSD/exclusion-volumes.md b/docs/HLSD/exclusion-volumes.md new file mode 100644 index 0000000000..1b68c256d5 --- /dev/null +++ b/docs/HLSD/exclusion-volumes.md @@ -0,0 +1,69 @@ +# Bed exclusions and toolhead collision volumes + +## Purpose and configuration + +Bed exclusions have two distinct meanings. A material keep-out prevents model +placement without prohibiting deliberate machine travel, such as entering a +filament cutter. A toolhead collision volume represents an obstacle that travel +and extrusion must avoid. Keeping separate settings preserves existing printer +profiles, project files and command-line usage without enabling new motion +constraints implicitly. + +- `bed_exclude_area` remains a points-array polygon and a shared, bed-fixed + material/placement keep-out. +- `bed_exclude_volumes` contains collision-volume polygons, with optional + `ZMIN..ZMAX;` prefixes and `|` separators. A polygon without a Z prefix applies + over the printable height. +- `bed_exclude_volume_mode` selects shared volumes, toolhead-relative volumes + derived from nozzle XY offsets, or individually configured extruder volumes. +- `extruder_bed_exclude_volumes` stores the individual definitions. These are + selected by physical extruder, not simply by filament slot. + +Material keep-outs and collision volumes are additive. Nozzle offsets apply only +to collision volumes in toolhead-relative mode. The existing bed area never moves +or disappears when collision volumes are configured. + +On belt printers, the region resolver projects material keep-outs onto the +tilted bed surface before placement and tower validation. Collision volumes +remain in model coordinates; the bed-surface projection is not applied to them. + +The printer settings expose the bed area as a normal editable field with Orca's +standard reset controls. Collision volumes appear directly below it in Printable +space, as a separate field. A bed-area polygon can be manually copied into this +field to define a full-height collision volume. Pasted volume syntax in the +area field requires confirmation before it is added to the volume settings; +declining or invalid input leaves the stored area intact. + +## Geometry and slicing + +The region resolver retains the distinction between material keep-outs and +collision volumes, and supplies nozzle-specific regions to placement, arrangement, +generated geometry and motion consumers. An object is checked conservatively +against the collision volumes for every nozzle it uses, over its complete geometry +rather than only a painted portion. Shared support geometry likewise uses a +conservative union of the relevant nozzle and instance exclusions. + +Collision-volume footprints are selected by their overlap with the applicable Z +slab. Brim and supported support-generation paths subtract these footprints before +extrusion generation. The travel router attempts to avoid active collision +volumes; the final G-code checker validates emitted motion independently. + +The checker cannot infer movements inside opaque firmware macros. Homing leaves +the affected coordinates unknown until explicit coordinates establish them. +Skirts and draft shields are not rebuilt around obstacles, extrusion is not +rerouted, and the circular XY sweep of spiral Z-hop is not available to the travel +router when it plans the primary travel. The final checker can warn about these +violations; that warning is not an automatic repair or a guarantee of safe output. + +## Preview + +Ground footprints remain visible. Nozzle-specific collision volumes have thin +nozzle-coloured borders; shared volumes and single-nozzle configurations do not +imply ownership by a particular filament. Automatic 3D previews are limited to +nearby object height to avoid obscuring the workspace. + +**View → Show all collision volumes** displays each volume over its complete +resolved Z range, including on an empty bed. Its default shortcut is Ctrl+Shift+K +(Command+Shift+K on macOS), configurable through Orca's shortcut settings. The +application remembers this display preference independently of printer presets; +it changes neither collision checking nor slicing results. diff --git a/localization/i18n/OrcaSlicer.pot b/localization/i18n/OrcaSlicer.pot index aa12e329b2..a98d6c4a6c 100644 --- a/localization/i18n/OrcaSlicer.pot +++ b/localization/i18n/OrcaSlicer.pot @@ -5320,6 +5320,9 @@ msgstr "" msgid "This parameter expects a valid template." msgstr "" +msgid "Invalid collision volume format. Use XxY, XxY, ... or ZMIN..ZMAX;XxY, XxY, ... and separate multiple volumes with |." +msgstr "" + msgid "Invalid pattern. Use N, N#K, or a comma-separated list with optional #K per entry. Examples: 5, 5#2, 1,7,9, 5,9#2,18." msgstr "" @@ -6518,6 +6521,12 @@ msgstr "" msgid "Show object labels in 3D scene." msgstr "" +msgid "Show all collision volumes" +msgstr "" + +msgid "Show the full height of every configured collision volume, including on an empty bed." +msgstr "" + msgid "Show &Overhang" msgstr "" @@ -11049,6 +11058,12 @@ msgstr "" msgid "Click to reset all settings to the last saved preset." msgstr "" +msgid "This definition contains collision-volume syntax. Add it to the toolhead collision volumes for G-code checking and travel avoidance? The existing excluded bed area will be preserved." +msgstr "" + +msgid "Add collision volumes" +msgstr "" + msgid "Prime tower is required for nozzle changing. There may be flaws on the model without prime tower. Are you sure you want to disable prime tower?" msgstr "" @@ -12708,6 +12723,17 @@ msgid "" "Is the disk full?" msgstr "" +#, possible-boost-format +msgid "A G-code move intersects a collision volume for extruder %1%. This may cause a printer collision." +msgstr "" + +msgid "A G-code move intersects a collision volume. This may cause a printer collision." +msgstr "" + +#, possible-boost-format +msgid "The intersecting move is at G-code line %1%. Its Z position is unknown after homing, so Orca checked it against every height." +msgstr "" + #. TRN %1% is the temporary file path, %2% the output file path, %3% the system error message. #, possible-boost-format msgid "" @@ -12974,6 +13000,14 @@ msgstr "" msgid "%1% is too close to exclusion area. There may be collisions when printing." msgstr "" +#, possible-boost-format +msgid "%1% intersects collision volumes for every available extruder." +msgstr "" + +#, possible-boost-format +msgid "%1% intersects a collision volume for extruder %2%." +msgstr "" + #, possible-boost-format msgid "%1% is too close to others, and collisions may be caused." msgstr "" @@ -13303,7 +13337,34 @@ msgstr "" msgid "Excluded bed area" msgstr "" -msgid "Unprintable area in XY plane. For example, X1 Series printers use the front left corner to cut filament during filament change. The area is expressed as polygon by points in following format: \"XxY, XxY, ...\"" +msgid "Unprintable area in XY plane. For example, X1 Series printers use the front left corner to cut filament during filament change. The area is expressed as a polygon in the format \"XxY, XxY, ...\". It constrains material and model placement, but allows machine travel. Configure toolhead collision volumes separately for G-code checking and travel avoidance." +msgstr "" + +msgid "Toolhead collision volumes" +msgstr "" + +msgid "Collision volumes used for model and generated-material exclusion, G-code checking, and travel avoidance. Use \"XxY, XxY, ...\" for a full-height polygon or \"ZMIN..ZMAX;XxY, XxY, ...\" for a Z-limited volume. Separate multiple volumes with \"|\". These volumes are additional to the excluded bed area. Automatic arrangement conservatively uses the bounding box of a non-convex volume." +msgstr "" + +msgid "Collision volume behavior" +msgstr "" + +msgid "Choose whether all nozzles use the same collision volumes, derive toolhead-relative volumes from each nozzle's XY offset, or configure independent volumes for every extruder. In individual mode, select each extruder on the Extruder page to configure its volumes." +msgstr "" + +msgid "Shared" +msgstr "" + +msgid "Toolhead-relative (nozzle offsets)" +msgstr "" + +msgid "Individual per extruder" +msgstr "" + +msgid "Extruder collision volumes" +msgstr "" + +msgid "Collision volumes used only by this extruder in individual mode. Use the same polygon and optional Z-range format as the shared collision volumes. Leave empty for no collision volumes on this extruder. Automatic arrangement conservatively uses the bounding box of a non-convex volume." msgstr "" msgid "Bed custom texture" @@ -18216,6 +18277,15 @@ msgstr "" msgid "invalid value " msgstr "" +msgid "Invalid collision volume definition." +msgstr "" + +msgid "A nozzle offset is required for every extruder when toolhead-relative collision volumes are enabled." +msgstr "" + +msgid "Invalid per-extruder collision volume definition." +msgstr "" + msgid "Invalid value when spiral vase mode is enabled: " msgstr "" diff --git a/src/OrcaSlicer.cpp b/src/OrcaSlicer.cpp index d125699932..67ee7c8ec4 100644 --- a/src/OrcaSlicer.cpp +++ b/src/OrcaSlicer.cpp @@ -104,6 +104,7 @@ #include "libslic3r/ModelArrange.hpp" #include "libslic3r/Platform.hpp" #include "libslic3r/Print.hpp" +#include "libslic3r/PrintConfig.hpp" #include "libslic3r/SLAPrint.hpp" #include "libslic3r/TriangleMesh.hpp" #include "libslic3r/Format/AMF.hpp" @@ -183,6 +184,12 @@ using namespace Slic3r; #define MAX_CLONEABLE_SIZE 512 +static Pointfs legacy_bed_exclude_area_points(const DynamicPrintConfig &config) +{ + const ConfigOptionPoints *option = config.option("bed_exclude_area"); + return option != nullptr ? option->values : Pointfs{}; +} + std::map cli_errors = { {CLI_SUCCESS, "Success."}, {CLI_ENVIRONMENT_ERROR, "Failed setting up server environment."}, @@ -1842,7 +1849,7 @@ int CLI::run(int argc, char **argv) //use Pointfs insteadof Points old_printable_area = config.option("printable_area", true)->values; - old_exclude_area = config.option("bed_exclude_area", true)->values; + old_exclude_area = legacy_bed_exclude_area_points(config); if (old_printable_area.size() >= 4) { BoundingBoxf old_printable_bbox(old_printable_area); old_printable_width = static_cast(old_printable_bbox.size().x()); @@ -4262,7 +4269,7 @@ int CLI::run(int argc, char **argv) Slic3r::GUI::PartPlateList partplate_list(NULL, m_models.data(), printer_technology); //use Pointfs insteadof Points Pointfs current_printable_area = m_print_config.opt("printable_area")->values; - Pointfs current_exclude_area = m_print_config.opt("bed_exclude_area")->values; + Pointfs current_exclude_area = legacy_bed_exclude_area_points(m_print_config); std::vector current_extruder_areas; //update part plate's size double print_height = m_print_config.opt_float("printable_height"); @@ -4672,7 +4679,7 @@ int CLI::run(int argc, char **argv) printer_plate.printer_name = config_name; temp_printable_area = config.option("printable_area", true)->values; - temp_exclude_area = config.option("bed_exclude_area", true)->values; + temp_exclude_area = legacy_bed_exclude_area_points(config); temp_wrapping_area = config.option("wrapping_exclude_area", true)->values; temp_extruder_areas = config.option("extruder_printable_area", true)->values; temp_extruder_print_heights = config.option("extruder_printable_height", true)->values; @@ -5395,7 +5402,7 @@ int CLI::run(int argc, char **argv) } // add the virtual object into unselect list if has - partplate_list.preprocess_exclude_areas(unselected, enable_wrapping_detect, i + 1); + partplate_list.preprocess_exclude_areas(unselected, m_print_config, enable_wrapping_detect, i + 1); if (avoid_extrusion_cali_region) partplate_list.preprocess_nonprefered_areas(unselected, i + 1); @@ -5427,7 +5434,8 @@ int CLI::run(int argc, char **argv) beds = get_shrink_bedpts(&m_print_config, arrange_cfg); - partplate_list.preprocess_exclude_areas(arrange_cfg.excluded_regions, enable_wrapping_detect, 1, scale_(1)); + partplate_list.preprocess_exclude_areas( + arrange_cfg.excluded_regions, m_print_config, enable_wrapping_detect, 1, scale_(1)); { BOOST_LOG_TRIVIAL(debug) << "arrange bedpts:" << beds[0].transpose() << ", " << beds[1].transpose() << ", " << beds[2].transpose() << ", " << beds[3].transpose(); @@ -5637,7 +5645,7 @@ int CLI::run(int argc, char **argv) } //add the virtual object into unselect list if has - partplate_list.preprocess_exclude_areas(unselected, enable_wrapping_detect); + partplate_list.preprocess_exclude_areas(unselected, m_print_config, enable_wrapping_detect); // Filament ids given on the command line size the tower for STL input. A project // records its filament use per plate, so count there and keep its tower positions. @@ -5868,7 +5876,8 @@ int CLI::run(int argc, char **argv) } // add the virtual object into unselect list if has - partplate_list.preprocess_exclude_areas(unselected, enable_wrapping_detect, plate_to_slice); + partplate_list.preprocess_exclude_areas( + unselected, m_print_config, enable_wrapping_detect, plate_to_slice); } @@ -5900,7 +5909,8 @@ int CLI::run(int argc, char **argv) beds=get_shrink_bedpts(&m_print_config, arrange_cfg); - partplate_list.preprocess_exclude_areas(arrange_cfg.excluded_regions, enable_wrapping_detect, 1, scale_(1)); + partplate_list.preprocess_exclude_areas( + arrange_cfg.excluded_regions, m_print_config, enable_wrapping_detect, 1, scale_(1)); { BOOST_LOG_TRIVIAL(debug) << "arrange bedpts:" << beds[0].transpose() << ", " << beds[1].transpose() << ", " << beds[2].transpose() << ", " << beds[3].transpose(); diff --git a/src/libslic3r/AppConfig.cpp b/src/libslic3r/AppConfig.cpp index 98efc032b8..0d62d6c553 100644 --- a/src/libslic3r/AppConfig.cpp +++ b/src/libslic3r/AppConfig.cpp @@ -410,6 +410,8 @@ void AppConfig::set_defaults() if (get("show_labels").empty()) set_bool("show_labels", false); + if (get("show_collision_volumes").empty()) + set_bool("show_collision_volumes", false); if (get("show_overhang").empty()) set_bool("show_overhang", false); diff --git a/src/libslic3r/Arrange.cpp b/src/libslic3r/Arrange.cpp index 8e5e57021c..997ae00a56 100644 --- a/src/libslic3r/Arrange.cpp +++ b/src/libslic3r/Arrange.cpp @@ -105,6 +105,46 @@ using ItemGroup = std::vector>; const double BIG_ITEM_TRESHOLD = 0.02; #define VITRIFY_TEMP_DIFF_THRSH 15 // bed temp can be higher than vitrify temp, but not higher than this thresh +static bool z_ranges_overlap(double first_min, double first_max, double second_min, double second_max) +{ + if (first_min > first_max) + std::swap(first_min, first_max); + if (second_min > second_max) + std::swap(second_min, second_max); + + // Touching a volume is treated as a collision. Arrangement may leave some + // usable space empty, but it must not create a marginally unsafe placement. + return first_max >= second_min - EPSILON && second_max >= first_min - EPSILON; +} + +template +static bool bed_exclusion_applies_impl(const T &item, const T &fixed_item) +{ + if (!fixed_item.is_bed_exclusion) + return false; + if (item.has_z_range && fixed_item.has_z_range && + !z_ranges_overlap(item.z_min, item.z_max, fixed_item.z_min, fixed_item.z_max)) + return false; + + // Shared volumes and unresolved object mappings apply conservatively to + // every nozzle. Otherwise only the owning physical nozzle participates. + return fixed_item.bed_exclusion_extruder_id < 0 || item.bed_exclusion_extruder_ids.empty() || + std::find(item.bed_exclusion_extruder_ids.begin(), item.bed_exclusion_extruder_ids.end(), + fixed_item.bed_exclusion_extruder_id) != item.bed_exclusion_extruder_ids.end(); +} + +bool has_bed_exclusion_regions(const ArrangePolygons &polygons) +{ + return std::any_of(polygons.begin(), polygons.end(), [](const ArrangePolygon &polygon) { + return polygon.is_bed_exclusion; + }); +} + +bool bed_exclusion_applies(const ArrangePolygon &item, const ArrangePolygon &fixed_item) +{ + return bed_exclusion_applies_impl(item, fixed_item); +} + void update_arrange_params(ArrangeParams& params, const DynamicPrintConfig* print_cfg, const ArrangePolygons& selected) { double skirt_distance = get_real_skirt_dist(*print_cfg); @@ -350,6 +390,14 @@ void fill_config(PConf& pcfg, const ArrangeParams ¶ms) { // Allow parallel execution. pcfg.parallel = params.parallel; + pcfg.should_check_collision = [](const Item &candidate, const Item &packed) { + if (packed.is_bed_exclusion) + return bed_exclusion_applies_impl(candidate, packed); + if (candidate.is_bed_exclusion) + return bed_exclusion_applies_impl(packed, candidate); + return true; + }; + // BBS: excluded regions in BBS bed for (auto& poly : params.excluded_regions) process_arrangeable(poly, pcfg.m_excluded_regions); @@ -1191,6 +1239,12 @@ static void process_arrangeable(const ArrangePolygon &arrpoly, item.itemId(arrpoly.itemid); item.extrude_ids = arrpoly.extrude_ids; item.height = arrpoly.height; + item.z_min = arrpoly.z_min; + item.z_max = arrpoly.z_max; + item.has_z_range = arrpoly.has_z_range; + item.is_bed_exclusion = arrpoly.is_bed_exclusion; + item.bed_exclusion_extruder_ids = arrpoly.bed_exclusion_extruder_ids; + item.bed_exclusion_extruder_id = arrpoly.bed_exclusion_extruder_id; item.name = arrpoly.name; //BBS: add virtual object logic item.is_virt_object = arrpoly.is_virt_object; diff --git a/src/libslic3r/Arrange.hpp b/src/libslic3r/Arrange.hpp index b63b8c938b..20f5e7db9a 100644 --- a/src/libslic3r/Arrange.hpp +++ b/src/libslic3r/Arrange.hpp @@ -81,6 +81,17 @@ struct ArrangePolygon { int itemid{ 0 }; // item id in the vector, used for accessing all possible params like extrude_id int is_applied{ 0 }; // transform has been applied double height{ 0 }; // item height + double z_min{ 0 }; // lowest occupied Z coordinate + double z_max{ 0 }; // highest occupied Z coordinate + bool has_z_range{ false }; // whether z_min / z_max are authoritative + bool is_bed_exclusion{ false }; // conditional bed-exclusion obstacle + // Physical nozzle ids used only for per-nozzle exclusion checks. These are + // deliberately separate from extrude_ids, which contains logical filament + // ids used by Orca's normal material-aware arrangement. Empty is treated + // conservatively as unresolved and therefore applicable to every nozzle. + std::vector bed_exclusion_extruder_ids{}; + // Zero-based nozzle owning an exclusion obstacle; -1 means shared. + int bed_exclusion_extruder_id{ -1 }; double brim_width{ 0 }; // brim width std::string name; @@ -201,6 +212,9 @@ void update_unselected_items_inflation(ArrangePolygons& unselected, const Dynami void update_selected_items_axis_align(ArrangePolygons& selected, const DynamicPrintConfig* print_cfg, const ArrangeParams& params); +bool has_bed_exclusion_regions(const ArrangePolygons& polygons); +bool bed_exclusion_applies(const ArrangePolygon& item, const ArrangePolygon& fixed_item); + Points get_shrink_bedpts(const DynamicPrintConfig* print_cfg, const ArrangeParams& params); /** diff --git a/src/libslic3r/Brim.cpp b/src/libslic3r/Brim.cpp index 23b515647b..1ab8cecbce 100644 --- a/src/libslic3r/Brim.cpp +++ b/src/libslic3r/Brim.cpp @@ -2,6 +2,7 @@ #include "BrimEarsPoint.hpp" #include "ClipperUtils.hpp" #include "EdgeGrid.hpp" +#include "ExclusionVolumeGeometry.hpp" #include "ExPolygon.hpp" #include "Flow.hpp" #include "Geometry.hpp" @@ -20,11 +21,14 @@ #include "PrintConfig.hpp" #include "MaterialType.hpp" #include "Model.hpp" +#include "Support/SupportCommon.hpp" #include #include #include #include #include +#include +#include #include #include #include @@ -48,6 +52,20 @@ namespace Slic3r { +static coord_t brim_exclusion_clearance(const Flow &flow) +{ + const coord_t width_spacing_delta = std::max(0, flow.scaled_width() - flow.scaled_spacing()); + return (width_spacing_delta + 1) / 2 + coord_t(SCALED_EPSILON); +} + +static bool combine_object_brims(const Print &print) +{ + const bool has_per_object_skirt_or_shield = print.config().skirt_type == stPerObject && + (print.has_skirt() || print.has_infinite_skirt()); + return print.config().combine_brims.value && !has_per_object_skirt_or_shield && + print.config().print_sequence != PrintSequence::ByObject; +} + static void append_and_translate(ExPolygons &dst, const ExPolygons &src, const PrintInstance &instance) { size_t dst_idx = dst.size(); expolygons_append(dst, src); @@ -444,6 +462,17 @@ static ExPolygons outer_inner_brim_area(const Print& print, { unsigned int support_material_extruder = printExtruders.front() + 1; Flow flow = print.brim_flow(); + std::vector> exclusion_regions_by_extruder; + if (has_bed_exclude_volumes(print.config())) { + exclusion_regions_by_extruder = get_bed_excluded_regions_by_extruder(print.config()); + // The established bed polygon below still clips the bed edge and + // legacy areas. Only explicit volumes use the new Z-aware trimming. + for (std::vector ®ions : exclusion_regions_by_extruder) + regions.erase(std::remove_if(regions.begin(), regions.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }), regions.end()); + } + const double first_layer_top_z = std::max(0.0, print.skirt_first_layer_height()); + const coord_t exclusion_clearance = brim_exclusion_clearance(flow); ExPolygons brim_area; ExPolygons no_brim_area; @@ -638,14 +667,13 @@ static ExPolygons outer_inner_brim_area(const Print& print, } } - int extruder_nums = print.config().nozzle_diameter.values.size(); std::vector extruder_unprintable_area = print.get_extruder_printable_polygons(); + const size_t extruder_count = print.config().nozzle_diameter.size(); // Orca: if per-extruder print area is not specified, use the whole bed as printable area for all extruders - if (extruder_unprintable_area.empty()) { - extruder_unprintable_area.resize(extruder_nums, Polygons{Model::getBedPolygon()}); - } - std::vector filament_map = print.get_filament_maps(); - + if (extruder_unprintable_area.empty()) + extruder_unprintable_area.resize(extruder_count, Polygons{Model::getBedPolygon()}); + const size_t physical_extruder_count = std::max( + extruder_count, extruder_unprintable_area.size()); if (print.has_wipe_tower() && !print.get_fake_wipe_tower().outer_wall.empty()) { ExPolygons expolyFromLines{}; for (auto polyline : print.get_fake_wipe_tower().outer_wall.begin()->second) { @@ -661,22 +689,36 @@ static ExPolygons outer_inner_brim_area(const Print& print, auto iter = std::find_if(objPrintVec.begin(), objPrintVec.end(), [object](const std::pair& item) { return item.first == object->id(); }); + std::vector object_physical_extruders; - if (iter != objPrintVec.end()) { - int extruder_id = filament_map[iter->second - 1] - 1; - auto bedPoly = extruder_unprintable_area[extruder_id]; - auto bedExPoly = diff_ex((offset(bedPoly, scale_(30.), jtRound, SCALED_RESOLUTION)), {bedPoly}); - if (!bedExPoly.empty()) { - extruder_no_brim_area.push_back(bedExPoly.front()); + if (iter != objPrintVec.end() && iter->second > 0) { + object_physical_extruders = bed_exclusion_physical_extruders( + print, { iter->second - 1 }, physical_extruder_count, 0); + for (const size_t extruder_id : object_physical_extruders) { + if (extruder_id >= extruder_unprintable_area.size()) + continue; + const Polygons &bed_poly = extruder_unprintable_area[extruder_id]; + ExPolygons bed_exterior = diff_ex( + offset(bed_poly, scale_(30.), jtRound, SCALED_RESOLUTION), bed_poly); + expolygons_append(extruder_no_brim_area, std::move(bed_exterior)); } //extruder_no_brim_area = offset2_ex(extruder_no_brim_area, scaled_flow_width, -scaled_flow_width); // connect scattered small areas to prevent generating very small brims - } - for (auto& [key, areas] : brimAreaMap) - if (key.object_id == object->id()) - areas = diff_ex(areas, extruder_no_brim_area); - + if (object_physical_extruders.empty()) { + object_physical_extruders.resize(physical_extruder_count); + std::iota(object_physical_extruders.begin(), object_physical_extruders.end(), size_t(0)); + } + const ExPolygons exclusions = active_bed_exclusion_footprints( + exclusion_regions_by_extruder, object_physical_extruders, + 0.0, first_layer_top_z, Point(0, 0), exclusion_clearance); + for (auto& [key, areas] : brimAreaMap) { + if (key.object_id != object->id()) + continue; + areas = diff_ex(areas, extruder_no_brim_area); + if (!exclusions.empty()) + areas = diff_ex(areas, exclusions); + } } brim_area.clear(); diff --git a/src/libslic3r/CMakeLists.txt b/src/libslic3r/CMakeLists.txt index 4acea143cc..f9866cf09f 100644 --- a/src/libslic3r/CMakeLists.txt +++ b/src/libslic3r/CMakeLists.txt @@ -127,6 +127,8 @@ set(lisbslic3r_sources Emboss.hpp EmbossShape.hpp enum_bitmask.hpp + ExclusionVolumeGeometry.cpp + ExclusionVolumeGeometry.hpp Execution/Execution.hpp Execution/ExecutionSeq.hpp Execution/ExecutionTBB.hpp @@ -257,6 +259,10 @@ set(lisbslic3r_sources GCode/ConflictChecker.hpp GCode/CoolingBuffer.cpp 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/Config.hpp b/src/libslic3r/Config.hpp index 9f70498499..495fac2263 100644 --- a/src/libslic3r/Config.hpp +++ b/src/libslic3r/Config.hpp @@ -37,6 +37,7 @@ #include #include +#include #include // The serialize() members below archive ConfigOption hierarchies through // cereal::base_class, whose registration machinery lives in polymorphic.hpp. @@ -1615,6 +1616,11 @@ public: bool deserialize(const std::string &str, bool append = false) override { + // Extended exclusion-volume syntax belongs to the dedicated string option. + // Rejecting it here also makes --bed-exclude-area fail instead of silently + // turning a volume definition into malformed legacy points. + if (str.find('|') != std::string::npos || str.find(';') != std::string::npos || str.find("..") != std::string::npos) + return false; if (! append) this->values.clear(); std::istringstream is(str); @@ -1635,18 +1641,18 @@ public: } private: - friend class cereal::access; - template void save(Archive& archive) const { - size_t cnt = this->values.size(); - archive(cnt); - archive.saveBinary((const char*)this->values.data(), sizeof(Vec2d) * cnt); - } - template void load(Archive& archive) { - size_t cnt; - archive(cnt); - this->values.assign(cnt, Vec2d()); - archive.loadBinary((char*)this->values.data(), sizeof(Vec2d) * cnt); - } + friend class cereal::access; + template void save(Archive& archive) const { + size_t cnt = this->values.size(); + archive(cnt); + archive.saveBinary((const char*)this->values.data(), sizeof(Vec2d) * cnt); + } + template void load(Archive& archive) { + size_t cnt; + archive(cnt); + this->values.assign(cnt, Vec2d()); + archive.loadBinary((char*)this->values.data(), sizeof(Vec2d) * cnt); + } }; class ConfigOptionPoint3 : public ConfigOptionSingle diff --git a/src/libslic3r/ExclusionVolumeGeometry.cpp b/src/libslic3r/ExclusionVolumeGeometry.cpp new file mode 100644 index 0000000000..cee9f9506f --- /dev/null +++ b/src/libslic3r/ExclusionVolumeGeometry.cpp @@ -0,0 +1,182 @@ +#include "ExclusionVolumeGeometry.hpp" +#include "ExPolygon.hpp" +#include "Point.hpp" +#include "Polygon.hpp" +#include "PrintConfig.hpp" +#include "libslic3r.h" +#include +#include +#include + +#include "BoundingBox.hpp" +#include "ClipperUtils.hpp" +#include "Geometry/ConvexHull.hpp" +#include "Print.hpp" + +#include +#include +#include + +namespace Slic3r { + +namespace { + +constexpr double Z_EPSILON_MM = 1e-6; + +void append_active_footprints( + Polygons &out, + const std::vector ®ions, + const double z_min, + const double z_max, + const Point &translation) +{ + for (const BedExcludeRegion ®ion : regions) { + if (region.polygon.points.size() < 3 || region.z_max < region.z_min || + !bed_exclusion_z_ranges_overlap(z_min, z_max, region.z_min, region.z_max)) + continue; + + Polygon footprint = region.polygon; + footprint.translate(translation); + out.emplace_back(std::move(footprint)); + } +} + +ExPolygons union_active_footprints(Polygons footprints, const coord_t clearance) +{ + if (footprints.empty()) + return {}; + + ExPolygons result = union_ex(footprints); + if (clearance > 0) + result = offset_ex(result, float(clearance)); + return result; +} + +} // namespace + +bool bed_exclusion_z_ranges_overlap( + double first_min, + double first_max, + double second_min, + double second_max) +{ + if (first_min > first_max) + std::swap(first_min, first_max); + if (second_min > second_max) + std::swap(second_min, second_max); + return first_max >= second_min - Z_EPSILON_MM && first_min <= second_max + Z_EPSILON_MM; +} + +Polygon bed_exclusion_arrange_polygon(const Polygon &polygon) +{ + if (polygon.points.size() < 3) + return polygon; + + const Polygon convex_hull = Geometry::convex_hull(polygon.points); + const double polygon_area = std::abs(polygon.area()); + const double hull_area = std::abs(convex_hull.area()); + const double tolerance = std::max(1.0, hull_area) * 1e-12; + if (std::abs(hull_area - polygon_area) <= tolerance) + return polygon; + + return get_extents(polygon).polygon(); +} + +ExPolygons active_bed_exclusion_footprints( + const std::vector ®ions, + const double z_min, + const double z_max, + const Point &translation, + const coord_t clearance) +{ + Polygons footprints; + footprints.reserve(regions.size()); + append_active_footprints(footprints, regions, z_min, z_max, translation); + return union_active_footprints(std::move(footprints), clearance); +} + +ExPolygons active_bed_exclusion_footprints( + const std::vector> ®ions_by_extruder, + const std::vector &physical_extruders, + const double z_min, + const double z_max, + const Point &translation, + const coord_t clearance) +{ + Polygons footprints; + std::vector visited(regions_by_extruder.size(), false); + for (const size_t extruder_id : physical_extruders) { + if (extruder_id >= regions_by_extruder.size() || visited[extruder_id]) + continue; + visited[extruder_id] = true; + const std::vector ®ions = regions_by_extruder[extruder_id]; + footprints.reserve(footprints.size() + regions.size()); + append_active_footprints(footprints, regions, z_min, z_max, translation); + } + return union_active_footprints(std::move(footprints), clearance); +} + +std::vector bed_exclusion_physical_extruders( + const Print &print, + const std::vector &filament_ids, + const size_t physical_extruder_count, + const int layer_id) +{ + if (physical_extruder_count == 0) + return {}; + + std::vector result; + const auto grouping = print.get_layered_nozzle_group_result(); + const bool automatic_mapping_resolved = + !is_auto_filament_map_mode(print.get_filament_map_mode()) || !print.is_BBL_printer() || + print.get_nozzle_group_result() != nullptr; + bool unresolved = filament_ids.empty(); + + for (const unsigned int filament_id : filament_ids) { + if (grouping) { + if (const auto nozzle = grouping->get_nozzle_for_filament(int(filament_id), layer_id); + nozzle.has_value() && nozzle->extruder_id >= 0 && + size_t(nozzle->extruder_id) < physical_extruder_count) { + result.emplace_back(size_t(nozzle->extruder_id)); + continue; + } + } + + const int resolved = bed_exclusion_extruder_for_filament( + filament_id, print.get_filament_maps(), print.get_filament_map_mode(), print.is_BBL_printer(), + automatic_mapping_resolved, physical_extruder_count); + if (resolved >= 0) + result.emplace_back(size_t(resolved)); + else + unresolved = true; + } + + std::sort(result.begin(), result.end()); + result.erase(std::unique(result.begin(), result.end()), result.end()); + if (!unresolved && !result.empty()) + return result; + + result.resize(physical_extruder_count); + std::iota(result.begin(), result.end(), size_t(0)); + return result; +} + +ExPolygons active_bed_exclusion_footprints_for_object( + const PrintObject &object, + const std::vector> ®ions_by_extruder, + const std::vector &physical_extruders, + const double z_min, + const double z_max, + const coord_t clearance) +{ + ExPolygons result; + for (const PrintInstance &instance : object.instances()) { + const Point instance_shift = instance.shift_without_plate_offset(); + const Point shift(-instance_shift.x(), -instance_shift.y()); + expolygons_append(result, active_bed_exclusion_footprints( + regions_by_extruder, physical_extruders, z_min, z_max, shift, clearance)); + } + return result.empty() ? ExPolygons{} : union_ex(result); +} + +} // namespace Slic3r diff --git a/src/libslic3r/ExclusionVolumeGeometry.hpp b/src/libslic3r/ExclusionVolumeGeometry.hpp new file mode 100644 index 0000000000..fc745bb5dd --- /dev/null +++ b/src/libslic3r/ExclusionVolumeGeometry.hpp @@ -0,0 +1,63 @@ +#pragma once + +#include "ExPolygon.hpp" +#include "Polygon.hpp" +#include "libslic3r.h" +#include "Point.hpp" +#include "PrintConfig.hpp" + +#include +#include + +namespace Slic3r { + +class Print; +class PrintObject; + +bool bed_exclusion_z_ranges_overlap(double first_min, double first_max, double second_min, double second_max); + +// libnest2d currently accepts only convex fixed obstacles. Keep convex +// exclusions exact and conservatively use the bounding box for concave ones. +Polygon bed_exclusion_arrange_polygon(const Polygon &polygon); + +// Return the union of exclusion footprints intersecting the requested extrusion +// slab. Regions are already resolved into physical-nozzle/model coordinates by +// PrintConfig; callers only provide the physical nozzles that may emit the +// generated geometry and the translation into the caller's coordinate space. +ExPolygons active_bed_exclusion_footprints( + const std::vector ®ions, + double z_min, + double z_max, + const Point &translation = Point(0, 0), + coord_t clearance = 0); + +ExPolygons active_bed_exclusion_footprints( + const std::vector> ®ions_by_extruder, + const std::vector &physical_extruders, + double z_min, + double z_max, + const Point &translation = Point(0, 0), + coord_t clearance = 0); + +// Resolve logical filaments to every physical extruder which may print them. +// An unresolved automatic mapping deliberately returns every physical +// extruder, keeping generated geometry conservative until tool assignment is +// known. +std::vector bed_exclusion_physical_extruders( + const Print &print, + const std::vector &filament_ids, + size_t physical_extruder_count, + int layer_id = -1); + +// Exclusion areas are stored in bed coordinates while generated support is +// shared in PrintObject coordinates. Return the conservative union transformed +// for every instance of the object. +ExPolygons active_bed_exclusion_footprints_for_object( + const PrintObject &object, + const std::vector> ®ions_by_extruder, + const std::vector &physical_extruders, + double z_min, + double z_max, + coord_t clearance = 0); + +} // namespace Slic3r diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index f6e3155efa..91f8535dfd 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -1,4 +1,5 @@ #include "ArcFitter.hpp" +#include #include "BoundingBox.hpp" #include "Circle.hpp" #include "Config.hpp" @@ -152,6 +153,53 @@ namespace fs = boost::filesystem; namespace Slic3r { +namespace { + +// Follow XY commands in a generated G-code block. This deliberately handles +// only standard motion/modal commands: an opaque macro that moves the head is +// already outside the position guarantees made by GCodeWriter. +std::optional emitted_xy_after_gcode(const std::string &gcode, const Vec2d &initial_xy) +{ + Vec2d position = initial_xy; + bool absolute = true; + bool coordinate_frame_known = true; + + GCodeReader reader; + reader.parse_buffer(gcode, [&position, &absolute, &coordinate_frame_known](GCodeReader &, const GCodeReader::GCodeLine &line) { + if (line.cmd_is("G90")) { + absolute = true; + return; + } + if (line.cmd_is("G91")) { + absolute = false; + return; + } + + const bool is_motion = line.cmd_is("G0") || line.cmd_is("G1") || line.cmd_is("G2") || line.cmd_is("G3"); + if (is_motion) { + if (line.has_x()) + position.x() = absolute ? line.x() : position.x() + line.x(); + if (line.has_y()) + position.y() = absolute ? line.y() : position.y() + line.y(); + return; + } + + // G92 changes the coordinate system without moving the machine, and + // G28 moves to a firmware-defined position. Do not invent a position + // if either command affects XY. + if (line.cmd_is("G92")) { + coordinate_frame_known = coordinate_frame_known && !line.has_x() && !line.has_y(); + } else if (line.cmd_is("G28")) { + const bool homes_all = !line.has_x() && !line.has_y() && !line.has_z(); + coordinate_frame_known = coordinate_frame_known && !homes_all && !line.has_x() && !line.has_y(); + } + }); + + return coordinate_frame_known ? std::optional(position) : std::nullopt; +} + +} // namespace + //! macro used to mark string used at localization, //! return same string #define L(s) (s) @@ -1056,6 +1104,9 @@ static std::vector get_path_of_change_filament(const Print& print) if (new_filament_id != -1 && new_filament_id != tcr.new_tool) throw Slic3r::InvalidArgument("Error: WipeTowerIntegration::append_tcr was asked to do a toolchange it didn't expect."); + const std::optional position_before_toolchange = + gcodegen.capture_toolchange_position(); + int new_extruder_id = get_extruder_index(*m_print_config, new_filament_id); // Logical nozzle grouping for this print (null on paths that don't populate it). @@ -1437,6 +1488,13 @@ static std::vector get_path_of_change_filament(const Print& print) // We have informed the m_writer about the current extruder_id, we can ignore the generated G-code. } + // The change G-code may move the carriage even when the incoming + // filament uses the same physical nozzle (the common AMS case). + // Synchronize before planning the tower-entry travel so exclusion + // avoidance starts from the emitted position, not the stale one. + if (position_before_toolchange) + gcodegen.synchronize_toolchange_position(*position_before_toolchange, toolchange_gcode_str); + if (need_travel_after_change_filament_gcode) { // move to start_pos for wiping after toolchange if (!is_used_travel_avoid_perimeter) { @@ -1585,6 +1643,8 @@ static std::vector get_path_of_change_filament(const Print& print) // Let the planner know we are traveling between objects. gcodegen.m_avoid_crossing_perimeters.use_external_mp_once(); + if (position_before_toolchange) + gcodegen.synchronize_toolchange_position(*position_before_toolchange, gcode); return gcode; } @@ -1596,6 +1656,9 @@ static std::vector get_path_of_change_filament(const Print& print) if (new_extruder_id != -1 && new_extruder_id != tcr.new_tool) throw Slic3r::InvalidArgument("Error: WipeTowerIntegration::append_tcr was asked to do a toolchange it didn't expect."); + const std::optional position_before_toolchange = + gcodegen.capture_toolchange_position(); + std::string gcode; // Toolchangeresult.gcode assumes the wipe tower corner is at the origin (except for priming lines) @@ -1880,6 +1943,8 @@ static std::vector get_path_of_change_filament(const Print& print) // Let the planner know we are traveling between objects. gcodegen.m_avoid_crossing_perimeters.use_external_mp_once(); + if (position_before_toolchange) + gcodegen.synchronize_toolchange_position(*position_before_toolchange, gcode); return gcode; } @@ -2757,6 +2822,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; @@ -2938,6 +3005,23 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessorResult* resu m_processor.result().nozzle_group_result = m_print->get_layered_nozzle_group_result(); m_processor.finalize(true); + if (m_processor.get_result().exclusion_volume_path_conflict) { + const int extruder_id = m_processor.get_result().exclusion_volume_conflict_extruder_id; + std::string warning = extruder_id >= 0 ? + Slic3r::format( + _(L("A G-code move intersects a collision volume for extruder %1%. This may cause a printer collision.")), + std::to_string(extruder_id + 1)) : + _(L("A G-code move intersects a collision volume. This may cause a printer collision.")); + if (m_processor.get_result().exclusion_volume_conflict_used_unknown_z) { + warning += "\n" + Slic3r::format( + _(L("The intersecting move is at G-code line %1%. Its Z position is unknown after homing, so Orca checked it against every height.")), + std::to_string(m_processor.get_result().exclusion_volume_conflict_gcode_id)); + } + print->active_step_add_warning( + PrintStateBase::WarningLevel::CRITICAL, + warning, + PrintStateBase::SlicingExclusionVolumeToolpath); + } // DoExport::update_print_estimated_times_stats(m_processor, print->m_print_statistics); DoExport::update_print_estimated_stats(m_processor, m_writer.extruders(), print->m_print_statistics, print->config()); // Printed-mass safety check. Flushed filament leaves the bed, so subtract it @@ -3020,6 +3104,7 @@ namespace DoExport { processor.initialize_from_context(nozzle_group_result); processor.initialize_result_moves(); processor.apply_config(config); + processor.configure_exclusion_volume_path_check(config); processor.enable_stealth_time_estimator(silent_time_estimator_enabled); } @@ -4449,6 +4534,17 @@ void GCode::_do_export(Print& print, GCodeOutputStream &file, ThumbnailsGenerato } } + // 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; @@ -5886,8 +5982,13 @@ std::string GCode::generate_object_skirt_group(const Print &print, object_skirt_tools, layer, extruder_id, m_skirt_group_done[group_idx]); } -std::string GCode::generate_object_brim(const Print &print, const PrintObject &object, size_t instance_id, bool first_layer, - const Layer *object_layer) +std::string GCode::generate_object_brim( + const Print &print, + const PrintObject &object, + const size_t instance_id, + const bool first_layer, + const unsigned int extruder_id, + const Layer *object_layer) { // Belt printers lay the brim onto the tilted belt over many layers, so there is // nothing special about the first one. The bands that coincide with an object @@ -5926,8 +6027,17 @@ std::string GCode::generate_object_brim(const Print &print, const PrintObject &o if (!first_layer) return {}; - auto emit_brim = [this](const ExtrusionEntityCollection& brim, const std::vector& instances) { + const bool wait_for_owner_filament = has_bed_exclude_volumes(m_config) && + active_bed_exclude_volume_mode(m_config) != BedExcludeVolumeMode::Shared; + auto emit_brim = [this, extruder_id, wait_for_owner_filament](const ExtrusionEntityCollection& brim, + const std::vector& instances, + const unsigned int brim_filament_id) { std::string gcode; + // Combined brims have an explicit owner filament. Waiting for that + // filament is only required when each nozzle has different obstacles. + // Otherwise retain Orca's established first-visit emission order. + if (wait_for_owner_filament && brim_filament_id != extruder_id) + return gcode; const bool already_emitted = std::none_of(instances.begin(), instances.end(), [this](const ObjectInstanceID& instance) { return m_objsWithBrim.find(instance) != m_objsWithBrim.end(); }); @@ -5952,7 +6062,7 @@ std::string GCode::generate_object_brim(const Print &print, const PrintObject &o std::string gcode; for (const Print::SkirtBrimGroup::Brim& brim : print.skirt_brim_groups()[group_idx].brims) if (std::find(brim.instances.begin(), brim.instances.end(), object_instance_id) != brim.instances.end()) - gcode += emit_brim(brim.brim, brim.instances); + gcode += emit_brim(brim.brim, brim.instances, brim.filament_id); return gcode; } @@ -7470,10 +7580,10 @@ LayerResult GCode::process_layer( // sweep below never re-emits it. if (extruder_id == (unsigned int)(vobj.belt_brim_filament() - 1) && belt_brim_emitted.insert({ instance_to_print.layer_id, instance_to_print.instance_id }).second) - gcode += generate_object_brim(print, vobj, instance_to_print.instance_id, first_layer, + gcode += generate_object_brim(print, vobj, instance_to_print.instance_id, first_layer, extruder_id, layer_to_print.object_layer); } else { - gcode += generate_object_brim(print, vobj, instance_to_print.instance_id, first_layer, + gcode += generate_object_brim(print, vobj, instance_to_print.instance_id, first_layer, extruder_id, layer_to_print.object_layer); } } @@ -8012,7 +8122,7 @@ LayerResult GCode::process_layer( continue; if (m_writer.filament() == nullptr || m_writer.filament()->id() != brim0) gcode += this->set_extruder(brim0, print_z); - gcode += generate_object_brim(print, *obj, instance_id, first_layer, ltp.object_layer); + gcode += generate_object_brim(print, *obj, instance_id, first_layer, brim0, ltp.object_layer); } } this->set_origin(saved_origin); @@ -8251,6 +8361,41 @@ void GCode::set_extruders(const std::vector &extruder_ids) } } +std::optional GCode::capture_toolchange_position() +{ + if (m_exclusion_volume_travel_avoidance.empty() || !m_last_pos_defined || m_writer.filament() == nullptr) + return std::nullopt; + + const Vec2d plate_offset = m_writer.get_xy_offset().cast(); + return ToolchangePositionState{ + this->point_to_gcode(m_last_pos.to_point()) - plate_offset + }; +} + +void GCode::synchronize_toolchange_position(const ToolchangePositionState &before, const std::string &emitted_gcode) +{ + if (m_writer.filament() == nullptr) + return; + + const std::optional emitted_xy = emitted_xy_after_gcode(emitted_gcode, before.emitted_xy); + if (!emitted_xy) + return; + + // GCodeWriter stores coordinates before applying the per-plate output + // offset. Convert the parsed file coordinates back into that space, then + // into model space using the newly active nozzle offset. + const Vec2d writer_xy = *emitted_xy + m_writer.get_xy_offset().cast(); + Vec3d writer_position = m_writer.get_position(); + writer_position.head<2>() = writer_xy; + m_writer.set_position(writer_position); + // Updating the known XY origin must not cancel Orca's deliberate + // post-toolchange Z restore. set_last_pos() normally marks the entire + // position as defined, so preserve the caller's state across the XY sync. + const bool last_pos_defined = m_last_pos_defined; + this->set_last_pos(this->gcode_to_point(writer_xy)); + m_last_pos_defined = last_pos_defined; +} + void GCode::set_origin(const Vec2d &pointf) { // if origin increases (goes towards right), last_pos decreases because it goes towards left @@ -10130,10 +10275,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; @@ -10143,6 +10295,66 @@ 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, + const bool include_planned_lift = false) { + if (m_exclusion_volume_travel_avoidance.empty() || path.size() < 2) + return false; + + const double target_z = z == DBL_MAX ? m_nominal_z : z; + double route_start_z = start_z_override.value_or(nominal_writer_z()); + double route_end_z = target_z; + if (include_planned_lift) { + const Vec2d destination_xy = this->point_to_gcode(path.back()); + std::tie(route_start_z, route_end_z) = m_writer.planned_travel_z( + Vec3d(destination_xy.x(), destination_xy.y(), target_z), + m_need_change_layer_lift_z); + } + const ExclusionVolumeTravelAvoidance::Result result = + m_exclusion_volume_travel_avoidance.route( + to_gcode_polyline(path), + route_start_z, + route_end_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; @@ -10208,6 +10420,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(); @@ -10223,16 +10443,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 - && m_layer != nullptr) { // A brim apron layer has no Layer to avoid crossing - // 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 && m_layer != nullptr) { // Belt brim apron layers have no Layer. + // 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, true) || + (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(); @@ -10264,6 +10490,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 @@ -10590,6 +10834,9 @@ std::string GCode::set_extruder(unsigned int new_filament_id, double print_z, bo if (!m_writer.need_toolchange(new_filament_id)) return ""; + const std::optional position_before_toolchange = + this->capture_toolchange_position(); + // if we are running a single-extruder setup, just set the extruder and return nothing if (!m_writer.multiple_extruders) { this->placeholder_parser().set("current_extruder", new_filament_id); @@ -10644,6 +10891,8 @@ std::string GCode::set_extruder(unsigned int new_filament_id, double print_z, bo gcode += toolchange_command; if (Extruder *fil = m_writer.filament()) fil->set_config_index((int)get_filament_config_index((int)fil->id())); + if (position_before_toolchange) + this->synchronize_toolchange_position(*position_before_toolchange, gcode); return gcode; } @@ -11060,6 +11309,8 @@ std::string GCode::set_extruder(unsigned int new_filament_id, double print_z, bo imex_pem_tool_for((int) new_filament_id, m_imex_parallel_mode, m_config.physical_extruder_map)); //Orca: tool changer or IDEX's firmware may change Z position, so we set it to unknown/undefined m_last_pos_defined = false; + if (position_before_toolchange) + this->synchronize_toolchange_position(*position_before_toolchange, gcode); return gcode; } diff --git a/src/libslic3r/GCode.hpp b/src/libslic3r/GCode.hpp index 38740abd7e..e9a346889a 100644 --- a/src/libslic3r/GCode.hpp +++ b/src/libslic3r/GCode.hpp @@ -14,6 +14,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" @@ -470,6 +471,7 @@ protected: const PrintObject &object, size_t instance_id, bool first_layer, + unsigned int extruder_id, const Layer *object_layer); // Belt printers: emit one brim-only apron layer. These print below the @@ -540,8 +542,16 @@ protected: 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(); @@ -766,6 +776,7 @@ protected: 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; bool m_timelapse_uses_pos{ false }; @@ -855,6 +866,18 @@ protected: Point3 m_last_pos; bool m_last_pos_defined; + struct ToolchangePositionState + { + Vec2d emitted_xy{Vec2d::Zero()}; + }; + + // Capture and restore the actual command-space position around a physical + // nozzle change. Model-space m_last_pos is tied to the active nozzle offset, + // while the machine position itself does not change when Tx is emitted. + std::optional capture_toolchange_position(); + void synchronize_toolchange_position(const ToolchangePositionState &before, + const std::string &emitted_gcode); + std::unique_ptr m_cooling_buffer; std::unique_ptr m_spiral_vase; std::unique_ptr m_pressure_equalizer; @@ -896,6 +919,10 @@ protected: // 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/ExclusionVolumePathCheck.cpp b/src/libslic3r/GCode/ExclusionVolumePathCheck.cpp new file mode 100644 index 0000000000..fbe3e6b465 --- /dev/null +++ b/src/libslic3r/GCode/ExclusionVolumePathCheck.cpp @@ -0,0 +1,234 @@ +#include "ExclusionVolumePathCheck.hpp" +#include "libslic3r/AABBTreeLines.hpp" +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/Line.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/PrintConfig.hpp" +#include +#include + +#include "libslic3r/Polygon.hpp" +#include "libslic3r/libslic3r.h" + +#include +#include +#include + +namespace Slic3r { + +namespace { + +constexpr double Z_EPSILON_MM = 1e-6; + +Point scaled_point(const Vec3d &point) +{ + return { scale_(point.x()), scale_(point.y()) }; +} + +BoundingBox line_bbox(const Point &a, const Point &b) +{ + BoundingBox bbox; + bbox.merge(a); + bbox.merge(b); + bbox.offset(SCALED_EPSILON); + return bbox; +} + +bool intervals_overlap(coord_t a_min, coord_t a_max, coord_t b_min, coord_t b_max) +{ + if (a_min > a_max) + std::swap(a_min, a_max); + if (b_min > b_max) + std::swap(b_min, b_max); + return std::max(a_min, b_min) <= std::min(a_max, b_max); +} + +bool collinear_segments_overlap(const Line &a, const Line &b) +{ + const Vec2crd a_dir = a.b - a.a; + if (a_dir == Vec2crd::Zero()) + return a.a == b.a || a.a == b.b; + + if (cross2(a_dir, b.a - a.a) != 0 || cross2(a_dir, b.b - a.a) != 0) + return false; + + return std::abs(a_dir.x()) >= std::abs(a_dir.y()) ? + intervals_overlap(a.a.x(), a.b.x(), b.a.x(), b.b.x()) : + intervals_overlap(a.a.y(), a.b.y(), b.a.y(), b.b.y()); +} + +bool overlaps_collinear_boundary(const Line &line, const Lines &edges) +{ + const BoundingBox line_bounds = line_bbox(line.a, line.b); + for (const Line &edge : edges) { + if (line_bounds.overlap(line_bbox(edge.a, edge.b)) && collinear_segments_overlap(line, edge)) + return true; + } + return false; +} + +bool clip_segment_to_z_range( + const Vec3d &from, + const Vec3d &to, + double z_min, + double z_max, + Vec3d &out_from, + Vec3d &out_to) +{ + const double segment_min_z = std::min(from.z(), to.z()); + const double segment_max_z = std::max(from.z(), to.z()); + if (segment_max_z < z_min - Z_EPSILON_MM || segment_min_z > z_max + Z_EPSILON_MM) + return false; + + double t0 = 0.0; + double t1 = 1.0; + const double dz = to.z() - from.z(); + if (std::abs(dz) < Z_EPSILON_MM) { + if (from.z() < z_min - Z_EPSILON_MM || from.z() > z_max + Z_EPSILON_MM) + return false; + } else { + const double z0 = (z_min - from.z()) / dz; + const double z1 = (z_max - from.z()) / dz; + t0 = std::max(t0, std::min(z0, z1)); + t1 = std::min(t1, std::max(z0, z1)); + if (t0 > t1 + Z_EPSILON_MM) + return false; + } + + t0 = std::clamp(t0, 0.0, 1.0); + t1 = std::clamp(t1, 0.0, 1.0); + const Vec3d delta = to - from; + out_from = from + t0 * delta; + out_to = from + t1 * delta; + return true; +} + +} // namespace + +void ExclusionVolumePathChecker::configure(const PrintConfig &config) +{ + clear(); + m_configured = true; + m_extruder_offsets = config.extruder_offset.values; + + const std::vector> regions = + get_bed_excluded_regions_by_extruder(config); + m_regions_by_extruder.resize(regions.size()); + if (m_extruder_offsets.size() < regions.size()) + m_extruder_offsets.resize(regions.size(), Vec2d::Zero()); + + for (size_t extruder_id = 0; extruder_id < regions.size(); ++extruder_id) { + std::vector &prepared = m_regions_by_extruder[extruder_id]; + prepared.reserve(regions[extruder_id].size()); + for (const BedExcludeRegion ®ion : regions[extruder_id]) { + // Legacy excluded areas are material keep-outs. Some stock profiles + // deliberately move the nozzle into them (for example, a cutter), so + // only explicitly configured collision volumes constrain motion. + if (!region.is_collision_volume() || region.polygon.points.size() < 3 || region.z_max < region.z_min) + continue; + + PreparedRegion item; + item.region = region; + item.bbox = BoundingBox(region.polygon.points); + item.bbox.offset(SCALED_EPSILON); + item.edge_tree = AABBTreeLines::LinesDistancer(to_lines(region.polygon)); + prepared.emplace_back(std::move(item)); + } + } +} + +void ExclusionVolumePathChecker::clear() +{ + m_configured = false; + m_extruder_offsets.clear(); + m_regions_by_extruder.clear(); + m_result = {}; +} + +bool ExclusionVolumePathChecker::segment_intersects_region( + const Vec3d &from, + const Vec3d &to, + const bool z_known, + const PreparedRegion ®ion) const +{ + Vec3d clipped_from = from; + Vec3d clipped_to = to; + if (z_known && !clip_segment_to_z_range( + from, to, region.region.z_min, region.region.z_max, clipped_from, clipped_to)) + return false; + + const Point a = scaled_point(clipped_from); + const Point b = scaled_point(clipped_to); + if (!line_bbox(a, b).overlap(region.bbox)) + return false; + + if (region.region.polygon.contains(a) || region.region.polygon.contains(b)) + return true; + if (a == b) + return false; + + const Line line(a, b); + if (!region.edge_tree.intersections_with_line(line).empty()) + return true; + + // The line tree intentionally omits collinear intersections. + return overlaps_collinear_boundary(line, region.edge_tree.get_lines()); +} + +void ExclusionVolumePathChecker::check_motion( + const Vec3d &from, + const Vec3d &to, + const bool start_xy_known, + const bool end_xy_known, + const bool start_z_known, + const bool end_z_known, + const int active_extruder_id, + const ExclusionVolumeMotionType motion_type, + const unsigned char source_move_type, + const unsigned int gcode_id, + const size_t move_id) +{ + if (!m_configured || m_result.has_any_conflict || !start_xy_known || !end_xy_known || + m_regions_by_extruder.empty()) + return; + + const bool z_known = start_z_known && end_z_known; + const bool active_extruder_valid = + active_extruder_id >= 0 && size_t(active_extruder_id) < m_regions_by_extruder.size(); + const size_t first_extruder = active_extruder_valid ? size_t(active_extruder_id) : 0; + const size_t last_extruder = active_extruder_valid ? first_extruder + 1 : m_regions_by_extruder.size(); + + for (size_t extruder_id = first_extruder; extruder_id < last_extruder; ++extruder_id) { + const Vec2d offset = extruder_id < m_extruder_offsets.size() ? + m_extruder_offsets[extruder_id] : Vec2d::Zero(); + Vec3d model_from = from; + Vec3d model_to = to; + model_from.head<2>() += offset; + model_to.head<2>() += offset; + + const std::vector ®ions = m_regions_by_extruder[extruder_id]; + for (size_t region_id = 0; region_id < regions.size(); ++region_id) { + if (!segment_intersects_region(model_from, model_to, z_known, regions[region_id])) + continue; + + m_result.has_any_conflict = true; + m_result.has_travel_conflict = motion_type == ExclusionVolumeMotionType::Travel; + m_result.has_extrusion_conflict = motion_type == ExclusionVolumeMotionType::Extrude; + m_result.has_other_motion_conflict = motion_type == ExclusionVolumeMotionType::Other; + m_result.first_hit = ExclusionVolumePathHit{ + move_id, + gcode_id, + motion_type, + source_move_type, + int(extruder_id), + region_id, + model_from, + model_to, + !z_known + }; + return; + } + } +} + +} // namespace Slic3r diff --git a/src/libslic3r/GCode/ExclusionVolumePathCheck.hpp b/src/libslic3r/GCode/ExclusionVolumePathCheck.hpp new file mode 100644 index 0000000000..af94ef0076 --- /dev/null +++ b/src/libslic3r/GCode/ExclusionVolumePathCheck.hpp @@ -0,0 +1,90 @@ +#pragma once + +#include "libslic3r/AABBTreeLines.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/Line.hpp" +#include "libslic3r/PrintConfig.hpp" + +#include +#include +#include + +namespace Slic3r { + +enum class ExclusionVolumeMotionType : unsigned char +{ + Travel, + Extrude, + Other +}; + +struct ExclusionVolumePathHit +{ + size_t move_id { 0 }; + unsigned int gcode_id { 0 }; + ExclusionVolumeMotionType motion_type { ExclusionVolumeMotionType::Other }; + unsigned char source_move_type { 0 }; + int extruder_id { -1 }; + size_t region_id { 0 }; + Vec3d from { Vec3d::Zero() }; + Vec3d to { Vec3d::Zero() }; + bool used_unknown_z { false }; +}; + +struct ExclusionVolumePathCheckResult +{ + bool has_any_conflict { false }; + bool has_travel_conflict { false }; + bool has_extrusion_conflict { false }; + bool has_other_motion_conflict { false }; + std::optional first_hit; +}; + +// Checks G-code coordinates as they are parsed. Exclusion regions are expressed +// in nozzle/model space, so each candidate physical extruder offset is applied +// before testing a motion. This keeps the checker independent of preview +// vertices, whose extruder_id field represents a filament rather than a nozzle. +class ExclusionVolumePathChecker +{ +public: + void configure(const PrintConfig &config); + void clear(); + + bool configured() const { return m_configured; } + const ExclusionVolumePathCheckResult &result() const { return m_result; } + + void check_motion( + const Vec3d &from, + const Vec3d &to, + bool start_xy_known, + bool end_xy_known, + bool start_z_known, + bool end_z_known, + int active_extruder_id, + ExclusionVolumeMotionType motion_type, + unsigned char source_move_type, + unsigned int gcode_id, + size_t move_id); + +private: + struct PreparedRegion + { + BedExcludeRegion region; + BoundingBox bbox; + AABBTreeLines::LinesDistancer edge_tree; + }; + + bool segment_intersects_region( + const Vec3d &from, + const Vec3d &to, + bool z_known, + const PreparedRegion ®ion) const; + + bool m_configured { false }; + std::vector m_extruder_offsets; + std::vector> m_regions_by_extruder; + ExclusionVolumePathCheckResult m_result; +}; + +} // namespace Slic3r diff --git a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp new file mode 100644 index 0000000000..5f702ccdec --- /dev/null +++ b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp @@ -0,0 +1,672 @@ +#include "ExclusionVolumeTravelAvoidance.hpp" +#include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/libslic3r.h" +#include +#include +#include + +#include "libslic3r/ClipperUtils.hpp" +#include "libslic3r/ExclusionVolumeGeometry.hpp" +#include "libslic3r/Line.hpp" +#include "libslic3r/Polygon.hpp" + +#include +#include +#include +#include + +namespace Slic3r { + +namespace { + +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 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 routed_polyline_inside_bed( + const Polyline &polyline, + const ExPolygons &valid_bed, + const bool allow_start_outside, + const bool allow_end_outside) +{ + if (valid_bed.empty()) + return true; + + const size_t last_idx = polyline.points.size() - 1; + for (size_t idx = 0; idx < polyline.points.size(); ++idx) { + if ((idx == 0 && allow_start_outside) || (idx == last_idx && allow_end_outside)) + continue; + if (!point_in_expolygons(valid_bed, polyline.points[idx], true)) + return false; + } + + for (size_t idx = 1; idx < polyline.points.size(); ++idx) { + // A start or end produced by machine G-code may legitimately lie on + // or beyond the printable boundary. Constrain only the route vertices + // Orca adds; the firmware-defined transition to the bed remains intact. + if ((idx == 1 && allow_start_outside) || (idx == last_idx && allow_end_outside)) + continue; + 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 bool allow_start_outside, + const bool allow_end_outside) +{ + 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 = routed_polyline_inside_bed( + forward, valid_bed, allow_start_outside, allow_end_outside); + const bool backward_bed_valid = routed_polyline_inside_bed( + backward, valid_bed, allow_start_outside, allow_end_outside); + 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(); + + 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); + + 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]); + space.regions.erase(std::remove_if(space.regions.begin(), space.regions.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }), space.regions.end()); + + 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); + BoundingBox bbox(region.polygon.points); + bbox.offset(m_clearance); + space.region_bboxes.emplace_back(std::move(bbox)); + } + + Polygon bed_shape = base_bed_shape; + bed_shape.translate(translation); + bed_shape.make_counter_clockwise(); + if (bed_shape.points.size() >= 3) { + space.valid_bed = offset_ex(bed_shape, -float(m_clearance)); + if (space.valid_bed.empty()) + space.valid_bed = union_ex(Polygons { std::move(bed_shape) }); + } + } +} + +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(); + }); +} + +const ExPolygons * +ExclusionVolumeTravelAvoidance::active_obstacles( + RoutingSpace &space, + double z_min, + double z_max) +{ + std::vector active_region_ids; + active_region_ids.reserve(space.regions.size()); + for (size_t region_id = 0; region_id < space.regions.size(); ++region_id) { + const BedExcludeRegion ®ion = space.regions[region_id]; + if (bed_exclusion_z_ranges_overlap(z_min, z_max, region.z_min, region.z_max)) + active_region_ids.emplace_back(region_id); + } + if (active_region_ids.empty()) + return nullptr; + + const auto cached = space.obstacle_cache.find(active_region_ids); + if (cached != space.obstacle_cache.end()) + return cached->second.empty() ? nullptr : &cached->second; + + std::vector active_regions; + active_regions.reserve(active_region_ids.size()); + for (const size_t region_id : active_region_ids) + active_regions.emplace_back(space.regions[region_id]); + + ExPolygons obstacles = active_bed_exclusion_footprints( + active_regions, z_min, z_max, Point(0, 0), m_clearance); + const auto cache_result = space.obstacle_cache.emplace( + std::move(active_region_ids), std::move(obstacles)); + return cache_result.first->second.empty() ? nullptr : &cache_result.first->second; +} + +ExclusionVolumeTravelAvoidance::Result ExclusionVolumeTravelAvoidance::route( + const Polyline &travel, + double start_z, + double end_z, + int extruder_id) +{ + 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; + } + + 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); + + // Most travels are nowhere near an exclusion. Reject them using the cheap + // precomputed boxes before unioning and inflating obstacle polygons. + const BoundingBox travel_bbox(travel.points); + bool has_active_z = false; + bool may_intersect = false; + for (size_t region_id = 0; region_id < space.regions.size(); ++region_id) { + const BedExcludeRegion ®ion = space.regions[region_id]; + if (!bed_exclusion_z_ranges_overlap(z_min, z_max, region.z_min, region.z_max)) + continue; + has_active_z = true; + if (region_id < space.region_bboxes.size() && space.region_bboxes[region_id].overlap(travel_bbox)) { + may_intersect = true; + break; + } + } + if (!has_active_z) { + result.detail = Detail::NoActiveObstacles; + return result; + } + if (!may_intersect) { + result.detail = Detail::NoIntersection; + return result; + } + + const ExPolygons *active = active_obstacles(space, z_min, z_max); + if (active == nullptr || active->empty()) { + result.detail = Detail::NoActiveObstacles; + return result; + } + result.active_obstacles = active->size(); + + const Point &start = travel.points.front(); + const Point &end = travel.points.back(); + const bool start_outside_bed = !space.valid_bed.empty() && + !point_in_expolygons(space.valid_bed, start, true); + const bool end_outside_bed = !space.valid_bed.empty() && + !point_in_expolygons(space.valid_bed, end, true); + const ExPolygons *start_obstacles = active_obstacles(space, start_z, start_z); + const ExPolygons *end_obstacles = active_obstacles(space, end_z, end_z); + if ((start_obstacles != nullptr && point_in_expolygons_interior(*start_obstacles, start)) || + (end_obstacles != nullptr && point_in_expolygons_interior(*end_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)) { + 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]; + const bool allow_a_outside = start_outside_bed && segment_idx == 0; + const bool allow_b_outside = end_outside_bed && segment_idx + 2 == path.points.size(); + const Polyline segment({a, b}); + if (!routed_polyline_inside_bed( + segment, space.valid_bed, allow_a_outside, allow_b_outside)) { + result.status = Status::Failed; + result.detail = Detail::SegmentOutsideBed; + return result; + } + + const std::optional obstacle_idx = first_intersected_obstacle(a, b, *active); + if (!obstacle_idx) + continue; + + const std::optional detour = detour_around_obstacle( + a, b, (*active)[*obstacle_idx], *active, space.valid_bed, + allow_a_outside, allow_b_outside); + 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, space.valid_bed); + if (!routed_polyline_inside_bed( + path, space.valid_bed, start_outside_bed, end_outside_bed) || + polyline_intersects_obstacles(path, *active)) { + 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..64dca94865 --- /dev/null +++ b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp @@ -0,0 +1,78 @@ +#pragma once + +#include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/libslic3r.h" +#include "libslic3r/BoundingBox.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); + +private: + struct RoutingSpace + { + std::vector regions; + std::vector region_bboxes; + ExPolygons valid_bed; + std::map, ExPolygons> obstacle_cache; + }; + + const ExPolygons *active_obstacles( + RoutingSpace &space, + double z_min, + double z_max); + + std::vector m_spaces; + coord_t m_clearance { 0 }; +}; + +} // namespace Slic3r diff --git a/src/libslic3r/GCode/GCodeProcessor.cpp b/src/libslic3r/GCode/GCodeProcessor.cpp index 5c8257f74f..ba22abf4a0 100644 --- a/src/libslic3r/GCode/GCodeProcessor.cpp +++ b/src/libslic3r/GCode/GCodeProcessor.cpp @@ -1,4 +1,5 @@ #include "libslic3r/ArcFitter.hpp" +#include "ExclusionVolumePathCheck.hpp" #include "libslic3r/Config.hpp" #include "libslic3r/CustomGCode.hpp" #include "libslic3r/Exception.hpp" @@ -2682,6 +2683,17 @@ void GCodeProcessorResult::reset() { wrapping_exclude_area = Pointfs(); //BBS: add toolpath_outside toolpath_outside = false; + exclusion_volume_path_checked = false; + exclusion_volume_path_conflict = false; + exclusion_volume_travel_conflict = false; + exclusion_volume_extrusion_conflict = false; + exclusion_volume_other_motion_conflict = false; + exclusion_volume_conflict_gcode_id = 0; + exclusion_volume_conflict_move_id = 0; + exclusion_volume_conflict_move_type = EMoveType::Noop; + exclusion_volume_conflict_extruder_id = -1; + exclusion_volume_conflict_region_id = 0; + exclusion_volume_conflict_used_unknown_z = false; //BBS: add label_object_enabled label_object_enabled = false; long_retraction_when_cut = false; @@ -3704,6 +3716,10 @@ void GCodeProcessor::reset() m_start_position = { 0.0f, 0.0f, 0.0f, 0.0f }; m_end_position = { 0.0f, 0.0f, 0.0f, 0.0f }; m_origin = { 0.0f, 0.0f, 0.0f, 0.0f }; + m_axis_position_known = { false, false, false }; + m_axis_origin_known = { true, true, true }; + m_processing_homing_move = false; + m_exclusion_volume_path_checker.clear(); m_cached_position.reset(); m_wiping = false; m_flushing = false; @@ -3916,6 +3932,40 @@ void GCodeProcessor::process_buffer(const std::string &buffer) }); } +void GCodeProcessor::configure_exclusion_volume_path_check(const PrintConfig &config) +{ + m_exclusion_volume_path_checker.configure(config); +} + +GCodeProcessor::PositionState GCodeProcessor::get_current_position() const +{ + PositionState state; + state.position = Vec3d(m_end_position[X], m_end_position[Y], m_end_position[Z]); + state.axis_known = m_axis_position_known; + return state; +} + +void GCodeProcessor::update_exclusion_volume_path_check_result() +{ + m_result.exclusion_volume_path_checked = m_exclusion_volume_path_checker.configured(); + const ExclusionVolumePathCheckResult &check = m_exclusion_volume_path_checker.result(); + m_result.exclusion_volume_path_conflict = check.has_any_conflict; + m_result.exclusion_volume_travel_conflict = check.has_travel_conflict; + m_result.exclusion_volume_extrusion_conflict = check.has_extrusion_conflict; + m_result.exclusion_volume_other_motion_conflict = check.has_other_motion_conflict; + + if (!check.first_hit) + return; + + const ExclusionVolumePathHit &hit = *check.first_hit; + m_result.exclusion_volume_conflict_gcode_id = hit.gcode_id; + m_result.exclusion_volume_conflict_move_id = hit.move_id; + m_result.exclusion_volume_conflict_move_type = static_cast(hit.source_move_type); + m_result.exclusion_volume_conflict_extruder_id = hit.extruder_id; + m_result.exclusion_volume_conflict_region_id = hit.region_id; + m_result.exclusion_volume_conflict_used_unknown_z = hit.used_unknown_z; +} + void GCodeProcessor::finalize(bool post_process) { m_result.z_offset = m_z_offset; @@ -3956,6 +4006,7 @@ void GCodeProcessor::finalize(bool post_process) if (m_enable_pre_heating) run_second_pass_injection(); } + update_exclusion_volume_path_check_result(); //BBS: update slice warning update_slice_warnings(); } @@ -5110,6 +5161,30 @@ void GCodeProcessor::process_G0(const GCodeReader::GCodeLine& line) process_G1(line); } +void GCodeProcessor::update_position_known_from_move( + const std::array, 4> &axes, + const G1DiscretizationOrigin origin) +{ + if (origin != G1DiscretizationOrigin::G1 || m_global_positioning_type != EPositioningType::Absolute) + return; + + for (unsigned char axis = X; axis <= Z; ++axis) { + if (axes[axis].has_value()) + m_axis_position_known[axis] = m_axis_origin_known[axis]; + } +} + +void GCodeProcessor::update_position_known_from_move(const GCodeReader::GCodeLine &line) +{ + if (m_global_positioning_type != EPositioningType::Absolute) + return; + + for (unsigned char axis = X; axis <= Z; ++axis) { + if (line.has(static_cast(axis))) + m_axis_position_known[axis] = m_axis_origin_known[axis]; + } +} + void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line, const std::optional& remaining_internal_g1_lines) { std::array, 4> g1_axes = { std::nullopt, std::nullopt, std::nullopt, std::nullopt }; @@ -5133,6 +5208,7 @@ void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line, const std::o void GCodeProcessor::process_G1(const std::array, 4>& axes, const std::optional& feedrate, G1DiscretizationOrigin origin, const std::optional& remaining_internal_g1_lines) { + const std::array start_axis_known = m_axis_position_known; int filament_id = get_filament_id(); int last_filament_id = get_last_filament_id(); float filament_diameter = (static_cast(filament_id) < m_result.filament_diameters.size()) ? m_result.filament_diameters[filament_id] : m_result.filament_diameters.back(); @@ -5182,6 +5258,7 @@ void GCodeProcessor::process_G1(const std::array, 4>& axes for (unsigned char a = X; a <= E; ++a) { m_end_position[a] = extract_absolute_position_on_axis((Axis)a, axes[a], double(area_filament_cross_section)); } + update_position_known_from_move(axes, origin); // updates feedrate from line, if present if (feedrate.has_value()) @@ -5203,6 +5280,40 @@ void GCodeProcessor::process_G1(const std::array, 4>& axes const float delta_xyz = std::sqrt(sqr(delta_pos[X]) + sqr(delta_pos[Y]) + sqr(delta_pos[Z])); m_travel_dist = delta_xyz; + if (!m_processing_homing_move) { + std::optional exclusion_motion_type; + switch (type) { + case EMoveType::Travel: + exclusion_motion_type = ExclusionVolumeMotionType::Travel; + break; + case EMoveType::Extrude: + case EMoveType::Wipe: + exclusion_motion_type = ExclusionVolumeMotionType::Extrude; + break; + case EMoveType::Retract: + case EMoveType::Unretract: + exclusion_motion_type = ExclusionVolumeMotionType::Other; + break; + default: + break; + } + + if (exclusion_motion_type) { + m_exclusion_volume_path_checker.check_motion( + Vec3d(m_start_position[X], m_start_position[Y], m_start_position[Z]), + Vec3d(m_end_position[X], m_end_position[Y], m_end_position[Z]), + start_axis_known[X] && start_axis_known[Y], + m_axis_position_known[X] && m_axis_position_known[Y], + start_axis_known[Z], + m_axis_position_known[Z], + get_extruder_id(false), + *exclusion_motion_type, + static_cast(type), + m_line_id, + m_result.moves.size()); + } + } + if (type == EMoveType::Extrude) { float volume_extruded_filament = area_filament_cross_section * delta_pos[E]; float area_toolpath_cross_section = volume_extruded_filament / delta_xyz; @@ -6238,6 +6349,10 @@ void GCodeProcessor::process_G2_G3(const GCodeReader::GCodeLine& line, bool cloc m_start_position = m_end_position; // this is required because we are skipping the call to process_gcode_line() internal_only_g1_line(adjust_target(end_position, prev_target), arc.delta_z() != 0.0, (segments == 1) ? feedrate : std::nullopt, extrusion); } + + // Internal linearized arc segments inherit the arc's starting certainty. + // Only the original absolute command may establish a newly known endpoint. + update_position_known_from_move(line); } //BBS @@ -6311,22 +6426,56 @@ void GCodeProcessor::process_G23(const GCodeReader::GCodeLine& line) store_move_vertex(EMoveType::Unretract); } +static std::array g28_homed_axes(const GCodeReader::GCodeLine &line) +{ + std::array homed { false, false, false }; + std::string_view raw = line.raw(); + const size_t command_end = raw.find_first_of(" \t;"); + size_t pos = command_end == std::string_view::npos ? raw.size() : command_end; + + while (pos < raw.size()) { + pos = raw.find_first_not_of(" \t", pos); + if (pos == std::string_view::npos || raw[pos] == ';') + break; + const size_t end = raw.find_first_of(" \t;", pos); + const std::string_view word = raw.substr(pos, end == std::string_view::npos ? raw.size() - pos : end - pos); + + const bool compact_axes = !word.empty() && std::all_of(word.begin(), word.end(), [](const char c) { + const char upper = static_cast(std::toupper(static_cast(c))); + return upper == 'X' || upper == 'Y' || upper == 'Z'; + }); + if (compact_axes) { + for (const char c : word) + homed[static_cast(std::toupper(static_cast(c)) - 'X')] = true; + } else if (!word.empty()) { + const char axis = static_cast(std::toupper(static_cast(word.front()))); + const bool numeric_axis_word = word.size() > 1 && + (std::isdigit(static_cast(word[1])) || word[1] == '+' || word[1] == '-' || word[1] == '.'); + if (axis >= 'X' && axis <= 'Z' && numeric_axis_word) + homed[static_cast(axis - 'X')] = true; + } + + if (end == std::string_view::npos || raw[end] == ';') + break; + pos = end; + } + return homed; +} + void GCodeProcessor::process_G28(const GCodeReader::GCodeLine& line) { std::string_view cmd = line.cmd(); std::string new_line_raw = { cmd.data(), cmd.size() }; - bool found = false; - if (line.has('X')) { + const std::array homed = g28_homed_axes(line); + const bool found = std::any_of(homed.begin(), homed.end(), [](const bool value) { return value; }); + if (homed[X]) { new_line_raw += " X0"; - found = true; } - if (line.has('Y')) { + if (homed[Y]) { new_line_raw += " Y0"; - found = true; } - if (line.has('Z')) { + if (homed[Z]) { new_line_raw += " Z0"; - found = true; } if (!found) new_line_raw += " X0 Y0 Z0"; @@ -6334,7 +6483,19 @@ void GCodeProcessor::process_G28(const GCodeReader::GCodeLine& line) GCodeReader::GCodeLine new_gline; GCodeReader reader; reader.parse_line(new_line_raw, [&](GCodeReader& reader, const GCodeReader::GCodeLine& gline) { new_gline = gline; }); + m_processing_homing_move = true; process_G1(new_gline); + m_processing_homing_move = false; + + // G28's physical endpoint is printer-specific even though the preview uses + // zero. Wait for a subsequent explicit absolute coordinate before checking + // a path from any homed axis. + for (unsigned char axis = X; axis <= Z; ++axis) { + if (!found || homed[axis]) { + m_axis_position_known[axis] = false; + m_axis_origin_known[axis] = true; + } + } } void GCodeProcessor::process_G90(const GCodeReader::GCodeLine& line) @@ -6353,16 +6514,19 @@ void GCodeProcessor::process_G92(const GCodeReader::GCodeLine& line) bool any_found = false; if (line.has_x()) { + m_axis_origin_known[X] = m_axis_position_known[X]; m_origin[X] = m_end_position[X] - line.x() * lengths_scale_factor; any_found = true; } if (line.has_y()) { + m_axis_origin_known[Y] = m_axis_position_known[Y]; m_origin[Y] = m_end_position[Y] - line.y() * lengths_scale_factor; any_found = true; } if (line.has_z()) { + m_axis_origin_known[Z] = m_axis_position_known[Z]; m_origin[Z] = m_end_position[Z] - line.z() * lengths_scale_factor; any_found = true; // Belt only: the start G-code's purge-blob advance + G92 Z0 resets leave a constant @@ -6387,6 +6551,8 @@ void GCodeProcessor::process_G92(const GCodeReader::GCodeLine& line) // The G92 may be called for axes that PrusaSlicer does not recognize, for example see GH issue #3510, // where G92 A0 B0 is called although the extruder axis is till E. for (unsigned char a = X; a <= E; ++a) { + if (a <= Z) + m_axis_origin_known[a] = m_axis_position_known[a]; m_origin[a] = m_end_position[a]; } } diff --git a/src/libslic3r/GCode/GCodeProcessor.hpp b/src/libslic3r/GCode/GCodeProcessor.hpp index 64902bd045..151faa10cb 100644 --- a/src/libslic3r/GCode/GCodeProcessor.hpp +++ b/src/libslic3r/GCode/GCodeProcessor.hpp @@ -13,6 +13,7 @@ #include "libslic3r/PrintConfig.hpp" #include "libslic3r/CustomGCode.hpp" #include "libslic3r/MultiNozzleUtils.hpp" +#include "libslic3r/GCode/ExclusionVolumePathCheck.hpp" #include "libslic3r/GCode/MachineFrameTransform.hpp" #include @@ -326,6 +327,17 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f; std::vector extruder_heights; //BBS: add toolpath_outside bool toolpath_outside; + bool exclusion_volume_path_checked { false }; + bool exclusion_volume_path_conflict { false }; + bool exclusion_volume_travel_conflict { false }; + bool exclusion_volume_extrusion_conflict { false }; + bool exclusion_volume_other_motion_conflict { false }; + unsigned int exclusion_volume_conflict_gcode_id { 0 }; + size_t exclusion_volume_conflict_move_id { 0 }; + EMoveType exclusion_volume_conflict_move_type { EMoveType::Noop }; + int exclusion_volume_conflict_extruder_id { -1 }; + size_t exclusion_volume_conflict_region_id { 0 }; + bool exclusion_volume_conflict_used_unknown_z { false }; //BBS: add object_label_enabled bool label_object_enabled; //BBS : extra retraction when change filament,experiment func @@ -412,6 +424,17 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f; bed_exclude_area = std::forward(other).bed_exclude_area; wrapping_exclude_area = std::forward(other).wrapping_exclude_area; toolpath_outside = std::forward(other).toolpath_outside; + exclusion_volume_path_checked = other.exclusion_volume_path_checked; + exclusion_volume_path_conflict = other.exclusion_volume_path_conflict; + exclusion_volume_travel_conflict = other.exclusion_volume_travel_conflict; + exclusion_volume_extrusion_conflict = other.exclusion_volume_extrusion_conflict; + exclusion_volume_other_motion_conflict = other.exclusion_volume_other_motion_conflict; + exclusion_volume_conflict_gcode_id = other.exclusion_volume_conflict_gcode_id; + exclusion_volume_conflict_move_id = other.exclusion_volume_conflict_move_id; + exclusion_volume_conflict_move_type = other.exclusion_volume_conflict_move_type; + exclusion_volume_conflict_extruder_id = other.exclusion_volume_conflict_extruder_id; + exclusion_volume_conflict_region_id = other.exclusion_volume_conflict_region_id; + exclusion_volume_conflict_used_unknown_z = other.exclusion_volume_conflict_used_unknown_z; label_object_enabled = std::forward(other).label_object_enabled; long_retraction_when_cut = std::forward(other).long_retraction_when_cut; timelapse_warning_code = std::forward(other).timelapse_warning_code; @@ -1206,6 +1229,10 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f; AxisCoords m_start_position; // mm AxisCoords m_end_position; // mm AxisCoords m_origin; // mm + std::array m_axis_position_known { false, false, false }; + std::array m_axis_origin_known { true, true, true }; + bool m_processing_homing_move { false }; + ExclusionVolumePathChecker m_exclusion_volume_path_checker; CachedPosition m_cached_position; bool m_wiping; bool m_flushing; // mark a section with real flush @@ -1355,6 +1382,15 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f; static unsigned int s_result_id; public: + struct PositionState + { + Vec3d position { Vec3d::Zero() }; + std::array axis_known { false, false, false }; + + bool has_known_xy() const { return axis_known[X] && axis_known[Y]; } + bool has_known_z() const { return axis_known[Z]; } + }; + GCodeProcessor(); void init_filament_maps_and_nozzle_type_when_import_only_gcode(); // Reprocessing an already-generated g-code (from-previous / imported g-code) does not rebuild @@ -1372,6 +1408,7 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f; const std::vector &filament_map, const std::vector>& unprintable_filament_types ); void apply_config(const PrintConfig& config); + void configure_exclusion_volume_path_check(const PrintConfig &config); void set_print(Print* print) { m_print = print; } // Locates extrusions in the objects and bodies it numbers, those objects listed beforehand. void set_mass_locator(MassLocator locator, std::vector objects) @@ -1398,6 +1435,7 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f; const GCodeProcessorResult& get_result() const { return m_result; } GCodeProcessorResult& result() { return m_result; } GCodeProcessorResult&& extract_result() { return std::move(m_result); } + PositionState get_current_position() const; // Load a G-code into a stand-alone G-code viewer. // throws CanceledException through print->throw_if_canceled() (sent by the caller as callback). @@ -1456,6 +1494,9 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f; void process_G1(const std::array, 4>& axes = { std::nullopt, std::nullopt, std::nullopt, std::nullopt }, const std::optional& feedrate = std::nullopt, G1DiscretizationOrigin origin = G1DiscretizationOrigin::G1, const std::optional& remaining_internal_g1_lines = std::nullopt); + void update_position_known_from_move(const std::array, 4> &axes, G1DiscretizationOrigin origin); + void update_position_known_from_move(const GCodeReader::GCodeLine &line); + void update_exclusion_volume_path_check_result(); // Arc Move void process_G2_G3(const GCodeReader::GCodeLine& line, bool clockwise); diff --git a/src/libslic3r/GCode/TimelapsePosPicker.cpp b/src/libslic3r/GCode/TimelapsePosPicker.cpp index 84b6677b94..2c18895d9a 100644 --- a/src/libslic3r/GCode/TimelapsePosPicker.cpp +++ b/src/libslic3r/GCode/TimelapsePosPicker.cpp @@ -98,9 +98,10 @@ namespace Slic3r { m_plate_height = unscale_(bed_bbox.max.y()); m_plate_width = unscale_(bed_bbox.max.x()); - Polygon bed_exclude_area; - for (size_t idx = 0; idx < config.bed_exclude_area.values.size(); ++idx) - bed_exclude_area.points.emplace_back(coord_t(scale_(config.bed_exclude_area.values[idx].x())), coord_t(scale_(config.bed_exclude_area.values[idx].y()))); + // Timelapse positions are selected in the bed plane. Use the resolved + // bed-level footprints instead of the legacy flat point array, which + // cannot represent multiple or per-nozzle exclusion polygons. + const Polygons bed_exclude_areas = get_bed_excluded_area(config); Point base_wp_pt = print->get_fake_wipe_tower().pos.cast(); base_wp_pt = Point{ scale_(base_wp_pt.x()),scale_(base_wp_pt.y()) }; @@ -120,7 +121,7 @@ namespace Slic3r { wipe_tower_area = expand_object_projection(wipe_tower_area, m_print_seq == PrintSequence::ByObject); for (size_t idx = 0; idx < extruder_count; ++idx) { - ExPolygons printable_area = diff_ex(diff(m_bed_polygon, bed_exclude_area), { wipe_tower_area }); + ExPolygons printable_area = diff_ex(diff(Polygons{ m_bed_polygon }, bed_exclude_areas), { wipe_tower_area }); if (idx < config.extruder_printable_area.size()) { Polygon extruder_printable_area; for (size_t j = 0; j < config.extruder_printable_area.values[idx].size(); ++j) @@ -681,4 +682,4 @@ namespace Slic3r { return true; } -} \ No newline at end of file +} diff --git a/src/libslic3r/GCodeWriter.cpp b/src/libslic3r/GCodeWriter.cpp index 805e6e2f52..617fc2ce54 100644 --- a/src/libslic3r/GCodeWriter.cpp +++ b/src/libslic3r/GCodeWriter.cpp @@ -1140,6 +1140,19 @@ std::string GCodeWriter::travel_to_xyz(const Vec3d &point, const std::string &co return out_string; } +std::pair GCodeWriter::planned_travel_z(const Vec3d &point, const bool force_z) const +{ + double destination_z = point.z(); + if (std::abs(m_to_lift) > EPSILON) { + if ((!this->is_current_position_clear() || m_pos != point) && + m_to_lift + m_pos.z() > point.z()) + destination_z = m_to_lift + m_pos.z(); + } else if (!force_z && !this->will_move_z(point.z())) { + destination_z = m_pos.z(); + } + return { m_pos.z(), destination_z }; +} + std::string GCodeWriter::travel_to_z(double z, const std::string &comment, bool force) { /* If target Z is lower than current Z but higher than nominal Z diff --git a/src/libslic3r/GCodeWriter.hpp b/src/libslic3r/GCodeWriter.hpp index fcbd68b282..02562fa651 100644 --- a/src/libslic3r/GCodeWriter.hpp +++ b/src/libslic3r/GCodeWriter.hpp @@ -97,6 +97,9 @@ public: double get_current_speed() const { return m_current_speed;} std::string travel_to_xy(const Vec2d &point, const std::string &comment = std::string()); std::string travel_to_xyz(const Vec3d &point, const std::string &comment = std::string(), bool force_z = false); + // Physical Z range which travel_to_xyz() will emit without mutating writer state. + // This includes an existing lift or a pending lazy lift. + std::pair planned_travel_z(const Vec3d &point, bool force_z = false) const; std::string travel_to_z(double z, const std::string &comment = std::string(), bool force = false); bool will_move_z(double z) const; std::string extrude_to_xy(const Vec2d &point, double dE, const std::string &comment = std::string(), bool force_no_extrusion = false); diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index aea1b2be36..c4cff42a64 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -17,6 +17,7 @@ #include "SLA/SupportPoint.hpp" #include "TextureDisplacement.hpp" #include "libslic3r.h" +#include "AABBTreeIndirect.hpp" #include "BuildVolume.hpp" #include "TexturePainting.hpp" #include "Format/AssimpImport.hpp" @@ -29,6 +30,7 @@ #include "TriangleMeshSlicer.hpp" #include "TriangleSelector.hpp" #include "MaterialType.hpp" +#include "Tesselate.hpp" #include "MeshRepair.hpp" #include "Format/AMF.hpp" @@ -39,6 +41,7 @@ #include "FaceDetector.hpp" #include "libslic3r/Geometry/ConvexHull.hpp" +#include "ClipperUtils.hpp" #include #include @@ -61,6 +64,7 @@ #include "SVG.hpp" #include +#include #include #include #include @@ -3241,6 +3245,9 @@ void Model::setPrintSpeedTable(const DynamicPrintConfig& config, const PrintConf //auto print_config = print.config(); //printSpeedMap.bed_poly.points = get_bed_shape(*(wxGetApp().plater()->config())); printSpeedMap.bed_poly.points = get_bed_shape(config); + // Collision volumes are additive to the legacy bed keep-out. Preserve the + // established printable-bed polygon so bed-edge and legacy-area brim + // clipping continue to work when collision volumes are also configured. Pointfs excluse_area_points = print_config.bed_exclude_area.values; Polygons exclude_polys; Polygon exclude_poly; @@ -3252,7 +3259,8 @@ void Model::setPrintSpeedTable(const DynamicPrintConfig& config, const PrintConf exclude_poly.points.clear(); } } - printSpeedMap.bed_poly = diff({ printSpeedMap.bed_poly }, exclude_polys)[0]; + if (!exclude_polys.empty()) + printSpeedMap.bed_poly = diff({ printSpeedMap.bed_poly }, exclude_polys)[0]; } // find temperature of heatend and bed and matierial of an given extruder @@ -3548,6 +3556,316 @@ Polygon ModelInstance::convex_hull_2d() return convex_hull; } +namespace { + +struct ExclusionPrismFootprintTriangle +{ + std::array vertices; + Vec2d min = Vec2d::Zero(); + Vec2d max = Vec2d::Zero(); +}; + +static double cross_2d(const Vec2d &a, const Vec2d &b) +{ + return a.x() * b.y() - a.y() * b.x(); +} + +template +static std::vector clip_polygon_by_signed_distance(const std::vector &input, DistanceFn distance) +{ + constexpr double clip_epsilon = 1e-8; + constexpr double duplicate_epsilon_sq = 1e-16; + + std::vector output; + if (input.empty()) + return output; + + auto append_point = [&output](const Vec3d &point) { + if (output.empty() || (output.back() - point).squaredNorm() > duplicate_epsilon_sq) + output.emplace_back(point); + }; + + Vec3d prev = input.back(); + double prev_distance = distance(prev); + bool prev_inside = prev_distance >= -clip_epsilon; + for (const Vec3d &curr : input) { + const double curr_distance = distance(curr); + const bool curr_inside = curr_distance >= -clip_epsilon; + + if (curr_inside != prev_inside) { + const double denom = prev_distance - curr_distance; + if (std::abs(denom) > clip_epsilon) { + const double t = prev_distance / denom; + append_point(prev + t * (curr - prev)); + } + } + if (curr_inside) + append_point(curr); + + prev = curr; + prev_distance = curr_distance; + prev_inside = curr_inside; + } + + if (output.size() > 1 && (output.front() - output.back()).squaredNorm() <= duplicate_epsilon_sq) + output.pop_back(); + + return output; +} + +static std::vector triangulated_prism_footprints(const Polygon &polygon) +{ + std::vector out; + if (polygon.points.size() < 3) + return out; + + ExPolygon expolygon; + expolygon.contour = polygon; + expolygon.contour.make_counter_clockwise(); + + std::vector triangles = triangulate_expolygon_2d(expolygon, NORMALS_UP); + if (triangles.empty()) { + triangles.reserve((polygon.points.size() - 2) * 3); + const Vec2d first(unscale(polygon.points.front().x()), unscale(polygon.points.front().y())); + for (size_t i = 1; i + 1 < polygon.points.size(); ++i) { + triangles.emplace_back(first); + triangles.emplace_back(unscale(polygon.points[i].x()), unscale(polygon.points[i].y())); + triangles.emplace_back(unscale(polygon.points[i + 1].x()), unscale(polygon.points[i + 1].y())); + } + } + + out.reserve(triangles.size() / 3); + for (size_t i = 0; i + 2 < triangles.size(); i += 3) { + ExclusionPrismFootprintTriangle tri; + tri.vertices = { triangles[i], triangles[i + 1], triangles[i + 2] }; + + const double area = cross_2d(tri.vertices[1] - tri.vertices[0], tri.vertices[2] - tri.vertices[0]); + if (std::abs(area) <= EPSILON) + continue; + if (area < 0.0) + std::swap(tri.vertices[1], tri.vertices[2]); + + tri.min = tri.vertices[0].cwiseMin(tri.vertices[1]).cwiseMin(tri.vertices[2]); + tri.max = tri.vertices[0].cwiseMax(tri.vertices[1]).cwiseMax(tri.vertices[2]); + out.emplace_back(std::move(tri)); + } + + return out; +} + +static bool triangle_bbox_intersects_prism_footprint(const Vec3d &p0, const Vec3d &p1, const Vec3d &p2, const ExclusionPrismFootprintTriangle &footprint) +{ + constexpr double bbox_epsilon = 1e-8; + const double tri_min_x = std::min({ p0.x(), p1.x(), p2.x() }); + const double tri_max_x = std::max({ p0.x(), p1.x(), p2.x() }); + const double tri_min_y = std::min({ p0.y(), p1.y(), p2.y() }); + const double tri_max_y = std::max({ p0.y(), p1.y(), p2.y() }); + + return tri_max_x >= footprint.min.x() - bbox_epsilon && + tri_min_x <= footprint.max.x() + bbox_epsilon && + tri_max_y >= footprint.min.y() - bbox_epsilon && + tri_min_y <= footprint.max.y() + bbox_epsilon; +} + +static std::vector clip_model_triangle_to_prism( + const Vec3d &p0, + const Vec3d &p1, + const Vec3d &p2, + const double z_min, + const double z_max, + const ExclusionPrismFootprintTriangle &footprint) +{ + std::vector clipped = { p0, p1, p2 }; + clipped = clip_polygon_by_signed_distance(clipped, [z_min](const Vec3d &p) { return p.z() - z_min; }); + clipped = clip_polygon_by_signed_distance(clipped, [z_max](const Vec3d &p) { return z_max - p.z(); }); + + for (size_t i = 0; i < footprint.vertices.size() && clipped.size() >= 3; ++i) { + const Vec2d &a = footprint.vertices[i]; + const Vec2d &b = footprint.vertices[(i + 1) % footprint.vertices.size()]; + const Vec2d edge = b - a; + clipped = clip_polygon_by_signed_distance(clipped, [a, edge](const Vec3d &p) { + return cross_2d(edge, Vec2d(p.x() - a.x(), p.y() - a.y())); + }); + } + + return clipped; +} + +static double polygon_3d_area2(const std::vector &polygon) +{ + if (polygon.size() < 3) + return 0.0; + + Vec3d normal = Vec3d::Zero(); + for (size_t i = 1; i + 1 < polygon.size(); ++i) + normal += (polygon[i] - polygon.front()).cross(polygon[i + 1] - polygon.front()); + return normal.norm(); +} + +static void append_clipped_polygon(indexed_triangle_set &out, const std::vector &polygon) +{ + if (polygon.size() < 3) + return; + + // Do not reserve exact capacity here. This helper may be called for many + // clipped fragments, so let std::vector grow amortized through emplace_back. + const int base = int(out.vertices.size()); + for (const Vec3d &point : polygon) + out.vertices.emplace_back(point.cast()); + + for (size_t i = 1; i + 1 < polygon.size(); ++i) { + stl_triangle_vertex_indices tri; + tri << base, base + int(i), base + int(i + 1); + out.indices.emplace_back(tri); + } +} + +static bool mesh_contains_point_linear(const indexed_triangle_set &its, const Vec3d &point) +{ + constexpr double ray_epsilon = 1e-6; + const Vec3d ray_direction = Vec3d::UnitX(); + double nearest_hit_distance = std::numeric_limits::infinity(); + size_t nearest_face = size_t(-1); + + for (size_t face_id = 0; face_id < its.indices.size(); ++face_id) { + const stl_triangle_vertex_indices &face = its.indices[face_id]; + double distance; + double u; + double v; + if (AABBTreeIndirect::detail::intersect_triangle( + point, ray_direction, + its.vertices[face[0]], its.vertices[face[1]], its.vertices[face[2]], + distance, u, v, ray_epsilon) && + distance > 0.0 && distance < nearest_hit_distance) { + nearest_hit_distance = distance; + nearest_face = face_id; + } + } + + // This matches AABBMesh::hit_result::is_inside(): for a consistently + // oriented closed mesh, the nearest face points along a ray leaving it. + return nearest_face != size_t(-1) && + its_unnormalized_normal(its, nearest_face).cast().dot(ray_direction) > 0.0; +} + +} // namespace + +bool ModelInstance::intersects_bed_exclude_region(const BedExcludeRegion ®ion, indexed_triangle_set *intersection_mesh) const +{ + // With no output mesh this is a fast yes/no test and returns on the first + // hit. With an output mesh it collects all clipped fragments for the red + // GUI intersection preview. + if (intersection_mesh != nullptr) + intersection_mesh->clear(); + + if (region.polygon.points.size() < 3) + return false; + + double z_min = region.z_min; + double z_max = region.z_max; + if (z_min > z_max) + std::swap(z_min, z_max); + if (z_max <= z_min + EPSILON) + return false; + + const std::vector footprints = triangulated_prism_footprints(region.polygon); + if (footprints.empty()) + return false; + + bool intersects = false; + const ModelObject *model_object = get_object(); + const Transform3d instance_matrix = get_matrix(); + + for (const ModelVolume *volume : model_object->volumes) { + if (! volume->is_model_part()) + continue; + + const indexed_triangle_set &its = volume->mesh().its; + if (its.vertices.empty() || its.indices.empty()) + continue; + + const Transform3d volume_matrix = instance_matrix * volume->get_matrix(); + bool volume_surface_intersects = false; + for (const stl_triangle_vertex_indices &face : its.indices) { + const Vec3d p0 = volume_matrix * its.vertices[face[0]].cast(); + const Vec3d p1 = volume_matrix * its.vertices[face[1]].cast(); + const Vec3d p2 = volume_matrix * its.vertices[face[2]].cast(); + + const double tri_min_z = std::min({ p0.z(), p1.z(), p2.z() }); + const double tri_max_z = std::max({ p0.z(), p1.z(), p2.z() }); + if (tri_max_z < z_min || tri_min_z > z_max) + continue; + + for (const ExclusionPrismFootprintTriangle &footprint : footprints) { + if (! triangle_bbox_intersects_prism_footprint(p0, p1, p2, footprint)) + continue; + + std::vector clipped = clip_model_triangle_to_prism(p0, p1, p2, z_min, z_max, footprint); + if (polygon_3d_area2(clipped) <= 1e-8) + continue; + + volume_surface_intersects = true; + intersects = true; + if (intersection_mesh == nullptr) + return true; + + append_clipped_polygon(*intersection_mesh, clipped); + } + } + + if (!volume_surface_intersects && !intersects) { + // Surface clipping cannot detect a prism wholly enclosed by a + // solid. In that topology, with no boundary crossing, one point + // inside the connected prism is sufficient to test containment. + const ExclusionPrismFootprintTriangle &footprint = footprints.front(); + const Vec2d probe_xy = (footprint.vertices[0] + footprint.vertices[1] + footprint.vertices[2]) / 3.0; + const Vec3d probe_world(probe_xy.x(), probe_xy.y(), z_min + 0.5 * (z_max - z_min)); + const Vec3d probe_local = volume_matrix.inverse() * probe_world; + + // A linear ray scan keeps this one-off fallback O(n) without + // adding ray tests to the usual surface-intersection path. + if (volume->mesh().bounding_box().contains(probe_local) && mesh_contains_point_linear(its, probe_local)) { + intersects = true; + if (intersection_mesh == nullptr) + return true; + } + } + } + + return intersects; +} + +bool ModelInstance::intersects_bed_exclude_regions( + const std::vector ®ions, + indexed_triangle_set *intersection_mesh) const +{ + if (intersection_mesh != nullptr) + intersection_mesh->clear(); + if (regions.empty()) + return false; + + const Polygon hull = const_cast(this)->convex_hull_2d(); + bool intersects = false; + for (const BedExcludeRegion ®ion : regions) { + if (intersection(Polygons{ region.polygon }, Polygons{ hull }).empty()) + continue; + + if (intersection_mesh == nullptr) { + if (intersects_bed_exclude_region(region)) + return true; + continue; + } + + indexed_triangle_set region_intersection; + if (intersects_bed_exclude_region(region, ®ion_intersection)) { + intersects = true; + if (!region_intersection.empty()) + its_merge(*intersection_mesh, region_intersection); + } + } + return intersects; +} + //BBS: invalidate instance's convex_hull_2d void ModelInstance::invalidate_convex_hull_2d() { diff --git a/src/libslic3r/Model.hpp b/src/libslic3r/Model.hpp index ea0a02cbe0..6d9797ff67 100644 --- a/src/libslic3r/Model.hpp +++ b/src/libslic3r/Model.hpp @@ -1519,6 +1519,8 @@ public: double get_auto_brim_width() const; // BBS Polygon convex_hull_2d(); + bool intersects_bed_exclude_region(const BedExcludeRegion ®ion, indexed_triangle_set *intersection_mesh = nullptr) const; + bool intersects_bed_exclude_regions(const std::vector ®ions, indexed_triangle_set *intersection_mesh = nullptr) const; void invalidate_convex_hull_2d(); // Getting the input polygon for arrange diff --git a/src/libslic3r/ModelArrange.cpp b/src/libslic3r/ModelArrange.cpp index c5c952577c..3db5d38258 100644 --- a/src/libslic3r/ModelArrange.cpp +++ b/src/libslic3r/ModelArrange.cpp @@ -192,8 +192,11 @@ ArrangePolygon get_instance_arrange_poly(ModelInstance* instance, const Slic3r:: ap.has_tree_support = true; } - auto size = obj->instance_convex_hull_bounding_box(instance).size(); - ap.height = size.z(); + const BoundingBoxf3 bbox = obj->instance_convex_hull_bounding_box(instance); + ap.height = bbox.size().z(); + ap.z_min = bbox.min.z(); + ap.z_max = bbox.max.z(); + ap.has_z_range = bbox.defined; ap.name = obj->name; return ap; } diff --git a/src/libslic3r/Preset.cpp b/src/libslic3r/Preset.cpp index 81b78ec092..40a3385371 100644 --- a/src/libslic3r/Preset.cpp +++ b/src/libslic3r/Preset.cpp @@ -1575,6 +1575,7 @@ static std::vector s_Preset_printer_options { "belt_frame_tilt_decouple", "belt_frame_tilt_angle", "belt_support_floor_offset", "enable_belt_purge_tower", + "bed_exclude_volumes", "bed_exclude_volume_mode", "extruder_bed_exclude_volumes", "gcode_flavor", "gcode_skip_config_block", "fan_kickstart", "part_cooling_fan_min_pwm", "fan_speedup_time", "fan_speedup_overhangs", "single_extruder_multi_material", "manual_filament_change", "file_start_gcode", "machine_start_gcode", "machine_end_gcode", "before_layer_change_gcode", "printing_by_object_gcode", "layer_change_gcode", "time_lapse_gcode", "wrapping_detection_gcode", "change_filament_gcode", "change_extrusion_role_gcode", diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 78e6ad4277..38c250c0ac 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -61,6 +61,7 @@ #include "BoundingBox.hpp" #include "Brim.hpp" #include "ClipperUtils.hpp" +#include "ExclusionVolumeGeometry.hpp" #include "Extruder.hpp" #include "FilamentMixer.hpp" #include "Flow.hpp" @@ -87,6 +88,7 @@ #include #include #include +#include #include #include #include @@ -127,6 +129,98 @@ template class PrintState; PrintRegion::PrintRegion(const PrintRegionConfig &config) : PrintRegion(config, config.hash()) {} PrintRegion::PrintRegion(PrintRegionConfig &&config) : PrintRegion(std::move(config), config.hash()) {} +static std::vector translated_bed_exclusion_volumes(const Print &print) +{ + std::vector regions = get_bed_excluded_regions(print.config()); + const Point print_origin(scale_(print.get_plate_origin().x()), scale_(print.get_plate_origin().y())); + + for (BedExcludeRegion ®ion : regions) + region.polygon.translate(print_origin); + + return regions; +} + +static std::vector> translated_bed_exclusion_volumes_by_extruder(const Print &print) +{ + std::vector> regions_by_extruder = get_bed_excluded_regions_by_extruder(print.config()); + const Point print_origin(scale_(print.get_plate_origin().x()), scale_(print.get_plate_origin().y())); + for (std::vector ®ions : regions_by_extruder) + for (BedExcludeRegion ®ion : regions) + region.polygon.translate(print_origin); + return regions_by_extruder; +} + +struct BedExclusionCollision +{ + size_t extruder_id; + bool collision_volume; +}; + +static bool intersects_bed_exclusion_purpose( + const ModelInstance &instance, + const std::vector ®ions, + const bool collision_volume) +{ + return std::any_of(regions.begin(), regions.end(), [&](const BedExcludeRegion ®ion) { + return region.is_collision_volume() == collision_volume && + instance.intersects_bed_exclude_region(region); + }); +} + +static std::optional colliding_bed_exclusion( + const Print &print, + const PrintObject &print_object, + const ModelInstance &instance, + const std::vector> ®ions_by_extruder) +{ + if (regions_by_extruder.empty()) + return std::nullopt; + + // The legacy area is shared by every nozzle. Report it with Orca's + // established wording even when opt-in collision volumes coexist. + if (intersects_bed_exclusion_purpose(instance, regions_by_extruder.front(), false)) + return BedExclusionCollision{ 0, false }; + + const bool automatic = is_auto_filament_map_mode(print.get_filament_map_mode()); + if (automatic && print.is_BBL_printer()) { + // Bambu automatic grouping owns the concrete filament assignment and + // the config starts with a non-authoritative [1, 1, ...] seed. Its + // geometric-unprintable input steers individual filaments away from + // colliding nozzles; validation only blocks an object when no nozzle + // can print it. + std::optional first_collision; + for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { + if (!intersects_bed_exclusion_purpose(instance, regions_by_extruder[extruder_id], true)) + return std::nullopt; + if (!first_collision.has_value()) + first_collision = extruder_id; + } + return first_collision.has_value() ? + std::optional(BedExclusionCollision{ *first_collision, true }) : std::nullopt; + } + + for (const unsigned int filament_id : print_object.printing_extruders()) { + const int resolved_extruder = bed_exclusion_extruder_for_filament( + filament_id, print.get_filament_maps(), print.get_filament_map_mode(), print.is_BBL_printer(), + true, regions_by_extruder.size()); + if (resolved_extruder < 0) + continue; + const size_t extruder_id = size_t(resolved_extruder); + if (intersects_bed_exclusion_purpose(instance, regions_by_extruder[extruder_id], true)) + return BedExclusionCollision{ extruder_id, true }; + } + return std::nullopt; +} + +static Polygons full_height_bed_exclusion_polygons(const std::vector ®ions) +{ + Polygons out; + for (const BedExcludeRegion ®ion : regions) + if (! region.has_z_range) + out.emplace_back(region.polygon); + return out; +} + //BBS // ORCA: Now this is a parameter //float Print::min_skirt_length = 0; @@ -187,8 +281,6 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n "reduce_crossing_wall", "max_travel_detour_distance", "printable_area", - //BBS: add bed_exclude_area - "bed_exclude_area", "thumbnail_size", "before_layer_change_gcode", "enable_pressure_advance", @@ -212,7 +304,6 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n "extruder_clearance_radius", "nozzle_height", "extruder_colour", - "extruder_offset", "filament_flow_ratio", "reduce_fan_stop_start_freq", "dont_slow_down_outer_wall", @@ -337,13 +428,27 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n }; static std::unordered_set steps_ignore; + static const std::unordered_set steps_exclusion_geometry = { + "bed_exclude_area", + "bed_exclude_volumes", + "bed_exclude_volume_mode", + "extruder_bed_exclude_volumes", + "extruder_offset" + }; std::vector steps; std::vector osteps; bool invalidated = false; for (const t_config_option_key &opt_key : opt_keys) { - if (steps_gcode.find(opt_key) != steps_gcode.end()) { + if (steps_exclusion_geometry.find(opt_key) != steps_exclusion_geometry.end()) { + // Exclusions are consumed while generating brims, support, tree + // support and wipe-tower geometry, not only during final export. + steps.emplace_back(psWipeTower); + steps.emplace_back(psSkirtBrim); + osteps.emplace_back(posSupportMaterial); + osteps.emplace_back(posSimplifySupportPath); + } else if (steps_gcode.find(opt_key) != steps_gcode.end()) { // These options only affect G-code export or they are just notes without influence on the generated G-code, // so there is nothing to invalidate. steps.emplace_back(psGCodeExport); @@ -787,10 +892,8 @@ StringObjectException Print::sequential_print_clearance_valid(const Print &print { StringObjectException single_object_exception; const auto& print_config = print.config(); - Polygons exclude_polys = get_bed_excluded_area(print_config); const Vec3d print_origin = print.get_plate_origin(); - std::for_each(exclude_polys.begin(), exclude_polys.end(), - [&print_origin](Polygon& p) { p.translate(scale_(print_origin.x()), scale_(print_origin.y())); }); + const std::vector> exclusion_volumes = translated_bed_exclusion_volumes_by_extruder(print); struct print_instance_info { @@ -841,22 +944,24 @@ StringObjectException Print::sequential_print_clearance_valid(const Print &print // Convert the shift from the PrintObject's coordinates into ModelObject's coordinates by removing the centering offset. convex_hull.translate(instance.shift - print_object->center_offset()); } - convex_hull_no_offset.translate(instance.shift - print_object->center_offset()); - //juedge the exclude area - if (!intersection(exclude_polys, convex_hull_no_offset).empty()) { + const std::optional exclusion_collision = colliding_bed_exclusion( + print, *print_object, *instance.model_instance, exclusion_volumes); + if (exclusion_collision.has_value()) { + const std::string collision_message = !exclusion_collision->collision_volume ? + (boost::format(L("%1% is too close to exclusion area. There may be collisions when printing.")) % instance.model_instance->get_object()->name).str() : + is_auto_filament_map_mode(print.get_filament_map_mode()) && print.is_BBL_printer() ? + (boost::format(L("%1% intersects collision volumes for every available extruder.")) % instance.model_instance->get_object()->name).str() : + (boost::format(L("%1% intersects a collision volume for extruder %2%.")) % instance.model_instance->get_object()->name % (exclusion_collision->extruder_id + 1)).str(); if (single_object_exception.string.empty()) { - single_object_exception.string = (boost::format(L("%1% is too close to exclusion area. There may be collisions when printing.")) %instance.model_instance->get_object()->name).str(); + single_object_exception.string = collision_message; // single_object_exception.object = instance.model_instance->get_object(); //ORCA: Pass ModelInstance instead of ModelObject single_object_exception.object = instance.model_instance; } else { - single_object_exception.string += "\n"+(boost::format(L("%1% is too close to exclusion area. There may be collisions when printing.")) %instance.model_instance->get_object()->name).str(); + single_object_exception.string += "\n" + collision_message; single_object_exception.object = nullptr; } - //if (polygons) { - // intersecting_idxs.emplace_back(convex_hulls_other.size()); - //} } // if output needed, collect indices (inside convex_hulls_other) of intersecting hulls @@ -1480,10 +1585,9 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, return {}; const auto& print_config = print.config(); - Polygons exclude_polys = get_bed_excluded_area(print_config); const Vec3d print_origin = print.get_plate_origin(); - std::for_each(exclude_polys.begin(), exclude_polys.end(), - [&print_origin](Polygon& p) { p.translate(scale_(print_origin.x()), scale_(print_origin.y())); }); + const std::vector> exclusion_volumes = translated_bed_exclusion_volumes_by_extruder(print); + const Polygons prime_tower_exclude_polys = full_height_bed_exclusion_polygons(translated_bed_exclusion_volumes(print)); Pointfs wrapping_detection_area = print_config.wrapping_exclude_area.values; Polygon wrapping_poly; @@ -1503,14 +1607,6 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, inst->model_instance->get_scaling_factor(), inst->model_instance->get_mirror())); volume_hull.translate(inst->shift - inst->print_object->center_offset()); - if (!intersection(exclude_polys, volume_hull).empty()) { - // return {inst->model_instance->get_object()->name + L(" is too close to exclusion area, there may be collisions when printing.") + "\n", - // inst->model_instance->get_object()}; - //ORCA: Pass ModelInstance instead of ModelObject - return {(boost::format(L("%1% is too close to exclusion area. There may be collisions when printing.")) % inst->model_instance->get_object()->name).str() + "\n", - inst->model_instance}; - } - if (print_config.enable_wrapping_detection.value && !intersection(wrapping_poly, volume_hull).empty()) { // return {inst->model_instance->get_object()->name + L(" is too close to clumping detection area, there may be collisions when printing.") + "\n", // inst->model_instance->get_object()}; @@ -1520,6 +1616,15 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, } current_instance_hulls.emplace_back(volume_hull); } + if (const std::optional exclusion_collision = colliding_bed_exclusion( + print, *inst->print_object, *inst->model_instance, exclusion_volumes); exclusion_collision.has_value()) { + const std::string message = !exclusion_collision->collision_volume ? + (boost::format(L("%1% is too close to exclusion area. There may be collisions when printing.")) % inst->model_instance->get_object()->name).str() : + is_auto_filament_map_mode(print.get_filament_map_mode()) && print.is_BBL_printer() ? + (boost::format(L("%1% intersects collision volumes for every available extruder.")) % inst->model_instance->get_object()->name).str() : + (boost::format(L("%1% intersects a collision volume for extruder %2%.")) % inst->model_instance->get_object()->name % (exclusion_collision->extruder_id + 1)).str(); + return {message + "\n", inst->model_instance}; + } if (!intersection(convex_hulls_other, current_instance_hulls).empty()) { if (warning) { @@ -1603,13 +1708,13 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, warning->string += L("Prime tower is too close to others, and collisions may be caused.\n"); } } - if (!intersection(exclude_polys, tower_polys_checked).empty()) { + if (!intersection(prime_tower_exclude_polys, tower_polys_checked).empty()) { return {L("Prime tower is too close to an exclusion area, and collisions will be caused.\n")}; } if (print_config.enable_wrapping_detection.value && !intersection({wrapping_poly}, tower_polys_checked).empty()) { return {L("Prime tower is too close to the clumping detection area, and collisions will be caused.\n")}; } - if (warning && !intersection(exclude_polys, tower_polys_estimated).empty()) { + if (warning && !intersection(prime_tower_exclude_polys, tower_polys_estimated).empty()) { warning->string += L("Prime tower is too close to an exclusion area. There may be collisions when printing.") + "\n"; } if (warning && print_config.enable_wrapping_detection.value && !intersection({wrapping_poly}, tower_polys_estimated).empty()) { @@ -3724,7 +3829,11 @@ void Print::process(long long *time_cost_with_cache, bool use_cache) // Orca: Build both the old object-keyed brim map and the per-instance // maps used by skirt/brim groups. m_brimMap.clear(); + m_brimFilamentMap.clear(); m_brimMapByInstance.clear(); + for (const auto& [object_id, filament] : objPrintVec) + if (filament > 0) + m_brimFilamentMap.emplace(object_id, filament - 1); m_first_layer_convex_hull.points.clear(); if (this->has_brim()) { Polygons islands_area; @@ -4152,7 +4261,22 @@ void Print::_make_skirt() } } - auto make_brims_for_skirt_brim_group = [this](const std::vector& group_instances) { + std::vector> brim_exclusion_regions; + if (has_bed_exclude_volumes(m_config)) { + brim_exclusion_regions = translated_bed_exclusion_volumes_by_extruder(*this); + for (std::vector ®ions : brim_exclusion_regions) + regions.erase(std::remove_if(regions.begin(), regions.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }), regions.end()); + } + const bool has_brim_exclusions = std::any_of( + brim_exclusion_regions.begin(), brim_exclusion_regions.end(), + [](const std::vector ®ions) { return !regions.empty(); }); + const bool has_nozzle_specific_brim_exclusions = has_brim_exclusions && + active_bed_exclude_volume_mode(m_config) != BedExcludeVolumeMode::Shared; + + auto make_brims_for_skirt_brim_group = + [this, &brim_exclusion_regions, has_nozzle_specific_brim_exclusions] + (const std::vector& group_instances) { std::vector brims; std::vector brim_instances; for (const ObjectInstanceID& instance : group_instances) { @@ -4161,10 +4285,31 @@ void Print::_make_skirt() brim_instances.push_back(instance); } + auto brim_filament = [this](const ObjectInstanceID& instance) -> std::optional { + const auto it = m_brimFilamentMap.find(instance.object_id); + return it == m_brimFilamentMap.end() ? std::nullopt : + std::optional(it->second); + }; + auto compatible_brim_nozzles = + [this, &brim_filament, &brim_exclusion_regions, has_nozzle_specific_brim_exclusions] + (const ObjectInstanceID& first, const ObjectInstanceID& second) { + if (!has_nozzle_specific_brim_exclusions) + return true; + const std::optional first_filament = brim_filament(first); + const std::optional second_filament = brim_filament(second); + return first_filament.has_value() && second_filament.has_value() && + bed_exclusion_physical_extruders( + *this, { *first_filament, *second_filament }, + brim_exclusion_regions.size(), 0).size() == 1; + }; + const bool combine_group_brims = m_config.combine_brims && brim_instances.size() > 1; if (!combine_group_brims) { - for (const ObjectInstanceID& instance : brim_instances) - brims.push_back({ m_brimMapByInstance.at(instance), { instance } }); + for (const ObjectInstanceID& instance : brim_instances) { + const std::optional filament = brim_filament(instance); + if (filament.has_value()) + brims.push_back({ m_brimMapByInstance.at(instance), { instance }, *filament }); + } return brims; } @@ -4192,6 +4337,7 @@ void Print::_make_skirt() for (size_t j = i + 1; j < brim_instances.size(); ++j) { const auto area_j = m_objectBrimAreasByInstance.find(brim_instances[j]); if (area_j != m_objectBrimAreasByInstance.end() && + compatible_brim_nozzles(brim_instances[i], brim_instances[j]) && !intersection_ex(offset_ex(area_i->second, brim_contact_distance, jtRound, SCALED_RESOLUTION), area_j->second).empty()) unite_brims(i, j); } @@ -4202,9 +4348,12 @@ void Print::_make_skirt() combined_brim_ids[find_brim_parent(i)].push_back(brim_instances[i]); for (const auto& [_, instances] : combined_brim_ids) { + const std::optional filament = brim_filament(instances.front()); + if (!filament.has_value()) + continue; if (instances.size() == 1) { const ObjectInstanceID& instance = instances.front(); - brims.push_back({ m_brimMapByInstance.at(instance), { instance } }); + brims.push_back({ m_brimMapByInstance.at(instance), { instance }, *filament }); continue; } @@ -4216,8 +4365,26 @@ void Print::_make_skirt() const float brim_cleanup_delta = std::max(scaled_resolution, float(SCALED_EPSILON)); combined_area = offset2_ex(combined_area, brim_cleanup_delta, -brim_cleanup_delta, jtRound, scaled_resolution); + // The group has one known physical nozzle. Clip after union and + // cleanup so the geometry consumed by path generation remains + // valid for the exact filament recorded on the combined brim. + const std::vector physical_extruders = bed_exclusion_physical_extruders( + *this, { *filament }, brim_exclusion_regions.size(), 0); + const coord_t width_spacing_delta = std::max( + 0, brim_flow().scaled_width() - brim_flow().scaled_spacing()); + const coord_t exclusion_clearance = + (width_spacing_delta + 1) / 2 + coord_t(SCALED_EPSILON); + const ExPolygons exclusions = active_bed_exclusion_footprints( + brim_exclusion_regions, physical_extruders, 0.0, + std::max(0.0, skirt_first_layer_height()), Point(0, 0), exclusion_clearance); + if (!exclusions.empty()) + combined_area = diff_ex(combined_area, exclusions); + if (combined_area.empty()) + continue; + Polygons islands_area; - brims.push_back({ makeBrimInfillFromPlateCoordinates(combined_area, *this, islands_area), instances }); + brims.push_back({ makeBrimInfillFromPlateCoordinates(combined_area, *this, islands_area), + instances, *filament }); } return brims; @@ -5542,6 +5709,7 @@ void Print::export_gcode_from_previous_file(const std::string& file, GCodeProces // (via ensure_nozzle_group_result), so the multi-nozzle send/monitor mapping survives here. if (result != nullptr && result->nozzle_group_result) processor.initialize_from_context(result->nozzle_group_result); + processor.configure_exclusion_volume_path_check(this->config()); //processor.enable_producers(true); processor.process_file(file); diff --git a/src/libslic3r/Print.hpp b/src/libslic3r/Print.hpp index b36349c587..8d214da02a 100644 --- a/src/libslic3r/Print.hpp +++ b/src/libslic3r/Print.hpp @@ -516,6 +516,7 @@ public: // returns 0-based indices of extruders used to print the object (without brim, support and other helper extrusions) std::vector object_extruders() const; + std::vector printing_extruders() const; // Called by make_perimeters() void slice(); @@ -1156,6 +1157,8 @@ public: struct Brim { ExtrusionEntityCollection brim; std::vector instances; + // Zero-based logical filament selected when the brim was planned. + unsigned int filament_id { unsigned(-1) }; }; ExtrusionEntityCollection skirt; @@ -1511,6 +1514,8 @@ private: bool m_has_shared_per_object_skirt { false }; // Orca: Object-keyed brim paths kept for existing code. std::map m_brimMap; + // Zero-based logical filament selected for each object's brim. + std::map m_brimFilamentMap; // Orca: Actual brim paths keyed by object instance. std::map m_brimMapByInstance; // Orca: Translated brim areas keyed by instance, used to find touching brims. diff --git a/src/libslic3r/PrintBase.hpp b/src/libslic3r/PrintBase.hpp index 7e2b17e48f..f3c40102f8 100644 --- a/src/libslic3r/PrintBase.hpp +++ b/src/libslic3r/PrintBase.hpp @@ -70,6 +70,7 @@ public: SlicingNeedSupportOn, SlicingEmptyGcodeLayers, SlicingGcodeOverlap, + SlicingExclusionVolumeToolpath, SlicingPreciseSeamWarning }; diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 91261690fd..8e1b2b028e 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -10,21 +10,23 @@ #include "FilamentMixer.hpp" #include "MaterialType.hpp" #include "I18N.hpp" -#include "enum_bitmask.hpp" +#include "LocalesUtils.hpp" #include "format.hpp" #include "GCode/Thumbnails.hpp" +#include +#include +#include +#include +#include "enum_bitmask.hpp" #include #include -#include #include #include #include -#include #include #include "libslic3r.h" #include -#include #include #include #include @@ -33,6 +35,8 @@ #include #include #include +#include +#include #include #include #include @@ -727,6 +731,13 @@ static const t_config_enum_values s_keys_map_FilamentMapMode = { }; CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(FilamentMapMode) +static const t_config_enum_values s_keys_map_BedExcludeVolumeMode = { + { "shared", int(BedExcludeVolumeMode::Shared) }, + { "toolhead_offset", int(BedExcludeVolumeMode::ToolheadOffset) }, + { "per_extruder", int(BedExcludeVolumeMode::PerExtruder) } +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(BedExcludeVolumeMode) + // IMEX: keep the legacy hyphenated wire strings so existing presets / 3MFs // deserialize unchanged after the coString -> coEnum migration. static const t_config_enum_values s_keys_map_ImexToolLayout = { @@ -1035,11 +1046,38 @@ void PrintConfigDef::init_common_params() def = this->add("bed_exclude_area", coPoints); def->label = L("Excluded bed area"); def->tooltip = L("Unprintable area in XY plane. For example, X1 Series printers use the front left corner to cut filament during filament change. " - "The area is expressed as polygon by points in following format: \"XxY, XxY, ...\""); + "The area is expressed as a polygon in the format \"XxY, XxY, ...\". It constrains material and model placement, " + "but allows machine travel. Configure toolhead collision volumes separately for G-code checking and travel avoidance."); def->mode = comAdvanced; def->gui_type = ConfigOptionDef::GUIType::one_string; def->set_default_value(new ConfigOptionPoints{ Vec2d(0, 0) }); + def = this->add("bed_exclude_volumes", coString); + def->label = L("Toolhead collision volumes"); + def->tooltip = L("Collision volumes used for model and generated-material exclusion, G-code checking, and travel avoidance. " + "Use \"XxY, XxY, ...\" for a full-height polygon or \"ZMIN..ZMAX;XxY, XxY, ...\" for a Z-limited volume. " + "Separate multiple volumes with \"|\". These volumes are additional to the excluded bed area. " + "Automatic arrangement conservatively uses the bounding box of a non-convex volume."); + def->mode = comAdvanced; + def->gui_type = ConfigOptionDef::GUIType::one_string; + def->set_default_value(new ConfigOptionString()); + + def = this->add("bed_exclude_volume_mode", coEnum); + def->label = L("Collision volume behavior"); + def->tooltip = L("Choose whether all nozzles use the same collision volumes, derive toolhead-relative volumes from each nozzle's XY offset, or configure independent volumes for every extruder. In individual mode, select each extruder on the Extruder page to configure its volumes."); + def->enum_keys_map = &ConfigOptionEnum::get_enum_values(); + def->enum_values = { "shared", "toolhead_offset", "per_extruder" }; + def->enum_labels = { L("Shared"), L("Toolhead-relative (nozzle offsets)"), L("Individual per extruder") }; + def->mode = comAdvanced; + def->set_default_value(new ConfigOptionEnum(BedExcludeVolumeMode::Shared)); + + def = this->add("extruder_bed_exclude_volumes", coStrings); + def->label = L("Extruder collision volumes"); + def->tooltip = L("Collision volumes used only by this extruder in individual mode. Use the same polygon and optional Z-range format as the shared collision volumes. Leave empty for no collision volumes on this extruder. Automatic arrangement conservatively uses the bounding box of a non-convex volume."); + def->mode = comAdvanced; + def->gui_type = ConfigOptionDef::GUIType::one_string; + def->set_default_value(new ConfigOptionStrings{ "" }); + def = this->add("bed_custom_texture", coString); def->label = L("Bed custom texture"); def->mode = comAdvanced; @@ -10131,6 +10169,7 @@ std::set printer_extruder_options = { "nozzle_diameter", "default_nozzle_volume_type", "extruder_printable_area", + "extruder_bed_exclude_volumes", "extruder_printable_height", "min_layer_height", "max_layer_height", @@ -12375,6 +12414,25 @@ std::map validate(const FullPrintConfig &cfg, bool und break; } + const bool collision_volumes_enabled = has_bed_exclude_volumes(cfg); + if (cfg.bed_exclude_volume_mode.value != BedExcludeVolumeMode::PerExtruder && + !cfg.bed_exclude_volumes.value.empty() && + !is_valid_bed_exclude_volumes_string(cfg.bed_exclude_volumes.value, cfg.printable_height.value)) { + error_message.emplace("bed_exclude_volumes", L("Invalid collision volume definition.")); + } + if (collision_volumes_enabled && cfg.bed_exclude_volume_mode.value == BedExcludeVolumeMode::ToolheadOffset && + cfg.extruder_offset.size() < cfg.nozzle_diameter.size()) { + error_message.emplace("extruder_offset", L("A nozzle offset is required for every extruder when toolhead-relative collision volumes are enabled.")); + } + if (collision_volumes_enabled && cfg.bed_exclude_volume_mode.value == BedExcludeVolumeMode::PerExtruder) { + for (const std::string &entry : cfg.extruder_bed_exclude_volumes.values) { + if (!is_valid_bed_exclude_volumes_string(entry, cfg.printable_height.value)) { + error_message.emplace("extruder_bed_exclude_volumes", L("Invalid per-extruder collision volume definition.")); + break; + } + } + } + // --perimeters if (cfg.wall_loops.value < 0) { error_message.emplace("wall_loops", _u8L("invalid value ") + std::to_string(cfg.wall_loops.value)); @@ -13756,31 +13814,513 @@ Points get_bed_shape(const PrintConfig &cfg, bool use_share) Points get_bed_shape(const SLAPrinterConfig &cfg) { return to_points(make_counter_clockwise(cfg.printable_area.values)); } -Polygons get_bed_excluded_area(const PrintConfig& cfg) +namespace { + +static bool looks_like_bed_exclusion_volume_syntax(const std::string &value) { - const Pointfs exclude_area_points = cfg.bed_exclude_area.values; + return value.find('|') != std::string::npos || (value.find("..") != std::string::npos && value.find(';') != std::string::npos); +} - // Belt printer: project exclusion zone points from the belt surface to machine-frame XY. - // On the belt surface Z=0, so the in-plane axis foreshortens by cos(tilt). The tilt - // axis decides which bed axis foreshortens: tilt about X (belt along Y) scales Y, - // tilt about Y (belt along X) scales X. Derived from belt_slice_rotation. - const bool is_belt = cfg.belt_printer.value; - const auto tilt = BeltTransformPipeline::physical_tilt( - cfg.belt_slice_rotation.value, cfg.belt_slice_rotation_angle.value); - const double cos_x = is_belt ? std::cos(Geometry::deg2rad(tilt.tilt_x_deg)) : 1.0; // foreshortens Y - const double cos_y = is_belt ? std::cos(Geometry::deg2rad(tilt.tilt_y_deg)) : 1.0; // foreshortens X +static bool parse_double_token(const std::string &text, double &out) +{ + std::string token = text; + boost::trim(token); + if (token.empty()) + return false; - Polygon exclude_poly; - for (int i = 0; i < exclude_area_points.size(); i++) { - auto pt = exclude_area_points[i]; - double x = is_belt ? pt.x() * cos_y : pt.x(); - double y = is_belt ? pt.y() * cos_x : pt.y(); - exclude_poly.points.emplace_back(scale_(x), scale_(y)); + size_t parsed = 0; + out = string_to_double_decimal_point(token, &parsed); + return parsed == token.size() && std::isfinite(out); +} + +static bool parse_z_range_token( + const std::string &token_in, + const double printable_height, + double &z_min, + double &z_max, + bool &has_z) +{ + std::string token = token_in; + boost::trim(token); + if (token.empty()) + return false; + + size_t range_pos = token.find(".."); + if (range_pos == std::string::npos) + return false; + + std::string min_token = token.substr(0, range_pos); + std::string max_token = token.substr(range_pos + 2); + boost::trim(min_token); + boost::trim(max_token); + + double parsed_min = 0.0; + double parsed_max = printable_height; + if (! min_token.empty() && ! parse_double_token(min_token, parsed_min)) + return false; + if (! max_token.empty() && ! parse_double_token(max_token, parsed_max)) + return false; + + z_min = std::clamp(parsed_min, 0.0, printable_height); + z_max = std::clamp(parsed_max, 0.0, printable_height); + has_z = true; + // A range wholly outside the printable height clamps to a plane, which is + // not a volume and must not participate in conservative unknown-Z checks. + return z_min < z_max; +} + +static std::optional parse_exclude_polygon_points(const std::string &points_str) +{ + Pointfs points; + std::vector point_tokens; + boost::split(point_tokens, points_str, boost::is_any_of(",")); + points.reserve(point_tokens.size()); + for (std::string point_token : point_tokens) { + boost::trim(point_token); + const size_t separator = point_token.find('x'); + if (separator == std::string::npos || point_token.find('x', separator + 1) != std::string::npos) + return std::nullopt; + + double x = 0.0; + double y = 0.0; + if (!parse_double_token(point_token.substr(0, separator), x) || + !parse_double_token(point_token.substr(separator + 1), y) || + !std::isfinite(x) || !std::isfinite(y)) + return std::nullopt; + points.emplace_back(x, y); + } + if (points.size() < 3) + return std::nullopt; + + Polygon polygon; + polygon.points.reserve(points.size()); + for (const Vec2d &pt : points) + polygon.points.emplace_back(scale_(pt.x()), scale_(pt.y())); + if (polygon.area() == 0.0) + return std::nullopt; + polygon.make_counter_clockwise(); + return polygon; +} + +static void append_legacy_bed_exclude_regions( + std::vector &out, + const Pointfs &legacy_points, + const double printable_height) +{ + if (legacy_points.size() < 3) + return; + + Polygon polygon; + polygon.points.reserve(legacy_points.size()); + for (const Vec2d &pt : legacy_points) + polygon.points.emplace_back(scale_(pt.x()), scale_(pt.y())); + polygon.make_counter_clockwise(); + + out.push_back({ std::move(polygon), 0.0, printable_height, + BedExcludeRegion::Purpose::MaterialKeepout, false }); +} + +static void append_bed_exclusion_volume_regions( + std::vector &out, + const std::string ®ion_specs_raw, + const double printable_height) +{ + std::vector region_specs; + boost::split(region_specs, region_specs_raw, boost::is_any_of("|\n")); + + for (const std::string &spec_raw : region_specs) { + std::string spec = spec_raw; + boost::trim(spec); + if (spec.empty()) + continue; + + std::vector fields; + boost::split(fields, spec, boost::is_any_of(";")); + + double z_min = 0.0; + double z_max = printable_height; + bool has_z_range = false; + std::string points_field; + bool invalid_z = false; + + for (std::string field : fields) { + boost::trim(field); + if (field.empty()) + continue; + + bool parsed_z_range = parse_z_range_token(field, printable_height, z_min, z_max, has_z_range); + if (parsed_z_range) + continue; + + if (field.find("..") != std::string::npos && field.find('x') == std::string::npos) { + invalid_z = true; + break; + } + + if (boost::algorithm::istarts_with(field, "points=")) + field = field.substr(std::string("points=").size()); + else if (boost::algorithm::istarts_with(field, "polygon=")) + field = field.substr(std::string("polygon=").size()); + + points_field = field; + } + + if (invalid_z) + continue; + + if (! has_z_range) { + z_min = 0.0; + z_max = printable_height; + } + + if (z_min >= z_max) + continue; + + std::optional polygon = parse_exclude_polygon_points(points_field); + if (! polygon) + continue; + + out.push_back({ std::move(*polygon), z_min, z_max, + BedExcludeRegion::Purpose::CollisionVolume, has_z_range }); + } +} + +static bool has_nonempty_string(const std::string &value) +{ + return std::any_of(value.begin(), value.end(), [](const char c) { return !std::isspace(static_cast(c)); }); +} + +static bool collision_volumes_configured( + const std::string &shared_specs, + const BedExcludeVolumeMode mode, + const std::vector &per_extruder_specs) +{ + if (mode == BedExcludeVolumeMode::PerExtruder) + return std::any_of(per_extruder_specs.begin(), per_extruder_specs.end(), has_nonempty_string); + return has_nonempty_string(shared_specs); +} + +static std::vector parse_master_bed_excluded_regions( + const Pointfs &legacy_points, + const std::string &shared_specs, + const bool use_collision_volumes, + const BedExcludeVolumeMode mode, + const double printable_height) +{ + std::vector regions; + const double height = std::max(0.0, printable_height); + // Legacy excluded areas remain a shared material/placement keep-out even + // when collision volumes are configured. Collision volumes add constraints; + // they do not silently remove the printer profile's established area. + append_legacy_bed_exclude_regions(regions, legacy_points, height); + if (use_collision_volumes && mode != BedExcludeVolumeMode::PerExtruder) + append_bed_exclusion_volume_regions(regions, shared_specs, height); + return regions; +} + +static void project_bed_material_keepouts(std::vector ®ions, const ConfigBase &cfg) +{ + const auto *belt = cfg.option("belt_printer"); + if (belt == nullptr || !belt->value) + return; + + const auto *axis = cfg.option>("belt_slice_rotation"); + const auto *angle = cfg.option("belt_slice_rotation_angle"); + if (axis == nullptr || angle == nullptr) + return; + + const auto tilt = BeltTransformPipeline::physical_tilt(axis->value, angle->value); + const double cos_x = std::cos(Geometry::deg2rad(tilt.tilt_x_deg)); + const double cos_y = std::cos(Geometry::deg2rad(tilt.tilt_y_deg)); + // Resolve bed-surface coordinates once, before any placement or tower + // consumer sees them. Collision volumes already use model coordinates. + for (BedExcludeRegion ®ion : regions) + if (!region.is_collision_volume()) + for (Point &point : region.polygon.points) + point = Point(scale_(unscale(point.x()) * cos_y), scale_(unscale(point.y()) * cos_x)); +} + +static std::vector resolve_bed_excluded_regions( + const std::vector &master_regions, + const BedExcludeVolumeMode mode, + const std::vector &per_extruder_specs, + const std::vector &extruder_offsets, + const size_t reference_extruder, + const size_t extruder_id, + const double printable_height) +{ + if (mode == BedExcludeVolumeMode::Shared) + return master_regions; + + if (mode == BedExcludeVolumeMode::PerExtruder) { + std::vector regions = master_regions; + if (extruder_id < per_extruder_specs.size()) + append_bed_exclusion_volume_regions( + regions, per_extruder_specs[extruder_id], std::max(0.0, printable_height)); + return regions; } - exclude_poly.make_counter_clockwise(); + std::vector regions = master_regions; + if (extruder_id >= extruder_offsets.size() || extruder_offsets.empty()) + return regions; - return {exclude_poly}; + const size_t clamped_reference = std::min(reference_extruder, extruder_offsets.size() - 1); + // A model-space point is emitted as model_position - extruder_offset. Therefore a + // carriage/toolhead obstacle described through the reference nozzle appears in another + // nozzle's model space translated by (other_offset - reference_offset). + const Vec2d delta = extruder_offsets[extruder_id] - extruder_offsets[clamped_reference]; + const Point translation(scale_(delta.x()), scale_(delta.y())); + for (BedExcludeRegion ®ion : regions) { + // Toolhead-relative offsets apply only to opt-in collision volumes. + // A legacy material keep-out is bed-fixed and shared by every nozzle. + if (region.is_collision_volume()) + region.polygon.translate(translation); + } + return regions; +} + +static size_t bed_exclusion_extruder_count( + const size_t nozzle_count, + const size_t offset_count, + const size_t per_extruder_count) +{ + return std::max(1, std::max({ nozzle_count, offset_count, per_extruder_count })); +} + +static std::vector flatten_bed_excluded_regions( + const BedExcludeVolumeMode mode, + std::vector> regions_by_extruder) +{ + if (regions_by_extruder.empty()) + return {}; + if (mode == BedExcludeVolumeMode::Shared) + return std::move(regions_by_extruder.front()); + + std::vector flattened; + // A shared legacy area is present in every resolved nozzle group so object + // validation sees it for every tool. Flatten it only once, while retaining + // every nozzle-specific collision volume. + bool material_keepout_added = false; + for (std::vector ®ions : regions_by_extruder) { + for (BedExcludeRegion ®ion : regions) { + if (!region.is_collision_volume()) { + if (material_keepout_added) + continue; + material_keepout_added = true; + } + flattened.emplace_back(std::move(region)); + } + } + return flattened; +} + +} // namespace + +int bed_exclusion_extruder_for_filament( + const size_t filament_id, const std::vector &configured_map, const FilamentMapMode map_mode, + const bool is_bambu, const bool automatic_map_resolved, const size_t extruder_count) +{ + if (extruder_count == 0) + return -1; + + const bool automatic = is_auto_filament_map_mode(map_mode); + if (automatic && is_bambu && !automatic_map_resolved) + return -1; + + // Generic multi-tool printers use filament ids as tool ids. Their global + // filament_map still carries the Bambu grouping seed [1, 1, ...], which is + // not a meaningful assignment for these machines. + if (automatic && !is_bambu && filament_id < extruder_count) + return int(filament_id); + + if (filament_id < configured_map.size() && configured_map[filament_id] > 0 && + size_t(configured_map[filament_id]) <= extruder_count) + return configured_map[filament_id] - 1; + + return filament_id < extruder_count ? int(filament_id) : -1; +} + +std::vector> get_bed_excluded_regions_by_extruder(const DynamicPrintConfig &cfg) +{ + const ConfigOptionFloat *height_option = cfg.opt("printable_height"); + const double printable_height = height_option != nullptr ? height_option->value : 0.0; + const ConfigOptionPoints *legacy_option = cfg.opt("bed_exclude_area"); + const ConfigOptionString *shared_option = cfg.opt("bed_exclude_volumes"); + const BedExcludeVolumeMode configured_mode = cfg.has("bed_exclude_volume_mode") ? + cfg.opt_enum("bed_exclude_volume_mode") : BedExcludeVolumeMode::Shared; + const ConfigOptionStrings *per_extruder_option = cfg.opt("extruder_bed_exclude_volumes"); + const ConfigOptionPoints *offset_option = cfg.opt("extruder_offset"); + const ConfigOptionFloats *nozzle_option = cfg.opt("nozzle_diameter"); + const ConfigOptionInt *reference_option = cfg.opt("master_extruder_id"); + + const Pointfs legacy_points = legacy_option != nullptr ? legacy_option->values : Pointfs{}; + const std::string shared_specs = shared_option != nullptr ? shared_option->value : std::string{}; + const std::vector per_extruder_specs = per_extruder_option != nullptr ? per_extruder_option->values : std::vector{}; + const bool use_collision_volumes = collision_volumes_configured(shared_specs, configured_mode, per_extruder_specs); + const BedExcludeVolumeMode active_mode = use_collision_volumes ? configured_mode : BedExcludeVolumeMode::Shared; + std::vector master_regions = parse_master_bed_excluded_regions( + legacy_points, shared_specs, use_collision_volumes, active_mode, printable_height); + project_bed_material_keepouts(master_regions, cfg); + const std::vector offsets = offset_option != nullptr ? offset_option->values : std::vector{}; + const size_t count = bed_exclusion_extruder_count( + nozzle_option != nullptr ? nozzle_option->size() : 0, + offsets.size(), per_extruder_specs.size()); + const size_t reference = reference_option != nullptr && reference_option->value > 0 ? size_t(reference_option->value - 1) : 0; + + std::vector> result; + result.reserve(count); + for (size_t extruder_id = 0; extruder_id < count; ++extruder_id) + result.emplace_back(resolve_bed_excluded_regions(master_regions, active_mode, per_extruder_specs, offsets, reference, extruder_id, printable_height)); + return result; +} + +std::vector> get_bed_excluded_regions_by_extruder(const PrintConfig &cfg) +{ + const double printable_height = cfg.printable_height.value; + const bool use_collision_volumes = collision_volumes_configured( + cfg.bed_exclude_volumes.value, cfg.bed_exclude_volume_mode.value, + cfg.extruder_bed_exclude_volumes.values); + const BedExcludeVolumeMode active_mode = use_collision_volumes ? + cfg.bed_exclude_volume_mode.value : BedExcludeVolumeMode::Shared; + std::vector master_regions = parse_master_bed_excluded_regions( + cfg.bed_exclude_area.values, cfg.bed_exclude_volumes.value, use_collision_volumes, + active_mode, printable_height); + project_bed_material_keepouts(master_regions, cfg); + const size_t count = bed_exclusion_extruder_count( + cfg.nozzle_diameter.size(), cfg.extruder_offset.size(), cfg.extruder_bed_exclude_volumes.size()); + const size_t reference = cfg.master_extruder_id.value > 0 ? size_t(cfg.master_extruder_id.value - 1) : 0; + + std::vector> result; + result.reserve(count); + for (size_t extruder_id = 0; extruder_id < count; ++extruder_id) { + result.emplace_back(resolve_bed_excluded_regions( + master_regions, active_mode, cfg.extruder_bed_exclude_volumes.values, + cfg.extruder_offset.values, reference, extruder_id, printable_height)); + } + return result; +} + +std::vector get_bed_excluded_regions(const DynamicPrintConfig &cfg, const size_t extruder_id) +{ + std::vector> regions = get_bed_excluded_regions_by_extruder(cfg); + return extruder_id < regions.size() ? std::move(regions[extruder_id]) : std::vector{}; +} + +std::vector get_bed_excluded_regions(const PrintConfig &cfg, const size_t extruder_id) +{ + std::vector> regions = get_bed_excluded_regions_by_extruder(cfg); + return extruder_id < regions.size() ? std::move(regions[extruder_id]) : std::vector{}; +} + +std::vector get_bed_excluded_regions(const DynamicPrintConfig &cfg) +{ + return flatten_bed_excluded_regions(active_bed_exclude_volume_mode(cfg), get_bed_excluded_regions_by_extruder(cfg)); +} + +std::vector get_bed_excluded_regions(const PrintConfig &cfg) +{ + return flatten_bed_excluded_regions(active_bed_exclude_volume_mode(cfg), get_bed_excluded_regions_by_extruder(cfg)); +} + +bool is_bed_exclusion_volume_syntax(const std::string &value) +{ + return looks_like_bed_exclusion_volume_syntax(value); +} + +bool is_valid_bed_exclude_volumes_string(const std::string &value, const double printable_height) +{ + if (value.empty()) + return true; + + std::vector specs; + boost::split(specs, value, boost::is_any_of("|\n")); + bool found_nonempty = false; + for (std::string spec : specs) { + boost::trim(spec); + if (spec.empty()) + continue; + found_nonempty = true; + std::vector parsed; + append_bed_exclusion_volume_regions(parsed, spec, std::max(0.0, printable_height)); + if (parsed.size() != 1) + return false; + } + return found_nonempty; +} + +void append_bed_exclude_volumes(DynamicPrintConfig &config, const std::string &definition) +{ + if (definition.empty()) + return; + + const auto append = [&definition](const std::string ¤t) { + return current.empty() ? definition : current + '|' + definition; + }; + const BedExcludeVolumeMode mode = config.has("bed_exclude_volume_mode") ? + config.opt_enum("bed_exclude_volume_mode") : BedExcludeVolumeMode::Shared; + if (mode == BedExcludeVolumeMode::PerExtruder) { + const ConfigOptionStrings *current = config.option("extruder_bed_exclude_volumes"); + std::vector definitions = current != nullptr ? current->values : std::vector{}; + const ConfigOptionFloats *nozzles = config.option("nozzle_diameter"); + const size_t extruder_count = std::max(1, nozzles != nullptr ? nozzles->size() : 0); + definitions.resize(std::max(definitions.size(), extruder_count)); + for (size_t extruder_id = 0; extruder_id < extruder_count; ++extruder_id) + definitions[extruder_id] = append(definitions[extruder_id]); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings(std::move(definitions))); + return; + } + + const ConfigOptionString *current = config.option("bed_exclude_volumes"); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString( + append(current != nullptr ? current->value : std::string{}))); +} + +bool has_bed_exclude_volumes(const DynamicPrintConfig &cfg) +{ + const ConfigOptionString *shared = cfg.opt("bed_exclude_volumes"); + const ConfigOptionStrings *per_extruder = cfg.opt("extruder_bed_exclude_volumes"); + const BedExcludeVolumeMode mode = cfg.has("bed_exclude_volume_mode") ? + cfg.opt_enum("bed_exclude_volume_mode") : BedExcludeVolumeMode::Shared; + return collision_volumes_configured( + shared != nullptr ? shared->value : std::string{}, mode, + per_extruder != nullptr ? per_extruder->values : std::vector{}); +} + +bool has_bed_exclude_volumes(const PrintConfig &cfg) +{ + return collision_volumes_configured( + cfg.bed_exclude_volumes.value, cfg.bed_exclude_volume_mode.value, + cfg.extruder_bed_exclude_volumes.values); +} + +BedExcludeVolumeMode active_bed_exclude_volume_mode(const DynamicPrintConfig &cfg) +{ + if (!has_bed_exclude_volumes(cfg) || !cfg.has("bed_exclude_volume_mode")) + return BedExcludeVolumeMode::Shared; + return cfg.opt_enum("bed_exclude_volume_mode"); +} + +BedExcludeVolumeMode active_bed_exclude_volume_mode(const PrintConfig &cfg) +{ + return has_bed_exclude_volumes(cfg) ? cfg.bed_exclude_volume_mode.value : BedExcludeVolumeMode::Shared; +} + +Polygons get_bed_excluded_area(const PrintConfig& cfg) +{ + const std::vector regions = get_bed_excluded_regions(cfg); + Polygons excluded_polygons; + excluded_polygons.reserve(regions.size()); + + for (const BedExcludeRegion ®ion : regions) { + if (region.has_z_range && region.z_min > EPSILON) + continue; + if (region.z_max <= EPSILON) + continue; + + excluded_polygons.emplace_back(region.polygon); + } + + return excluded_polygons; } Polygon get_bed_shape_with_excluded_area(const PrintConfig& cfg, bool use_share) diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index 55e82656f0..0ebeabb3eb 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -630,6 +630,14 @@ enum FilamentMapMode { fmmDefault }; +// Defines how bed exclusion volumes are resolved for printers with multiple +// independently positioned nozzles/toolheads. +enum class BedExcludeVolumeMode { + Shared = 0, + ToolheadOffset, + PerExtruder +}; + // All auto modes are ordered before fmmManual (see the enum ordering note above). inline bool is_auto_filament_map_mode(FilamentMapMode mode) { return mode < fmmManual; @@ -1973,6 +1981,9 @@ PRINT_CONFIG_CLASS_DERIVED_DEFINE( ((ConfigOptionStrings, parallel_printheads_bed_exclude_areas)) //BBS: add bed_exclude_area ((ConfigOptionPoints, bed_exclude_area)) + ((ConfigOptionString, bed_exclude_volumes)) + ((ConfigOptionEnum, bed_exclude_volume_mode)) + ((ConfigOptionStrings, extruder_bed_exclude_volumes)) ((ConfigOptionPoints, head_wrap_detect_zone)) // BBS ((ConfigOptionString, bed_custom_texture)) @@ -2521,6 +2532,42 @@ Polygon get_shared_poly(const std::vector& extruder_polys); Points get_bed_shape(const DynamicPrintConfig &cfg, bool use_share = true); Points get_bed_shape(const PrintConfig &cfg, bool use_share = false); Points get_bed_shape(const SLAPrinterConfig &cfg); +struct BedExcludeRegion { + enum class Purpose { + MaterialKeepout, + CollisionVolume + }; + + Polygon polygon; + double z_min { 0.0 }; + double z_max { 0.0 }; + Purpose purpose { Purpose::MaterialKeepout }; + bool has_z_range { false }; + + bool is_collision_volume() const { return purpose == Purpose::CollisionVolume; } +}; +std::vector get_bed_excluded_regions(const DynamicPrintConfig& cfg); +std::vector get_bed_excluded_regions(const PrintConfig& cfg); +std::vector get_bed_excluded_regions(const DynamicPrintConfig &cfg, size_t extruder_id); +std::vector get_bed_excluded_regions(const PrintConfig &cfg, size_t extruder_id); +std::vector> get_bed_excluded_regions_by_extruder(const DynamicPrintConfig &cfg); +std::vector> get_bed_excluded_regions_by_extruder(const PrintConfig &cfg); +// Resolve the nozzle whose exclusion regions apply to a filament. Filament +// and return ids are 0-based. Returns -1 while Bambu automatic grouping has +// no concrete assignment. +int bed_exclusion_extruder_for_filament(size_t filament_id, const std::vector &configured_map, + FilamentMapMode map_mode, bool is_bambu, bool automatic_map_resolved, + size_t extruder_count); +bool is_bed_exclusion_volume_syntax(const std::string &value); +bool is_valid_bed_exclude_volumes_string(const std::string &value, double printable_height); +// Add shared definitions without replacing existing volumes or changing the +// configured multi-nozzle mode. In individual mode the new definitions are +// applied to every physical extruder. +void append_bed_exclude_volumes(DynamicPrintConfig &config, const std::string &definition); +bool has_bed_exclude_volumes(const DynamicPrintConfig &cfg); +bool has_bed_exclude_volumes(const PrintConfig &cfg); +BedExcludeVolumeMode active_bed_exclude_volume_mode(const DynamicPrintConfig &cfg); +BedExcludeVolumeMode active_bed_exclude_volume_mode(const PrintConfig &cfg); Slic3r::Polygons get_bed_excluded_area(const PrintConfig& cfg); Slic3r::Polygon get_bed_shape_with_excluded_area(const PrintConfig& cfg, bool use_share = false); bool has_skirt(const DynamicPrintConfig& cfg); diff --git a/src/libslic3r/PrintObject.cpp b/src/libslic3r/PrintObject.cpp index 4e5e359839..6dd48e530d 100644 --- a/src/libslic3r/PrintObject.cpp +++ b/src/libslic3r/PrintObject.cpp @@ -354,6 +354,23 @@ std::vector> PrintObject::detect_extruder_geometric_unprintables() std::vector> geometric_unprintables(extruder_size); // the container to return + std::vector> exclusion_regions = get_bed_excluded_regions_by_extruder(m_print->config()); + exclusion_regions.resize(extruder_size); + const Point plate_origin(scale_(m_print->get_plate_origin().x()), scale_(m_print->get_plate_origin().y())); + for (std::vector ®ions : exclusion_regions) + for (BedExcludeRegion ®ion : regions) + region.polygon.translate(plate_origin); + + const std::vector used_filaments = printing_extruders(); + for (size_t extruder_id = 0; extruder_id < exclusion_regions.size(); ++extruder_id) { + const bool collision = std::any_of(m_instances.begin(), m_instances.end(), [&](const PrintInstance &instance) { + return instance.model_instance != nullptr && + instance.model_instance->intersects_bed_exclude_regions(exclusion_regions[extruder_id]); + }); + if (collision) + geometric_unprintables[extruder_id].insert(used_filaments.begin(), used_filaments.end()); + } + std::vector printable_height_per_extruder = m_print->config().extruder_printable_height.values; assert(printable_height_per_extruder.size() == extruder_size); @@ -4561,6 +4578,24 @@ std::vector PrintObject::object_extruders() const return extruders; } +std::vector PrintObject::printing_extruders() const +{ + std::vector extruders = object_extruders(); + if (has_support_material()) { + const size_t filament_count = print()->config().filament_diameter.size(); + auto append_fixed_filament = [&](const int filament_id) { + if (filament_id > 0) + extruders.emplace_back(std::min(size_t(filament_id - 1), filament_count > 0 ? filament_count - 1 : 0)); + }; + append_fixed_filament(config().support_filament.value); + append_fixed_filament(config().support_interface_filament.value); + } + if (extruders.empty()) + extruders.emplace_back(0); + sort_remove_duplicates(extruders); + return extruders; +} + bool PrintObject::update_layer_height_profile(const ModelObject &model_object, const SlicingParameters &slicing_parameters, std::vector &layer_height_profile) { bool updated = false; diff --git a/src/libslic3r/Support/SupportCommon.cpp b/src/libslic3r/Support/SupportCommon.cpp index dddbfcf189..0cca31adca 100644 --- a/src/libslic3r/Support/SupportCommon.cpp +++ b/src/libslic3r/Support/SupportCommon.cpp @@ -1,4 +1,5 @@ #include "../ClipperUtils.hpp" +#include "../ExclusionVolumeGeometry.hpp" #include "../ClipperZUtils.hpp" #include "../ExtrusionEntityCollection.hpp" #include "../Layer.hpp" @@ -55,6 +56,132 @@ namespace Slic3r { +namespace { + +int object_layer_id_at_z(const PrintObject &object, const coordf_t print_z) +{ + const ConstLayerPtrsAdaptor layers = object.layers(); + if (layers.empty()) + return -1; + const auto it = std::lower_bound(layers.begin(), layers.end(), print_z - EPSILON, + [](const Layer *layer, const coordf_t z) { return layer->print_z < z; }); + return int(it == layers.end() ? layers.size() - 1 : size_t(it - layers.begin())); +} + +bool support_layer_uses_interface_material(const SupportGeneratorLayer &layer) +{ + return one_of(layer.layer_type, { + SupporLayerType::RaftInterface, + SupporLayerType::BottomContact, + SupporLayerType::BottomInterface, + SupporLayerType::TopContact, + SupporLayerType::TopInterface }); +} + +void trim_polygons(Polygons &polygons, const Polygons &excluded) +{ + if (!polygons.empty() && !excluded.empty()) + polygons = diff(polygons, excluded, ApplySafetyOffset::Yes); +} + +} // namespace + +std::vector support_exclusion_filaments( + const PrintObject &object, + const bool interface_material) +{ + const int configured = interface_material ? object.config().support_interface_filament.value : + object.config().support_filament.value; + if (configured > 0) + return { unsigned(configured - 1) }; + + // "Current filament" is assigned during tool ordering, not from the + // supported object. It may therefore use a filament from another object, + // or one selected for flush-into-support, on any particular layer. + return object.print() == nullptr ? object.object_extruders() : object.print()->extruders(false); +} + +std::vector support_exclusion_areas_for_layers( + const PrintObject &object, + const std::vector> &layer_z_ranges, + const bool interface_material) +{ + std::vector result(layer_z_ranges.size()); + if (layer_z_ranges.empty() || object.print() == nullptr) + return result; + + const Print &print = *object.print(); + // Preserve established support output for legacy bed-exclude areas. Support + // avoidance is an opt-in property of explicit collision volumes. + if (!has_bed_exclude_volumes(print.config())) + return result; + + std::vector> regions_by_extruder = + get_bed_excluded_regions_by_extruder(print.config()); + for (std::vector ®ions : regions_by_extruder) + regions.erase(std::remove_if(regions.begin(), regions.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }), regions.end()); + if (regions_by_extruder.empty() || + std::all_of(regions_by_extruder.begin(), regions_by_extruder.end(), + [](const std::vector ®ions) { return regions.empty(); })) + return result; + + const std::vector filaments = support_exclusion_filaments(object, interface_material); + for (size_t idx = 0; idx < layer_z_ranges.size(); ++idx) { + const auto [z_min, z_max] = layer_z_ranges[idx]; + const int layer_id = object_layer_id_at_z(object, z_max); + const std::vector physical_extruders = bed_exclusion_physical_extruders( + print, filaments, regions_by_extruder.size(), layer_id); + result[idx] = to_polygons(active_bed_exclusion_footprints_for_object( + object, regions_by_extruder, physical_extruders, z_min, z_max, coord_t(SCALED_EPSILON))); + } + return result; +} + +void trim_support_layers_by_exclusion_volumes( + const 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) +{ + SupportGeneratorLayersPtr layers; + layers.reserve(raft_layers.size() + bottom_contacts.size() + top_contacts.size() + + intermediate_layers.size() + interface_layers.size() + base_interface_layers.size()); + for (const SupportGeneratorLayersPtr *source : { + &raft_layers, &bottom_contacts, &top_contacts, &intermediate_layers, + &interface_layers, &base_interface_layers }) + append(layers, *source); + std::sort(layers.begin(), layers.end()); + layers.erase(std::unique(layers.begin(), layers.end()), layers.end()); + + for (const bool interface_material : { false, true }) { + SupportGeneratorLayersPtr selected; + std::vector> z_ranges; + for (SupportGeneratorLayer *layer : layers) { + if (layer != nullptr && support_layer_uses_interface_material(*layer) == interface_material) { + selected.emplace_back(layer); + z_ranges.emplace_back(layer->bottom_print_z(), layer->print_z); + } + } + + const std::vector excluded = + support_exclusion_areas_for_layers(object, z_ranges, interface_material); + for (size_t idx = 0; idx < selected.size(); ++idx) { + SupportGeneratorLayer &layer = *selected[idx]; + trim_polygons(layer.polygons, excluded[idx]); + if (layer.contact_polygons) + trim_polygons(*layer.contact_polygons, excluded[idx]); + if (layer.overhang_polygons) + trim_polygons(*layer.overhang_polygons, excluded[idx]); + if (layer.enforcer_polygons) + trim_polygons(*layer.enforcer_polygons, excluded[idx]); + } + } +} + // 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 diff --git a/src/libslic3r/Support/SupportCommon.hpp b/src/libslic3r/Support/SupportCommon.hpp index ca91ecc5ae..f50c2d7a6c 100644 --- a/src/libslic3r/Support/SupportCommon.hpp +++ b/src/libslic3r/Support/SupportCommon.hpp @@ -56,6 +56,32 @@ void tree_supports_generate_paths(ExtrusionEntitiesPtr &dst, const Polygons &pol void fill_expolygons_with_sheath_generate_paths( ExtrusionEntitiesPtr &dst, const Polygons &polygons, Fill *filler, float density, ExtrusionRole role, const Flow &flow, const SupportParameters& support_params, bool with_sheath, bool no_sort); +// Return every logical filament which may be selected for this support role. +// An explicit assignment has one result; "current filament" is intentionally +// print-wide because Orca resolves it later while ordering tools and wiping. +std::vector support_exclusion_filaments( + const PrintObject &object, + bool interface_material); + +// Build conservative, object-local exclusion masks for generated support. +// `interface_material` selects the support-interface filament; false selects +// the base support filament. Each pair describes the actual extrusion slab. +std::vector support_exclusion_areas_for_layers( + const PrintObject &object, + const std::vector> &layer_z_ranges, + bool interface_material); + +// Remove exclusion volumes from every support and raft polygon category before +// SupportLayer installation and toolpath generation. +void trim_support_layers_by_exclusion_volumes( + const 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); + // returns sorted layers SupportGeneratorLayersPtr generate_support_layers( PrintObject &object, diff --git a/src/libslic3r/Support/SupportMaterial.cpp b/src/libslic3r/Support/SupportMaterial.cpp index 8ac9172bfd..54a1de8a2c 100644 --- a/src/libslic3r/Support/SupportMaterial.cpp +++ b/src/libslic3r/Support/SupportMaterial.cpp @@ -553,6 +553,10 @@ void PrintObjectSupportMaterial::generate(PrintObject &object) BOOST_LOG_TRIVIAL(info) << "Support generator - Creating layers"; + trim_support_layers_by_exclusion_volumes( + object, raft_layers, bottom_contacts, top_contacts, intermediate_layers, + interface_layers, base_interface_layers); + // For debugging purposes, one may want to show only some of the support extrusions. // raft_layers.clear(); // bottom_contacts.clear(); diff --git a/src/libslic3r/Support/TreeModelVolumes.cpp b/src/libslic3r/Support/TreeModelVolumes.cpp index 33d379c2b5..6ecf735a0e 100644 --- a/src/libslic3r/Support/TreeModelVolumes.cpp +++ b/src/libslic3r/Support/TreeModelVolumes.cpp @@ -192,22 +192,18 @@ TreeModelVolumes::TreeModelVolumes( } }); } - 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 + + if (!additional_excluded_areas.empty()) { + m_anti_overhang.resize(std::max(m_anti_overhang.size(), additional_excluded_areas.size())); + tbb::parallel_for(tbb::blocked_range(0, additional_excluded_areas.size()), + [&](const tbb::blocked_range &range) { + for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++layer_idx) { + append(m_anti_overhang[layer_idx], additional_excluded_areas[layer_idx]); + m_anti_overhang[layer_idx] = union_(m_anti_overhang[layer_idx]); + } + }); + } } void TreeModelVolumes::precalculate(const PrintObject& print_object, const coord_t max_layer, std::function throw_on_cancel) @@ -488,7 +484,8 @@ void TreeModelVolumes::calculateCollision(const coord_t radius, const LayerIndex if (calculate_placable) data_placeable.allocate(data.begin(), data.end()); - for (size_t outline_idx : layer_outline_indices) + for (size_t outline_pos = 0; outline_pos < layer_outline_indices.size(); ++outline_pos) { + const size_t outline_idx = layer_outline_indices[outline_pos]; 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; @@ -525,7 +522,7 @@ void TreeModelVolumes::calculateCollision(const coord_t radius, const LayerIndex }); // 2) Sum over top / bottom ranges. - const bool processing_last_mesh = outline_idx == layer_outline_indices.back(); + const bool processing_last_mesh = outline_pos + 1 == 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] @@ -624,6 +621,7 @@ void TreeModelVolumes::calculateCollision(const coord_t radius, const LayerIndex // Calculating just the collision areas. } } + } #ifdef SLIC3R_TREESUPPORTS_PROGRESS { std::lock_guard critical_section(*m_critical_progress); diff --git a/src/libslic3r/Support/TreeSupport3D.cpp b/src/libslic3r/Support/TreeSupport3D.cpp index ef267fba68..e2bd31eadd 100644 --- a/src/libslic3r/Support/TreeSupport3D.cpp +++ b/src/libslic3r/Support/TreeSupport3D.cpp @@ -3485,12 +3485,41 @@ static void generate_support_areas(Print &print, TreeSupport* tree_support, cons 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()); + const size_t num_raft_layers_for_exclusions = config.raft_layers.size(); + std::vector> tree_layer_z_ranges; + tree_layer_z_ranges.reserve(num_raft_layers_for_exclusions + print_object.layer_count()); + coordf_t previous_z = 0.; + for (const coordf_t print_z : config.raft_layers) { + tree_layer_z_ranges.emplace_back(previous_z, print_z); + previous_z = print_z; + } + for (const Layer *layer : print_object.layers()) { + tree_layer_z_ranges.emplace_back(layer->print_z - layer->height, layer->print_z); + } + // A tree is one continuous structure while "current filament" may + // alternate between base and interface nozzles from layer to layer. + // Planning against both masks prevents a locally valid layer from + // forcing a branch through another possible nozzle's exclusion volume. + std::vector exclusion_areas = + support_exclusion_areas_for_layers(print_object, tree_layer_z_ranges, false); + const bool tree_uses_interface_material = !config.raft_layers.empty() || + print_object.config().support_interface_top_layers.value > 0 || + number_of_support_interface_bottom_layers(print_object.config()) > 0; + if (tree_uses_interface_material) { + const std::vector interface_exclusion_areas = + support_exclusion_areas_for_layers(print_object, tree_layer_z_ranges, true); + for (size_t layer_idx = 0; layer_idx < exclusion_areas.size(); ++layer_idx) { + append(exclusion_areas[layer_idx], interface_exclusion_areas[layer_idx]); + exclusion_areas[layer_idx] = union_(exclusion_areas[layer_idx]); + } + } + // 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 */{} }; + exclusion_areas }; //FIXME generating overhangs just for the first mesh of the group. assert(processing.second.size() == 1); @@ -3638,6 +3667,9 @@ static void generate_support_areas(Print &print, TreeSupport* tree_support, cons // Produce the support G-code. 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); + trim_support_layers_by_exclusion_volumes( + print_object, raft_layers, bottom_contacts, top_contacts, intermediate_layers, + interface_layers, base_interface_layers); SupportGeneratorLayersPtr layers_sorted = generate_support_layers(print_object, raft_layers, bottom_contacts, top_contacts, intermediate_layers, interface_layers, base_interface_layers); // BBS: This is a hack to avoid the support being generated outside the bed area. See #4769. diff --git a/src/slic3r/GUI/3DScene.cpp b/src/slic3r/GUI/3DScene.cpp index 3895275a33..071663b851 100644 --- a/src/slic3r/GUI/3DScene.cpp +++ b/src/slic3r/GUI/3DScene.cpp @@ -58,6 +58,8 @@ #include #include +#include + #include #include @@ -1454,10 +1456,31 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo BuildVolume plate_build_volume(pp_bed_shape, build_volume.printable_height(), build_volume.extruder_areas(), build_volume.extruder_heights()); const std::vector& exclude_areas = curr_plate->get_exclude_areas(); + const DynamicPrintConfig *plater_config = GUI::wxGetApp().plater()->config(); + std::vector> exclusion_regions; + // Legacy bed-exclude areas retain Orca's existing 2D presentation. The + // per-extruder 3D state is needed only after collision volumes are enabled. + if (has_bed_exclude_volumes(*plater_config)) { + exclusion_regions = get_bed_excluded_regions_by_extruder(*plater_config); + // The native BuildVolume path below already presents the shared legacy + // area. Merge only opt-in collision volumes into nozzle-specific state. + for (std::vector ®ions : exclusion_regions) + regions.erase(std::remove_if(regions.begin(), regions.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }), regions.end()); + } + const Vec3d plate_origin = curr_plate->get_origin(); + const Point exclusion_offset(scale_(plate_origin.x()), scale_(plate_origin.y())); + for (std::vector ®ions : exclusion_regions) + for (BedExcludeRegion ®ion : regions) + region.polygon.translate(exclusion_offset); + std::map>> objects_unprintable_filaments; - int extruder_count = build_volume.get_extruder_area_count(); + const DynamicPrintConfig &plate_project_config = GUI::wxGetApp().preset_bundle->project_config; + const int build_volume_extruder_count = build_volume.get_extruder_area_count(); + const int extruder_count = std::max(build_volume_extruder_count, int(exclusion_regions.size())); std::vector> unprintable_filament_ids(extruder_count, std::set()); std::set partly_objects_set; + std::map, std::vector> instance_inside_exclusion_regions; const ModelObjectPtrs &model_objects = model.objects; for (GLVolume* volume : this->volumes) { @@ -1472,7 +1495,7 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo //FIXME this test does not evaluate collision of a build volume bounding box with non-convex objects. const BoundingBoxf3& bb = volume_bbox(*volume); state = plate_build_volume.volume_state_bbox(bb); - if ((state == BuildVolume::ObjectState::Inside) && (extruder_count > 1)) + if ((state == BuildVolume::ObjectState::Inside) && (build_volume_extruder_count > 1)) { state = plate_build_volume.check_volume_bbox_state_with_extruder_areas(bb, inside_extruders); } @@ -1486,7 +1509,7 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo const indexed_triangle_set& convex_mesh_it = volume_convex_mesh(*volume).its; const Transform3f trafo = volume->world_matrix().cast(); state = plate_build_volume.object_state(convex_mesh_it, trafo, volume_sinking(*volume)); - if ((state == BuildVolume::ObjectState::Inside) && (extruder_count > 1)) + if ((state == BuildVolume::ObjectState::Inside) && (build_volume_extruder_count > 1)) { state = plate_build_volume.check_object_state_with_extruder_areas(convex_mesh_it, trafo, inside_extruders); } @@ -1499,12 +1522,52 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo } assert(state != BuildVolume::ObjectState::Below); + // Preserve Orca's native printable-area result separately. + // Exclusion collisions have current-map semantics and must not + // leak into the later "unprintable on every possible nozzle" + // aggregation used by automatic printable-area assignment. + const std::vector printable_area_inside_extruders = inside_extruders; + + // Newer Orca resolves live multi-nozzle placement through this + // per-extruder state vector. Merge exclusion-volume collisions + // into the same source of truth instead of relying only on the + // legacy PartPlate::check_outside() path. + if ((state == BuildVolume::ObjectState::Inside || state == BuildVolume::ObjectState::Limited) && + volume->object_idx() >= 0 && volume->object_idx() < int(model_objects.size()) && + volume->instance_idx() >= 0 && + volume->instance_idx() < int(model_objects[volume->object_idx()]->instances.size())) { + inside_extruders.resize(extruder_count, true); + + const std::pair instance_key{ volume->object_idx(), volume->instance_idx() }; + auto [cache_it, inserted] = instance_inside_exclusion_regions.emplace( + instance_key, std::vector(extruder_count, true)); + if (inserted) { + const ModelInstance *instance = model_objects[volume->object_idx()]->instances[volume->instance_idx()]; + for (size_t extruder_id = 0; extruder_id < exclusion_regions.size(); ++extruder_id) { + if (instance->intersects_bed_exclude_regions(exclusion_regions[extruder_id])) + cache_it->second[extruder_id] = false; + } + } + + bool exclusion_limited = false; + for (size_t extruder_id = 0; extruder_id < cache_it->second.size(); ++extruder_id) { + if (!cache_it->second[extruder_id]) { + inside_extruders[extruder_id] = false; + exclusion_limited = true; + } + } + + if (exclusion_limited && state == BuildVolume::ObjectState::Inside) + state = extruder_count > 1 ? BuildVolume::ObjectState::Limited : BuildVolume::ObjectState::Colliding; + + } + if (state == BuildVolume::ObjectState::Limited) { //unprintable_filament_ids.resize(inside_extruders.size()); ModelObject *model_object = model_objects[volume->object_idx()]; ModelVolume *model_volume = model_object->volumes[volume->volume_idx()]; - for (size_t i = 0; i < inside_extruders.size(); ++i) { - if (!inside_extruders[i]) { + for (size_t i = 0; i < printable_area_inside_extruders.size(); ++i) { + if (!printable_area_inside_extruders[i]) { std::vector filaments = model_volume->get_extruders(); unprintable_filament_ids[i].insert(filaments.begin(), filaments.end()); if (object_results) { @@ -1579,8 +1642,7 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo //check per-object error for extruder areas if (object_results && (extruder_count > 1)) { - const auto& project_config = Slic3r::GUI::wxGetApp().preset_bundle->project_config; - object_results->mode = curr_plate->get_real_filament_map_mode(project_config); + object_results->mode = curr_plate->get_real_filament_map_mode(plate_project_config); if (object_results->mode < FilamentMapMode::fmmManual) { std::vector conflict_filament_vector; @@ -1642,8 +1704,7 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo else { std::set conflict_filaments_set; - const auto& project_config = Slic3r::GUI::wxGetApp().preset_bundle->project_config; - std::vector filament_maps = curr_plate->get_real_filament_maps(project_config); + std::vector filament_maps = curr_plate->get_real_filament_maps(plate_project_config); for (auto& object_map: objects_unprintable_filaments) { ModelObject *model_object = object_map.first; @@ -1658,7 +1719,8 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo for (int filament: filaments_set) { - if (filament_maps[filament - 1] == extruder_id) + if (filament > 0 && size_t(filament) <= filament_maps.size() && + filament_maps[filament - 1] == extruder_id) { object_filament_info.manual_filaments.emplace(filament, extruder_id); object_results->filament_maps[filament] = extruder_id; @@ -1675,6 +1737,7 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo object_results->filaments = std::vector(conflict_filaments_set.begin(), conflict_filaments_set.end()); } } + } /*for (GLVolume* volume : this->volumes) diff --git a/src/slic3r/GUI/3DScene.hpp b/src/slic3r/GUI/3DScene.hpp index d7ff4168c8..ac31946c80 100644 --- a/src/slic3r/GUI/3DScene.hpp +++ b/src/slic3r/GUI/3DScene.hpp @@ -69,7 +69,7 @@ enum ModelInstanceEPrintVolumeState : unsigned char; using ModelObjectPtrs = std::vector; struct ObjectFilamentInfo { - ModelObject* object; + ModelObject* object { nullptr }; std::map manual_filaments; //manual mode: filament id -> extruder id can not be printed std::vector auto_filaments; //auto mode: filaments in all extruder's outside area diff --git a/src/slic3r/GUI/ConfigValueFormatter.cpp b/src/slic3r/GUI/ConfigValueFormatter.cpp index 8536e6731d..58f219a9ed 100644 --- a/src/slic3r/GUI/ConfigValueFormatter.cpp +++ b/src/slic3r/GUI/ConfigValueFormatter.cpp @@ -242,7 +242,7 @@ wxString get_string_value(const std::string& opt_key, const DynamicPrintConfig& return get_thumbnails_string(points.values); } else if (pure_key == "bed_exclude_area") { - return get_thumbnails_string(config.option(pure_key)->values); + return from_u8(config.option(pure_key)->serialize()); } else if (pure_key == "head_wrap_detect_zone") { return get_thumbnails_string(config.option(pure_key)->values); diff --git a/src/slic3r/GUI/ConfigWizard.cpp b/src/slic3r/GUI/ConfigWizard.cpp index 5d14f8162e..d04e3f718a 100644 --- a/src/slic3r/GUI/ConfigWizard.cpp +++ b/src/slic3r/GUI/ConfigWizard.cpp @@ -2671,7 +2671,8 @@ ConfigWizard::ConfigWizard(wxWindow *parent) p->load_vendors(); //BBS: add bed exclude areas p->custom_config.reset(DynamicPrintConfig::new_from_defaults_keys({ - "gcode_flavor", "printable_area", "bed_exclude_area", "bed_custom_texture", "bed_custom_model", "nozzle_diameter", "filament_diameter", "thumbnails" + "gcode_flavor", "printable_area", "bed_exclude_area", "bed_exclude_volumes", "bed_exclude_volume_mode", "extruder_bed_exclude_volumes", + "bed_custom_texture", "bed_custom_model", "nozzle_diameter", "filament_diameter", "thumbnails" //, "nozzle_temperature", "bed_temperature" })); diff --git a/src/slic3r/GUI/Field.cpp b/src/slic3r/GUI/Field.cpp index f2ae0490d9..55c491f811 100644 --- a/src/slic3r/GUI/Field.cpp +++ b/src/slic3r/GUI/Field.cpp @@ -733,6 +733,14 @@ void Field::get_value_by_opt_type(wxString& str, const bool check_value/* = true m_value = into_u8(str); } break; + } else if (m_opt.opt_key == "bed_exclude_volumes" || m_opt.opt_key == "extruder_bed_exclude_volumes") { + const std::string definition = into_u8(str); + if (!is_valid_bed_exclude_volumes_string(definition, std::numeric_limits::max())) { + show_error(m_parent, _L("Invalid collision volume format. Use XxY, XxY, ... or ZMIN..ZMAX;XxY, XxY, ... and separate multiple volumes with |.")); + const std::string old_value = m_value.empty() ? std::string{} : boost::any_cast(m_value); + set_value(from_u8(old_value), true); + break; + } } else if (m_opt.opt_key == "extra_solid_infills") { std::string ustr(str.utf8_string()); // New rule: accept either interval form (N or N#K) or explicit list (e.g. 1,7,9), with optional quotes. @@ -784,11 +792,18 @@ void Field::get_value_by_opt_type(wxString& str, const bool check_value/* = true case coPoints: { std::vector out_values; str.Replace(" ", wxEmptyString, true); + const bool bed_exclusion_volume_syntax = m_opt_id == "bed_exclude_area" && + (str.Find("|") != wxNOT_FOUND || (str.Find("..") != wxNOT_FOUND && str.Find(";") != wxNOT_FOUND)); + if (bed_exclusion_volume_syntax) { + // Leave volume validation and the copy prompt to the printer tab. + m_value = into_u8(str); + break; + } if (!str.IsEmpty()) { bool invalid_val = false; - wxStringTokenizer thumbnails(str, ","); - while (thumbnails.HasMoreTokens()) { - wxString token = thumbnails.GetNextToken(); + wxStringTokenizer points(str, ","); + while (points.HasMoreTokens()) { + wxString token = points.GetNextToken(); double x, y; wxStringTokenizer thumbnail(token, "x"); if (thumbnail.HasMoreTokens()) { @@ -807,10 +822,11 @@ void Field::get_value_by_opt_type(wxString& str, const bool check_value/* = true if (invalid_val) { wxString text_value; - if (!m_value.empty()) + if (!m_value.empty() && boost::any_cast>(&m_value) != nullptr) text_value = get_thumbnails_string(boost::any_cast>(m_value)); set_value(text_value, true); - show_error(m_parent, format_wxstr(_L("Invalid format. Expected vector format: \"%1%\""),"XxY, XxY, ..." )); + show_error(m_parent, format_wxstr(_L("Invalid format. Expected vector format: \"%1%\""), "XxY, XxY, ...")); + break; } } diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index 50ba576736..12e05605fc 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -1886,27 +1886,31 @@ static std::pair construct_extruder_unprintable_error(ObjectFilament auto mode = object_result.mode; for (auto& obj_filament : object_result.object_filaments) { + bool found_left = false; + bool found_right = false; + if (mode == FilamentMapMode::fmmManual) { for (auto& elem : obj_filament.manual_filaments) { - bool found_left = false, found_right = false; - int filamnet_id = elem.first; int extruder_id = elem.second; - if (extruder_id == 1 && !found_left) { + if (extruder_id == 1) { found_left = true; - left_unprintable_objects.emplace_back(obj_filament); } - if (extruder_id == 2 && !found_right) { + if (extruder_id == 2) { found_right = true; - right_unprintable_objects.emplace_back(obj_filament); } } } else { if (!obj_filament.auto_filaments.empty()) { - left_unprintable_objects.emplace_back(obj_filament); - right_unprintable_objects.emplace_back(obj_filament); + found_left = true; + found_right = true; } } + + if (found_left) + left_unprintable_objects.emplace_back(obj_filament); + if (found_right) + right_unprintable_objects.emplace_back(obj_filament); } Preset &preset = GUI::wxGetApp().preset_bundle->printers.get_edited_preset(); @@ -1942,7 +1946,7 @@ static std::pair construct_extruder_unprintable_error(ObjectFilament model_prefix = (boost::format(_u8L("The position or size of some models exceeds the %s's printable range.")) % nozzle_name).str(); else model_prefix = (boost::format(_u8L("The position or size of the model %s exceeds the %s's printable range.")) - %object_result.object_filaments.front().object->name % nozzle_name).str(); + %unprintable_objs.front().object->name % nozzle_name).str(); tips[idx] += model_prefix; tips[idx] += (boost::format(_u8L(" Please check and adjust the part's position or size to fit the printable range:\n"))).str(); @@ -2813,7 +2817,6 @@ void GLCanvas3D::_render_scene(const Camera& camera, const Size& cnv_size) // Design tab: replace the plate's corner-origin grid with the origin-centred CAD grid. _render_cad_grid(camera.get_view_matrix(), camera.get_projection_matrix()); m_frame_profiler.mark("plates"); - //BBS: add outline logic // Depth pass for object-on-object and self shadows; consumed by the gouraud shader below. _render_shadows(camera.get_view_matrix(), camera.get_projection_matrix()); @@ -2821,6 +2824,14 @@ void GLCanvas3D::_render_scene(const Camera& camera, const Size& cnv_size) _render_objects(GLVolumeCollection::ERenderType::Opaque, !m_gizmos.is_running()); _render_below_plate_volumes(); m_frame_profiler.mark("objects"); + // Collision previews follow the same visibility rule as the bed. + const bool show_exclusion_intersections = m_show_bed && + (!m_main_toolbar.is_enabled() || + (gizmo_type != GLGizmosManager::FdmSupports && gizmo_type != GLGizmosManager::Seam && + gizmo_type != GLGizmosManager::MmSegmentation && gizmo_type != GLGizmosManager::FuzzySkin)); + if (show_exclusion_intersections) + wxGetApp().plater()->get_partplate_list().render_exclusion_volume_intersections( + camera.get_view_matrix(), camera.get_projection_matrix()); _render_sla_slices(); _render_selection(); _render_objects(GLVolumeCollection::ERenderType::Transparent, !m_gizmos.is_running()); @@ -4871,6 +4882,8 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) // It should be detection of volume change // Not only detection of some modifiers !!! if (evt.Dragging()) { + if (PartPlate *plate = wxGetApp().plater()->get_partplate_list().get_curr_plate()) + plate->clear_exclusion_volume_intersections(); GLGizmosManager::EType c = m_gizmos.get_current_type(); if (current_printer_technology() == ptFFF && (fff_print()->config().print_sequence == PrintSequence::ByObject)) { @@ -5099,6 +5112,8 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) if (!m_mouse.drag.move_requires_threshold) { m_mouse.dragging = true; + if (PartPlate *plate = wxGetApp().plater()->get_partplate_list().get_curr_plate()) + plate->clear_exclusion_volume_intersections(); Vec3d cur_pos = m_mouse.drag.start_position_3D; // we do not want to translate objects if the user just clicked on an object while pressing shift to remove it from the selection and then drag if (m_selection.contains_volume(get_first_hover_volume_idx())) { @@ -6205,6 +6220,13 @@ void GLCanvas3D::set_cursor(ECursorType type) void GLCanvas3D::mouse_up_cleanup() { + // Both direct dragging and gizmo manipulation clear the expensive red + // exclusion-intersection mesh while moving. Gizmo drags do not always set + // m_mouse.dragging, so every completed mouse operation must allow the + // cached preview to restore/recompute that mesh. + if (PartPlate *plate = wxGetApp().plater()->get_partplate_list().get_curr_plate()) + plate->invalidate_exclusion_volume_preview(); + m_moving = false; m_camera_movement = false; m_mouse.drag.move_volume_idx = -1; diff --git a/src/slic3r/GUI/GUI.cpp b/src/slic3r/GUI/GUI.cpp index e376bfc097..b7e41dac98 100644 --- a/src/slic3r/GUI/GUI.cpp +++ b/src/slic3r/GUI/GUI.cpp @@ -263,8 +263,18 @@ void change_opt_value(DynamicPrintConfig& config, const t_config_option_key& opt } break; case coPoints:{ + if (opt_key == "bed_exclude_area" && boost::any_cast(&value) != nullptr) { + // Tab handles pasted volume syntax after this callback. Do not + // deserialize it as points: failure would erase the saved area + // before the user can accept or cancel the copy operation. + break; + } if (opt_key == "printable_area" || opt_key == "bed_exclude_area" || opt_key == "thumbnails" || opt_key == "wrapping_exclude_area" ) { config.option(opt_key)->values = boost::any_cast>(value); + if (opt_key == "bed_exclude_area") { + ConfigOptionPoints normalized(boost::any_cast>(value)); + config.option(opt_key)->deserialize(normalized.serialize()); + } break; } auto vec_new = std::make_unique(boost::any_cast(value)); diff --git a/src/slic3r/GUI/Jobs/ArrangeJob.cpp b/src/slic3r/GUI/Jobs/ArrangeJob.cpp index 3cdbd5b275..fd4fdee4ed 100644 --- a/src/slic3r/GUI/Jobs/ArrangeJob.cpp +++ b/src/slic3r/GUI/Jobs/ArrangeJob.cpp @@ -50,6 +50,58 @@ namespace Slic3r { namespace GUI { using ArrangePolygon = arrangement::ArrangePolygon; +void set_arrange_polygon_bed_exclusion_extruders(ArrangePolygon &polygon, const ModelObject &object, + const PartPlate &plate, const DynamicPrintConfig &config) +{ + polygon.bed_exclusion_extruder_ids.clear(); + if (active_bed_exclude_volume_mode(config) == BedExcludeVolumeMode::Shared) + return; + + const ConfigOptionFloats *nozzle_diameters = config.opt("nozzle_diameter"); + const size_t extruder_count = nozzle_diameters != nullptr ? nozzle_diameters->size() : 0; + if (extruder_count == 0) + return; + + PresetBundle *preset_bundle = wxGetApp().preset_bundle; + if (preset_bundle == nullptr) + return; + + const DynamicPrintConfig &project_config = preset_bundle->project_config; + // Automatic Bambu mapping may be recalculated after arrangement or differ + // between destination plates. Leave it unresolved so every nozzle volume + // is checked rather than embedding a temporary assignment in the item. + if (preset_bundle->is_bbl_vendor() && + is_auto_filament_map_mode(plate.get_real_filament_map_mode(project_config))) + return; + + std::set extruder_ids; + for (const auto &mapping : plate.get_object_filament_extruders(object, project_config, extruder_count)) + extruder_ids.emplace(int(mapping.second)); + polygon.bed_exclusion_extruder_ids.assign(extruder_ids.begin(), extruder_ids.end()); +} + +static void set_arrange_polygon_bed_exclusion_extruders_for_all_plates(ArrangePolygon &polygon, + const ModelObject &object, + PartPlateList &plate_list, + const DynamicPrintConfig &config) +{ + polygon.bed_exclusion_extruder_ids.clear(); + if (active_bed_exclude_volume_mode(config) == BedExcludeVolumeMode::Shared) + return; + + std::set extruder_ids; + for (int plate_index = 0; plate_index < plate_list.get_plate_count(); ++plate_index) { + ArrangePolygon mapped = polygon; + set_arrange_polygon_bed_exclusion_extruders(mapped, object, *plate_list.get_plate(plate_index), config); + if (mapped.bed_exclusion_extruder_ids.empty()) { + polygon.bed_exclusion_extruder_ids.clear(); + return; + } + extruder_ids.insert(mapped.bed_exclusion_extruder_ids.begin(), mapped.bed_exclusion_extruder_ids.end()); + } + polygon.bed_exclusion_extruder_ids.assign(extruder_ids.begin(), extruder_ids.end()); +} + // Cache the wti info class WipeTower: public GLCanvas3D::WipeTowerInfo { public: @@ -194,11 +246,14 @@ void ArrangeJob::clear_input() current_plate_index = 0; } -ArrangePolygon ArrangeJob::prepare_arrange_polygon(void* model_instance) +ArrangePolygon ArrangeJob::prepare_arrange_polygon(void *model_instance, const PartPlate *mapping_plate) { ModelInstance* instance = (ModelInstance*)model_instance; const Slic3r::DynamicPrintConfig& config = wxGetApp().preset_bundle->full_config(); - return get_instance_arrange_poly(instance, config); + ArrangePolygon polygon = get_instance_arrange_poly(instance, config); + if (mapping_plate != nullptr) + set_arrange_polygon_bed_exclusion_extruders(polygon, *instance->get_object(), *mapping_plate, config); + return polygon; } void ArrangeJob::prepare_selected() { @@ -234,6 +289,8 @@ void ArrangeJob::prepare_selected() { for (size_t i = 0; i < inst_sel.size(); ++i) { ModelInstance* mi = mo->instances[i]; ArrangePolygon&& ap = prepare_arrange_polygon(mo->instances[i]); + set_arrange_polygon_bed_exclusion_extruders_for_all_plates( + ap, *mo, plate_list, wxGetApp().preset_bundle->full_config()); //BBS: partplate_list preprocess //remove the locked plate's instances, neither in selected, nor in un-selected bool locked = plate_list.preprocess_arrange_polygon(oidx, i, ap, inst_sel[i]); @@ -309,6 +366,8 @@ void ArrangeJob::prepare_all() { for (size_t i = 0; i < mo->instances.size(); ++i) { ModelInstance * mi = mo->instances[i]; ArrangePolygon&& ap = prepare_arrange_polygon(mo->instances[i]); + set_arrange_polygon_bed_exclusion_extruders_for_all_plates( + ap, *mo, plate_list, wxGetApp().preset_bundle->full_config()); //BBS: partplate_list preprocess //remove the locked plate's instances, neither in selected, nor in un-selected bool locked = plate_list.preprocess_arrange_polygon(oidx, i, ap, true); @@ -350,7 +409,7 @@ void ArrangeJob::prepare_all() { bool enable_wrapping = current_config.option("enable_wrapping_detection")->value; // add the virtual object into unselect list if has - plate_list.preprocess_exclude_areas(m_unselected, enable_wrapping, MAX_NUM_PLATES); + plate_list.preprocess_exclude_areas(m_unselected, wxGetApp().preset_bundle->full_config(), enable_wrapping, MAX_NUM_PLATES); prepare_belt_regions(MAX_NUM_PLATES); } @@ -503,7 +562,7 @@ void ArrangeJob::prepare_partplate() { for (size_t inst_idx = 0; inst_idx < mo->instances.size(); ++inst_idx) { bool in_plate = plate->contain_instance(oidx, inst_idx) || plate->intersect_instance(oidx, inst_idx); - ArrangePolygon&& ap = prepare_arrange_polygon(mo->instances[inst_idx]); + ArrangePolygon&& ap = prepare_arrange_polygon(mo->instances[inst_idx], plate); ArrangePolygons& cont = mo->instances[inst_idx]->printable ? (in_plate ? m_selected : m_unselected) : @@ -534,7 +593,8 @@ void ArrangeJob::prepare_partplate() { bool enable_wrapping = current_config.option("enable_wrapping_detection")->value; // add the virtual object into unselect list if has - plate_list.preprocess_exclude_areas(m_unselected, enable_wrapping, current_plate_index + 1); + plate_list.preprocess_exclude_areas( + m_unselected, wxGetApp().preset_bundle->full_config(), enable_wrapping, current_plate_index + 1); prepare_belt_regions(current_plate_index + 1); } @@ -686,7 +746,7 @@ void ArrangeJob::process(Ctl &ctl) imex.add_keep_outs(m_unselected); bool enable_wrapping = global_config.option("enable_wrapping_detection")->value; - partplate_list.preprocess_exclude_areas(params.excluded_regions, enable_wrapping, 1, scale_(1)); + partplate_list.preprocess_exclude_areas(params.excluded_regions, global_config, enable_wrapping, 1, scale_(1)); BOOST_LOG_TRIVIAL(debug) << "arrange bedpts:" << bedpts[0].transpose() << ", " << bedpts[1].transpose() << ", " << bedpts[2].transpose() << ", " << bedpts[3].transpose(); diff --git a/src/slic3r/GUI/Jobs/ArrangeJob.hpp b/src/slic3r/GUI/Jobs/ArrangeJob.hpp index a31b65cea3..4383174f56 100644 --- a/src/slic3r/GUI/Jobs/ArrangeJob.hpp +++ b/src/slic3r/GUI/Jobs/ArrangeJob.hpp @@ -16,10 +16,17 @@ namespace Slic3r { class ModelInstance; +class ModelObject; namespace GUI { class Plater; +class PartPlate; + +void set_arrange_polygon_bed_exclusion_extruders(arrangement::ArrangePolygon &polygon, + const ModelObject &object, + const PartPlate &plate, + const DynamicPrintConfig &config); class ArrangeJob : public Job { @@ -71,7 +78,7 @@ class ArrangeJob : public Job void prepare_belt_regions(int num_plates); void prepare_imex_zones(); - ArrangePolygon prepare_arrange_polygon(void* instance); + ArrangePolygon prepare_arrange_polygon(void *instance, const PartPlate *mapping_plate = nullptr); protected: diff --git a/src/slic3r/GUI/Jobs/FillBedJob.cpp b/src/slic3r/GUI/Jobs/FillBedJob.cpp index 91981852dd..f3da5e631b 100644 --- a/src/slic3r/GUI/Jobs/FillBedJob.cpp +++ b/src/slic3r/GUI/Jobs/FillBedJob.cpp @@ -79,6 +79,7 @@ void FillBedJob::prepare() bool selected = (oidx == m_object_idx); ArrangePolygon ap = get_instance_arrange_poly(mo->instances[inst_idx], global_config); + set_arrange_polygon_bed_exclusion_extruders(ap, *mo, *plate, global_config); BoundingBox ap_bb = ap.transformed_poly().contour.bounding_box(); ap.name = mo->name; @@ -146,8 +147,8 @@ void FillBedJob::prepare() bool enable_wrapping = global_config.option("enable_wrapping_detection")->value; //add the virtual object into unselect list if has double scaled_exclusion_gap = scale_(1); - plate_list.preprocess_exclude_areas(params.excluded_regions, enable_wrapping, 1, scaled_exclusion_gap); - plate_list.preprocess_exclude_areas(m_unselected, enable_wrapping); + plate_list.preprocess_exclude_areas(params.excluded_regions, global_config, enable_wrapping, 1, scaled_exclusion_gap); + plate_list.preprocess_exclude_areas(m_unselected, global_config, enable_wrapping); m_bedpts = get_bed_shape(*m_plater->config()); @@ -173,11 +174,14 @@ void FillBedJob::prepare() auto polys = offset_ex(m_selected.front().poly, params.min_obj_distance / 2); ExPolygon poly = polys.empty() ? m_selected.front().poly : polys.front(); double poly_area = poly.area() / sc; + const ArrangePolygon &fill_template = m_selected.front(); double unsel_area = std::accumulate(m_unselected.begin(), m_unselected.end(), 0., - [cur_plate_index](double s, const auto &ap) { + [cur_plate_index, &fill_template](double s, const auto &ap) { //BBS: m_unselected instance is in the same partplate - return s + (ap.bed_idx == cur_plate_index) * ap.poly.area(); + const bool exclusion_applies = !ap.is_bed_exclusion || + bed_exclusion_applies(fill_template, ap); + return s + (ap.bed_idx == cur_plate_index && exclusion_applies) * ap.poly.area(); //return s + (ap.bed_idx == 0) * ap.poly.area(); }) / sc; @@ -192,36 +196,24 @@ void FillBedJob::prepare() //sel_id = std::max(sel_id, 0); ModelInstance *mi = model_object->instances[sel_id]; ArrangePolygon template_ap = get_instance_arrange_poly(mi, global_config); + set_arrange_polygon_bed_exclusion_extruders(template_ap, *model_object, *plate, global_config); - int obj_idx; - double offset_base, offset; - bool was_one_instance; - if (m_instances) { - obj_idx = m_plater->get_selected_object_idx(); - offset_base = m_plater->canvas3D()->get_size_proportional_to_max_bed_size(0.05); - offset = offset_base; - was_one_instance = model_object->instances.size()==1; - } - - for (int i = 0; i < needed_items; ++i, offset += offset_base) { + for (int i = 0; i < needed_items; ++i) { ArrangePolygon ap = template_ap; ap.poly = m_selected.front().poly; ap.bed_idx = PartPlateList::MAX_PLATES_COUNT; ap.itemid = -1; - ap.setter = [this, offset](const ArrangePolygon &p) { + ap.setter = [this, mi](const ArrangePolygon &p) { ModelObject *mo = m_plater->model().objects[m_object_idx]; - ModelObject *obj; if (m_instances) { - ModelInstance* model_instance = mo->instances.back(); - Vec3d offset_vec = model_instance->get_offset() + Vec3d(offset, offset, 0.0); - mo->add_instance(offset_vec, model_instance->get_scaling_factor(), model_instance->get_rotation(), model_instance->get_mirror()); - obj = mo; + ModelInstance *new_instance = mo->add_instance(*mi); + new_instance->apply_arrange_result(p.translation.cast(), p.rotation); } else { ModelObject* newObj = m_plater->model().add_object(*mo); newObj->name = mo->name +" "+ std::to_string(p.itemid); - obj = newObj; + for (ModelInstance *new_instance : newObj->instances) + new_instance->apply_arrange_result(p.translation.cast(), p.rotation); } - for (ModelInstance *newInst : obj->instances) { newInst->apply_arrange_result(p.translation.cast(), p.rotation); } //m_plater->sidebar().obj_list()->paste_objects_into_list({m_plater->model().objects.size()-1}); }; m_selected.emplace_back(ap); @@ -279,21 +271,65 @@ void FillBedJob::process(Ctl &ctl) // final align用的是凸包,在有fixed item的情况下可能找到的参考点位置是错的,这里就不做了。见STUDIO-3265 params.do_final_align = !is_bbl; - if (m_selected.size() > 100){ + if (m_selected.size() > 100) { // too many items, just find grid empty cells to put them - Vec2f step = unscaled(get_extents(m_selected.front().poly).size()) + Vec2f(m_selected.front().brim_width, m_selected.front().brim_width); - std::vector empty_cells = Plater::get_empty_cells(step); - size_t n=std::min(m_selected.size(), empty_cells.size()); - for (size_t i = 0; i < n; i++) { - m_selected[i].translation = scaled(empty_cells[i]); - m_selected[i].bed_idx= 0; + std::vector occupied_boxes; + for (const ArrangePolygon &fixed : m_unselected) { + if (fixed.bed_idx != 0 || fixed.is_extrusion_cali_object) + continue; + + if (fixed.is_bed_exclusion) { + const bool relevant = std::any_of( + m_selected.begin(), m_selected.end(), [&fixed](const ArrangePolygon &item) { + return bed_exclusion_applies(item, fixed); + }); + if (!relevant) + continue; + } + + BoundingBox bbox = get_extents(fixed.transformed_poly()); + bbox.offset(std::max(0, fixed.inflation)); + occupied_boxes.emplace_back(unscale(bbox.min), unscale(bbox.max)); } - for (size_t i = n; i < m_selected.size(); i++) { - m_selected[i].bed_idx = -1; + + // Fill the remaining space without disturbing instances which are + // already placed. Besides matching the meaning of "Fill bed", this + // also prevents candidates rejected by the grid from remaining under + // newly placed copies at their old positions. + const Vec3d plate_origin = partplate_list.get_curr_plate()->get_origin(); + for (const ArrangePolygon &existing : m_selected) { + if (existing.priority == 0 || existing.bed_idx != 0) + continue; + + BoundingBox bbox = get_extents(existing.transformed_poly()); + bbox.offset(std::max(0, existing.inflation)); + BoundingBoxf local_box(unscale(bbox.min), unscale(bbox.max)); + local_box.translate(Vec2d(-plate_origin.x(), -plate_origin.y())); + occupied_boxes.emplace_back(std::move(local_box)); } - } - else + + const Vec2f step = unscaled(get_extents(m_selected.front().poly).size()) + + Vec2f(m_selected.front().brim_width, m_selected.front().brim_width); + const bool has_conditional_exclusions = has_bed_exclusion_regions(m_unselected); + const std::vector empty_cells = + Plater::get_empty_cells(step, occupied_boxes, !has_conditional_exclusions); + + size_t cell_index = 0; + for (ArrangePolygon &item : m_selected) { + if (item.priority != 0) + continue; + + if (cell_index < empty_cells.size()) { + item.translation = scaled(empty_cells[cell_index++]); + item.bed_idx = 0; + } else { + item.bed_idx = arrangement::UNARRANGED; + } + } + + } else { arrangement::arrange(m_selected, m_unselected, m_bedpts, params); + } // finalize just here. ctl.update_status(100, ctl.was_canceled() ? @@ -358,6 +394,17 @@ void FillBedJob::finalize(bool canceled, std::exception_ptr &eptr) obj_list->update_printable_state(i, 0); } + if (m_instances && model_object->instances.size() > inst_cnt) { + const size_t new_instance_count = model_object->instances.size() - inst_cnt; + // Match the normal add-instance flow: update the scene before the + // object tree starts referring to the newly created instances. + m_plater->update(); + // A single-instance object has no instance children in the object + // tree yet, so the first refresh must add the original as well. + obj_list->increase_object_instances( + m_object_idx, inst_cnt == 1 ? new_instance_count + 1 : new_instance_count); + } + BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ": paste_objects_into_list"; /*for (ArrangePolygon& ap : m_selected) { @@ -368,10 +415,9 @@ void FillBedJob::finalize(bool canceled, std::exception_ptr &eptr) //model_object->ensure_on_bed(); //BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ": model_object->ensure_on_bed()"; - if (m_instances) {// && wxGetApp().app_config->get("auto_arrange") == "true") { - m_plater->set_prepare_state(Job::PREPARE_STATE_MENU); - m_plater->arrange(); - } + // FillBedJob has already computed and validated the final positions. + // The instance tree is synchronized above, so rerunning the general + // arranger here would only risk discarding a valid fill result. m_plater->update(); { diff --git a/src/slic3r/GUI/MainFrame.cpp b/src/slic3r/GUI/MainFrame.cpp index c36a895a17..e729e33ad7 100644 --- a/src/slic3r/GUI/MainFrame.cpp +++ b/src/slic3r/GUI/MainFrame.cpp @@ -909,6 +909,10 @@ bool MainFrame::handle_global_shortcut(const KeyChord& chord) m_plater->get_current_canvas3D()->post_event(SimpleEvent(wxEVT_PAINT)); } break; + case Shortcut::ShowCollisionVolumes: + if (m_plater && m_plater->is_view3D_shown() && m_plater->printer_technology() == ptFFF) + m_plater->show_collision_volumes(!m_plater->are_collision_volumes_shown()); + break; case Shortcut::ViewDefault: if (m_plater) { select_view("plate"); @@ -3471,6 +3475,14 @@ void MainFrame::init_menubar_as_editor() [this]() { return m_plater->is_view3D_shown(); }, [this]() { return m_plater->are_view3D_labels_shown(); }, this); m_shortcut_menu_items.push_back({ show_labels, Shortcut::ShowLabels, _L("Show &Labels"), true }); + wxMenuItem* show_collision_volumes = append_menu_check_item( + viewMenu, wxID_ANY, shortcut_label(_L("Show all collision volumes"), Shortcut::ShowCollisionVolumes, true), + _L("Show the full height of every configured collision volume, including on an empty bed."), + [this](wxCommandEvent&) { m_plater->show_collision_volumes(!m_plater->are_collision_volumes_shown()); }, this, + [this]() { return m_plater->is_view3D_shown() && m_plater->printer_technology() == ptFFF; }, + [this]() { return m_plater->are_collision_volumes_shown(); }, this); + m_shortcut_menu_items.push_back({ show_collision_volumes, Shortcut::ShowCollisionVolumes, _L("Show all collision volumes"), true }); + append_menu_check_item(viewMenu, wxID_ANY, _L("Show &Overhang"), _L("Show object overhang highlight in 3D scene."), [this](wxCommandEvent &) { m_plater->show_view3D_overhang(!m_plater->is_view3D_overhang_shown()); diff --git a/src/slic3r/GUI/OptionsGroup.cpp b/src/slic3r/GUI/OptionsGroup.cpp index 8af4cfeef8..924932916c 100644 --- a/src/slic3r/GUI/OptionsGroup.cpp +++ b/src/slic3r/GUI/OptionsGroup.cpp @@ -1209,7 +1209,7 @@ boost::any ConfigOptionsGroup::get_config_value(const DynamicPrintConfig& config if (opt_key == "printable_area") ret = get_thumbnails_string(config.option(opt_key)->values); else if (opt_key == "bed_exclude_area") - ret = get_thumbnails_string(config.option(opt_key)->values); + ret = from_u8(config.option(opt_key)->serialize()); else if (opt_key == "wrapping_exclude_area") ret = get_thumbnails_string(config.option(opt_key)->values); else @@ -1320,7 +1320,7 @@ boost::any ConfigOptionsGroup::get_config_value2(const DynamicPrintConfig& confi if (opt_key == "printable_area") ret = get_thumbnails_string(config.option(opt_key)->values); else if (opt_key == "bed_exclude_area") - ret = get_thumbnails_string(config.option(opt_key)->values); + ret = from_u8(config.option(opt_key)->serialize()); else if (opt_key == "wrapping_exclude_area") ret = get_thumbnails_string(config.option(opt_key)->values); else diff --git a/src/slic3r/GUI/PartPlate.cpp b/src/slic3r/GUI/PartPlate.cpp index 5e75696cf3..f8de4fbfc9 100644 --- a/src/slic3r/GUI/PartPlate.cpp +++ b/src/slic3r/GUI/PartPlate.cpp @@ -76,6 +76,8 @@ #include "libslic3r/GCode/WipeTowerEstimate.hpp" #include "libslic3r/ClipperUtils.hpp" #include "libslic3r/BoundingBox.hpp" +#include "libslic3r/ExclusionVolumeGeometry.hpp" +#include "libslic3r/Tesselate.hpp" #include "libslic3r/Geometry.hpp" #include "libslic3r/GCode/ThumbnailData.hpp" #include "libslic3r/IMEXHelpers.hpp" @@ -1467,6 +1469,144 @@ static bool init_model_from_lines(GLModel &model, const Lines3 &lines) return true; } +static ExPolygon expolygon_from_polygon(const Polygon &polygon) +{ + ExPolygon expolygon; + expolygon.contour = polygon; + expolygon.contour.make_counter_clockwise(); + return expolygon; +} + +static void append_expolygon_triangles(GLModel::Geometry &init_data, const ExPolygon &expolygon, float z) +{ + const std::vector triangles = triangulate_expolygon_2f(expolygon, NORMALS_UP); + if (triangles.empty() || triangles.size() % 3 != 0) + return; + + Vec2f min = triangles.front(); + Vec2f max = min; + for (const Vec2f &v : triangles) { + min = min.cwiseMin(v).eval(); + max = max.cwiseMax(v).eval(); + } + + const Vec2f size = max - min; + if (size.x() <= 0.0f || size.y() <= 0.0f) + return; + + Vec2f inv_size = size.cwiseInverse(); + inv_size.y() *= -1.0f; + + init_data.reserve_vertices(init_data.vertices_count() + triangles.size()); + init_data.reserve_indices(init_data.indices_count() + triangles.size()); + for (const Vec2f &v : triangles) { + init_data.add_vertex(Vec3f(v.x(), v.y(), z), (Vec2f)(v - min).cwiseProduct(inv_size).eval()); + const unsigned int vertices_counter = (unsigned int)init_data.vertices_count(); + if (vertices_counter % 3 == 0) + init_data.add_triangle(vertices_counter - 3, vertices_counter - 2, vertices_counter - 1); + } +} + +static bool init_model_from_polygons(GLModel &model, const Polygons &polygons, float z) +{ + model.reset(); + if (polygons.empty()) + return true; + + GLModel::Geometry init_data; + init_data.format = { GLModel::Geometry::EPrimitiveType::Triangles, GLModel::Geometry::EVertexLayout::P3T2 }; + + for (const Polygon &polygon : polygons) { + if (polygon.points.size() < 3) + continue; + + append_expolygon_triangles(init_data, expolygon_from_polygon(polygon), z); + } + + if (!init_data.is_empty()) + model.init_from(std::move(init_data)); + + return true; +} + +static bool init_model_from_expolygons(GLModel &model, const ExPolygons &expolygons, float z) +{ + model.reset(); + if (expolygons.empty()) + return true; + + GLModel::Geometry init_data; + init_data.format = { GLModel::Geometry::EPrimitiveType::Triangles, GLModel::Geometry::EVertexLayout::P3T2 }; + + for (const ExPolygon &expolygon : expolygons) { + if (expolygon.contour.points.size() < 3) + continue; + + append_expolygon_triangles(init_data, expolygon, z); + } + + if (!init_data.is_empty()) + model.init_from(std::move(init_data)); + + return true; +} + +struct ExclusionVolumePrismPreview +{ + Polygon footprint; + double z_min { 0.0 }; + double z_max { 0.0 }; +}; + +static bool init_exclusion_volume_prism_model(GLModel &model, const std::vector &prisms) +{ + model.reset(); + if (prisms.empty()) + return true; + + GLModel::Geometry init_data; + init_data.format = { GLModel::Geometry::EPrimitiveType::Triangles, GLModel::Geometry::EVertexLayout::P3 }; + + for (const ExclusionVolumePrismPreview &prism : prisms) { + const Polygon &polygon = prism.footprint; + const float z_min = static_cast(prism.z_min); + const float z_max = static_cast(prism.z_max); + if (polygon.points.size() < 3 || z_max <= z_min) + continue; + + init_data.reserve_vertices(init_data.vertices_count() + 4 * polygon.points.size()); + init_data.reserve_indices(init_data.indices_count() + 6 * polygon.points.size()); + for (size_t i = 0; i < polygon.points.size(); ++i) { + const Point &p0 = polygon.points[i]; + const Point &p1 = polygon.points[(i + 1) % polygon.points.size()]; + + init_data.add_vertex(Vec3f(unscale(p0.x()), unscale(p0.y()), z_min)); + init_data.add_vertex(Vec3f(unscale(p1.x()), unscale(p1.y()), z_min)); + init_data.add_vertex(Vec3f(unscale(p1.x()), unscale(p1.y()), z_max)); + init_data.add_vertex(Vec3f(unscale(p0.x()), unscale(p0.y()), z_max)); + + const unsigned int base = (unsigned int)init_data.vertices_count() - 4; + init_data.add_triangle(base, base + 1, base + 2); + init_data.add_triangle(base, base + 2, base + 3); + } + + const ExPolygon expolygon = expolygon_from_polygon(polygon); + const std::vector triangles = triangulate_expolygon_2f(expolygon, NORMALS_UP); + init_data.reserve_vertices(init_data.vertices_count() + triangles.size()); + init_data.reserve_indices(init_data.indices_count() + triangles.size()); + const unsigned int cap_base = (unsigned int)init_data.vertices_count(); + for (const Vec2f &v : triangles) + init_data.add_vertex(Vec3f(v.x(), v.y(), z_max)); + for (size_t i = 0; i + 2 < triangles.size(); i += 3) + init_data.add_triangle(cap_base + (unsigned int)i, cap_base + (unsigned int)i + 1, cap_base + (unsigned int)i + 2); + } + + if (!init_data.is_empty()) + model.init_from(std::move(init_data)); + + return true; +} + static void init_raycaster_from_model(PickingModel& model) { assert(model.mesh_raycaster == nullptr); @@ -1886,6 +2026,410 @@ void PartPlate::render_exclude_area(bool force_default_color) { glsafe(::glDepthMask(GL_TRUE)); } +double PartPlate::max_broad_phase_intersecting_object_height(const Polygons& regions) const +{ + if (m_model == nullptr) + return 0.0; + + double max_height = 0.0; + + for (const std::pair &object_instance : obj_to_instance_set) { + const int obj_id = object_instance.first; + const int instance_id = object_instance.second; + if (obj_id < 0 || obj_id >= int(m_model->objects.size())) + continue; + + ModelObject *object = m_model->objects[obj_id]; + if (instance_id < 0 || instance_id >= int(object->instances.size())) + continue; + + ModelInstance *instance = object->instances[instance_id]; + if (!instance->printable) + continue; + + Polygon hull = instance->convex_hull_2d(); + bool intersects_region = false; + for (const Polygon ®ion : regions) { + if (!intersection(Polygons{ region }, Polygons{ hull }).empty()) { + intersects_region = true; + break; + } + } + + if (!intersects_region) + continue; + + const BoundingBoxf3 instance_box = object->instance_convex_hull_bounding_box(instance_id); + max_height = std::max(max_height, instance_box.max.z()); + } + + return max_height; +} + +std::string PartPlate::exclusion_volume_preview_cache_key(const std::vector ®ions) const +{ + std::ostringstream key; + key << std::setprecision(17); + key << "plate:" << m_origin.x() << ',' << m_origin.y() << ',' << m_height << ';'; + + key << "regions:" << regions.size() << ';'; + for (const BedExcludeRegion ®ion : regions) { + key << region.z_min << ".." << region.z_max << ':' + << int(region.purpose) << ':' << region.has_z_range << ':' + << region.polygon.points.size(); + for (const Point &point : region.polygon.points) + key << ',' << point.x() << 'x' << point.y(); + key << ';'; + } + + key << "instances:" << obj_to_instance_set.size() << ';'; + if (m_model != nullptr) { + for (const std::pair &object_instance : obj_to_instance_set) { + const int obj_id = object_instance.first; + const int instance_id = object_instance.second; + key << obj_id << ':' << instance_id << ':'; + if (obj_id < 0 || obj_id >= int(m_model->objects.size())) { + key << "invalid;"; + continue; + } + + const ModelObject *object = m_model->objects[obj_id]; + if (instance_id < 0 || instance_id >= int(object->instances.size())) { + key << "invalid;"; + continue; + } + + const ModelInstance *instance = object->instances[instance_id]; + key << static_cast(object) << ':' << static_cast(instance) << ':' + << object->volumes.size() << ':' << instance->printable << ':'; + + const Transform3d instance_matrix = instance->get_matrix(); + for (int r = 0; r < int(instance_matrix.matrix().rows()); ++r) + for (int c = 0; c < int(instance_matrix.matrix().cols()); ++c) + key << instance_matrix.matrix()(r, c) << ','; + + for (const ModelVolume *volume : object->volumes) { + key << static_cast(volume) << ':'; + for (const int filament_id : volume->get_extruders()) + key << 'f' << filament_id << ','; + const Transform3d volume_matrix = volume->get_matrix(); + for (int r = 0; r < int(volume_matrix.matrix().rows()); ++r) + for (int c = 0; c < int(volume_matrix.matrix().cols()); ++c) + key << volume_matrix.matrix()(r, c) << ','; + } + key << ';'; + } + } + + return key.str(); +} + +void PartPlate::update_exclusion_volume_preview_models() +{ + if (!m_exclusion_volume_preview_dirty) + return; + m_exclusion_volume_preview_dirty = false; + + const DynamicPrintConfig *config = m_plater != nullptr ? m_plater->config() : nullptr; + if (config == nullptr) { + m_exclusion_volume_preview_cache_key.clear(); + m_exclusion_volume_floor_triangles.reset(); + m_exclusion_volume_border_triangles.reset(); + m_extruder_exclusion_volume_borders.clear(); + m_active_exclusion_volume_prisms.reset(); + m_exclusion_volume_intersection_triangles.reset(); + m_exclusion_volume_intersections_cleared = false; + return; + } + + const std::vector> regions_by_extruder = get_bed_excluded_regions_by_extruder(*config); + std::vector regions; + const BedExcludeVolumeMode mode = active_bed_exclude_volume_mode(*config); + for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { + if (mode == BedExcludeVolumeMode::Shared && extruder_id > 0) + break; + for (const BedExcludeRegion ®ion : regions_by_extruder[extruder_id]) { + if (!region.is_collision_volume() && extruder_id > 0) + continue; + regions.emplace_back(region); + } + } + // A coloured border communicates which physical nozzle owns a footprint. + // With only one nozzle the exclusion applies to every filament, so using + // the first filament colour would incorrectly imply material ownership. + const bool show_nozzle_ownership = + regions_by_extruder.size() > 1 && mode != BedExcludeVolumeMode::Shared; + std::ostringstream grouped_key; + const bool show_all_volumes = m_plater->are_collision_volumes_shown(); + grouped_key << exclusion_volume_preview_cache_key(regions) << "mode:" << int(mode) + << ";show_all:" << show_all_volumes << ";groups:"; + for (const std::vector &group : regions_by_extruder) + grouped_key << group.size() << ','; + const std::vector filament_colors = m_plater->get_extruder_colors_from_plater_config(); + std::vector preview_colors(regions_by_extruder.size()); + + // Use the same effective filament-to-nozzle policy as collision checks so + // the coloured border never implies a mapping the validator does not use. + const DynamicPrintConfig &project_config = wxGetApp().preset_bundle->project_config; + const std::vector filament_map = get_effective_exclusion_filament_maps( + project_config, filament_colors.size(), regions_by_extruder.size()); + grouped_key << "map:"; + for (const int extruder_id : filament_map) + grouped_key << extruder_id << ','; + grouped_key << ';'; + grouped_key << "object_maps:"; + if (m_model != nullptr) { + for (const std::pair &object_instance : obj_to_instance_set) { + const int object_id = object_instance.first; + if (object_id < 0 || object_id >= int(m_model->objects.size())) + continue; + grouped_key << object_id << ':'; + for (const auto &[filament_id, extruder_id] : get_object_filament_extruders( + *m_model->objects[object_id], project_config, regions_by_extruder.size())) + grouped_key << filament_id << '>' << extruder_id << ','; + grouped_key << ';'; + } + } + for (size_t filament_id = 0; filament_id < filament_colors.size(); ++filament_id) { + const int mapped_extruder = filament_id < filament_map.size() ? filament_map[filament_id] - 1 : int(filament_id); + if (mapped_extruder >= 0 && size_t(mapped_extruder) < preview_colors.size() && preview_colors[mapped_extruder].empty()) + preview_colors[mapped_extruder] = filament_colors[filament_id]; + } + + if (const ConfigOptionStrings *extruder_colors = config->opt("extruder_colour"); + extruder_colors != nullptr) { + for (size_t extruder_id = 0; extruder_id < preview_colors.size() && extruder_id < extruder_colors->size(); ++extruder_id) + if (preview_colors[extruder_id].empty()) + preview_colors[extruder_id] = extruder_colors->values[extruder_id]; + } + for (const std::string &color : preview_colors) + grouped_key << color << ','; + const std::string cache_key = grouped_key.str(); + if (cache_key == m_exclusion_volume_preview_cache_key && !m_exclusion_volume_intersections_cleared) + return; + m_exclusion_volume_preview_cache_key = cache_key; + m_exclusion_volume_intersections_cleared = false; + + m_exclusion_volume_floor_triangles.reset(); + m_exclusion_volume_border_triangles.reset(); + m_extruder_exclusion_volume_borders.clear(); + m_active_exclusion_volume_prisms.reset(); + m_exclusion_volume_intersection_triangles.reset(); + + const Point plate_offset(scale_(m_origin.x()), scale_(m_origin.y())); + Polygons floor_regions; + ExPolygons border_regions; + const coord_t ribbon_width = scale_(1.6); + struct PreviewRegion { + BedExcludeRegion region; + Polygon footprint; + size_t extruder_id; + }; + std::vector preview_regions; + Polygons preview_footprints; + std::vector active_prisms; + + if (show_nozzle_ownership) { + static const std::array fallback_colors = { + ColorRGBA{ .18f, .52f, .95f, .92f }, ColorRGBA{ .95f, .35f, .22f, .92f }, + ColorRGBA{ .25f, .72f, .38f, .92f }, ColorRGBA{ .72f, .34f, .88f, .92f }, + ColorRGBA{ .95f, .68f, .16f, .92f }, ColorRGBA{ .18f, .76f, .78f, .92f } + }; + const coord_t tool_border_width = scale_(0.55); + for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { + ColorRGBA color = fallback_colors[extruder_id % fallback_colors.size()]; + if (extruder_id < preview_colors.size()) { + ColorRGBA decoded; + if (decode_color(preview_colors[extruder_id], decoded)) { + color = decoded; + color.a(0.92f); + } + } + + for (const BedExcludeRegion ®ion_src : regions_by_extruder[extruder_id]) { + if (!region_src.is_collision_volume()) + continue; + Polygon footprint = region_src.polygon; + footprint.translate(plate_offset); + footprint.make_counter_clockwise(); + const Polygons inner = offset(Polygons{ footprint }, -tool_border_width, jtMiter, 2.0); + const ExPolygons border = inner.empty() ? ExPolygons{ expolygon_from_polygon(footprint) } : diff_ex(Polygons{ footprint }, inner); + auto model = std::make_unique(); + // Nozzle colours identify the bed footprint, not the volume's + // vertical position, so keep this border with the grey preview. + const float border_z = GROUND_Z + 0.026f; + if (init_model_from_expolygons(*model, border, border_z) && model->is_initialized()) + m_extruder_exclusion_volume_borders.emplace_back(std::move(model), color); + } + } + } + + for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { + // Shared regions are identical for every nozzle. Keeping one copy + // avoids duplicate floor, prism and intersection geometry. + if (mode == BedExcludeVolumeMode::Shared && extruder_id > 0) + break; + + for (const BedExcludeRegion ®ion_src : regions_by_extruder[extruder_id]) { + // The legacy area is shared and bed-fixed, even when nozzle-specific + // collision volumes are active. Keep only one preview copy. + if (!region_src.is_collision_volume() && extruder_id > 0) + continue; + Polygon region = region_src.polygon; + region.translate(plate_offset); + region.make_counter_clockwise(); + BedExcludeRegion translated_region = region_src; + translated_region.polygon = region; + preview_regions.push_back({ std::move(translated_region), region, extruder_id }); + preview_footprints.emplace_back(region); + + // Legacy polygons continue to use Orca's existing grey bed preview; + // the additional floor/ribbon belongs only to collision volumes. + if (region_src.is_collision_volume()) { + if (!region_src.has_z_range || region_src.z_min <= EPSILON) { + floor_regions.emplace_back(region); + } else { + const Polygons inner = offset(Polygons{ region }, -ribbon_width, jtMiter, 2.0); + ExPolygons border = inner.empty() ? ExPolygons{ expolygon_from_polygon(region) } : diff_ex(Polygons{ region }, inner); + border_regions.insert(border_regions.end(), border.begin(), border.end()); + } + } + } + } + + // Automatic previews stay limited to nearby objects. The View toggle lets + // profile authors inspect the complete configured height on an empty bed. + const double preview_height = show_all_volumes ? 0.0 : + max_broad_phase_intersecting_object_height(preview_footprints); + if (show_all_volumes || preview_height > EPSILON) { + for (const PreviewRegion &preview_region : preview_regions) { + const BedExcludeRegion ®ion_src = preview_region.region; + if (!region_src.is_collision_volume()) + continue; + const double z_min = region_src.has_z_range ? region_src.z_min : 0.0; + const double z_max = show_all_volumes ? region_src.z_max : std::min(region_src.z_max, preview_height); + if (z_max > z_min + EPSILON) + active_prisms.push_back({ preview_region.footprint, z_min, z_max }); + } + } + + indexed_triangle_set intersection_triangles; + if (m_model != nullptr && !preview_regions.empty()) { + for (const std::pair &object_instance : obj_to_instance_set) { + const int obj_id = object_instance.first; + const int instance_id = object_instance.second; + if (obj_id < 0 || obj_id >= int(m_model->objects.size())) + continue; + + ModelObject *object = m_model->objects[obj_id]; + if (instance_id < 0 || instance_id >= int(object->instances.size())) + continue; + + ModelInstance *instance = object->instances[instance_id]; + if (!instance->printable) + continue; + + std::set relevant_extruders; + if (mode != BedExcludeVolumeMode::Shared) { + for (const auto &mapping : get_object_filament_extruders( + *object, project_config, regions_by_extruder.size())) + relevant_extruders.emplace(mapping.second); + } + + Polygon hull = instance->convex_hull_2d(); + const BoundingBoxf3 instance_box = object->instance_convex_hull_bounding_box(instance_id); + for (const PreviewRegion &preview_region : preview_regions) { + if (preview_region.region.is_collision_volume() && mode != BedExcludeVolumeMode::Shared && + relevant_extruders.find(preview_region.extruder_id) == relevant_extruders.end()) + continue; + + const BedExcludeRegion ®ion = preview_region.region; + if (intersection(Polygons{ preview_region.footprint }, Polygons{ hull }).empty()) + continue; + if (instance_box.max.z() < region.z_min || instance_box.min.z() > region.z_max) + continue; + + // The preview path intentionally requests the full clipped mesh. + // Boolean-only placement checks call this without an output mesh. + indexed_triangle_set region_intersections; + if (instance->intersects_bed_exclude_region(region, ®ion_intersections) && !region_intersections.empty()) + its_merge(intersection_triangles, region_intersections); + } + } + } + + if (!floor_regions.empty() && !init_model_from_polygons(m_exclusion_volume_floor_triangles, floor_regions, GROUND_Z + 0.01f)) + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ":Unable to create exclusion volume floor preview triangles\n"; + + if (!border_regions.empty() && !init_model_from_expolygons(m_exclusion_volume_border_triangles, border_regions, GROUND_Z + 0.018f)) + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ":Unable to create exclusion volume preview border\n"; + + if (!active_prisms.empty() && !init_exclusion_volume_prism_model(m_active_exclusion_volume_prisms, active_prisms)) + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ":Unable to create active exclusion volume preview prisms\n"; + + if (!intersection_triangles.empty()) + m_exclusion_volume_intersection_triangles.init_from(intersection_triangles); +} + +void PartPlate::render_exclusion_volume_previews(bool force_default_color) +{ + if (force_default_color) + return; + + update_exclusion_volume_preview_models(); + + const ColorRGBA floor_color = m_selected ? ColorRGBA{ .86f, .86f, .86f, .70f } : ColorRGBA{ .60f, .60f, .60f, .30f }; + const ColorRGBA ribbon_color{ .60f, .60f, .60f, .70f }; + const ColorRGBA prism_color{ .52f, .52f, .52f, .38f }; + + glsafe(::glDepthMask(GL_FALSE)); + + m_exclusion_volume_floor_triangles.set_color(floor_color); + m_exclusion_volume_floor_triangles.render(); + + m_exclusion_volume_border_triangles.set_color(ribbon_color); + m_exclusion_volume_border_triangles.render(); + + for (auto &colored_border : m_extruder_exclusion_volume_borders) { + colored_border.first->set_color(colored_border.second); + colored_border.first->render(); + } + + m_active_exclusion_volume_prisms.set_color(prism_color); + m_active_exclusion_volume_prisms.render(); + + glsafe(::glLineWidth(1.0f * m_scale_factor)); + glsafe(::glDepthMask(GL_TRUE)); +} + +void PartPlate::render_exclusion_volume_intersections() +{ + if (!m_exclusion_volume_intersection_triangles.is_initialized()) + return; + + const ColorRGBA intersection_color{ .68f, .02f, .02f, .58f }; + + glsafe(::glEnable(GL_POLYGON_OFFSET_FILL)); + glsafe(::glPolygonOffset(-1.0f, -1.0f)); + + m_exclusion_volume_intersection_triangles.set_color(intersection_color); + m_exclusion_volume_intersection_triangles.render(); + + glsafe(::glDisable(GL_POLYGON_OFFSET_FILL)); +} + +void PartPlate::clear_exclusion_volume_intersections() +{ + m_exclusion_volume_intersection_triangles.reset(); + m_exclusion_volume_intersections_cleared = true; +} + +void PartPlate::invalidate_exclusion_volume_preview() +{ + m_exclusion_volume_preview_dirty = true; +} + + /*void PartPlate::render_background_for_picking(const ColorRGBA render_color) const { unsigned int triangles_vcount = m_triangles.get_vertices_count(); @@ -2992,6 +3536,122 @@ int PartPlate::get_logical_extruder_by_filament_id(const DynamicConfig& g_config return filament_map[idx - 1] - 1; } +std::vector PartPlate::get_effective_exclusion_filament_maps( + const DynamicConfig &g_config, const size_t filament_count, const size_t extruder_count) const +{ + std::vector result(filament_count, 0); + if (extruder_count == 0) + return result; + + const std::vector configured_map = get_real_filament_maps(g_config); + const FilamentMapMode map_mode = get_real_filament_map_mode(g_config); + PresetBundle *preset_bundle = wxGetApp().preset_bundle; + const bool is_bambu = preset_bundle != nullptr && preset_bundle->is_bbl_vendor(); + const bool automatic = is_auto_filament_map_mode(map_mode); + const bool automatic_map_resolved = !automatic || !get_filament_maps().empty(); + for (size_t filament_id = 0; filament_id < filament_count; ++filament_id) { + const int extruder_id = bed_exclusion_extruder_for_filament( + filament_id, configured_map, map_mode, is_bambu, automatic_map_resolved, extruder_count); + if (extruder_id >= 0) + result[filament_id] = extruder_id + 1; + } + return result; +} + +std::map PartPlate::get_object_filament_extruders( + const ModelObject &object, const DynamicConfig &g_config, const size_t extruder_count) const +{ + std::set filament_ids; + const DynamicPrintConfig &process_config = wxGetApp().preset_bundle->prints.get_edited_preset().config; + const auto effective_option = [&object, &process_config](const char *key) -> const ConfigOption * { + if (const ConfigOption *option = object.config.option(key); option != nullptr) + return option; + return process_config.option(key); + }; + const auto effective_int = [&effective_option](const char *key) { + const ConfigOption *option = effective_option(key); + return option != nullptr ? option->getInt() : 0; + }; + const auto effective_float = [&effective_option](const char *key) { + const ConfigOption *option = effective_option(key); + return option != nullptr ? option->getFloat() : 0.0; + }; + const auto effective_bool = [&effective_option](const char *key) { + const ConfigOption *option = effective_option(key); + return option != nullptr && option->getBool(); + }; + + const bool has_brim = effective_int("brim_type") != int(BrimType::btNoBrim) && effective_float("brim_width") > 0.0; + const int wall_loops = effective_int("wall_loops"); + const double sparse_infill_density = effective_float("sparse_infill_density"); + const int top_shell_layers = effective_int("top_shell_layers"); + const int bottom_shell_layers = effective_int("bottom_shell_layers"); + const std::array, 6> feature_filament_keys = { + std::pair{ "outer_wall_filament_id", wall_loops > 0 || has_brim }, + std::pair{ "inner_wall_filament_id", wall_loops > 1 }, + std::pair{ "sparse_infill_filament_id", sparse_infill_density > 0.0 }, + std::pair{ "internal_solid_filament_id", sparse_infill_density > 0.0 || top_shell_layers > 0 || bottom_shell_layers > 0 }, + std::pair{ "top_surface_filament_id", top_shell_layers > 0 }, + std::pair{ "bottom_surface_filament_id", bottom_shell_layers > 0 } + }; + auto collect_config_filaments = [&filament_ids, &feature_filament_keys](const DynamicConfig &config) { + for (const auto &[key, active] : feature_filament_keys) { + if (active) { + if (const ConfigOption *option = config.option(key); option != nullptr && option->getInt() > 0) + filament_ids.emplace(option->getInt()); + } + } + if (const ConfigOption *option = config.option("extruder"); option != nullptr && option->getInt() > 0) + filament_ids.emplace(option->getInt()); + }; + + for (const ModelVolume *volume : object.volumes) { + const std::vector volume_filaments = volume->get_extruders(); + filament_ids.insert(volume_filaments.begin(), volume_filaments.end()); + collect_config_filaments(volume->config.get()); + } + collect_config_filaments(object.config.get()); + for (const auto &layer_range : object.layer_config_ranges) + collect_config_filaments(layer_range.second.get()); + + // Process-level feature assignments also apply when the object has no + // override. This mirrors the relevant parts of PrintObject::printing_extruders() + // closely enough for an unsliced placement preview. + for (const auto &[key, active] : feature_filament_keys) { + if (active && !object.config.has(key) && process_config.has(key) && process_config.opt_int(key) > 0) + filament_ids.emplace(process_config.opt_int(key)); + } + + const bool has_support = effective_bool("enable_support") || effective_int("raft_layers") > 0; + if (has_support) { + const int support_filament = effective_int("support_filament"); + const int interface_filament = effective_int("support_interface_filament"); + if (support_filament > 0) + filament_ids.emplace(support_filament); + if (interface_filament > 0) + filament_ids.emplace(interface_filament); + } + + // Match Orca's normal fallback for an unassigned object. + if (filament_ids.empty()) + filament_ids.emplace(1); + + const size_t required_filament_count = filament_ids.empty() ? 0 : size_t(*filament_ids.rbegin()); + const std::vector filament_map = get_effective_exclusion_filament_maps( + g_config, required_filament_count, extruder_count); + std::map result; + for (const int filament_id : filament_ids) { + if (filament_id <= 0) + continue; + + const int mapped_extruder = size_t(filament_id) <= filament_map.size() && filament_map[filament_id - 1] > 0 ? + filament_map[filament_id - 1] - 1 : -1; + if (mapped_extruder >= 0 && size_t(mapped_extruder) < extruder_count) + result.emplace(filament_id, size_t(mapped_extruder)); + } + return result; +} + std::vector PartPlate::get_used_filaments() { std::vector used_filaments; @@ -3513,6 +4173,7 @@ void PartPlate::clear(bool clear_sliced_result) { obj_to_instance_set.clear(); instance_outside_set.clear(); + invalidate_exclusion_volume_preview(); if (clear_sliced_result) { m_ready_for_slice = true; update_slice_result_valid_state(false); @@ -3592,6 +4253,7 @@ void PartPlate::set_pos_and_size(Vec3d& origin, int width, int depth, double hei m_width = width; m_depth = depth; m_height = height; + invalidate_exclusion_volume_preview(); if (with_instance_move && m_plater) m_plater->mark_plate_toolbar_image_dirty(); @@ -3721,6 +4383,7 @@ void PartPlate::set_print(PrintBase* print, GCodeResult* result, int index) m_print_index = index; m_print->set_plate_origin(m_origin); + invalidate_exclusion_volume_preview(); return; } @@ -3841,7 +4504,14 @@ bool PartPlate::check_outside(int obj_id, int instance_id, BoundingBoxf3* boundi ModelInstance* instance = object->instances[instance_id]; BoundingBoxf3 instance_box = bounding_box? *bounding_box: object->instance_convex_hull_bounding_box(instance_id); - Polygon hull = instance->convex_hull_2d(); + // Reuse the hull across exclusion and IMEX checks, but do not build it for + // instances rejected by the plate bounds or printers with no relevant zones. + std::optional instance_hull; + const auto get_instance_hull = [&]() -> const Polygon & { + if (!instance_hull) + instance_hull = instance->convex_hull_2d(); + return *instance_hull; + }; BoundingBoxf3 plate_box = get_plate_box(); this->open_belt_y(plate_box); if (instance_box.max.z() > plate_box.min.z()) @@ -3860,34 +4530,66 @@ bool PartPlate::check_outside(int obj_id, int instance_id, BoundingBoxf3* boundi else if (plate_box.contains(instance_box)) { - if (m_exclude_bounding_box.size() > 0) - { - Polygon hull = instance->convex_hull_2d(); - int index; - for (index = 0; index < m_exclude_bounding_box.size(); index ++) - { - Polygon p = m_exclude_bounding_box[index].polygon(true); // instance convex hull is scaled, so we need to scale here - if (intersection({ p }, { hull }).empty() == false) - //if (m_exclude_bounding_box[index].intersects(instance_box)) - { - break; - } - } - if (index >= m_exclude_bounding_box.size()) - outside = false; - } - else - outside = false; + outside = false; + const DynamicPrintConfig *config = m_plater != nullptr ? m_plater->config() : nullptr; + bool checked_config_regions = false; + if (config != nullptr) { + const std::vector> regions_by_extruder = + get_bed_excluded_regions_by_extruder(*config); + const BedExcludeVolumeMode mode = active_bed_exclude_volume_mode(*config); + // The legacy outside flag has no filament/nozzle context. Always + // check the shared legacy area here, but let the newer per-extruder + // pipeline handle nozzle-specific collision volumes. + const Point plate_offset(scale_(m_origin.x()), scale_(m_origin.y())); + const Polygon &hull = get_instance_hull(); + + const size_t groups_to_check = regions_by_extruder.empty() ? 0 : 1; + for (size_t group_id = 0; group_id < groups_to_check; ++group_id) { + const std::vector &extruder_regions = regions_by_extruder[group_id]; + for (const BedExcludeRegion ®ion_src : extruder_regions) { + if (mode != BedExcludeVolumeMode::Shared && region_src.is_collision_volume()) + continue; + checked_config_regions = true; + Polygon region = region_src.polygon; + region.translate(plate_offset); + region.make_counter_clockwise(); + + if (intersection(Polygons{ region }, Polygons{ hull }).empty()) + continue; + + if (instance_box.max.z() < region_src.z_min || instance_box.min.z() > region_src.z_max) + continue; + + BedExcludeRegion translated_region = region_src; + translated_region.polygon = std::move(region); + if (instance->intersects_bed_exclude_region(translated_region)) { + outside = true; + break; + } + } + if (outside) + break; + } + } + + if (!checked_config_regions && m_exclude_bounding_box.size() > 0) { + const Polygon &hull = get_instance_hull(); + for (const BoundingBoxf3 &exclude_box : m_exclude_bounding_box) { + Polygon p = exclude_box.polygon(true); // instance convex hull is scaled, so we need to scale here + if (!intersection({ p }, { hull }).empty()) { + outside = true; + break; + } + } + } } // IDEX/IQEX placement check (prepare-mode bounding-box test). // Block objects that overlap secondary (copy/mirror) zones or the carriage // danger strip at the primary zone boundary. Reuses the existing // outside=true → instance_outside_set → update_states() → blocks slicing path. - // Reuse the hull computed above: ModelInstance::convex_hull_2d() is NOT cached - // (Model.cpp has the validity guard commented out), so recomputing it here would - // cost every user a per-instance hull rebuild, including on non-IMEX printers. - if (!outside && imex_hull_violates(hull)) + if (!outside && (!m_imex_secondary_zone_boxes.empty() || !m_imex_collision_zones.empty()) && + imex_hull_violates(get_instance_hull())) outside = true; return outside; @@ -3953,6 +4655,7 @@ int PartPlate::add_instance(int obj_id, int instance_id, bool move_position, Bou std::pair pair(obj_id, instance_id); obj_to_instance_set.insert(pair); + invalidate_exclusion_volume_preview(); BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << boost::format(": plate_id %1%, add instance obj_id %2%, instance_id %3%, move_position %4%") % m_plate_index % obj_id % instance_id % move_position; @@ -3995,6 +4698,7 @@ int PartPlate::remove_instance(int obj_id, int instance_id) it = obj_to_instance_set.find(std::pair(obj_id, instance_id)); if (it != obj_to_instance_set.end()) { obj_to_instance_set.erase(it); + invalidate_exclusion_volume_preview(); BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << boost::format(":plate_id %1%, found obj_id %2%, instance_id %3%") % m_plate_index % obj_id % instance_id; result = 0; } @@ -4054,6 +4758,7 @@ void PartPlate::translate_all_instance(Vec3d position) } } } + invalidate_exclusion_volume_preview(); return; } @@ -4088,6 +4793,7 @@ void PartPlate::duplicate_all_instance(unsigned int dup_count, bool need_skip, s for ( size_t new_instance_id = 0; new_instance_id < newObj->instances.size(); new_instance_id++ ) { obj_to_instance_set.emplace(std::pair(new_obj_id, new_instance_id)); + invalidate_exclusion_volume_preview(); BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": duplicate object into plate: index_pair [%1%,%2%], obj_id %3%") % new_obj_id % new_instance_id % newObj->id().id; } } @@ -4131,6 +4837,7 @@ void PartPlate::update_instance_exclude_status(int obj_id, int instance_id, Boun std::set>::iterator it; outside = check_outside(obj_id, instance_id, bounding_box); + invalidate_exclusion_volume_preview(); it = instance_outside_set.find(std::pair(obj_id, instance_id)); if (it == instance_outside_set.end()) { @@ -4158,6 +4865,7 @@ void PartPlate::update_object_index(int obj_idx_removed, int obj_idx_max) } obj_to_instance_set.clear(); obj_to_instance_set = temp_set; + invalidate_exclusion_volume_preview(); //update the instance_outside_set temp_set.clear(); @@ -4413,6 +5121,8 @@ void PartPlate::generate_exclude_polygon(ExPolygon &exclude_polygon) bool PartPlate::set_shape(const Pointfs& shape, const Pointfs& exclude_areas, const std::vector& extruder_areas, const std::vector& extruder_heights, Vec2d position, float height_to_lid, float height_to_rod) { + invalidate_exclusion_volume_preview(); + Pointfs new_shape, new_exclude_areas; m_extruder_heights = extruder_heights; for (const Vec2d& p : shape) { @@ -4633,6 +5343,7 @@ void PartPlate::render(const Transform3d& view_matrix, const Transform3d& projec } render_wrapping_detection_area(force_background_color); } + render_exclusion_volume_previews(force_background_color); } render_height_limit(mode); @@ -5073,6 +5784,7 @@ void PartPlate::set_filament_map_mode(const FilamentMapMode& mode) clear_filament_map_mode(); else m_config.option>("filament_map_mode", true)->value = mode; + invalidate_exclusion_volume_preview(); } std::vector PartPlate::get_filament_maps() const @@ -5087,12 +5799,14 @@ std::vector PartPlate::get_filament_maps() const void PartPlate::set_filament_maps(const std::vector& f_maps) { m_config.option("filament_map", true)->values = f_maps; + invalidate_exclusion_volume_preview(); } void PartPlate::clear_filament_map() { if (m_config.has("filament_map")) m_config.erase("filament_map"); + invalidate_exclusion_volume_preview(); } std::vector PartPlate::get_filament_volume_maps() const @@ -5810,6 +6524,39 @@ void PartPlateList::update_plates() set_shapes(m_shape, m_exclude_areas, m_wrapping_exclude_areas, m_extruder_areas, m_extruder_heights, m_logo_texture_filename, m_height_to_lid, m_height_to_rod); } +void PartPlateList::invalidate_exclusion_volume_previews() +{ + for (PartPlate *plate : m_plate_list) + if (plate != nullptr) + plate->invalidate_exclusion_volume_preview(); +} + +void PartPlateList::render_exclusion_volume_intersections( + const Transform3d &view_matrix, + const Transform3d &projection_matrix) +{ + GLShaderProgram *shader = wxGetApp().get_shader("flat"); + if (shader == nullptr) + return; + + shader->start_using(); + shader->set_uniform("view_model_matrix", view_matrix); + shader->set_uniform("projection_matrix", projection_matrix); + + glsafe(::glEnable(GL_DEPTH_TEST)); + glsafe(::glEnable(GL_BLEND)); + glsafe(::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); + glsafe(::glDepthMask(GL_FALSE)); + + for (PartPlate *plate : m_plate_list) + if (plate != nullptr) + plate->render_exclusion_volume_intersections(); + + glsafe(::glDepthMask(GL_TRUE)); + glsafe(::glDisable(GL_BLEND)); + shader->stop_using(); +} + int PartPlateList::create_plate(bool adjust_position) { PartPlate* plate = NULL; @@ -5918,6 +6665,7 @@ int PartPlateList::duplicate_plate(int index) // go over the instances and pair with the object for (size_t new_instance_id = 0; new_instance_id < object_copy->instances.size(); new_instance_id++){ new_plate->obj_to_instance_set.emplace(std::pair(new_obj_id, new_instance_id)); + new_plate->invalidate_exclusion_volume_preview(); BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": duplicate object into plate: index_pair [%1%,%2%], obj_id %3%") % new_obj_id % new_instance_id % object_copy->id().id; } } @@ -6903,7 +7651,8 @@ bool PartPlateList::preprocess_arrange_polygon_other_locked(int obj_index, int i return locked; } -bool PartPlateList::preprocess_exclude_areas(arrangement::ArrangePolygons &unselected, bool enable_wrapping_detect, int num_plates, float inflation) +bool PartPlateList::preprocess_exclude_areas(arrangement::ArrangePolygons &unselected, const DynamicPrintConfig &config, + bool enable_wrapping_detect, int num_plates, float inflation) { bool added = false; @@ -6935,10 +7684,47 @@ bool PartPlateList::preprocess_exclude_areas(arrangement::ArrangePolygons &unsel } added = true; } + const BedExcludeVolumeMode mode = active_bed_exclude_volume_mode(config); + const bool use_resolved_regions = has_bed_exclude_volumes(config); - // excluded area - if (m_exclude_areas.size() > 0) - { + if (use_resolved_regions) { + const std::vector> regions_by_extruder = + get_bed_excluded_regions_by_extruder(config); + const size_t extruder_count = mode == BedExcludeVolumeMode::Shared ? + std::min(1, regions_by_extruder.size()) : regions_by_extruder.size(); + + for (size_t extruder_id = 0; extruder_id < extruder_count; ++extruder_id) { + for (size_t region_id = 0; region_id < regions_by_extruder[extruder_id].size(); ++region_id) { + const BedExcludeRegion ®ion = regions_by_extruder[extruder_id][region_id]; + if (!region.is_collision_volume() || region.polygon.points.size() < 3 || + (region.has_z_range && region.z_max <= region.z_min + EPSILON)) + continue; + + for (int plate_idx = 0; plate_idx < num_plates; ++plate_idx) { + arrangement::ArrangePolygon blocker; + blocker.poly.contour = bed_exclusion_arrange_polygon(region.polygon); + blocker.translation = Vec2crd::Zero(); + blocker.rotation = 0.0; + blocker.is_virt_object = true; + blocker.is_bed_exclusion = true; + blocker.bed_exclusion_extruder_id = mode == BedExcludeVolumeMode::Shared ? -1 : int(extruder_id); + blocker.bed_idx = plate_idx; + blocker.height = std::max(0.0, region.z_max - region.z_min); + blocker.z_min = region.z_min; + blocker.z_max = region.z_max; + blocker.has_z_range = region.has_z_range; + blocker.name = "BedExclusionVolume" + std::to_string(extruder_id) + "_" + std::to_string(region_id); + blocker.inflation = inflation; + unselected.emplace_back(std::move(blocker)); + } + added = true; + } + } + } + + // Keep Orca's established legacy-area arrange obstacle alongside any + // explicit collision-volume blockers. The two settings are additive. + if (!m_exclude_areas.empty()) { //has exclude areas PartPlate *plate = m_plate_list[0]; diff --git a/src/slic3r/GUI/PartPlate.hpp b/src/slic3r/GUI/PartPlate.hpp index 043fc3ee82..d90e6f2767 100644 --- a/src/slic3r/GUI/PartPlate.hpp +++ b/src/slic3r/GUI/PartPlate.hpp @@ -19,11 +19,14 @@ #include #include #include +#include #include +#include #include #include #include #include +#include #include #include "libslic3r/ObjectID.hpp" @@ -159,6 +162,14 @@ private: PickingModel m_triangles; GLModel m_exclude_triangles; GLModel m_wrapping_detection_triangles; + GLModel m_exclusion_volume_floor_triangles; + GLModel m_exclusion_volume_border_triangles; + std::vector, ColorRGBA>> m_extruder_exclusion_volume_borders; + GLModel m_active_exclusion_volume_prisms; + GLModel m_exclusion_volume_intersection_triangles; + std::string m_exclusion_volume_preview_cache_key; + bool m_exclusion_volume_preview_dirty { true }; + bool m_exclusion_volume_intersections_cleared { false }; GLModel m_logo_triangles; GLModel m_gridlines; GLModel m_gridlines_bolder; @@ -241,6 +252,11 @@ private: void render_logo(bool bottom, bool render_cali = true); void render_logo_texture(GLTexture &logo_texture, GLModel &logo_buffer, bool bottom); void render_exclude_area(bool force_default_color); + void render_exclusion_volume_previews(bool force_default_color); + void render_exclusion_volume_intersections(); + void update_exclusion_volume_preview_models(); + std::string exclusion_volume_preview_cache_key(const std::vector ®ions) const; + double max_broad_phase_intersecting_object_height(const Polygons& regions) const; //void render_background_for_picking(const ColorRGBA render_color) const; void render_grid(bool bottom); void render_wrapping_detection_area(bool force_default_color); @@ -485,6 +501,16 @@ public: const std::vector& get_slice_filaments_info() const { return slice_filaments_info; } int get_physical_extruder_by_filament_id(const DynamicConfig& g_config, int idx) const; int get_logical_extruder_by_filament_id(const DynamicConfig& g_config, int idx) const; + // Resolve the mapping policy used specifically by exclusion regions. + // Values are 1-based nozzle ids; 0 means automatic Bambu mapping has not + // produced a concrete plate-local assignment yet. + std::vector get_effective_exclusion_filament_maps(const DynamicConfig &g_config, size_t filament_count, + size_t extruder_count) const; + // 1-based filament id -> 0-based nozzle/exclusion-region id for the + // object's current plate mapping. Includes every filament referenced by + // any model volume (including painted facets). + std::map get_object_filament_extruders(const ModelObject &object, const DynamicConfig &g_config, + size_t extruder_count) const; bool check_filament_printable(const DynamicPrintConfig & config, wxString& error_message); bool check_tpu_printable_status(const DynamicPrintConfig & config, const std::vector &tpu_filaments); bool check_mixture_of_pla_and_petg(const DynamicPrintConfig & config); @@ -508,6 +534,8 @@ public: //check whether instance is outside the plate or not bool check_outside(int obj_id, int instance_id, BoundingBoxf3* bounding_box = nullptr); + void clear_exclusion_volume_intersections(); + void invalidate_exclusion_volume_preview(); //judge whether instance is intesected with plate or not bool intersect_instance(int obj_id, int instance_id, BoundingBoxf3* bounding_box = nullptr); @@ -713,6 +741,8 @@ public: for (std::vector>::iterator it = instances_outside.begin(); it != instances_outside.end(); ++it) instance_outside_set.insert(std::pair(it->first, it->second)); + + invalidate_exclusion_volume_preview(); } template void save(Archive& ar) const { std::vector> objects_and_instances; @@ -893,6 +923,8 @@ public: // Pantheon: update plates after moving plate to the front void update_plates(); + void invalidate_exclusion_volume_previews(); + void render_exclusion_volume_intersections(const Transform3d &view_matrix, const Transform3d &projection_matrix); /*basic plate operations*/ //create an empty plate and return its index @@ -1009,7 +1041,8 @@ public: //preprocess an arrangement::ArrangePolygon, return true if it is in a locked plate bool preprocess_arrange_polygon(int obj_index, int instance_index, arrangement::ArrangePolygon& arrange_polygon, bool selected); bool preprocess_arrange_polygon_other_locked(int obj_index, int instance_index, arrangement::ArrangePolygon& arrange_polygon, bool selected); - bool preprocess_exclude_areas(arrangement::ArrangePolygons& unselected, bool enable_wrapping_detect, int num_plates = 16, float inflation = 0); + bool preprocess_exclude_areas(arrangement::ArrangePolygons &unselected, const DynamicPrintConfig &config, + bool enable_wrapping_detect, int num_plates = 16, float inflation = 0); bool preprocess_nonprefered_areas(arrangement::ArrangePolygons& regions, int num_plates = 1, float inflation=0); void postprocess_bed_index_for_selected(arrangement::ArrangePolygon& arrange_polygon); diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index d55f417842..a7e3a9ca6d 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -7830,7 +7830,8 @@ Plater::priv::priv(Plater *q, MainFrame *main_frame) , main_frame(main_frame) //BBS: add bed_exclude_area , config(Slic3r::DynamicPrintConfig::new_from_defaults_keys({ - "printable_area", "bed_exclude_area", "wrapping_exclude_area", "extruder_printable_area", "bed_custom_texture", "bed_custom_model", "print_sequence", + "printable_area", "bed_exclude_area", "bed_exclude_volumes", "bed_exclude_volume_mode", "extruder_bed_exclude_volumes", "extruder_offset", + "wrapping_exclude_area", "extruder_printable_area", "bed_custom_texture", "bed_custom_model", "print_sequence", "extruder_clearance_radius", "extruder_clearance_height_to_lid", "extruder_clearance_height_to_rod", "nozzle_height", "skirt_type", "skirt_loops", "skirt_speed","min_skirt_length", "skirt_distance", "skirt_start_angle", @@ -19124,6 +19125,19 @@ bool Plater::is_view3D_shown() const { return p->is_view3D_shown(); } bool Plater::are_view3D_labels_shown() const { return p->are_view3D_labels_shown(); } void Plater::show_view3D_labels(bool show) { p->show_view3D_labels(show); } +bool Plater::are_collision_volumes_shown() const +{ + return wxGetApp().app_config->get_bool("show_collision_volumes"); +} + +void Plater::show_collision_volumes(bool show) +{ + wxGetApp().app_config->set_bool("show_collision_volumes", show); + p->partplate_list.invalidate_exclusion_volume_previews(); + p->view3D->get_canvas3d()->set_as_dirty(); + p->view3D->get_canvas3d()->request_extra_frame(); +} + bool Plater::is_view3D_overhang_shown() const { return p->is_view3D_overhang_shown(); } void Plater::show_view3D_overhang(bool show) { p->show_view3D_overhang(show); } @@ -21495,6 +21509,7 @@ void Plater::on_config_change(const DynamicPrintConfig &config) { bool update_scheduled = false; bool bed_shape_changed = false; + bool exclusion_preview_changed = false; bool imex_changed = false; //bool print_sequence_changed = false; t_config_option_keys diff_keys = p->config->diff(config); @@ -21513,6 +21528,7 @@ void Plater::on_config_change(const DynamicPrintConfig &config) if (update_filament_colors_in_full_config()) { p->sidebar->update_mixed_filament_list(); + p->partplate_list.invalidate_exclusion_volume_previews(); p->sidebar->obj_list()->update_filament_colors(); p->sidebar->update_dynamic_filament_list(); continue; @@ -21536,6 +21552,12 @@ void Plater::on_config_change(const DynamicPrintConfig &config) } p->config->set_key_value(opt_key, config.option(opt_key)->clone()); + if (opt_key == "bed_exclude_volume_mode" || opt_key == "bed_exclude_area" || + opt_key == "bed_exclude_volumes" || opt_key == "extruder_bed_exclude_volumes" || opt_key == "extruder_offset" || + opt_key == "master_extruder_id" || opt_key == "nozzle_diameter" || + opt_key == "printable_height" || opt_key == "extruder_colour") + exclusion_preview_changed = true; + if (opt_key == "printer_technology") { this->set_printer_technology(config.opt_enum(opt_key)); // print technology is changed, so we should to update a search list @@ -21547,7 +21569,8 @@ void Plater::on_config_change(const DynamicPrintConfig &config) p->partplate_list.invalid_all_slice_result(); } //BBS: add bed_exclude_area - else if (opt_key == "printable_area" || opt_key == "bed_exclude_area" + else if (opt_key == "printable_area" || opt_key == "bed_exclude_volume_mode" || opt_key == "bed_exclude_area" + || opt_key == "bed_exclude_volumes" || opt_key == "extruder_bed_exclude_volumes" || opt_key == "extruder_offset" || opt_key == "bed_custom_texture" || opt_key == "bed_custom_model" || opt_key == "extruder_clearance_height_to_lid" || opt_key == "extruder_clearance_height_to_rod") { @@ -21569,6 +21592,7 @@ void Plater::on_config_change(const DynamicPrintConfig &config) } else if(opt_key == "extruder_colour") { update_scheduled = true; + p->partplate_list.invalidate_exclusion_volume_previews(); //p->sidebar->obj_list()->update_extruder_colors(); } else if (opt_key == "printable_height") { @@ -21593,8 +21617,12 @@ void Plater::on_config_change(const DynamicPrintConfig &config) else if (opt_key == "support_interface_filament" || opt_key == "support_filament" || opt_key == "outer_wall_filament_id" || opt_key == "inner_wall_filament_id" || opt_key == "sparse_infill_filament_id" || opt_key == "internal_solid_filament_id" || - opt_key == "top_surface_filament_id" || opt_key == "bottom_surface_filament_id") { + opt_key == "top_surface_filament_id" || opt_key == "bottom_surface_filament_id" || + opt_key == "enable_support" || opt_key == "raft_layers" || opt_key == "wall_loops" || + opt_key == "sparse_infill_density" || opt_key == "top_shell_layers" || + opt_key == "bottom_shell_layers" || opt_key == "brim_type" || opt_key == "brim_width") { update_scheduled = true; + p->partplate_list.invalidate_exclusion_volume_previews(); } // IDEX/IQEX: when is_imex toggles the mode icon needs to be repositioned on every plate. // set_shape() short-circuits when the bed geometry is unchanged, so we refresh explicitly. @@ -21608,8 +21636,16 @@ void Plater::on_config_change(const DynamicPrintConfig &config) p->view3D->get_canvas3d()->set_as_dirty(); } - if (bed_shape_changed) + if (bed_shape_changed) { set_bed_shape(); + get_current_canvas3D()->requires_check_outside_state(); + } + + if (exclusion_preview_changed) + p->partplate_list.invalidate_exclusion_volume_previews(); + + if (bed_shape_changed || exclusion_preview_changed) + get_current_canvas3D()->request_extra_frame(); // After any bed-shape or is_imex change, ensure the IMEX mode icon geometry and // raycaster are correct. set_shape() short-circuits when the bed is unchanged, @@ -21690,9 +21726,10 @@ void Plater::set_bed_shape() const } } } + const ConfigOptionPoints *bed_exclude_area = p->config->option("bed_exclude_area"); set_bed_shape(p->config->option("printable_area")->values, //BBS: add bed exclude areas - p->config->option("bed_exclude_area")->values, + bed_exclude_area->values, p->config->option("wrapping_exclude_area")->values, p->config->option("printable_height")->value, p->config->option("extruder_printable_area")->values, @@ -21933,6 +21970,7 @@ void Plater::set_global_filament_map(const std::vector& filament_map) { auto& project_config = wxGetApp().preset_bundle->project_config; project_config.option("filament_map")->values = filament_map; + p->partplate_list.invalidate_exclusion_volume_previews(); } void Plater::set_global_filament_volume_map(const std::vector& filament_volume_map) @@ -22185,6 +22223,7 @@ void Plater::changed_mesh(int obj_idx) void Plater::changed_object(ModelObject &object){ assert(object.get_model() == &p->model); // is object from same model? object.invalidate_bounding_box(); + p->partplate_list.invalidate_exclusion_volume_previews(); // recenter and re - align to Z = 0 object.ensure_on_bed(p->printer_technology != ptSLA); @@ -22226,6 +22265,8 @@ void Plater::changed_objects(const std::vector& object_idxs) if (object_idxs.empty()) return; + p->partplate_list.invalidate_exclusion_volume_previews(); + for (size_t obj_idx : object_idxs) { if (obj_idx < p->model.objects.size()) { if (p->model.objects[obj_idx]->min_z() >= SINKING_Z_THRESHOLD) @@ -22414,7 +22455,9 @@ void Plater::clone_selection() dlg.ShowModal(); } -std::vector Plater::get_empty_cells(const Vec2f step) +std::vector Plater::get_empty_cells(const Vec2f step, + const std::vector &local_exclude_boxes, + bool include_plate_exclude_areas) { PartPlate* plate = wxGetApp().plater()->get_partplate_list().get_curr_plate(); BoundingBoxf3 build_volume = plate->get_build_volume(true); @@ -22423,11 +22466,18 @@ std::vector Plater::get_empty_cells(const Vec2f step) std::vector cells; auto min_x = step(0)/2;// start_point.x() - step(0) * int((start_point.x() - bbox.min.x()) / step(0)); auto min_y = step(1)/2;// start_point.y() - step(1) * int((start_point.y() - bbox.min.y()) / step(1)); - auto& exclude_box3s = plate->get_exclude_areas(); std::vector exclude_boxs; - for (auto& box : exclude_box3s) { - Vec2d vmin(box.min.x(), box.min.y()), vmax(box.max.x(), box.max.y()); - exclude_boxs.emplace_back(vmin, vmax); + if (include_plate_exclude_areas) { + const auto &exclude_box3s = plate->get_exclude_areas(); + for (const auto &box : exclude_box3s) { + Vec2d vmin(box.min.x(), box.min.y()), vmax(box.max.x(), box.max.y()); + exclude_boxs.emplace_back(vmin, vmax); + } + } + const Vec3d plate_origin = plate->get_origin(); + for (BoundingBoxf box : local_exclude_boxes) { + box.translate(Vec2d(plate_origin.x(), plate_origin.y())); + exclude_boxs.emplace_back(std::move(box)); } for (float x = min_x + bbox.min.x(); x < bbox.max.x() - step(0) / 2; x += step(0)) for (float y = min_y + bbox.min.y(); y < bbox.max.y() - step(1) / 2; y += step(1)) { diff --git a/src/slic3r/GUI/Plater.hpp b/src/slic3r/GUI/Plater.hpp index a879226b42..f00cdbacc8 100644 --- a/src/slic3r/GUI/Plater.hpp +++ b/src/slic3r/GUI/Plater.hpp @@ -505,6 +505,9 @@ public: bool are_view3D_labels_shown() const; void show_view3D_labels(bool show); + bool are_collision_volumes_shown() const; + void show_collision_volumes(bool show); + bool is_view3D_overhang_shown() const; void show_view3D_overhang(bool show); @@ -770,7 +773,9 @@ public: void split_volume(); void optimize_rotation(); // find all empty cells on the plate and won't overlap with exclusion areas - static std::vector get_empty_cells(const Vec2f step); + static std::vector get_empty_cells(const Vec2f step, + const std::vector &local_exclude_boxes = {}, + bool include_plate_exclude_areas = true); //BBS: void fill_color(int extruder_id); diff --git a/src/slic3r/GUI/Shortcuts.cpp b/src/slic3r/GUI/Shortcuts.cpp index b3809ade38..03fc6937b8 100644 --- a/src/slic3r/GUI/Shortcuts.cpp +++ b/src/slic3r/GUI/Shortcuts.cpp @@ -147,6 +147,7 @@ constexpr std::array shortcut_table = {{ // Display SHORTCUT(ShowLabels, "show_labels", L("Show object labels in 3D scene."), GLOBAL, { 'E', CTRL }), + SHORTCUT(ShowCollisionVolumes, "show_collision_volumes", L("Show all collision volumes"), GLOBAL, { 'K', CTRL_SHIFT }), SHORTCUT(ShowWireframe, "show_wireframe", L("Show/Hide wireframe"), CANVAS, { WXK_RETURN, CTRL_SHIFT }), SHORTCUT(ToggleGcodeWindow, "toggle_gcode_window", L("On/Off G-code window"), PREVIEW, { 'C' }), SHORTCUT(ToggleOneLayerMode, "toggle_one_layer_mode", L("On/Off one layer mode of the vertical slider"), PREVIEW, { 'L' }), diff --git a/src/slic3r/GUI/Shortcuts.hpp b/src/slic3r/GUI/Shortcuts.hpp index 50652af000..ddc9a7ed8d 100644 --- a/src/slic3r/GUI/Shortcuts.hpp +++ b/src/slic3r/GUI/Shortcuts.hpp @@ -46,7 +46,7 @@ enum class Shortcut : uint8_t { // Camera ViewDefault, ViewTop, ViewBottom, ViewFront, ViewRear, ViewLeft, ViewRight, ViewPlate, ZoomIn, ZoomOut, Mouse3DSettings, // Display - ShowLabels, ShowWireframe, ToggleGcodeWindow, ToggleOneLayerMode, ToggleBeltRawGcode, + ShowLabels, ShowCollisionVolumes, ShowWireframe, ToggleGcodeWindow, ToggleOneLayerMode, ToggleBeltRawGcode, // Application Preferences, Search, SwitchView, CollapseSidebar, ReloadDevicePage, KeyboardShortcuts, Quit, // Speed Dial diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 00fd72e57f..a6c72dd406 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -81,6 +81,7 @@ #include "wxExtensions.hpp" #include "PresetComboBoxes.hpp" #include +#include #include "GUI_App.hpp" #include "GUI_ObjectList.hpp" @@ -1944,6 +1945,36 @@ void Tab::on_value_change(const std::string& opt_key, const boost::any& value) return; } + // The bed-area point option cannot store collision-volume syntax. Offer to + // copy it to the volume setting while retaining the area's previous value. + if (opt_key == "bed_exclude_area" && m_type == Preset::TYPE_PRINTER) { + const std::string *definition = boost::any_cast(&value); + if (definition != nullptr && is_bed_exclusion_volume_syntax(*definition)) { + const double printable_height = m_config->opt_float("printable_height"); + if (!is_valid_bed_exclude_volumes_string(*definition, printable_height)) { + show_error(wxGetApp().plater(), _L("Invalid collision volume format. Use XxY, XxY, ... or ZMIN..ZMAX;XxY, XxY, ... and separate multiple volumes with |.")); + reload_config(); + return; + } + + MessageDialog dialog( + wxGetApp().plater(), + _L("This definition contains collision-volume syntax. Add it to the toolhead collision volumes for G-code checking and travel avoidance? The existing excluded bed area will be preserved."), + _L("Add collision volumes"), wxICON_QUESTION | wxYES | wxNO); + if (dialog.ShowModal() == wxID_YES) { + DynamicPrintConfig converted = *m_config; + append_bed_exclude_volumes(converted, *definition); + load_config(converted); + reload_config(); + on_presets_changed(); + wxGetApp().plater()->update(); + } else { + reload_config(); + } + return; + } + } + // Keep this preset's "plugins" manifest in sync when a plugin picker changes, so full_config() and // save_to_json() always find resolved "name;uuid;capability" references and rebuild it nowhere else. // Also drop any plugin config override entries for a capability the change just stopped @@ -1966,6 +1997,25 @@ void Tab::on_value_change(const std::string& opt_key, const boost::any& value) printer_tab->on_gcode_flavor_changed(); } + if (opt_key == "bed_exclude_volume_mode" && m_type == Preset::TYPE_PRINTER && + m_config->opt_enum("bed_exclude_volume_mode") == BedExcludeVolumeMode::PerExtruder) { + auto *per_extruder = m_config->option("extruder_bed_exclude_volumes"); + const auto *shared = m_config->option("bed_exclude_volumes"); + const size_t extruder_count = m_config->option("nozzle_diameter")->size(); + const bool definitions_empty = per_extruder == nullptr || + std::all_of(per_extruder->values.begin(), per_extruder->values.end(), [](const std::string &entry) { return entry.empty(); }); + + if (definitions_empty && shared != nullptr && extruder_count > 0) { + const std::string serialized = shared->value; + const bool valid_shared_definition = + is_valid_bed_exclude_volumes_string(serialized, std::numeric_limits::max()); + DynamicPrintConfig new_conf = *m_config; + new_conf.set_key_value("extruder_bed_exclude_volumes", + new ConfigOptionStrings(std::vector(extruder_count, valid_shared_definition ? serialized : std::string{}))); + m_config_manipulation.apply(m_config, &new_conf); + } + } + if (opt_key == "compatible_prints") this->compatible_widget_reload(m_compatible_prints); if (opt_key == "compatible_printers") @@ -5250,11 +5300,15 @@ void TabPrinter::build_fff() Option option = optgroup->get_option("bed_exclude_area"); option.opt.full_width = true; optgroup->append_single_option_line(option, "printer_basic_information_printable_space#excluded-bed-area"); - // optgroup->append_single_option_line("printable_area"); + + option = optgroup->get_option("bed_exclude_volumes"); + option.opt.full_width = true; + optgroup->append_single_option_line(option, "printer_basic_information_printable_space#toolhead-collision-volumes"); + optgroup->append_single_option_line("bed_exclude_volume_mode", "printer_basic_information_printable_space#toolhead-collision-volumes"); + optgroup->append_single_option_line("printable_height", "printer_basic_information_printable_space#printable-height"); - optgroup->append_single_option_line("support_multi_bed_types","printer_basic_information_printable_space#support-multi-bed-types"); + optgroup->append_single_option_line("support_multi_bed_types", "printer_basic_information_printable_space#support-multi-bed-types"); optgroup->append_single_option_line("best_object_pos", "printer_basic_information_printable_space#best-object-position"); - // todo: for multi_extruder test optgroup->append_single_option_line("z_offset", "printer_basic_information_printable_space#z-offset"); optgroup->append_single_option_line("preferred_orientation", "printer_basic_information_printable_space#preferred-orientation"); @@ -6068,6 +6122,10 @@ if (is_marlin_flavor) option.opt.full_width = true; optgroup->append_single_option_line(option, "printer_extruder_basic_information#extruder-printable-area"); + Option exclusion_option = optgroup->get_option("extruder_bed_exclude_volumes", extruder_idx); + exclusion_option.opt.full_width = true; + optgroup->append_single_option_line(exclusion_option, "printer_basic_information_printable_space#toolhead-collision-volumes"); + optgroup->m_on_change = [this](const t_config_option_key& opt_key, boost::any value) { // The page edits the extruder selected on the variant switch. @@ -6549,6 +6607,16 @@ void TabPrinter::toggle_options() const bool support_parallel_printheads = printer_cfg.opt_bool("support_parallel_printheads"); toggle_line("parallel_printheads_count", support_parallel_printheads); + const size_t exclusion_extruder_count = m_preset_bundle->get_printer_extruder_count(); + // UI visibility follows the selected mode even before any volumes are + // entered. The runtime resolver still ignores empty configurations. + const BedExcludeVolumeMode exclusion_mode = m_config->opt_enum("bed_exclude_volume_mode"); + // Legacy areas and collision volumes are additive. Keep the established + // material keep-out editable while the opt-in motion constraints exist. + toggle_option("bed_exclude_area", true); + toggle_line("bed_exclude_volume_mode", exclusion_extruder_count > 1); + toggle_line("bed_exclude_volumes", exclusion_extruder_count <= 1 || exclusion_mode != BedExcludeVolumeMode::PerExtruder); + toggle_line("fan_direction", m_config->opt_bool("auxiliary_fan")); // The cooling filter and air filtration are alternative accessories: show only the one the printer supports. @@ -6665,6 +6733,9 @@ void TabPrinter::toggle_options() toggle_option("extruder_printable_area", false, i); // disable toggle_line("extruder_printable_area", m_preset_bundle->get_printer_extruder_count() == 2, i); //hide + const bool per_extruder_exclusions = + m_config->opt_enum("bed_exclude_volume_mode") == BedExcludeVolumeMode::PerExtruder; + toggle_line("extruder_bed_exclude_volumes", m_preset_bundle->get_printer_extruder_count() > 1 && per_extruder_exclusions, i); toggle_option("extruder_printable_height", false, i); toggle_line("extruder_printable_height", m_preset_bundle->get_printer_extruder_count() == 2, i); diff --git a/tests/fff_print/CMakeLists.txt b/tests/fff_print/CMakeLists.txt index a8e0f1575d..4cf0826a2c 100644 --- a/tests/fff_print/CMakeLists.txt +++ b/tests/fff_print/CMakeLists.txt @@ -6,6 +6,7 @@ add_executable(${_TEST_NAME}_tests test_cooling.cpp test_extrusion_entity.cpp test_extrusion_processor.cpp + test_exclusion_volumes.cpp test_fill.cpp test_flow.cpp test_gcode_processor.cpp diff --git a/tests/fff_print/test_exclusion_volumes.cpp b/tests/fff_print/test_exclusion_volumes.cpp new file mode 100644 index 0000000000..6b20d07973 --- /dev/null +++ b/tests/fff_print/test_exclusion_volumes.cpp @@ -0,0 +1,812 @@ +#include +#include +#include +#include +#include +#include "libslic3r/Config.hpp" +#include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Polygon.hpp" +#include "libslic3r/Polyline.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/libslic3r.h" +#include +#include +#include +#include +#include + +#include "libslic3r/GCode/ExclusionVolumePathCheck.hpp" +#include "libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp" +#include "libslic3r/GCode/GCodeProcessor.hpp" +#include "libslic3r/ClipperUtils.hpp" +#include "libslic3r/Print.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/Support/SupportCommon.hpp" +#include "libslic3r/Support/SupportLayer.hpp" + +#include "test_helpers.hpp" +#include "test_utils.hpp" + +#include +#include +#include +#include +#include + +using namespace Slic3r; +using Catch::Matchers::WithinAbs; + +namespace { + +DynamicPrintConfig exclusion_config( + BedExcludeVolumeMode mode = BedExcludeVolumeMode::Shared, + const std::string &shared = "0..10;40x40,60x40,60x60,40x60", + const std::vector &per_extruder = {}) +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + const size_t extruder_count = std::max(1, per_extruder.size()); + config.set_num_extruders(extruder_count); + config.set_key_value("nozzle_diameter", new ConfigOptionFloats(extruder_count, 0.4)); + config.set_key_value("extruder_offset", new ConfigOptionPoints(extruder_count, Vec2d::Zero())); + config.set_key_value("extruder_printable_height", new ConfigOptionFloatsNullable(extruder_count, 100.0)); + config.set_key_value("printable_height", new ConfigOptionFloat(100.0)); + config.set_key_value("printable_area", new ConfigOptionPoints{ + Vec2d(0.0, 0.0), Vec2d(100.0, 0.0), Vec2d(100.0, 100.0), Vec2d(0.0, 100.0), + }); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(mode)); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString(shared)); + if (!per_extruder.empty()) + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings(per_extruder)); + return config; +} + +DynamicPrintConfig legacy_exclusion_config() +{ + DynamicPrintConfig config = exclusion_config(); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString()); + config.set_deserialize_strict("bed_exclude_area", "40x40,60x40,60x60,40x60"); + return config; +} + +FullPrintConfig static_config(const DynamicPrintConfig &dynamic) +{ + FullPrintConfig config; + // full_print_config() also contains GUI/profile-only keys which are not + // members of the static slicing config used by these lower-level classes. + config.apply(dynamic, true); + return config; +} + +Polyline travel(std::initializer_list points) +{ + Points scaled_points; + scaled_points.reserve(points.size()); + for (const Vec2d &point : points) + scaled_points.emplace_back(Point::new_scale(point)); + return Polyline(std::move(scaled_points)); +} + +Vec2d to_mm(const Point &point) +{ + return point.cast() * SCALING_FACTOR; +} + +struct Rect +{ + double min_x; + double min_y; + double max_x; + double max_y; +}; + +bool point_inside_open_rect(const Vec2d &point, const Rect &rect) +{ + return point.x() > rect.min_x && point.x() < rect.max_x && + point.y() > rect.min_y && point.y() < rect.max_y; +} + +// Independent Liang-Barsky-style test oracle for the simple rectangular +// obstacles used here. This deliberately does not call the production path +// checker, so matching bugs in the checker and router cannot hide each other. +bool segment_enters_open_rect(const Vec2d &from, const Vec2d &to, const Rect &rect) +{ + if (point_inside_open_rect(from, rect) || point_inside_open_rect(to, rect)) + return true; + + double t_min = 0.0; + double t_max = 1.0; + const Vec2d delta = to - from; + const auto clip_axis = [&](double origin, double direction, double min_value, double max_value, + double &lower, double &upper) { + if (std::abs(direction) < 1e-12) + return origin > min_value && origin < max_value; + double first = (min_value - origin) / direction; + double second = (max_value - origin) / direction; + if (first > second) + std::swap(first, second); + lower = std::max(lower, first); + upper = std::min(upper, second); + return lower < upper; + }; + + if (!clip_axis(from.x(), delta.x(), rect.min_x, rect.max_x, t_min, t_max)) + return false; + if (!clip_axis(from.y(), delta.y(), rect.min_y, rect.max_y, t_min, t_max)) + return false; + if (t_min >= t_max) + return false; + + const double midpoint_t = 0.5 * (std::max(0.0, t_min) + std::min(1.0, t_max)); + return midpoint_t >= 0.0 && midpoint_t <= 1.0 && + point_inside_open_rect(from + midpoint_t * delta, rect); +} + +void check_path_avoids_rect(const Polyline &path, const Rect &rect) +{ + REQUIRE(path.points.size() >= 2); + for (size_t idx = 1; idx < path.points.size(); ++idx) + CHECK_FALSE(segment_enters_open_rect(to_mm(path.points[idx - 1]), to_mm(path.points[idx]), rect)); +} + +ExclusionVolumePathChecker configured_checker(const FullPrintConfig &config) +{ + ExclusionVolumePathChecker checker; + checker.configure(config); + return checker; +} + +void check_motion( + ExclusionVolumePathChecker &checker, + const Vec3d &from, + const Vec3d &to, + int extruder_id = 0, + ExclusionVolumeMotionType type = ExclusionVolumeMotionType::Travel, + bool start_xy_known = true, + bool end_xy_known = true, + bool start_z_known = true, + bool end_z_known = true, + unsigned int gcode_id = 17, + size_t move_id = 23) +{ + checker.check_motion( + from, to, start_xy_known, end_xy_known, start_z_known, end_z_known, + extruder_id, type, 7, gcode_id, move_id); +} + +struct ProcessorExclusionResult +{ + bool checked {false}; + bool conflict {false}; + bool travel_conflict {false}; + bool extrusion_conflict {false}; + int conflict_extruder_id {-1}; +}; + +class ScopedBblPrinterMode +{ +public: + explicit ScopedBblPrinterMode(bool enabled) + : m_previous(GCodeProcessor::s_IsBBLPrinter) + { + GCodeProcessor::s_IsBBLPrinter = enabled; + } + + ~ScopedBblPrinterMode() { GCodeProcessor::s_IsBBLPrinter = m_previous; } + +private: + bool m_previous; +}; + +ProcessorExclusionResult run_processor(const FullPrintConfig &config, const std::string &gcode) +{ + ScopedTemporaryFile file(".gcode"); + { + std::ofstream output(file.string()); + output << gcode; + } + + // The processor exposes this mode as shared state. Restore it after each + // invocation so these tests remain independent of Catch2 execution order. + ScopedBblPrinterMode printer_mode(false); + GCodeProcessor processor; + processor.apply_config(config); + processor.configure_exclusion_volume_path_check(config); + processor.process_file(file.string()); + const GCodeProcessorResult &result = processor.get_result(); + return { + result.exclusion_volume_path_checked, + result.exclusion_volume_path_conflict, + result.exclusion_volume_travel_conflict, + result.exclusion_volume_extrusion_conflict, + result.exclusion_volume_conflict_extruder_id, + }; +} + +Polygon rectangle(double min_x, double min_y, double max_x, double max_y) +{ + Polygon polygon({ + Point::new_scale(min_x, min_y), + Point::new_scale(max_x, min_y), + Point::new_scale(max_x, max_y), + Point::new_scale(min_x, max_y), + }); + polygon.make_counter_clockwise(); + return polygon; +} + +bool polygons_cover(const Polygons &polygons, double x, double y) +{ + const Point point = Point::new_scale(x, y); + const ExPolygons expolygons = union_ex(polygons); + return std::any_of(expolygons.begin(), expolygons.end(), + [&point](const ExPolygon &polygon) { return polygon.contains(point); }); +} + +struct BrimRun +{ + double total_length {0.0}; + bool intersects_test_region {false}; + bool leaves_bed {false}; +}; + +BrimRun generate_brim(const std::string &exclusion_definition, const Vec2d &object_position = Vec2d(40.0, 40.0)) +{ + DynamicPrintConfig config = exclusion_config(BedExcludeVolumeMode::Shared, exclusion_definition); + // Brim clipping normally receives the cached bed polygon initialized by + // the application. Give this headless fixture an explicit nozzle-reachable + // area so it exercises the same boundary path without mutating global state. + config.set_key_value("extruder_printable_area", new ConfigOptionPointsGroups{{ + Vec2d(0.0, 0.0), Vec2d(100.0, 0.0), Vec2d(100.0, 100.0), Vec2d(0.0, 100.0), + }}); + config.set_deserialize_strict({ + {"skirt_loops", "0"}, + {"brim_type", "outer_only"}, + {"brim_width", "10"}, + {"initial_layer_line_width", "0.5"}, + }); + + TriangleMesh mesh = make_cube(20.0, 20.0, 20.0); + mesh.translate(float(object_position.x()), float(object_position.y()), 0.0f); + Print print; + Model model; + Test::init_print(std::vector{std::move(mesh)}, print, model, config, nullptr, false); + print.process(); + + Polylines paths; + for (const Print::SkirtBrimGroup &group : print.skirt_brim_groups()) + for (const Print::SkirtBrimGroup::Brim &brim : group.brims) { + Polylines current = brim.brim.as_polylines(); + paths.insert(paths.end(), std::make_move_iterator(current.begin()), std::make_move_iterator(current.end())); + } + + BrimRun result; + for (const Polyline &path : paths) + result.total_length += path.length(); + result.intersects_test_region = + !intersection_pl(paths, Polygons{rectangle(32.0, 35.0, 38.0, 65.0)}).empty(); + result.leaves_bed = std::any_of(paths.begin(), paths.end(), [](const Polyline &path) { + return std::any_of(path.points.begin(), path.points.end(), [](const Point &point) { + const Vec2d position = to_mm(point); + return position.x() < -EPSILON || position.x() > 100.0 + EPSILON || + position.y() < -EPSILON || position.y() > 100.0 + EPSILON; + }); + }); + return result; +} + +DynamicPrintConfig support_config(int support_filament, int interface_filament) +{ + DynamicPrintConfig config = exclusion_config( + BedExcludeVolumeMode::PerExtruder, "", + {"0..10;4x4,12x4,12x12,4x12", "0..10;22x4,30x4,30x12,22x12"}); + // PrintObject clamps support role ids against the number of logical + // filaments, represented by filament_diameter in the static config. + config.set_key_value("filament_diameter", new ConfigOptionFloats{1.75, 1.75}); + config.set_key_value("filament_map_mode", new ConfigOptionEnum(fmmManual)); + config.set_key_value("filament_map", new ConfigOptionInts{1, 2}); + config.set_key_value("support_filament", new ConfigOptionInt(support_filament)); + config.set_key_value("support_interface_filament", new ConfigOptionInt(interface_filament)); + return config; +} + +struct SupportPrintFixture +{ + Model model; + Print print; + + explicit SupportPrintFixture(const DynamicPrintConfig &config) + { + ModelObject *object = model.add_object(); + ModelVolume *first = object->add_volume(make_cube(20.0, 20.0, 20.0)); + ModelVolume *second = object->add_volume(make_cube(20.0, 20.0, 20.0)); + first->config.set("extruder", 1); + second->config.set("extruder", 2); + // Pin the role assignments on the object as well as the process + // config. This fixture intentionally exercises support exclusion + // selection, not the separate preset-remapping subsystem. + object->config.set("support_filament", config.opt_int("support_filament")); + object->config.set("support_interface_filament", config.opt_int("support_interface_filament")); + object->add_instance(); + object->ensure_on_bed(); + print.apply(model, config); + } + + PrintObject &object() { return *print.objects_mutable().front(); } +}; + +} // namespace + +TEST_CASE("Path checker ignores clear motions and motions outside the active Z slab", "[ExclusionVolume][GCode]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + + SECTION("clear XY") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(10.0, 10.0, 5.0), Vec3d(20.0, 20.0, 5.0)); + CHECK_FALSE(checker.result().has_any_conflict); + } + + SECTION("above volume") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(20.0, 50.0, 20.0), Vec3d(80.0, 50.0, 20.0)); + CHECK_FALSE(checker.result().has_any_conflict); + } + + SECTION("below volume") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(20.0, 50.0, -5.0), Vec3d(80.0, 50.0, -5.0)); + CHECK_FALSE(checker.result().has_any_conflict); + } +} + +TEST_CASE("Legacy excluded areas do not constrain machine motion", "[ExclusionVolume][GCode][Compatibility]") +{ + const FullPrintConfig config = static_config(legacy_exclusion_config()); + const Polyline direct = travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}); + + auto checker = configured_checker(config); + check_motion(checker, Vec3d(20.0, 50.0, 5.0), Vec3d(80.0, 50.0, 5.0)); + CHECK_FALSE(checker.result().has_any_conflict); + + ExclusionVolumeTravelAvoidance router; + router.init(config, Vec3d::Zero()); + const auto route = router.route(direct, 5.0, 5.0, 0); + CHECK(route.status == ExclusionVolumeTravelAvoidance::Status::Unchanged); + CHECK(route.detail == ExclusionVolumeTravelAvoidance::Detail::NoActiveObstacles); + CHECK(route.path.points == direct.points); +} + +TEST_CASE("G-code preview retains the bed area alongside collision volumes", "[ExclusionVolume][GCode][Compatibility][Regression]") +{ + const auto mode = GENERATE(BedExcludeVolumeMode::Shared, BedExcludeVolumeMode::ToolheadOffset, + BedExcludeVolumeMode::PerExtruder); + DynamicPrintConfig config = exclusion_config(mode, "0..10;70x70,80x70,80x80,70x80", + {"0..10;70x70,80x70,80x80,70x80"}); + config.set_deserialize_strict("bed_exclude_area", "0x0,18x0,18x28,0x28"); + ScopedTemporaryFile file(".gcode"); + { + std::ofstream output(file.string()); + REQUIRE(output.is_open()); + output << "; generated by OrcaSlicer\nG90\nM83\nG1 X30 Y30 Z0.2 F3000\n" + << "; CONFIG_BLOCK_START\n"; + for (const std::string &key : config.keys()) + output << "; " << key << " = " << config.opt_serialize(key) << '\n'; + output << "; CONFIG_BLOCK_END\n"; + REQUIRE(output.good()); + } + ScopedBblPrinterMode printer_mode(false); + GCodeProcessor processor; + // Standalone preview loading uses the embedded DynamicPrintConfig, not + // the streaming writer's PrintConfig overload. + processor.process_file(file.string()); + CHECK(processor.get_result().bed_exclude_area == config.option("bed_exclude_area")->values); +} + +TEST_CASE("Collision volumes preserve the configured cutter travel points", "[ExclusionVolume][GCode][Compatibility][Regression]") +{ + DynamicPrintConfig config = Test::multifilament_config(2, { + {"enable_prime_tower", "0"}, {"gcode_flavor", "klipper"}, + {"start_end_points", "20x-3,60x90"}, {"bed_exclude_area", "0x0,18x0,18x28,0x28"}, + {"change_filament_gcode", ";CUTTER_PATH [travel_point_1_x],[travel_point_1_y];[travel_point_2_x],[travel_point_2_y];[travel_point_3_x],[travel_point_3_y]"}, + }); + const auto cutter_path = [](const DynamicPrintConfig &settings) { + Model model; + Print print; + const std::vector> overrides{ + {{"extruder", "1"}}, {{"extruder", "2"}}}; + std::vector meshes; + for (const double x : {30.0, 45.0}) { + TriangleMesh mesh = make_cube(5.0, 5.0, 0.6); + mesh.translate(Vec3f(float(x), 40.0f, 0.0f)); + meshes.push_back(std::move(mesh)); + } + Test::init_print(std::move(meshes), print, model, settings, &overrides, false); + const std::string gcode = Test::gcode(print); + const size_t marker = gcode.find(";CUTTER_PATH "); + REQUIRE(marker != std::string::npos); + return gcode.substr(marker, gcode.find('\n', marker) - marker); + }; + const std::string expected = cutter_path(config); + // The configured endpoint differs from the fallback (54, 245), so this + // comparison cannot pass by silently disabling the cutter-area calculation. + CHECK_THAT(expected, Catch::Matchers::ContainsSubstring("60")); + CHECK_THAT(expected, Catch::Matchers::ContainsSubstring("90")); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("0..10;80x80,90x80,90x90,80x90")); + CHECK(cutter_path(config) == expected); +} + +TEST_CASE("Path checker detects crossing inside and boundary motions", "[ExclusionVolume][GCode]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + const auto [from, to] = GENERATE(table({ + {Vec3d(20.0, 50.0, 5.0), Vec3d(80.0, 50.0, 5.0)}, + {Vec3d(45.0, 45.0, 5.0), Vec3d(55.0, 55.0, 5.0)}, + {Vec3d(20.0, 40.0, 5.0), Vec3d(80.0, 40.0, 5.0)}, + {Vec3d(50.0, 20.0, -5.0), Vec3d(50.0, 80.0, 15.0)}, + })); + + auto checker = configured_checker(config); + check_motion(checker, from, to); + CHECK(checker.result().has_any_conflict); + REQUIRE(checker.result().first_hit.has_value()); + CHECK(checker.result().first_hit->extruder_id == 0); +} + +TEST_CASE("Path checker records motion classification and stable first-hit metadata", "[ExclusionVolume][GCode]") +{ + const auto [type, travel_hit, extrusion_hit, other_hit] = GENERATE(table({ + {ExclusionVolumeMotionType::Travel, true, false, false}, + {ExclusionVolumeMotionType::Extrude, false, true, false}, + {ExclusionVolumeMotionType::Other, false, false, true }, + })); + + auto checker = configured_checker(static_config(exclusion_config())); + check_motion(checker, Vec3d(20.0, 50.0, 5.0), Vec3d(80.0, 50.0, 5.0), 0, type, + true, true, true, true, 101, 202); + check_motion(checker, Vec3d(20.0, 50.0, 5.0), Vec3d(80.0, 50.0, 5.0), 0, type, + true, true, true, true, 303, 404); + + const ExclusionVolumePathCheckResult &result = checker.result(); + CHECK(result.has_travel_conflict == travel_hit); + CHECK(result.has_extrusion_conflict == extrusion_hit); + CHECK(result.has_other_motion_conflict == other_hit); + REQUIRE(result.first_hit.has_value()); + CHECK(result.first_hit->gcode_id == 101); + CHECK(result.first_hit->move_id == 202); + CHECK(result.first_hit->source_move_type == 7); +} + +TEST_CASE("Path checker handles unknown coordinates conservatively without inventing XY", "[ExclusionVolume][GCode]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + + SECTION("unknown XY start is ignored") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(0.0, 0.0, 5.0), Vec3d(80.0, 50.0, 5.0), 0, + ExclusionVolumeMotionType::Travel, false, true); + CHECK_FALSE(checker.result().has_any_conflict); + } + + SECTION("unknown Z checks every height and marks the result") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(20.0, 50.0, 100.0), Vec3d(80.0, 50.0, 100.0), 0, + ExclusionVolumeMotionType::Travel, true, true, false, false); + REQUIRE(checker.result().first_hit.has_value()); + CHECK(checker.result().first_hit->used_unknown_z); + } +} + +TEST_CASE("Path checker selects the active nozzle and applies its XY offset", "[ExclusionVolume][GCode][MultiNozzle]") +{ + DynamicPrintConfig dynamic = exclusion_config( + BedExcludeVolumeMode::PerExtruder, "", {"", "0..10;40x40,60x40,60x60,40x60"}); + dynamic.set_key_value("extruder_offset", new ConfigOptionPoints{Vec2d::Zero(), Vec2d(20.0, 0.0)}); + const FullPrintConfig config = static_config(dynamic); + + SECTION("unrelated nozzle remains clear") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(20.0, 50.0, 5.0), Vec3d(80.0, 50.0, 5.0), 0); + CHECK_FALSE(checker.result().has_any_conflict); + } + + SECTION("active nozzle offset converts emitted coordinates into model space") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(0.0, 50.0, 5.0), Vec3d(50.0, 50.0, 5.0), 1); + REQUIRE(checker.result().first_hit.has_value()); + CHECK(checker.result().first_hit->extruder_id == 1); + CHECK_THAT(checker.result().first_hit->from.x(), WithinAbs(20.0, 1e-9)); + } + + SECTION("unknown active nozzle checks all physical nozzles") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(0.0, 50.0, 5.0), Vec3d(50.0, 50.0, 5.0), -1); + REQUIRE(checker.result().first_hit.has_value()); + CHECK(checker.result().first_hit->extruder_id == 1); + } +} + +TEST_CASE("Travel router leaves clear and vertically separated paths unchanged", "[ExclusionVolume][TravelRouting]") +{ + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + + const Polyline clear = travel({Vec2d(10.0, 10.0), Vec2d(90.0, 10.0)}); + auto result = router.route(clear, 5.0, 5.0, 0); + CHECK(result.status == ExclusionVolumeTravelAvoidance::Status::Unchanged); + CHECK(result.detail == ExclusionVolumeTravelAvoidance::Detail::NoIntersection); + CHECK(result.path.points == clear.points); + + const Polyline crossing = travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}); + result = router.route(crossing, 20.0, 20.0, 0); + CHECK(result.status == ExclusionVolumeTravelAvoidance::Status::Unchanged); + CHECK(result.detail == ExclusionVolumeTravelAvoidance::Detail::NoActiveObstacles); +} + +TEST_CASE("Travel router produces a safe in-bed detour around an active volume", "[ExclusionVolume][TravelRouting]") +{ + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + const Polyline direct = travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}); + + const auto result = router.route(direct, 5.0, 5.0, 0); + REQUIRE(result.status == ExclusionVolumeTravelAvoidance::Status::Rerouted); + REQUIRE(result.path.points.size() > 2); + CHECK(result.path.points.front() == direct.points.front()); + CHECK(result.path.points.back() == direct.points.back()); + check_path_avoids_rect(result.path, Rect{40.0, 40.0, 60.0, 60.0}); + for (const Point &point : result.path.points) { + const Vec2d position = to_mm(point); + CHECK(position.x() >= 0.0); + CHECK(position.x() <= 100.0); + CHECK(position.y() >= 0.0); + CHECK(position.y() <= 100.0); + } +} + +TEST_CASE("Travel router activates volumes touched by a sloped Z move", "[ExclusionVolume][TravelRouting]") +{ + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + const Polyline direct = travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}); + + const auto result = router.route(direct, -5.0, 15.0, 0); + REQUIRE(result.status == ExclusionVolumeTravelAvoidance::Status::Rerouted); + check_path_avoids_rect(result.path, Rect{40.0, 40.0, 60.0, 60.0}); +} + +TEST_CASE("Travel router reports unsafe endpoints unknown tools and blocked beds", "[ExclusionVolume][TravelRouting]") +{ + SECTION("endpoint inside") { + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + const auto result = router.route(travel({Vec2d(50.0, 50.0), Vec2d(80.0, 50.0)}), 5.0, 5.0, 0); + CHECK(result.status == ExclusionVolumeTravelAvoidance::Status::EndpointInside); + CHECK(result.detail == ExclusionVolumeTravelAvoidance::Detail::EndpointInside); + } + + SECTION("unknown tool") { + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + const auto result = router.route(travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}), 5.0, 5.0, -1); + CHECK(result.status == ExclusionVolumeTravelAvoidance::Status::Failed); + CHECK(result.detail == ExclusionVolumeTravelAvoidance::Detail::UnknownExtruder); + } + + SECTION("obstacle separates the bed") { + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config( + BedExcludeVolumeMode::Shared, "0..10;45x0,55x0,55x100,45x100")), Vec3d::Zero()); + const auto result = router.route(travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}), 5.0, 5.0, 0); + CHECK(result.status == ExclusionVolumeTravelAvoidance::Status::Failed); + } +} + +TEST_CASE("Travel router uses only the active nozzle exclusion set", "[ExclusionVolume][TravelRouting][MultiNozzle]") +{ + const FullPrintConfig config = static_config(exclusion_config( + BedExcludeVolumeMode::PerExtruder, "", {"0..10;40x40,60x40,60x60,40x60", ""})); + ExclusionVolumeTravelAvoidance router; + router.init(config, Vec3d::Zero()); + const Polyline direct = travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}); + + CHECK(router.route(direct, 5.0, 5.0, 0).status == ExclusionVolumeTravelAvoidance::Status::Rerouted); + const auto clear = router.route(direct, 5.0, 5.0, 1); + CHECK(clear.status == ExclusionVolumeTravelAvoidance::Status::Unchanged); + CHECK(clear.detail == ExclusionVolumeTravelAvoidance::Detail::NoActiveObstacles); +} + +TEST_CASE("Travel router accepts firmware positions outside the printable boundary", "[ExclusionVolume][TravelRouting]") +{ + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + + SECTION("start outside") { + const auto result = router.route( + travel({Vec2d(-5.0, 50.0), Vec2d(80.0, 50.0)}), 5.0, 5.0, 0); + REQUIRE(result.status == ExclusionVolumeTravelAvoidance::Status::Rerouted); + check_path_avoids_rect(result.path, Rect{40.0, 40.0, 60.0, 60.0}); + } + + SECTION("end outside") { + const auto result = router.route( + travel({Vec2d(20.0, 50.0), Vec2d(105.0, 50.0)}), 5.0, 5.0, 0); + REQUIRE(result.status == ExclusionVolumeTravelAvoidance::Status::Rerouted); + check_path_avoids_rect(result.path, Rect{40.0, 40.0, 60.0, 60.0}); + } +} + +TEST_CASE("G-code processor ignores the artificial first XY origin and checks subsequent travel", "[ExclusionVolume][GCodeProcessor]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + + SECTION("first explicit position has no invented start") { + const ProcessorExclusionResult result = run_processor(config, "G90\nG1 X80 Y50 Z5 F6000\n"); + CHECK(result.checked); + CHECK_FALSE(result.conflict); + } + + SECTION("next motion starts at the established position") { + const ProcessorExclusionResult result = run_processor(config, "G90\nG1 X80 Y50 Z5 F6000\nG1 X20 Y50\n"); + CHECK(result.conflict); + CHECK(result.travel_conflict); + } +} + +TEST_CASE("G-code processor tracks absolute relative and reset coordinate state", "[ExclusionVolume][GCodeProcessor]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + + SECTION("relative move crosses the volume") { + const ProcessorExclusionResult result = run_processor( + config, "G90\nG1 X20 Y50 Z5\nG91\nG1 X60 Y0\n"); + CHECK(result.conflict); + } + + SECTION("G92 preserves a known transformed coordinate frame") { + const ProcessorExclusionResult result = run_processor( + config, "G90\nG1 X20 Y50 Z5\nG92 X0 Y0\nG1 X60 Y0\n"); + CHECK(result.conflict); + } + + SECTION("homing does not create a synthetic checked move") { + const ProcessorExclusionResult result = run_processor(config, "G28\nG1 X80 Y50 Z5\n"); + CHECK_FALSE(result.conflict); + } + + SECTION("full or XY homing makes the XY start position unknown") { + const std::string homing = GENERATE( + std::string("G28"), std::string("G28 X"), std::string("G28 X Y"), + std::string("G28 XY"), std::string("G28 X0 Y0"), std::string("G28 XYZ"), + std::string("G28 W")); + const ProcessorExclusionResult result = run_processor( + config, "G90\nG1 X20 Y50 Z5\n" + homing + "\nG1 X80 Y50 Z5\n"); + CHECK_FALSE(result.conflict); + } + + SECTION("Z-only homing preserves the known XY position") { + const std::string homing = GENERATE( + std::string("G28 Z P0"), std::string("G28 Z Z_OFFSET -0.07")); + const ProcessorExclusionResult result = run_processor( + config, "G90\nG1 X20 Y50 Z5\n" + homing + "\nG1 X80 Y50 Z5\n"); + CHECK(result.conflict); + } +} + +TEST_CASE("G-code processor classifies extrusion conflicts", "[ExclusionVolume][GCodeProcessor]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + const ProcessorExclusionResult result = run_processor( + config, "G90\nM83\nG1 X20 Y50 Z5\nG1 X80 Y50 E1\n"); + + CHECK(result.conflict); + CHECK(result.extrusion_conflict); + CHECK_FALSE(result.travel_conflict); +} + +TEST_CASE("G-code processor changes the active physical nozzle at tool selection", "[ExclusionVolume][GCodeProcessor][MultiNozzle]") +{ + const FullPrintConfig config = static_config(exclusion_config( + BedExcludeVolumeMode::PerExtruder, "", {"", "0..10;40x40,60x40,60x60,40x60"})); + + const ProcessorExclusionResult first_tool = run_processor(config, "G90\nT0\nG1 X20 Y50 Z5\nG1 X80 Y50\n"); + CHECK_FALSE(first_tool.conflict); + + const ProcessorExclusionResult second_tool = run_processor(config, "G90\nT1\nG1 X20 Y50 Z5\nG1 X80 Y50\n"); + CHECK(second_tool.conflict); + CHECK(second_tool.conflict_extruder_id == 1); +} + +TEST_CASE("Brim paths are clipped only by exclusions active on the first layer", "[ExclusionVolume][Brim]") +{ + const BrimRun active = generate_brim("0..1;32x35,38x35,38x65,32x65"); + const BrimRun raised = generate_brim("10..20;32x35,38x35,38x65,32x65"); + + REQUIRE(active.total_length > 0.0); + REQUIRE(raised.total_length > 0.0); + CHECK_FALSE(active.intersects_test_region); + CHECK(raised.intersects_test_region); + CHECK(active.total_length < raised.total_length); +} + +TEST_CASE("Brim paths remain clipped to the bed without collision volumes", "[ExclusionVolume][Brim][Regression]") +{ + const BrimRun brim = generate_brim("", Vec2d(21.0, 5.0)); + REQUIRE(brim.total_length > 0.0); + CHECK_FALSE(brim.leaves_bed); +} + +TEST_CASE("Support exclusion masks follow explicit and current-filament roles", "[ExclusionVolume][Support][MultiNozzle]") +{ + SECTION("explicit support roles select one physical nozzle each") { + SupportPrintFixture fixture(support_config(1, 2)); + CHECK(support_exclusion_filaments(fixture.object(), false) == std::vector{0}); + CHECK(support_exclusion_filaments(fixture.object(), true) == std::vector{1}); + + const auto base_masks = support_exclusion_areas_for_layers(fixture.object(), {{0.0, 1.0}}, false); + const auto interface_masks = support_exclusion_areas_for_layers(fixture.object(), {{0.0, 1.0}}, true); + REQUIRE(base_masks.size() == 1); + REQUIRE(interface_masks.size() == 1); + // PrintObject support geometry is centred around the object's local + // origin; the plate-space regions above are shifted by (10, 10). + CHECK(polygons_cover(base_masks.front(), -4.0, -4.0)); + CHECK_FALSE(polygons_cover(base_masks.front(), 14.0, -4.0)); + CHECK_FALSE(polygons_cover(interface_masks.front(), -4.0, -4.0)); + CHECK(polygons_cover(interface_masks.front(), 14.0, -4.0)); + } + + SECTION("current filament remains conservative across every used nozzle") { + SupportPrintFixture fixture(support_config(0, 2)); + std::vector filaments = support_exclusion_filaments(fixture.object(), false); + std::sort(filaments.begin(), filaments.end()); + CHECK(filaments == std::vector{0, 1}); + + const auto masks = support_exclusion_areas_for_layers(fixture.object(), {{0.0, 1.0}, {11.0, 12.0}}, false); + REQUIRE(masks.size() == 2); + CHECK(polygons_cover(masks[0], -4.0, -4.0)); + CHECK(polygons_cover(masks[0], 14.0, -4.0)); + CHECK(masks[1].empty()); + } +} + +TEST_CASE("Support trimming applies the correct nozzle mask to every polygon category", "[ExclusionVolume][Support][MultiNozzle]") +{ + SupportPrintFixture fixture(support_config(1, 2)); + const Polygon source = rectangle(-20.0, -20.0, 40.0, 20.0); + + SupportGeneratorLayer base; + base.layer_type = SupporLayerType::Base; + base.print_z = 1.0; + base.height = 0.2; + base.polygons = {source}; + base.contact_polygons = std::make_unique(Polygons{source}); + base.overhang_polygons = std::make_unique(Polygons{source}); + base.enforcer_polygons = std::make_unique(Polygons{source}); + + SupportGeneratorLayer interface; + interface.layer_type = SupporLayerType::TopInterface; + interface.print_z = 1.0; + interface.height = 0.2; + interface.polygons = {source}; + + const SupportGeneratorLayersPtr none; + const SupportGeneratorLayersPtr base_layers{&base}; + const SupportGeneratorLayersPtr interface_layers{&interface}; + trim_support_layers_by_exclusion_volumes( + fixture.object(), none, none, none, base_layers, interface_layers, none); + + // Base support uses filament 1 and interface support uses filament 2. + CHECK_FALSE(polygons_cover(base.polygons, -4.0, -4.0)); + CHECK(polygons_cover(base.polygons, 14.0, -4.0)); + CHECK(polygons_cover(interface.polygons, -4.0, -4.0)); + CHECK_FALSE(polygons_cover(interface.polygons, 14.0, -4.0)); + + // The same sanitization is mandatory for the auxiliary support categories. + REQUIRE(base.contact_polygons != nullptr); + REQUIRE(base.overhang_polygons != nullptr); + REQUIRE(base.enforcer_polygons != nullptr); + CHECK_FALSE(polygons_cover(*base.contact_polygons, -4.0, -4.0)); + CHECK_FALSE(polygons_cover(*base.overhang_polygons, -4.0, -4.0)); + CHECK_FALSE(polygons_cover(*base.enforcer_polygons, -4.0, -4.0)); +} diff --git a/tests/fff_print/test_print.cpp b/tests/fff_print/test_print.cpp index 29decadcdd..bd51352b60 100644 --- a/tests/fff_print/test_print.cpp +++ b/tests/fff_print/test_print.cpp @@ -286,6 +286,39 @@ size_t count_opt_key(const std::vector& warnings, const s [&](const StringObjectException& w) { return w.opt_key == key; }); } +DynamicPrintConfig dual_extruder_exclusion_config( + BedExcludeVolumeMode mode, + const std::vector &per_extruder, + const std::vector &filament_map = {1}) +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_num_extruders(2); + config.set_key_value("nozzle_diameter", new ConfigOptionFloats{0.4, 0.4}); + config.set_key_value("extruder_offset", new ConfigOptionPoints{Vec2d::Zero(), Vec2d(20.0, 0.0)}); + config.set_key_value("extruder_printable_height", new ConfigOptionFloatsNullable{256.0, 256.0}); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(mode)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings(per_extruder)); + config.set_key_value("filament_map_mode", new ConfigOptionEnum(fmmManual)); + config.set_key_value("filament_map", new ConfigOptionInts(filament_map)); + return config; +} + +StringObjectException validate_multimaterial_cube(const DynamicPrintConfig &config) +{ + Model model; + ModelObject *object = model.add_object(); + ModelVolume *first = object->add_volume(cube(20)); + ModelVolume *second = object->add_volume(cube(20)); + first->config.set("extruder", 1); + second->config.set("extruder", 2); + object->add_instance(); + object->ensure_on_bed(); + + Print print; + print.apply(model, config); + return print.validate(); +} + // Make `default_acceleration` exceed the machine's extruding-acceleration limit. void trigger_acceleration_warning(DynamicPrintConfig& c) { @@ -312,6 +345,73 @@ void trigger_precise_wall_warning(DynamicPrintConfig& c) } // namespace +TEST_CASE("Print validation applies individual exclusion volumes to the mapped physical extruder", "[Print][ExclusionVolume][MultiNozzle]") +{ + const std::string colliding = "0..256;-100x-100,300x-100,300x300,-100x300"; + std::vector warnings; + + SECTION("mapped colliding extruder is rejected") { + const DynamicPrintConfig config = dual_extruder_exclusion_config( + BedExcludeVolumeMode::PerExtruder, {colliding, ""}, {1}); + const StringObjectException error = validate_cubes(config, warnings); + CHECK(error.string.find("extruder 1") != std::string::npos); + } + + SECTION("mapped clear extruder is accepted") { + const DynamicPrintConfig config = dual_extruder_exclusion_config( + BedExcludeVolumeMode::PerExtruder, {colliding, ""}, {2}); + const StringObjectException error = validate_cubes(config, warnings); + CHECK(error.string.empty()); + } + + SECTION("an unrelated nozzle exclusion does not reject the object") { + const DynamicPrintConfig config = dual_extruder_exclusion_config( + BedExcludeVolumeMode::PerExtruder, {"", colliding}, {1}); + const StringObjectException error = validate_cubes(config, warnings); + CHECK(error.string.empty()); + } +} + +TEST_CASE("Print validation applies shared exclusions and ignores volumes above the object", "[Print][ExclusionVolume]") +{ + std::vector warnings; + + SECTION("shared volume intersects") { + DynamicPrintConfig config = dual_extruder_exclusion_config(BedExcludeVolumeMode::Shared, {"", ""}, {2}); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("0..30;-100x-100,300x-100,300x300,-100x300")); + const StringObjectException error = validate_cubes(config, warnings); + CHECK(error.string.find("extruder 2") != std::string::npos); + } + + SECTION("elevated shared volume clears a 20mm cube") { + DynamicPrintConfig config = dual_extruder_exclusion_config(BedExcludeVolumeMode::Shared, {"", ""}, {1}); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("30..50;-100x-100,300x-100,300x300,-100x300")); + const StringObjectException error = validate_cubes(config, warnings); + CHECK(error.string.empty()); + } +} + +TEST_CASE("Legacy excluded areas retain object placement validation", "[Print][ExclusionVolume][Compatibility]") +{ + DynamicPrintConfig config = dual_extruder_exclusion_config( + BedExcludeVolumeMode::Shared, {"", ""}, {1}); + config.set_deserialize_strict("bed_exclude_area", "-100x-100,300x-100,300x300,-100x300"); + + std::vector warnings; + const StringObjectException error = validate_cubes(config, warnings); + CHECK_FALSE(error.string.empty()); +} + +TEST_CASE("Print validation checks every nozzle used by a multimaterial object", "[Print][ExclusionVolume][MultiNozzle]") +{ + const std::string colliding = "0..256;-100x-100,300x-100,300x300,-100x300"; + const DynamicPrintConfig config = dual_extruder_exclusion_config( + BedExcludeVolumeMode::PerExtruder, {"", colliding}, {1, 2}); + + const StringObjectException error = validate_multimaterial_cube(config); + CHECK(error.string.find("extruder 2") != std::string::npos); +} + // --------------------------------------------------------------------------- // {first_object_name} filename placeholder // --------------------------------------------------------------------------- diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index 44afdece7c..a42ead92e4 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -37,6 +37,7 @@ add_executable(${_TEST_NAME}_tests test_preset_options.cpp test_edge_grid.cpp test_elephant_foot_compensation.cpp + test_exclusion_volumes.cpp test_fill_corner_smoothing.cpp test_filament_mixer.cpp test_fill_plane_path.cpp diff --git a/tests/libslic3r/test_3mf.cpp b/tests/libslic3r/test_3mf.cpp index 7287b9d5d3..00721b952f 100644 --- a/tests/libslic3r/test_3mf.cpp +++ b/tests/libslic3r/test_3mf.cpp @@ -1,5 +1,6 @@ #include +#include #include #include #include @@ -51,6 +52,7 @@ #include #include #include +#include #include #include #include // for std::enable_if_t @@ -180,6 +182,78 @@ SCENARIO("Export+Import geometry to/from 3mf file cycle", "[3mf]") { } } +TEST_CASE("Volumetric per-extruder exclusions survive a 3MF round-trip", "[3mf][ExclusionVolume][MultiNozzle]") +{ + // The importer creates a backup tree for the reloaded model. Give that + // process-global temp root a writable, isolated location on every OS. + ScopedSlic3rTemporaryDir temporary_dir("orca_exclusion"); + + Model model; + ModelObject *object = model.add_object(); + object->add_volume(make_cube(10.0, 10.0, 10.0)); + object->add_instance(); + + // Keep the project config intentionally sparse: this test owns only the + // exclusion settings and should not depend on unrelated printer-profile + // defaults surviving the project archive round-trip. + DynamicPrintConfig source; + source.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + source.set_deserialize_strict("bed_exclude_area", "0x0,10x0,10x10,0x10"); + source.set_key_value("bed_exclude_volumes", new ConfigOptionString("0..10;1x1,2x1,2x2,1x2")); + source.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{ + "0..25;5x5,15x5,15x15,5x15", + "30..80;40x40,55x40,55x55,40x55|0..5;70x10,80x10,80x20,70x20", + }); + + const boost::filesystem::path backup_dir = temporary_dir.path() / "source_backup"; + model.set_backup_path(backup_dir.string()); + + const boost::filesystem::path path = temporary_dir.path() / "round_trip.3mf"; + const std::string path_string = path.string(); + auto plate = std::make_unique(); + plate->plate_index = 0; + StoreParams store_params; + store_params.path = path_string.c_str(); + store_params.model = &model; + store_params.config = &source; + store_params.plate_data_list.push_back(plate.get()); + store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence; + REQUIRE(store_bbs_3mf(store_params)); + + Model reloaded_model; + DynamicPrintConfig reloaded; + ConfigSubstitutionContext substitutions{ForwardCompatibilitySubstitutionRule::Disable}; + PlateDataPtrs reloaded_plates; + std::vector project_presets; + bool is_bbl_3mf = false; + bool is_orca_3mf = false; + Semver file_version; + const bool loaded = load_bbs_3mf( + path_string.c_str(), &reloaded, &substitutions, &reloaded_model, &reloaded_plates, + &project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr, + LoadStrategy::LoadModel | LoadStrategy::LoadConfig); + release_PlateData_list(reloaded_plates); + + REQUIRE(loaded); + REQUIRE(reloaded.option>("bed_exclude_volume_mode") != nullptr); + CHECK(reloaded.option>("bed_exclude_volume_mode")->value == + BedExcludeVolumeMode::PerExtruder); + + const auto *areas = reloaded.option("extruder_bed_exclude_volumes"); + REQUIRE(areas != nullptr); + REQUIRE(areas->values.size() == 2); + CHECK(areas->values == source.option("extruder_bed_exclude_volumes")->values); + + const auto *shared_volumes = reloaded.option("bed_exclude_volumes"); + REQUIRE(shared_volumes != nullptr); + CHECK(shared_volumes->value == source.opt_string("bed_exclude_volumes")); + + const auto *legacy = reloaded.option("bed_exclude_area"); + REQUIRE(legacy != nullptr); + CHECK(legacy->serialize() == "0x0,10x0,10x10,0x10"); +} + SCENARIO("Mirrored instance transforms survive 3mf round trips", "[3mf][Regression]") { const bool bbs_format = GENERATE(false, true); diff --git a/tests/libslic3r/test_appconfig.cpp b/tests/libslic3r/test_appconfig.cpp index 01ceebc538..d4149c4fce 100644 --- a/tests/libslic3r/test_appconfig.cpp +++ b/tests/libslic3r/test_appconfig.cpp @@ -8,6 +8,17 @@ using namespace Slic3r; +TEST_CASE("Full collision-volume previews are opt-in and retain the user's preference", "[AppConfig][ExclusionVolume]") +{ + AppConfig config; + config.set_defaults(); + CHECK_FALSE(config.get_bool("show_collision_volumes")); + + config.set_bool("show_collision_volumes", true); + config.set_defaults(); + CHECK(config.get_bool("show_collision_volumes")); +} + TEST_CASE("AppConfig network version helpers", "[AppConfig]") { AppConfig config; diff --git a/tests/libslic3r/test_arrange.cpp b/tests/libslic3r/test_arrange.cpp index 9d3164050e..68669949a6 100644 --- a/tests/libslic3r/test_arrange.cpp +++ b/tests/libslic3r/test_arrange.cpp @@ -505,3 +505,71 @@ TEST_CASE("Layered printing does not floor the object distance", "[Arrange]") update_selected_items_inflation(items, &cfg, p); CHECK(p.min_obj_distance == 0); } + +TEST_CASE("Bed exclusions apply by physical nozzle and overlapping Z range", "[Arrange][ExclusionVolume][MultiNozzle]") +{ + ArrangePolygon object = make_square(scaled(20.)); + object.has_z_range = true; + object.z_min = 0.0; + object.z_max = 20.0; + object.bed_exclusion_extruder_ids = {1}; + + ArrangePolygon exclusion = make_square(scaled(20.)); + exclusion.is_bed_exclusion = true; + exclusion.has_z_range = true; + exclusion.z_min = 10.0; + exclusion.z_max = 30.0; + exclusion.bed_exclusion_extruder_id = 1; + + CHECK(bed_exclusion_applies(object, exclusion)); + + exclusion.bed_exclusion_extruder_id = 0; + CHECK_FALSE(bed_exclusion_applies(object, exclusion)); + + // Empty physical-nozzle assignments mean unresolved, so arrangement stays conservative. + object.bed_exclusion_extruder_ids.clear(); + CHECK(bed_exclusion_applies(object, exclusion)); + + object.bed_exclusion_extruder_ids = {0}; + object.z_max = 9.0; + CHECK_FALSE(bed_exclusion_applies(object, exclusion)); + + // Touching at one Z plane is intentionally treated as a collision. + object.z_max = 10.0; + CHECK(bed_exclusion_applies(object, exclusion)); +} + +TEST_CASE("Shared bed exclusions apply to every arranged object", "[Arrange][ExclusionVolume]") +{ + ArrangePolygon object = make_square(scaled(20.)); + object.bed_exclusion_extruder_ids = {1}; + + ArrangePolygon shared = make_square(scaled(20.)); + shared.is_bed_exclusion = true; + shared.bed_exclusion_extruder_id = -1; + + CHECK(has_bed_exclusion_regions({shared})); + CHECK_FALSE(has_bed_exclusion_regions({object})); + CHECK(bed_exclusion_applies(object, shared)); +} + +TEST_CASE("Arrange keeps relevant objects outside conditional exclusion obstacles", "[Arrange][ExclusionVolume]") +{ + ArrangePolygon exclusion = make_square(scaled(30.)); + exclusion.translation = Vec2crd(scaled(35.0), scaled(35.0)); + exclusion.is_bed_exclusion = true; + exclusion.bed_exclusion_extruder_id = 0; + + ArrangePolygons items = squares(4, 20.0); + for (ArrangePolygon &item : items) + item.bed_exclusion_extruder_ids = {0}; + + arrange(items, {exclusion}, bed(100.0, 100.0), quiet_params(scaled(1.0))); + + const ExPolygon excluded_shape = exclusion.transformed_poly(); + for (const ArrangePolygon &item : items) { + REQUIRE(item.bed_idx == 0); + CHECK(intersection(ExPolygons{item.transformed_poly()}, ExPolygons{excluded_shape}).empty()); + } + require_no_overlap(items); +} diff --git a/tests/libslic3r/test_exclusion_volumes.cpp b/tests/libslic3r/test_exclusion_volumes.cpp new file mode 100644 index 0000000000..d006e88b54 --- /dev/null +++ b/tests/libslic3r/test_exclusion_volumes.cpp @@ -0,0 +1,601 @@ +#include +#include +#include +#include +#include +#include "libslic3r/Config.hpp" +#include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Polygon.hpp" +#include "libslic3r/libslic3r.h" + +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/ExclusionVolumeGeometry.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/TriangleMesh.hpp" + +#include +#include +#include +#include +#include +#include + +using namespace Slic3r; +using Catch::Matchers::WithinAbs; + +namespace { + +Polygon rectangle(double min_x, double min_y, double max_x, double max_y) +{ + Polygon polygon({ + Point::new_scale(min_x, min_y), + Point::new_scale(max_x, min_y), + Point::new_scale(max_x, max_y), + Point::new_scale(min_x, max_y), + }); + polygon.make_counter_clockwise(); + return polygon; +} + +BedExcludeRegion region(double min_x, double min_y, double max_x, double max_y, + double z_min, double z_max, bool has_z_range = true) +{ + return {rectangle(min_x, min_y, max_x, max_y), z_min, z_max, + BedExcludeRegion::Purpose::CollisionVolume, has_z_range}; +} + +DynamicPrintConfig two_extruder_config() +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_num_extruders(2); + config.set_key_value("nozzle_diameter", new ConfigOptionFloats{0.4, 0.6}); + config.set_key_value("extruder_offset", new ConfigOptionPoints{Vec2d(0.0, 0.0), Vec2d(20.0, 5.0)}); + config.set_key_value("extruder_printable_height", new ConfigOptionFloatsNullable{200.0, 200.0}); + config.set_key_value("master_extruder_id", new ConfigOptionInt(1)); + config.set_key_value("printable_height", new ConfigOptionFloat(200.0)); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("10..30;0x0,10x0,10x10,0x10")); + return config; +} + +BoundingBox bounds(const BedExcludeRegion ®ion) +{ + return get_extents(region.polygon); +} + +double unscaled_x(coord_t value) +{ + return unscale(value); +} + +bool contains(const ExPolygons &polygons, double x, double y) +{ + const Point point = Point::new_scale(x, y); + return std::any_of(polygons.begin(), polygons.end(), [&](const ExPolygon &polygon) { + return polygon.contains(point); + }); +} + +struct CubeModel +{ + Model model; + ModelInstance *instance {nullptr}; + + explicit CubeModel(const Vec3d &offset = Vec3d::Zero(), const Vec3d &size = Vec3d(20.0, 20.0, 20.0)) + { + ModelObject *object = model.add_object(); + object->add_volume(make_cube(size.x(), size.y(), size.z())); + instance = object->add_instance(); + instance->set_offset(offset); + } +}; + +} // namespace + +TEST_CASE("Legacy exclusion polygons keep their point representation", "[ExclusionVolume][PrintConfig]") +{ + ConfigOptionPoints option; + REQUIRE(option.deserialize("0x0,10x0,10x10,0x10")); + REQUIRE(option.values.size() == 4); + CHECK(option.serialize() == "0x0,10x0,10x10,0x10"); + CHECK_FALSE(is_bed_exclusion_volume_syntax(option.serialize())); +} + +TEST_CASE("Belt material keep-outs are projected once without projecting collision volumes", "[ExclusionVolume][PrintConfig][Belt][Regression]") +{ + const auto [belt, axis, angle, scale_x, scale_y] = GENERATE(table({ + {true, BeltRotationAxis::X, 60.0, 1.0, 0.5}, + {true, BeltRotationAxis::X, -60.0, 1.0, 0.5}, + {true, BeltRotationAxis::Y, 60.0, 0.5, 1.0}, + {true, BeltRotationAxis::Z, 60.0, 1.0, 1.0}, + {true, BeltRotationAxis::None, 60.0, 1.0, 1.0}, + {false, BeltRotationAxis::X, 60.0, 1.0, 1.0}, + })); + const auto mode = GENERATE(BedExcludeVolumeMode::Shared, BedExcludeVolumeMode::ToolheadOffset, + BedExcludeVolumeMode::PerExtruder); + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("belt_printer", new ConfigOptionBool(belt)); + config.set_key_value("belt_slice_rotation", new ConfigOptionEnum(axis)); + config.set_key_value("belt_slice_rotation_angle", new ConfigOptionFloat(angle)); + config.set_deserialize_strict("bed_exclude_area", "100x100,150x100,150x150,100x150"); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(mode)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{ + "10..30;0x0,10x0,10x10,0x10", "10..30;20x5,30x5,30x15,20x15"}); + + PrintConfig fixed; + fixed.apply(config, true); + const auto dynamic_regions = get_bed_excluded_regions_by_extruder(config); + const auto fixed_regions = get_bed_excluded_regions_by_extruder(fixed); + REQUIRE(dynamic_regions.size() == 2); + REQUIRE(fixed_regions.size() == 2); + for (size_t nozzle = 0; nozzle < dynamic_regions.size(); ++nozzle) { + REQUIRE(dynamic_regions[nozzle].size() == 2); + REQUIRE(fixed_regions[nozzle].size() == 2); + const BoundingBox area = bounds(dynamic_regions[nozzle][0]); + CHECK_THAT(unscale(area.min.x()), WithinAbs(100.0 * scale_x, 1e-5)); + CHECK_THAT(unscale(area.min.y()), WithinAbs(100.0 * scale_y, 1e-5)); + CHECK_THAT(unscale(area.max.x()), WithinAbs(150.0 * scale_x, 1e-5)); + CHECK_THAT(unscale(area.max.y()), WithinAbs(150.0 * scale_y, 1e-5)); + CHECK(dynamic_regions[nozzle][0].polygon.points == fixed_regions[nozzle][0].polygon.points); + const double offset_x = mode == BedExcludeVolumeMode::Shared ? 0.0 : 20.0 * nozzle; + const double offset_y = mode == BedExcludeVolumeMode::Shared ? 0.0 : 5.0 * nozzle; + CHECK(dynamic_regions[nozzle][1].polygon.points == rectangle(offset_x, offset_y, offset_x + 10.0, offset_y + 10.0).points); + CHECK(dynamic_regions[nozzle][1].polygon.points == fixed_regions[nozzle][1].polygon.points); + } + // The older polygon API must not apply the projection a second time. + const Polygons projected = get_bed_excluded_area(fixed); + REQUIRE(projected.size() == 1); + CHECK(projected.front().points == fixed_regions.front().front().polygon.points); + CHECK(config.option("bed_exclude_area")->serialize() == "100x100,150x100,150x150,100x150"); +} + +TEST_CASE("Belt object intersections use the projected bed area", "[ExclusionVolume][PrintConfig][Belt][Regression]") +{ + const auto [y, collides] = GENERATE(table({ + {80.0, true}, {95.0, true}, {110.0, false}, {125.0, false}, {140.0, false}, + })); + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_key_value("belt_printer", new ConfigOptionBool(true)); + config.set_key_value("belt_slice_rotation", new ConfigOptionEnum(BeltRotationAxis::X)); + config.set_key_value("belt_slice_rotation_angle", new ConfigOptionFloat(45.0)); + config.set_deserialize_strict("bed_exclude_area", "100x100,150x100,150x150,100x150"); + const auto regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 1); + CubeModel cube(Vec3d(120.0, y, 0.0), Vec3d(10.0, 10.0, 10.0)); + CHECK(cube.instance->intersects_bed_exclude_region(regions.front()) == collides); +} + +TEST_CASE("Legacy point options reject collision-volume syntax", "[ExclusionVolume][PrintConfig]") +{ + const std::string definition = "0..10;0x0,10x0,10x10,0x10|20x20,30x20,30x30,20x30"; + ConfigOptionPoints option; + CHECK_FALSE(option.deserialize(definition)); + CHECK(option.values.empty()); + CHECK(is_bed_exclusion_volume_syntax(definition)); +} + +TEST_CASE("A bed-area polygon can also define a full-height collision volume", "[ExclusionVolume][PrintConfig]") +{ + const std::string definition = "0x0,20x0,20x10,10x10,10x20,0x20"; + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict("bed_exclude_area", definition); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString(definition)); + const auto regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 2); + CHECK(regions[0].polygon.points == regions[1].polygon.points); +} + +TEST_CASE("Copied volumes preserve the bed area, existing definitions and nozzle mode", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + const std::string converted = "40x40,50x40,50x50,40x50"; + DynamicPrintConfig config = two_extruder_config(); + config.set_deserialize_strict("bed_exclude_area", converted); + + SECTION("toolhead-relative definitions remain shared") { + config.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::ToolheadOffset)); + append_bed_exclude_volumes(config, converted); + + CHECK(config.opt_enum("bed_exclude_volume_mode") == BedExcludeVolumeMode::ToolheadOffset); + CHECK(config.opt_string("bed_exclude_volumes") == + "10..30;0x0,10x0,10x10,0x10|40x40,50x40,50x50,40x50"); + } + + SECTION("individual definitions receive the former shared keep-out") { + config.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{"", "60x60,70x60,70x70,60x70"}); + append_bed_exclude_volumes(config, converted); + + CHECK(config.opt_enum("bed_exclude_volume_mode") == BedExcludeVolumeMode::PerExtruder); + const ConfigOptionStrings *per_extruder = config.option("extruder_bed_exclude_volumes"); + REQUIRE(per_extruder != nullptr); + REQUIRE(per_extruder->values.size() == 2); + CHECK(per_extruder->values[0] == converted); + CHECK(per_extruder->values[1] == "60x60,70x60,70x70,60x70|40x40,50x40,50x50,40x50"); + } + + CHECK(config.option("bed_exclude_area")->serialize() == converted); + + // Resetting just the opt-in settings must leave the original keep-out intact. + config.set_key_value("bed_exclude_volumes", new ConfigOptionString()); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{""}); + CHECK_FALSE(has_bed_exclude_volumes(config)); + CHECK(config.option("bed_exclude_area")->serialize() == converted); +} + +TEST_CASE("Exclusion syntax validation accepts supported forms and rejects malformed regions", "[ExclusionVolume][PrintConfig]") +{ + const auto [definition, valid] = GENERATE(table({ + {"", true}, + {"0x0,10x0,10x10,0x10", true}, + {"0..10;0x0,10x0,10x10,0x10", true}, + {"0.5..10.5;0x0,10x0,10x10,0x10", true}, + {"..10;0x0,10x0,10x10,0x10", true}, + {"10..;0x0,10x0,10x10,0x10", true}, + {"0x0,10x0,10x10,0x10|20x20,30x20,30x30,20x30", true}, + {"20..10;0x0,10x0,10x10,0x10", false}, + {"10..10;0x0,10x0,10x10,0x10", false}, + {"300..400;0x0,10x0,10x10,0x10", false}, + {"zero..10;0x0,10x0,10x10,0x10", false}, + {"0..10;0x0,10x0", false}, + {"0..10;", false}, + {"|", false}, + })); + + DYNAMIC_SECTION(definition) { + CHECK(is_valid_bed_exclude_volumes_string(definition, 200.0) == valid); + } +} + +TEST_CASE("Extended exclusion Z ranges are defaulted and clamped to printable height", "[ExclusionVolume][PrintConfig]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_key_value("printable_height", new ConfigOptionFloat(100.0)); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString( + "-20..25;0x0,10x0,10x10,0x10|75..150;20x0,30x0,30x10,20x10|..;40x0,50x0,50x10,40x10")); + + const std::vector regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 3); + CHECK_THAT(regions[0].z_min, WithinAbs(0.0, 1e-9)); + CHECK_THAT(regions[0].z_max, WithinAbs(25.0, 1e-9)); + CHECK_THAT(regions[1].z_min, WithinAbs(75.0, 1e-9)); + CHECK_THAT(regions[1].z_max, WithinAbs(100.0, 1e-9)); + CHECK_THAT(regions[2].z_min, WithinAbs(0.0, 1e-9)); + CHECK_THAT(regions[2].z_max, WithinAbs(100.0, 1e-9)); +} + +TEST_CASE("CLI keeps legacy areas and collision volumes on separate options", "[ExclusionVolume][PrintConfig][CLI]") +{ + const char *legacy_area_argv[] = { + "orca-slicer", "--bed-exclude-area", "0x0,10x0,10x10,0x10" + }; + DynamicPrintAndCLIConfig legacy_area_config; + t_config_option_keys extra; + t_config_option_keys keys; + REQUIRE(legacy_area_config.read_cli(3, legacy_area_argv, &extra, &keys)); + REQUIRE(legacy_area_config.opt("bed_exclude_area") != nullptr); + CHECK(legacy_area_config.opt("bed_exclude_area")->values.size() == 4); + + const char *volume_argv[] = { + "orca-slicer", "--bed-exclude-volumes", "0..10;0x0,10x0,10x10,0x10" + }; + DynamicPrintAndCLIConfig volume_config; + extra.clear(); + keys.clear(); + REQUIRE(volume_config.read_cli(3, volume_argv, &extra, &keys)); + CHECK(volume_config.opt_string("bed_exclude_volumes") == volume_argv[2]); + + const char *legacy_argv[] = { + "orca-slicer", "--bed-exclude-area", "0..10;0x0,10x0,10x10,0x10" + }; + DynamicPrintAndCLIConfig legacy_config; + extra.clear(); + keys.clear(); + CHECK_FALSE(legacy_config.read_cli(3, legacy_argv, &extra, &keys)); +} + +TEST_CASE("Legacy areas and collision volumes remain additive", "[ExclusionVolume][PrintConfig]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_key_value("printable_height", new ConfigOptionFloat(100.0)); + config.set_deserialize_strict("bed_exclude_area", "0x0,10x0,10x10,0x10"); + + auto regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 1); + CHECK_FALSE(regions.front().is_collision_volume()); + CHECK_FALSE(has_bed_exclude_volumes(config)); + + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("20x20,30x20,30x30,20x30")); + regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 2); + CHECK_FALSE(regions[0].is_collision_volume()); + CHECK(regions[0].polygon.contains(Point::new_scale(5.0, 5.0))); + CHECK(regions[1].is_collision_volume()); + CHECK(regions[1].polygon.contains(Point::new_scale(25.0, 25.0))); +} + +TEST_CASE("An invalid collision-volume definition does not suppress the legacy area", "[ExclusionVolume][PrintConfig]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict("bed_exclude_area", "0x0,10x0,10x10,0x10"); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("not a polygon")); + + CHECK(has_bed_exclude_volumes(config)); + const auto regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 1); + CHECK_FALSE(regions.front().is_collision_volume()); + CHECK_FALSE(is_valid_bed_exclude_volumes_string(config.opt_string("bed_exclude_volumes"), 100.0)); +} + +TEST_CASE("An empty collision-volume configuration falls back to the legacy area", "[ExclusionVolume][PrintConfig]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_num_extruders(2); + config.set_deserialize_strict("bed_exclude_area", "0x0,10x0,10x10,0x10"); + config.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{"", ""}); + + CHECK_FALSE(has_bed_exclude_volumes(config)); + CHECK(active_bed_exclude_volume_mode(config) == BedExcludeVolumeMode::Shared); + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 1); + REQUIRE(groups[1].size() == 1); + CHECK_FALSE(groups[0][0].is_collision_volume()); +} + +TEST_CASE("Shared exclusion volumes resolve identically for every extruder", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::Shared)); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 1); + REQUIRE(groups[1].size() == 1); + CHECK(groups[0][0].polygon.points == groups[1][0].polygon.points); + CHECK_THAT(groups[0][0].z_min, WithinAbs(10.0, 1e-9)); + CHECK_THAT(groups[0][0].z_max, WithinAbs(30.0, 1e-9)); + + // A shared compatibility view contains one definition, not one duplicate per nozzle. + CHECK(get_bed_excluded_regions(config).size() == 1); +} + +TEST_CASE("Toolhead-relative exclusion volumes follow nozzle offset deltas", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::ToolheadOffset)); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 1); + REQUIRE(groups[1].size() == 1); + const BoundingBox reference = bounds(groups[0][0]); + const BoundingBox shifted = bounds(groups[1][0]); + CHECK_THAT(unscaled_x(shifted.min.x() - reference.min.x()), WithinAbs(20.0, 1e-6)); + CHECK_THAT(unscaled_x(shifted.min.y() - reference.min.y()), WithinAbs(5.0, 1e-6)); +} + +TEST_CASE("Toolhead-relative mode offsets collision volumes but not the shared legacy area", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_deserialize_strict("bed_exclude_area", "70x70,80x70,80x80,70x80"); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::ToolheadOffset)); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 2); + REQUIRE(groups[1].size() == 2); + CHECK_FALSE(groups[0][0].is_collision_volume()); + CHECK_FALSE(groups[1][0].is_collision_volume()); + CHECK(groups[0][0].polygon.points == groups[1][0].polygon.points); + CHECK(groups[0][1].polygon.points != groups[1][1].polygon.points); + + const auto flattened = get_bed_excluded_regions(config); + CHECK(flattened.size() == 3); + CHECK(std::count_if(flattened.begin(), flattened.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }) == 1); +} + +TEST_CASE("Toolhead-relative exclusions honour a non-default reference extruder", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("master_extruder_id", new ConfigOptionInt(2)); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::ToolheadOffset)); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + const BoundingBox first = bounds(groups[0][0]); + const BoundingBox reference = bounds(groups[1][0]); + CHECK_THAT(unscaled_x(first.min.x() - reference.min.x()), WithinAbs(-20.0, 1e-6)); + CHECK_THAT(unscaled_x(first.min.y() - reference.min.y()), WithinAbs(-5.0, 1e-6)); +} + +TEST_CASE("Individual exclusion volumes remain authoritative per extruder", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{ + "0..25;0x0,8x0,8x8,0x8|40..60;20x20,30x20,30x30,20x30", + "", + }); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + CHECK(groups[0].size() == 2); + CHECK(groups[1].empty()); + CHECK(get_bed_excluded_regions(config).size() == 2); +} + +TEST_CASE("Individual collision volumes retain the shared legacy area", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_deserialize_strict("bed_exclude_area", "70x70,80x70,80x80,70x80"); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{ + "0..25;0x0,8x0,8x8,0x8", "0..25;20x0,28x0,28x8,20x8" + }); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 2); + REQUIRE(groups[1].size() == 2); + CHECK_FALSE(groups[0][0].is_collision_volume()); + CHECK(groups[0][0].polygon.points == groups[1][0].polygon.points); + CHECK(groups[0][1].is_collision_volume()); + CHECK(groups[1][1].is_collision_volume()); +} + +TEST_CASE("Individual exclusion validation accepts omitted trailing extruders", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig dynamic = two_extruder_config(); + dynamic.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + dynamic.set_key_value("extruder_bed_exclude_volumes", + new ConfigOptionStrings{"0..25;0x0,8x0,8x8,0x8"}); + + FullPrintConfig config; + config.apply(dynamic, true); + const std::map errors = validate(config); + CHECK(errors.find("extruder_bed_exclude_volumes") == errors.end()); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + CHECK(groups[0].size() == 1); + CHECK(groups[1].empty()); +} + +TEST_CASE("Legacy bed helpers include only regions touching the first layer", "[ExclusionVolume][PrintConfig]") +{ + DynamicPrintConfig dynamic = DynamicPrintConfig::full_print_config(); + dynamic.set_key_value("printable_height", new ConfigOptionFloat(100.0)); + dynamic.set_key_value("bed_exclude_volumes", new ConfigOptionString( + "0..5;0x0,10x0,10x10,0x10|20..30;20x0,30x0,30x10,20x10")); + PrintConfig config; + config.apply(dynamic, true); + + const Polygons bed_regions = get_bed_excluded_area(config); + REQUIRE(bed_regions.size() == 1); + CHECK(bed_regions.front().contains(Point::new_scale(5.0, 5.0))); + CHECK_FALSE(bed_regions.front().contains(Point::new_scale(25.0, 5.0))); +} + +TEST_CASE("Filament mapping resolves physical exclusion extruders conservatively", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + CHECK(bed_exclusion_extruder_for_filament(0, {2, 1}, fmmManual, false, true, 2) == 1); + CHECK(bed_exclusion_extruder_for_filament(1, {2, 1}, fmmManual, false, true, 2) == 0); + + // Generic automatic multi-tool printers use matching logical and physical ids. + CHECK(bed_exclusion_extruder_for_filament(1, {1, 1}, fmmAutoForMatch, false, false, 2) == 1); + + // Until Bambu automatic grouping has produced a concrete mapping, every nozzle remains possible. + CHECK(bed_exclusion_extruder_for_filament(0, {1}, fmmAutoForMatch, true, false, 2) == -1); + CHECK(bed_exclusion_extruder_for_filament(0, {2}, fmmAutoForMatch, true, true, 2) == 1); + CHECK(bed_exclusion_extruder_for_filament(3, {}, fmmManual, false, true, 2) == -1); +} + +TEST_CASE("Exclusion Z overlap treats touching slabs conservatively", "[ExclusionVolume][Geometry]") +{ + CHECK(bed_exclusion_z_ranges_overlap(0.0, 10.0, 10.0, 20.0)); + CHECK(bed_exclusion_z_ranges_overlap(10.0, 0.0, 20.0, 10.0)); + CHECK_FALSE(bed_exclusion_z_ranges_overlap(0.0, 9.0, 10.0, 20.0)); +} + +TEST_CASE("Arrange keeps convex exclusions exact and bounds concave exclusions", "[ExclusionVolume][Geometry][Arrange]") +{ + const Polygon convex = rectangle(0.0, 0.0, 10.0, 10.0); + CHECK(bed_exclusion_arrange_polygon(convex).points == convex.points); + + Polygon concave({ + Point::new_scale(0.0, 0.0), Point::new_scale(10.0, 0.0), + Point::new_scale(10.0, 4.0), Point::new_scale(4.0, 4.0), + Point::new_scale(4.0, 10.0), Point::new_scale(0.0, 10.0), + }); + concave.make_counter_clockwise(); + REQUIRE_FALSE(concave.contains(Point::new_scale(8.0, 8.0))); + + const Polygon blocker = bed_exclusion_arrange_polygon(concave); + CHECK(blocker.points.size() == 4); + CHECK(blocker.contains(Point::new_scale(8.0, 8.0))); +} + +TEST_CASE("Active exclusion footprints select Z range nozzle translation and clearance", "[ExclusionVolume][Geometry][MultiNozzle]") +{ + const std::vector> regions_by_extruder{ + {region(0.0, 0.0, 10.0, 10.0, 0.0, 5.0)}, + {region(20.0, 0.0, 30.0, 10.0, 10.0, 20.0)}, + }; + + ExPolygons active = active_bed_exclusion_footprints( + regions_by_extruder, {1, 1, 99}, 12.0, 13.0, Point::new_scale(5.0, 2.0), scale_(1.0)); + REQUIRE(active.size() == 1); + CHECK(contains(active, 26.0, 3.0)); + CHECK(contains(active, 35.5, 3.0)); + CHECK_FALSE(contains(active, 5.0, 5.0)); + + CHECK(active_bed_exclusion_footprints(regions_by_extruder, {0}, 6.0, 9.0).empty()); +} + +TEST_CASE("Exact model intersection respects XY Z and preview collection", "[ExclusionVolume][Model]") +{ + CubeModel cube(Vec3d(30.0, 40.0, 0.0)); + + // Cross the cube's outer surface so this case can also verify the red + // preview, which is built from clipped surface triangles. The enclosed + // prism topology is covered separately below. + const BedExcludeRegion crossing = region(45.0, 45.0, 55.0, 55.0, 5.0, 15.0); + const BedExcludeRegion above = region(45.0, 45.0, 55.0, 55.0, 25.0, 30.0); + const BedExcludeRegion outside = region(60.0, 70.0, 70.0, 80.0, 0.0, 20.0); + + CHECK(cube.instance->intersects_bed_exclude_region(crossing)); + CHECK_FALSE(cube.instance->intersects_bed_exclude_region(above)); + CHECK_FALSE(cube.instance->intersects_bed_exclude_region(outside)); + + indexed_triangle_set preview; + CHECK(cube.instance->intersects_bed_exclude_region(crossing, &preview)); + CHECK_FALSE(preview.empty()); + CHECK_FALSE(cube.instance->intersects_bed_exclude_region(above, &preview)); + CHECK(preview.empty()); +} + +TEST_CASE("Exact model intersection follows instance and volume transforms", "[ExclusionVolume][Model]") +{ + CubeModel cube(Vec3d(50.0, 50.0, 0.0)); + cube.instance->set_rotation(Vec3d(0.0, 0.0, PI / 4.0)); + cube.instance->set_scaling_factor(Vec3d(1.5, 0.5, 1.0)); + + CHECK(cube.instance->intersects_bed_exclude_region(region(50.0, 50.0, 55.0, 55.0, 0.0, 20.0))); + CHECK_FALSE(cube.instance->intersects_bed_exclude_region(region(100.0, 100.0, 110.0, 110.0, 0.0, 20.0))); +} + +TEST_CASE("Exact model intersection detects an exclusion prism enclosed by a solid", "[ExclusionVolume][Model]") +{ + // A surface-only test misses this topology: the exclusion prism is fully + // enclosed, so none of the block's surface triangles enters the prism. + CubeModel block(Vec3d(200.0, 300.0, 0.0), Vec3d(100.0, 100.0, 60.0)); + const BedExcludeRegion enclosed = region(230.0, 330.0, 260.0, 358.0, 8.0, 22.0); + const BedExcludeRegion enclosing = region(190.0, 290.0, 310.0, 410.0, -5.0, 65.0); + const BedExcludeRegion above = region(230.0, 330.0, 260.0, 358.0, 65.0, 75.0); + + CHECK(block.instance->intersects_bed_exclude_region(enclosed)); + CHECK_FALSE(block.instance->intersects_bed_exclude_region(above)); + + indexed_triangle_set preview; + CHECK(block.instance->intersects_bed_exclude_region(enclosed, &preview)); + // There is no model surface inside a fully enclosed prism from which to + // build the usual red clipped-surface preview. + CHECK(preview.empty()); + + // Pin the opposite containment topology too. Here the model surface lies + // inside the prism, so the existing clipped preview remains available. + CHECK(block.instance->intersects_bed_exclude_region(enclosing, &preview)); + CHECK_FALSE(preview.empty()); + + // The multi-region wrapper must preserve the collision result even when + // that optional surface preview is empty. + CHECK(block.instance->intersects_bed_exclude_regions({above, enclosed}, &preview)); + CHECK(preview.empty()); +} diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index 727709f5b2..f1cd69b601 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -2,6 +2,7 @@ get_filename_component(_TEST_NAME ${CMAKE_CURRENT_LIST_DIR} NAME) add_executable(${_TEST_NAME}_tests ${_TEST_NAME}_tests_main.cpp test_bambu_filament_ids.cpp + test_bed_exclusion_fields.cpp test_config_value_formatter.cpp test_creality_cfs_match.cpp test_dev_mapping.cpp diff --git a/tests/slic3rutils/test_bed_exclusion_fields.cpp b/tests/slic3rutils/test_bed_exclusion_fields.cpp new file mode 100644 index 0000000000..2c02e5578a --- /dev/null +++ b/tests/slic3rutils/test_bed_exclusion_fields.cpp @@ -0,0 +1,39 @@ +#include +#include "libslic3r/Point.hpp" +#include + +#include "libslic3r/PrintConfig.hpp" +#include "slic3r/GUI/GUI.hpp" + +#include + +using namespace Slic3r; + +TEST_CASE("Pasted volume syntax leaves the saved bed area intact pending confirmation", "[ExclusionVolume][GUI][Regression]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + const std::string area = "0x0,20x0,20x10,10x10,10x20,0x20"; + config.set_deserialize_strict("bed_exclude_area", area); + const std::string pasted = "5..10;40x40,50x40,50x50,40x50"; + + // OptionsGroup updates the config before Tab asks whether to copy the text. + GUI::change_opt_value(config, "bed_exclude_area", boost::any(pasted)); + CHECK(config.option("bed_exclude_area")->serialize() == area); + CHECK_FALSE(has_bed_exclude_volumes(config)); + + append_bed_exclude_volumes(config, pasted); + CHECK(config.opt_string("bed_exclude_volumes") == pasted); + CHECK(config.option("bed_exclude_area")->serialize() == area); +} + +TEST_CASE("The normal bed-area field still accepts arbitrary polygons and clearing", "[ExclusionVolume][GUI][Regression]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + const Pointfs polygon{Vec2d(0, 0), Vec2d(20, 0), Vec2d(20, 10), Vec2d(10, 10), Vec2d(10, 20), Vec2d(0, 20)}; + GUI::change_opt_value(config, "bed_exclude_area", boost::any(polygon)); + CHECK(config.option("bed_exclude_area")->values == polygon); + CHECK_FALSE(has_bed_exclude_volumes(config)); + + GUI::change_opt_value(config, "bed_exclude_area", boost::any(Pointfs{})); + CHECK(config.option("bed_exclude_area")->values.empty()); +} diff --git a/tests/slic3rutils/test_shortcuts.cpp b/tests/slic3rutils/test_shortcuts.cpp index 171d3257b0..036c769dc0 100644 --- a/tests/slic3rutils/test_shortcuts.cpp +++ b/tests/slic3rutils/test_shortcuts.cpp @@ -221,6 +221,7 @@ TEST_CASE("Every shortcut is listed under the section of its table row", "[Short CHECK(shortcut_section(Shortcut::GizmoBrimEars) == ShortcutSection::Gizmos); CHECK(shortcut_section(Shortcut::MovesSliderEnd) == ShortcutSection::Sliders); CHECK(shortcut_section(Shortcut::ViewDefault) == ShortcutSection::Camera); + CHECK(shortcut_section(Shortcut::ShowCollisionVolumes) == ShortcutSection::Display); CHECK(shortcut_section(Shortcut::KeyboardShortcuts) == ShortcutSection::Application); CHECK(shortcut_section(Shortcut::Quit) == ShortcutSection::Application); CHECK(std::string(section_name(ShortcutSection::SlicingAndPrinting)) == "Slicing and printing");