diff --git a/src/libslic3r/FilamentGroup.cpp b/src/libslic3r/FilamentGroup.cpp index 5536a13282..4782214afc 100644 --- a/src/libslic3r/FilamentGroup.cpp +++ b/src/libslic3r/FilamentGroup.cpp @@ -85,13 +85,14 @@ namespace Slic3r return h; } + // Flush volume (mm^3) to a time-equivalent score (s): volume -> mass (1.26 g/cm^3) -> flushing + // time (180 s/g) x 2 correction. Shared by evaluate_score and calc_one_change_budget. + static constexpr double FLUSH_VOLUME_TO_SCORE = 1.26 * 180.0 * 2.0 / 1000.0; + static double evaluate_score(const double flush, const double time, const bool with_time = false) { if (!with_time) return flush; - double approx_density = 1.26; // g/cm^3 - double approx_flush_speed = 180; // s/g - double correction_factor = 2; - double flush_score = flush * approx_density * approx_flush_speed * correction_factor / 1000; + double flush_score = flush * FLUSH_VOLUME_TO_SCORE; return flush_score + time; } @@ -226,6 +227,33 @@ namespace Slic3r return total / std::max(dedup_factor, 1); } + double FilamentGroup::calc_one_change_budget(const std::vector& used_filaments) const + { + // The median, over every pair of used filaments, of the flush in the costlier direction: + // what one typical change costs with this palette. The median ignores a few extreme pairs + // (black to white) and follows the palette: large for dark/light mixes, small for similar + // colours. 0 for fewer than two filaments or no flush matrix, leaving the absolute and + // relative floors in update_memoryed_groups. + const size_t n = used_filaments.size(); + if (n < 2 || ctx.model_info.flush_matrix.empty()) + return 0.0; + + std::vector pair_flush; + for (const auto& fm : ctx.model_info.flush_matrix) + for (size_t i = 0; i < n; ++i) + for (size_t j = i + 1; j < n; ++j) + pair_flush.push_back(std::max(fm[used_filaments[i]][used_filaments[j]], + fm[used_filaments[j]][used_filaments[i]])); + if (pair_flush.empty()) + return 0.0; + + const size_t mid = pair_flush.size() / 2; + std::nth_element(pair_flush.begin(), pair_flush.begin() + mid, pair_flush.end()); + + constexpr double one_change_margin = 1.2; // so that a whole typical change fits the tolerance + return pair_flush[mid] * FLUSH_VOLUME_TO_SCORE * one_change_margin; + } + std::vector FilamentGroup::calc_group_by_enum( int k, const std::vector& used_filaments, @@ -238,6 +266,7 @@ namespace Slic3r static constexpr int BEST_FIT_LIMIT_REWARD = 10; int n = (int)used_filaments.size(); + const double one_change_budget = calc_one_change_budget(used_filaments); std::vector> candidates(n); for (int i = 0; i < n; i++) { @@ -364,7 +393,7 @@ namespace Slic3r } MemoryedGroup mg(used_labels, score, prefer_level); - update_memoryed_groups(mg, ctx.group_info.max_gap_threshold, m_memoryed_heap); + update_memoryed_groups(mg, one_change_budget, ctx.group_info.max_gap_threshold, m_memoryed_heap); } if (cost) *cost = best_flush; @@ -381,6 +410,7 @@ namespace Slic3r KMediods PAM(k, (int)used_filaments.size(), distance_evaluator, ctx.machine_info.master_extruder_id); PAM.set_unplacable_limits(unplaceable_limits); PAM.set_memory_threshold(ctx.group_info.max_gap_threshold); + PAM.set_one_change_budget(calc_one_change_budget(used_filaments)); std::vector, int>> cluster_size_limit; for (auto& [extruder_id, nozzles] : ctx.nozzle_info.extruder_nozzle_list) { @@ -443,6 +473,12 @@ namespace Slic3r std::vector> machine_filament_info = machine_filament_info_; machine_filament_info.resize(2); + // With no filament reported by the printer (not connected, AMS not synced) every candidate + // costs the same, so keep the first one rather than let the tie order decide. + if (std::all_of(machine_filament_info.begin(), machine_filament_info.end(), + [](const std::vector& filaments) { return filaments.empty(); })) + return filament_to_nozzles.size() ? filament_to_nozzles.front() : std::vector(); + int best_cost = std::numeric_limits::max(); std::vectorbest_map; @@ -462,7 +498,9 @@ namespace Slic3r if (group_colors[i].empty()) continue; if (machine_filament_info[i].empty()) { - group_cost += group_colors.size() * fail_cost; + // Per filament, the scale of the matching below; per extruder would make the + // groupings that use fewer extruders the cheaper ones. + group_cost += (int)group_colors[i].size() * fail_cost; continue; } std::vector>distance_matrix(group_colors[i].size(), std::vector(machine_filament_info[i].size())); @@ -515,16 +553,17 @@ namespace Slic3r } - void FilamentGroupUtils::update_memoryed_groups(const MemoryedGroup& item, const double gap_threshold, MemoryedGroupHeap& groups) + void FilamentGroupUtils::update_memoryed_groups(const MemoryedGroup& item, const double one_change_budget, const double gap_threshold, MemoryedGroupHeap& groups) { - auto emplace_if_accepatle = [gap_threshold](MemoryedGroupHeap& heap, const MemoryedGroup& elem, const MemoryedGroup& best) { - if (best.cost == 0) { - if (std::abs(elem.cost - best.cost) <= ABSOLUTE_FLUSH_GAP_TOLERANCE) - heap.push(elem); - return; - } - double gap_rate = (double)std::abs(elem.cost - best.cost) / (double)best.cost; - if (gap_rate <= gap_threshold) + // Keep candidates up to about five typical filament changes worse than the best, so that + // select_best_group_for_ams can prefer a grouping that matches the filaments loaded in the + // printer (two filaments kept on the extruder that has them, a lone filament on the + // non-master extruder) over the plain least-flush split. The absolute and relative floors + // cover a zero budget and very large scores. + auto emplace_if_accepatle = [one_change_budget, gap_threshold](MemoryedGroupHeap& heap, const MemoryedGroup& elem, const MemoryedGroup& best) { + double gap = std::abs(elem.cost - best.cost); + double tolerance = std::max(std::max(ABSOLUTE_FLUSH_GAP_TOLERANCE * 6.0, one_change_budget * 5.0), best.cost * gap_threshold); + if (gap <= tolerance) heap.push(elem); }; @@ -849,7 +888,7 @@ namespace Slic3r double curr_cluster_cost = evaluate_labels(curr_cluster_labels); MemoryedGroup g(curr_cluster_labels, curr_cluster_cost, 1); - update_memoryed_groups(g, memory_threshold, memoryed_groups); + update_memoryed_groups(g, m_one_change_budget, memory_threshold, memoryed_groups); bool mediods_changed = true; while (mediods_changed && within_budget()) { @@ -884,7 +923,7 @@ namespace Slic3r curr_cluster_cost = evaluate_labels(curr_cluster_labels); MemoryedGroup g(curr_cluster_labels, curr_cluster_cost, 1); - update_memoryed_groups(g, memory_threshold, memoryed_groups); + update_memoryed_groups(g, m_one_change_budget, memory_threshold, memoryed_groups); } } diff --git a/src/libslic3r/FilamentGroup.hpp b/src/libslic3r/FilamentGroup.hpp index b090a22fe0..8398fe419f 100644 --- a/src/libslic3r/FilamentGroup.hpp +++ b/src/libslic3r/FilamentGroup.hpp @@ -72,7 +72,7 @@ namespace Slic3r using MemoryedGroupHeap = std::priority_queue, std::greater>; - void update_memoryed_groups(const MemoryedGroup& item,const double gap_threshold, MemoryedGroupHeap& groups); + void update_memoryed_groups(const MemoryedGroup& item, const double one_change_budget, const double gap_threshold, MemoryedGroupHeap& groups); } struct FilamentGroupContext @@ -183,6 +183,9 @@ namespace Slic3r std::vector calc_group_by_kmedoids(int k, const std::vector& used_filaments, const std::unordered_map>& unplaceable_limits, int* cost = nullptr); + // The cost of one typical filament change, on the evaluate_score scale; sizes the candidate pool + double calc_one_change_budget(const std::vector& used_filaments) const; + std::map rebuild_unprintables(const std::vector& used_filaments, const std::map& extruder_unprintables); std::unordered_map> rebuild_nozzle_unprintables(const std::vector& used_filaments, const std::unordered_map>& extruder_unprintables, const std::vector& filament_volume_map); @@ -238,6 +241,7 @@ namespace Slic3r void set_unplacable_limits(const std::unordered_map>& unplacable_limits) { m_unplaceable_limits = unplacable_limits; } void set_memory_threshold(double threshold) { memory_threshold = threshold; } + void set_one_change_budget(double budget) { m_one_change_budget = budget; } MemoryedGroupHeap get_memoryed_groups()const { return memoryed_groups; } void do_clustering(const FilamentGroupContext& context, const ClusteringBudget& budget); @@ -268,6 +272,7 @@ namespace Slic3r int m_elem_count; int m_default_group_id{ 0 }; double memory_threshold{ 0 }; + double m_one_change_budget{ 0 }; }; } #endif // !FILAMENT_GROUP_HPP diff --git a/src/libslic3r/GCode/ToolOrdering.cpp b/src/libslic3r/GCode/ToolOrdering.cpp index 64b2151221..75fcace426 100644 --- a/src/libslic3r/GCode/ToolOrdering.cpp +++ b/src/libslic3r/GCode/ToolOrdering.cpp @@ -1672,13 +1672,13 @@ static FilamentGroupContext build_filament_group_context( return context; } -// Orca: restore the master-extruder preference. Orca historically ran -// optimize_group_for_master_extruder / can_swap_groups after grouping so a light-filament print stays -// on the primary/master extruder. A weak in-enum penalty alone cannot overcome a pre-existing -// non-zero right-extruder self-flush term in the flush matrix (which otherwise pulls a lone filament -// onto the non-master extruder and changes H2D/H2C g-code). We re-apply the preference ONLY in this -// slicing wrapper — never in the FilamentGroup engine or the test harness — so existing prints keep -// their extruder assignment while the new engine's genuine multi-filament grouping deltas still land. +// Orca: the master-extruder preference for flush-mode grouping on two-extruder machines. It keeps a +// light-filament print on the master extruder, which the engine's own in-enum penalty is too weak to +// do against a non-zero right-extruder self-flush term in the flush matrix (that term pulls a lone +// filament onto the non-master extruder). It lives in this slicing wrapper, not in the FilamentGroup +// engine, so the engine and its golden tests stay comparable with BambuStudio's. It only breaks ties +// against the filaments loaded in the printer: get_recommended_filament_maps keeps the engine's +// grouping when that matches them better. static bool can_swap_extruder_groups(int extruder_id_0, const std::set& group_0, int extruder_id_1, const std::set& group_1, const FilamentGroupContext& ctx) { using namespace FilamentGroupUtils; @@ -1839,11 +1839,20 @@ MultiNozzleUtils::LayeredNozzleGroupResult ToolOrdering::get_recommended_filamen if (!has_multiple_nozzle) fg.get_custom_seq = get_custom_seq; ret = fg.calc_filament_group(); - // Flush-mode auto grouping: restore the master-extruder preference - // (optimize_group_for_master_extruder). Match mode assigns by AMS colour and never had - // it. Kept out of the FilamentGroup engine so the test harness is unaffected. - if (context.group_info.mode == FGMode::FlushMode) - ret = apply_master_extruder_preference(context, used_filaments, ret); + // Flush mode prefers the master extruder; match mode groups by the AMS colours alone. + // select_best_group_for_ams keeps the first candidate on a tie and when the printer + // reports no filaments, so the preferred grouping loses only to one that matches the + // loaded filaments strictly better. + if (context.group_info.mode == FGMode::FlushMode) { + std::vector preferred = apply_master_extruder_preference(context, used_filaments, ret); + std::vector used_filament_info; + for (auto f : used_filaments) + used_filament_info.emplace_back(context.model_info.filament_info[f]); + // The context's nozzle list, which the nozzle ids in ret index (one entry per + // physical nozzle), not the one-per-extruder nozzle_list above. + ret = select_best_group_for_ams({preferred, ret}, context.nozzle_info.nozzle_list, used_filaments, used_filament_info, + context.machine_info.machine_filament_info, context.group_info.has_filament_switcher); + } } } diff --git a/tests/filament_group/filament_group_regression_main.cpp b/tests/filament_group/filament_group_regression_main.cpp index ec3264ba2c..932b2286a8 100644 --- a/tests/filament_group/filament_group_regression_main.cpp +++ b/tests/filament_group/filament_group_regression_main.cpp @@ -24,6 +24,8 @@ #include #include #include "libslic3r/FilamentGroup.hpp" +#include "libslic3r/FilamentGroupUtils.hpp" +#include "libslic3r/PrintConfig.hpp" #include #include #include @@ -230,6 +232,12 @@ static constexpr ClusteringBudget FIXED_SEARCH_BUDGET{ // Graded against the BambuStudio golden the harness was ported from, one-directional at 3%. // +// In flush mode the goldens grade the least-flush search, so those cases run without the printer's +// filaments. With them, the AMS match may choose a grouping up to about five filament changes worse +// that matches the loaded filaments better, which the goldens predate; the [filament_group] tests that +// put filaments where the printer has them loaded cover that choice. Match-mode cases group by the +// printer's filaments and keep them. +// // The tolerance is a parity allowance, and it also covers a small spread across standard libraries. // The k-medoids search seeds each restart with std::shuffle, whose algorithm the C++ standard leaves // unspecified, so libstdc++, libc++ and the MSVC STL permute the same seed differently, start from @@ -249,7 +257,12 @@ TEST_CASE("FilamentGroup golden regression", "[filament_group][golden]") { auto tc = load_test_case(file_path); REQUIRE(tc.base_result.has_value()); - auto result = run_and_evaluate(tc.context, FIXED_SEARCH_BUDGET); + auto search_context = tc.context; + if (search_context.group_info.mode == FGMode::FlushMode) + for (auto& filaments : search_context.machine_info.machine_filament_info) + filaments.clear(); + + auto result = run_and_evaluate(search_context, FIXED_SEARCH_BUDGET); auto eval = full_evaluate_map(tc.context, result.filament_map); auto& base = *tc.base_result; @@ -335,3 +348,131 @@ TEST_CASE("FilamentGroup property checks", "[filament_group][property]") { } } } + +// ============ Layer 3: Matching the filaments loaded in the printer ============ + +// Two extruders with one nozzle each, as on the H2D and X2D, extruder 0 being the master. A change +// between two different filaments flushes `flush`, and a load or an unload takes 29 s, so no +// grouping scores 0. +static FilamentGroupContext two_extruder_context(const std::vector& filaments, + const std::vector>& layer_filaments, + float flush) +{ + const int n = (int)filaments.size(); + FilamentGroupContext ctx{}; + ctx.nozzle_info.nozzle_list = {{"0.4", NozzleVolumeType::nvtStandard, 0, 0}, + {"0.4", NozzleVolumeType::nvtStandard, 1, 1}}; + ctx.nozzle_info.extruder_nozzle_list = {{0, {0}}, {1, {1}}}; + + ctx.machine_info.max_group_size = {4, 4}; + ctx.machine_info.prefer_non_model_filament = {false, false}; + ctx.machine_info.master_extruder_id = 0; + ctx.machine_info.machine_filament_info.resize(2); + + std::vector> matrix(n, std::vector(n, flush)); + for (int i = 0; i < n; ++i) + matrix[i][i] = 0; + ctx.model_info.flush_matrix = {matrix, matrix}; + ctx.model_info.unprintable_filaments.resize(2); + ctx.model_info.layer_filaments = layer_filaments; + ctx.model_info.filament_info = filaments; + for (int i = 0; i < n; ++i) + ctx.model_info.filament_ids.push_back("GFL_" + std::to_string(i)); + + ctx.group_info.total_filament_num = n; + ctx.group_info.max_gap_threshold = 0.01; + ctx.group_info.mode = FGMode::FlushMode; + ctx.group_info.strategy = FGStrategy::BestCost; + ctx.group_info.filament_volume_map.assign(n, (int)NozzleVolumeType::nvtHybrid); + + ctx.speed_info.change_time_params = {/*selector_load_time*/ 14.5f, /*selector_unload_time*/ 14.5f, + /*standard_load_time*/ 29.f, /*standard_unload_time*/ 29.f}; + ctx.speed_info.ams_preload_enabled = {false, false}; + return ctx; +} + +static FilamentGroupUtils::FilamentInfo filament(const char* color, const char* type) +{ + return {FilamentGroupUtils::Color(color), type, false}; +} + +static FilamentGroupUtils::MachineFilamentInfo loaded(const char* color, const char* type, int extruder_id) +{ + FilamentGroupUtils::MachineFilamentInfo info; + info.color = FilamentGroupUtils::Color(color); + info.type = type; + info.is_support = false; + info.extruder_id = extruder_id; + info.is_extended = false; + return info; +} + +static std::vector grouped_extruders(const FilamentGroupContext& ctx) +{ + FilamentGroup fg(ctx); + std::vector extruders; + for (int nozzle : fg.calc_filament_group()) + extruders.push_back(ctx.nozzle_info.nozzle_list[nozzle].extruder_id); + return extruders; +} + +TEST_CASE("Filament-saving grouping puts a lone filament on the extruder that has it loaded", "[filament_group]") { + auto ctx = two_extruder_context({filament("#F95D73", "PETG")}, std::vector>(10, {0}), 0.f); + ctx.machine_info.machine_filament_info[0] = {loaded("#FF6A13", "ABS", 0), loaded("#F98C36", "PLA", 0), loaded("#BCBCBC", "PETG", 0)}; + ctx.machine_info.machine_filament_info[1] = {loaded("#F95D73", "PETG", 1)}; + + CHECK(grouped_extruders(ctx) == std::vector{1}); +} + +TEST_CASE("Filament-saving grouping keeps two filaments on the extruder that has both loaded when it costs a few changes", "[filament_group]") { + // Split, the two print without a change; on one extruder, two changes, within the budget of + // about five. + auto ctx = two_extruder_context({filament("#FFFFFF", "PLA"), filament("#000000", "PLA")}, {{0}, {1}, {0}}, 100.f); + ctx.machine_info.machine_filament_info[0] = {loaded("#FF0000", "PETG", 0)}; + ctx.machine_info.machine_filament_info[1] = {loaded("#FFFFFF", "PLA", 1), loaded("#000000", "PLA", 1)}; + + CHECK(grouped_extruders(ctx) == std::vector{1, 1}); +} + +TEST_CASE("Filament-saving grouping splits two filaments when keeping them together costs many changes", "[filament_group]") { + auto ctx = two_extruder_context({filament("#FFFFFF", "PLA"), filament("#000000", "PLA")}, {{0}, {1}, {0}, {1}, {0}, {1}, {0}}, 100.f); + ctx.machine_info.machine_filament_info[0] = {loaded("#FF0000", "PETG", 0)}; + ctx.machine_info.machine_filament_info[1] = {loaded("#FFFFFF", "PLA", 1), loaded("#000000", "PLA", 1)}; + + auto extruders = grouped_extruders(ctx); + REQUIRE(extruders.size() == 2); + CHECK(extruders[0] != extruders[1]); +} + +TEST_CASE("Filament-saving grouping keeps the least-flush split when the printer reports no filaments", "[filament_group]") { + auto ctx = two_extruder_context({filament("#FFFFFF", "PLA"), filament("#000000", "PLA")}, {{0}, {1}, {0}}, 100.f); + + auto extruders = grouped_extruders(ctx); + REQUIRE(extruders.size() == 2); + CHECK(extruders[0] != extruders[1]); +} + +TEST_CASE("Filament-saving grouping keeps a lone filament on the master extruder when neither extruder has it loaded", "[filament_group]") { + // The master reports nothing; the other extruder holds only a filament of another type. + auto ctx = two_extruder_context({filament("#FFFFFF", "PLA")}, std::vector>(10, {0}), 0.f); + ctx.machine_info.machine_filament_info[1] = {loaded("#FFFFFF", "PETG", 1)}; + + CHECK(grouped_extruders(ctx) == std::vector{0}); +} + +TEST_CASE("Near-optimal groupings are kept within five filament changes, 60 points or 1 % of the best", "[filament_group]") { + using namespace FilamentGroupUtils; + auto kept = [](double best, double candidate, double one_change_budget) { + MemoryedGroupHeap heap; + update_memoryed_groups(MemoryedGroup({0}, best, 1), one_change_budget, 0.01, heap); + update_memoryed_groups(MemoryedGroup({1}, candidate, 1), one_change_budget, 0.01, heap); + return heap.size() == 2; + }; + + CHECK(kept(100, 160, 0)); + CHECK_FALSE(kept(100, 161, 0)); + CHECK(kept(100, 200, 20)); + CHECK_FALSE(kept(100, 201, 20)); + CHECK(kept(20000, 20200, 0)); + CHECK_FALSE(kept(20000, 20201, 0)); +} diff --git a/tests/libslic3r/test_toolordering_nozzle_group.cpp b/tests/libslic3r/test_toolordering_nozzle_group.cpp index 33f8083125..77bd188915 100644 --- a/tests/libslic3r/test_toolordering_nozzle_group.cpp +++ b/tests/libslic3r/test_toolordering_nozzle_group.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include @@ -217,6 +218,121 @@ TEST_CASE("Grouping context spans the filament count with mis-sized config array } } +namespace { +// A filament the printer reports loaded, in the form Plater hands to Print::set_extruder_filament_info. +DynamicPrintConfig loaded_filament(const std::string &colour, const std::string &type, const std::string &tray_name) +{ + DynamicPrintConfig tray; + tray.set_key_value("filament_colour", new ConfigOptionStrings{colour}); + tray.set_key_value("filament_type", new ConfigOptionStrings{type}); + tray.set_key_value("tray_name", new ConfigOptionStrings{tray_name}); + tray.set_key_value("filament_is_support", new ConfigOptionBools{false}); + return tray; +} + +// A two-extruder Bambu printer whose master is the second extruder, as on the H2D (one nozzle on +// each extruder) and the H2C (six on the second), printing PLA in the given colours. A change +// between two of them flushes extruder_flush[e] on extruder e. +DynamicPrintConfig master_second_extruder_config(int second_extruder_nozzles, const std::vector &colours, + const std::vector &extruder_flush = {100., 100.}) +{ + const size_t n = colours.size(); + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.option("nozzle_diameter", true)->values = {0.4, 0.4}; + config.option("extruder_max_nozzle_count", true)->values = {1, second_extruder_nozzles}; + config.option("extruder_nozzle_stats", true)->values = {"Standard#1", "Standard#" + std::to_string(second_extruder_nozzles)}; + config.option("extruder_type", true)->values = {etDirectDrive, etDirectDrive}; + config.option("nozzle_volume_type", true)->values = {nvtStandard, nvtStandard}; + config.option("extruder_ams_count", true)->values = {"1#0|4#1", "1#0|4#1"}; + config.option("master_extruder_id", true)->value = 2; + config.option("machine_load_filament_time", true)->value = 29.; + config.option("machine_unload_filament_time", true)->value = 29.; + + config.option("filament_colour", true)->values = colours; + config.option("filament_type", true)->values = std::vector(n, "PLA"); + config.option("filament_is_support", true)->values = std::vector(n, 0); + config.option("filament_diameter", true)->values = std::vector(n, 1.75); + config.option("filament_map", true)->values = std::vector(n, 2); + // One n x n matrix per extruder. + std::vector flush; + for (int extruder = 0; extruder < 2; ++extruder) + for (size_t from = 0; from < n; ++from) + for (size_t to = 0; to < n; ++to) + flush.push_back(from == to ? 0. : extruder_flush[extruder]); + config.option("flush_volumes_matrix", true)->values = flush; + config.option("flush_multiplier", true)->values = {1., 1.}; + return config; +} +} // namespace + +TEST_CASE("Filament-saving grouping puts a filament on the extruder the printer has it loaded in", "[ToolOrdering]") +{ + Model model; + model.add_object("cube", "", make_cube(20, 20, 20))->add_instance(); + Print print; + print.apply(model, master_second_extruder_config(1, {"#F98C36"})); + print.is_BBL_printer() = true; + // Only the first (non-master) extruder holds the printed PLA. + print.set_extruder_filament_info({{loaded_filament("#F98C36", "PLA", "A1"), loaded_filament("#BCBCBC", "PETG", "A2")}, + {loaded_filament("#F95D73", "PETG", "Ext")}}); + + auto result = ToolOrdering::get_recommended_filament_maps({{0}, {0}, {0}}, &print, FilamentMapMode::fmmAutoForFlush, {}, {}); + + REQUIRE(result.get_extruder_id(0) == 0); +} + +TEST_CASE("Filament-saving grouping keeps a lone filament on the master extruder when the printer reports none", "[ToolOrdering]") +{ + Model model; + model.add_object("cube", "", make_cube(20, 20, 20))->add_instance(); + Print print; + print.apply(model, master_second_extruder_config(1, {"#F98C36"})); + print.is_BBL_printer() = true; + + auto result = ToolOrdering::get_recommended_filament_maps({{0}, {0}, {0}}, &print, FilamentMapMode::fmmAutoForFlush, {}, {}); + + REQUIRE(result.get_extruder_id(0) == 1); +} + +TEST_CASE("Filament-saving grouping prefers the master extruder when the printer's filaments match no grouping better", "[ToolOrdering]") +{ + // Three PLAs in turn, flushing far less on the first extruder: the least-flush grouping puts two + // of them there, and the master preference swaps the groups. The printer holds only PETG, so + // neither grouping matches it better and the swap stands. + Model model; + model.add_object("cube", "", make_cube(20, 20, 20))->add_instance(); + Print print; + print.apply(model, master_second_extruder_config(1, {"#FFFFFF", "#000000", "#808080"}, {10., 100.})); + print.is_BBL_printer() = true; + print.set_extruder_filament_info({{loaded_filament("#FF0000", "PETG", "A1")}, {loaded_filament("#F95D73", "PETG", "Ext")}}); + + auto result = ToolOrdering::get_recommended_filament_maps({{0}, {1}, {2}, {0}, {1}, {2}}, &print, FilamentMapMode::fmmAutoForFlush, {}, {}); + + int on_master = 0; + for (int f = 0; f < 3; ++f) + on_master += result.get_extruder_id(f) == 1; + REQUIRE(on_master == 2); +} + +TEST_CASE("Filament-saving grouping on a multi-nozzle printer keeps filaments on the extruder the printer has them loaded in", "[ToolOrdering][H2C]") +{ + // On the H2C layout the master preference would move both filaments to the master's first two + // nozzles, so choosing between that and the printer's match resolves nozzle ids past one per + // extruder. + Model model; + model.add_object("cube", "", make_cube(20, 20, 20))->add_instance(); + Print print; + print.apply(model, master_second_extruder_config(6, {"#F98C36", "#FFFFFF"})); + print.is_BBL_printer() = true; + print.set_extruder_filament_info({{loaded_filament("#F98C36", "PLA", "A1"), loaded_filament("#FFFFFF", "PLA", "A2")}, + {loaded_filament("#F95D73", "PETG", "Ext")}}); + + auto result = ToolOrdering::get_recommended_filament_maps({{0}, {1}, {0}}, &print, FilamentMapMode::fmmAutoForFlush, {}, {}); + + REQUIRE(result.get_extruder_id(0) == 0); + REQUIRE(result.get_extruder_id(1) == 0); +} + TEST_CASE("H2C dynamic selector: per-layer nozzle ids reach the g-code surface", "[ToolOrdering][H2C][Dynamic]") { // The per-layer regroup engine