#include "FilamentGroup.hpp" #include "GCode/ToolOrderUtils.hpp" #include "FlushVolPredictor.hpp" #include #include #include #include #include #include #include "libslic3r/Log.hpp" namespace Slic3r { using namespace FilamentGroupUtils; static constexpr long long ENUM_THRESHOLD = 10000; static constexpr long long ENUM_EARLY_EXIT = 10000000; constexpr uint32_t GOLDEN_RATIO_32 = 0x9e3779b9; // 计算单对“工程耗材—设备耗材”的匹配成本,供最小费用算法汇总整个匹配方案。 static int calc_match_mode_cost(float color_distance, const std::string& model_filament_id, const std::string& machine_filament_id, int max_assignment_count) { // 1. 将颜色距离保留两位精度并转为整数,避免直接转换造成截断。 constexpr int kColorDistanceScale = 100; // 2. 一个方案最多有 N 次小类不匹配;使用 N+1 权重,保证颜色差异始终优先。 const int color_priority_weight = std::max(1, max_assignment_count) + 1; const int quantized_color_distance = static_cast(std::lround(color_distance * kColorDistanceScale)); const int weighted_color_cost = quantized_color_distance * color_priority_weight; // 3. filament_id 表示耗材小类:一致不加成本,不一致加 1,仅在同色时择优。 const bool filament_id_match = !model_filament_id.empty() && !machine_filament_id.empty() && model_filament_id == machine_filament_id; const int filament_id_mismatch_cost = filament_id_match ? 0 : 1; // 4. 单对成本 = 颜色成本 × (N+1) + 小类不匹配成本,求解器再对全部匹配求和。 return weighted_color_cost + filament_id_mismatch_cost; } static bool filament_diameter_matches_nozzle_volume(const FilamentGroupUtils::FilamentInfo &filament, NozzleVolumeType volume_type) { if (filament.diameter <= 0.f) return true; const bool uses_285_filament = filament.diameter > 2.5f; const bool uses_285_path = volume_type == NozzleVolumeType::nvtTPU285; return uses_285_filament == uses_285_path; } // clear the array and heap,save the groups in heap to the array static void change_memoryed_heaps_to_arrays(MemoryedGroupHeap& heap,const int total_filament_num,const std::vector& used_filaments, std::vector>& arrs) { // switch the label idx arrs.clear(); while (!heap.empty()) { auto top = heap.top(); heap.pop(); std::vector labels_tmp(total_filament_num, 0); for (size_t idx = 0; idx < top.group.size(); ++idx) labels_tmp[used_filaments[idx]] = top.group[idx]; arrs.emplace_back(std::move(labels_tmp)); } } static std::unordered_map get_merged_filament_map(const std::unordered_map>& merged_filaments) { std::unordered_map filament_merge_map; for (auto elem : merged_filaments) { for (auto f : elem.second) { //traverse filaments in merged group filament_merge_map[f] = elem.first; } } return filament_merge_map; } // 喷嘴枚举去重使用的语义 hash:直径、流量类型、所属挤出机、已装料和容量都会影响可交换性。 static uint64_t fnv_hash_nozzle(const std::string& diameter, int volume_type, int is_right_extruder, int loaded_filament = -1, int capacity = -1) { constexpr uint64_t FNV_OFFSET_BASIS = 14695981039346656037ULL; constexpr uint64_t FNV_PRIME = 1099511628211ULL; constexpr uint64_t SALT_A = 0xA5A5A5A5A5A5A5A5ULL; constexpr uint64_t SALT_B = 0x5A5A5A5A5A5A5A5AULL; constexpr uint64_t SALT_C = 0x3C3C3C3C3C3C3C3CULL; constexpr uint64_t SALT_D = 0x9696969696969696ULL; uint64_t h = FNV_OFFSET_BASIS; for (unsigned char c : diameter) { h ^= static_cast(c); h *= FNV_PRIME; } h ^= static_cast(volume_type) + SALT_A; h *= FNV_PRIME; h ^= static_cast(is_right_extruder) + SALT_B; h *= FNV_PRIME; if (loaded_filament >= 0) { h ^= static_cast(loaded_filament) + SALT_C; h *= FNV_PRIME; } if (capacity >= 0) { h ^= static_cast(capacity) + SALT_D; h *= FNV_PRIME; } return h; } // 冲刷体积(mm^3)折算成时间等价分(秒):体积→质量(密度/1000)→冲刷耗时(速度)→×2修正 // evaluate_score 与 calc_one_change_budget 共用,避免两处系数漂移 static constexpr double FLUSH_VOLUME_TO_SCORE = 1.26 /*密度g/cm^3*/ * 180.0 /*冲刷s/g*/ * 2.0 /*修正*/ / 1000.0; // == 0.4536 static double evaluate_score(const double flush, const double time, const bool with_time = false) { if (!with_time) return flush; double flush_score = flush * FLUSH_VOLUME_TO_SCORE; return flush_score + time; } static double calc_change_time_for_group( const std::vector& filament_change_seq, const std::vector& nozzle_change_seq, const std::vector& logical_filaments, const std::vector& nozzle_list, const MultiNozzleUtils::FilamentChangeTimeParams& time_params, const std::vector& ams_preload_enabled, const std::vector& group_of_filament) { auto r = MultiNozzleUtils::simulate_filament_change_time( logical_filaments, nozzle_list, filament_change_seq, nozzle_change_seq, group_of_filament, time_params, ams_preload_enabled); return r.actual_time; } static double full_evaluate( const std::vector& used_filaments, const std::vector& filament_nozzle_map, const FilamentGroupContext& ctx, std::optional&)>> get_custom_seq = std::nullopt, int* out_flush = nullptr) { auto group_res = MultiNozzleUtils::LayeredNozzleGroupResult::create(filament_nozzle_map, ctx.nozzle_info.nozzle_list, used_filaments); if (!group_res) { if (out_flush) *out_flush = 0; return 0.0; } MultiNozzleUtils::NozzleStatusRecorder initial_status; for (auto& [nozzle_id, filament_id] : ctx.nozzle_info.nozzle_status) { if (filament_id >= 0) { int extruder_id = 0; for (const auto& nozzle : ctx.nozzle_info.nozzle_list) { if (nozzle.group_id == nozzle_id) { extruder_id = nozzle.extruder_id; break; } } initial_status.set_nozzle_status(nozzle_id, filament_id, extruder_id); } } std::vector> filament_sequences; int flush = reorder_filaments_for_multi_nozzle_extruder( used_filaments, *group_res, ctx.model_info.layer_filaments, ctx.model_info.flush_matrix, get_custom_seq ? *get_custom_seq : std::function&)>{}, &filament_sequences, initial_status ); if (out_flush) *out_flush = flush; double change_time = 0.0; if (!filament_sequences.empty()) { std::vector filament_change_seq; std::vector nozzle_change_seq; int prev_fil = -1, prev_nozzle = -1; for (const auto& layer_seq : filament_sequences) { for (unsigned int fil : layer_seq) { auto nozzle_info = group_res->get_first_nozzle_for_filament(fil); if (!nozzle_info) continue; int nid = nozzle_info->group_id; if ((int)fil == prev_fil && nid == prev_nozzle) continue; filament_change_seq.push_back(static_cast(fil)); nozzle_change_seq.push_back(nid); prev_fil = (int)fil; prev_nozzle = nid; } } std::vector logical_filaments(used_filaments.begin(), used_filaments.end()); std::vector group_of_filament(used_filaments.size(), 0); for (size_t fi = 0; fi < used_filaments.size(); ++fi) { int nozzle_id = filament_nozzle_map[used_filaments[fi]]; if (nozzle_id >= 0 && nozzle_id < (int)ctx.nozzle_info.nozzle_list.size()) group_of_filament[fi] = ctx.nozzle_info.nozzle_list[nozzle_id].extruder_id; } change_time = calc_change_time_for_group( filament_change_seq, nozzle_change_seq, logical_filaments, ctx.nozzle_info.nozzle_list, ctx.speed_info.change_time_params, ctx.speed_info.ams_preload_enabled, group_of_filament ); } double print_time = 0.0; if (ctx.speed_info.group_with_time) { TimeEvaluator time_evaluator(ctx.speed_info); print_time = time_evaluator.get_estimated_time(filament_nozzle_map); } return evaluate_score(flush, change_time + print_time, true); } static long long estimate_dedup_enum_count(int k, int n, const FilamentGroupContext& ctx) { if (n <= 0 || k <= 0) return 0; long long total = 1; for (int i = 0; i < n; ++i) { total *= k; if (total > ENUM_EARLY_EXIT) return total; } if (k <= 1) return total; int dedup_factor = 1; std::map nozzle_type_count; for (const auto& nozzle : ctx.nozzle_info.nozzle_list) { auto it = ctx.nozzle_info.nozzle_status.find(nozzle.group_id); int loaded_filament = (it != ctx.nozzle_info.nozzle_status.end()) ? it->second : -1; int nozzle_capacity = nozzle.group_id < static_cast(ctx.nozzle_info.per_nozzle_capacity.size()) ? ctx.nozzle_info.per_nozzle_capacity[nozzle.group_id] : -1; uint64_t hash = fnv_hash_nozzle(nozzle.diameter, nozzle.volume_type, nozzle.extruder_id > 0, loaded_filament, nozzle_capacity); nozzle_type_count[hash]++; } for (auto& [hash, count] : nozzle_type_count) { int factorial = 1; for (int i = 2; i <= count; ++i) factorial *= i; dedup_factor *= factorial; } return total / std::max(dedup_factor, 1); } double FilamentGroup::calc_one_change_budget(const std::vector& used_filaments) const { // “一次换料”预算:对所有已用料两两组合,各取“较贵方向”的 flush,再取中位数作为 // “典型一次换料”的代价。中位数天然对个别极端色对(如纯黑↔纯白)免疫,随调色板自适应: // 暗↔亮预算大、近似色预算小。最后折算到与 evaluate_score 相同的分数尺度。 // 空/单料/零矩阵时返回 0,退回 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()); const double typical_flush = pair_flush[mid]; constexpr double kOneChangeMargin = 1.2; // 留余量,保证完整一次换料仍在容忍度内 return typical_flush * FLUSH_VOLUME_TO_SCORE * kOneChangeMargin; } std::vector FilamentGroup::calc_group_by_enum( int k, const std::vector& used_filaments, const std::unordered_map>& unplaceable_limits, int* cost) { static constexpr int UNPLACEABLE_LIMIT_REWARD = 10000; static constexpr int MAX_SIZE_LIMIT_REWARD = 5000; static constexpr int SUPPORT_PREFER_REWARD = 100; 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++) { std::unordered_set group_set; if (auto it = unplaceable_limits.find(i); it != unplaceable_limits.end()) { for (int g = 0; g < k; g++) group_set.insert(g); for (int g : it->second) group_set.erase(g); } else { for (int g = 0; g < k; g++) group_set.insert(g); } candidates[i].assign(group_set.begin(), group_set.end()); } auto vector_equal = [](const std::vector& a, const std::vector& b) -> bool { if (a.size() != b.size()) return false; for (size_t i = 0; i < a.size(); i++) { if (a[i] != b[i]) return false; } return true; }; auto vector_hash = [](const std::vector& v) -> size_t { size_t h = 0; for (auto val : v) { h ^= val + GOLDEN_RATIO_32 + (h << 6) + (h >> 2); } return h; }; std::unordered_set, decltype(vector_hash), decltype(vector_equal)> group_set(0, vector_hash, vector_equal); std::vector group_hashs; std::vector nozzles_hash(k); for (int nozzle_idx = 0; nozzle_idx < k; ++nozzle_idx) { const auto& nozzle = ctx.nozzle_info.nozzle_list[nozzle_idx]; auto it = ctx.nozzle_info.nozzle_status.find(nozzle.group_id); int loaded_filament = (it != ctx.nozzle_info.nozzle_status.end()) ? it->second : -1; int nozzle_capacity = nozzle_idx < static_cast(ctx.nozzle_info.per_nozzle_capacity.size()) ? ctx.nozzle_info.per_nozzle_capacity[nozzle_idx] : -1; nozzles_hash[nozzle_idx] = fnv_hash_nozzle(nozzle.diameter, nozzle.volume_type, nozzle.extruder_id > 0, loaded_filament, nozzle_capacity); } std::vector best_full_map(ctx.group_info.total_filament_num, ctx.machine_info.master_extruder_id); double best_score = std::numeric_limits::max(); int best_prefer_level = 0; int best_flush = 0; const long long total = (long long)std::pow(k, n); for (long long mask = 0; mask < total; mask++) { long long num = mask; std::unordered_map> nozzles_filaments; std::vector groups_count(k, 0); std::vector used_labels(n, 0); for (int i = 0; i < n; i++) { int g_id = num % k; num /= k; used_labels[i] = g_id; nozzles_filaments[g_id].emplace_back(i); groups_count[g_id]++; } // Hash dedup group_hashs.clear(); for (auto& nf : nozzles_filaments) { uint64_t filament_mask = 0; for (int filament : nf.second) filament_mask |= (1ULL << filament); size_t gh = nozzles_hash[nf.first]; gh ^= (std::hash{}(filament_mask) + GOLDEN_RATIO_32 + (gh << 6) + (gh >> 2)); group_hashs.emplace_back(gh); } std::sort(group_hashs.begin(), group_hashs.end()); if (group_set.find(group_hashs) != group_set.end()) continue; group_set.insert(group_hashs); // Prefer level int prefer_level = 0; int placeable_count = 0; for (int i = 0; i < n; i++) { if (std::find(candidates[i].begin(), candidates[i].end(), used_labels[i]) != candidates[i].end()) placeable_count++; } prefer_level += placeable_count * UNPLACEABLE_LIMIT_REWARD; // Per-nozzle capacity (indexed by nozzle group_id), provided by ctx for every machine. const std::vector& nozzle_caps = ctx.nozzle_info.per_nozzle_capacity; bool size_ok = true; for (int g = 0; g < k; g++) { if (g < (int)nozzle_caps.size() && groups_count[g] > nozzle_caps[g]) size_ok = false; } if (size_ok) prefer_level += MAX_SIZE_LIMIT_REWARD; if (ctx.group_info.strategy == FGStrategy::BestFit) { bool all_full = true; for (int g = 0; g < k; g++) { if (g < (int)nozzle_caps.size() && groups_count[g] < nozzle_caps[g]) all_full = false; } if (all_full) prefer_level += BEST_FIT_LIMIT_REWARD; } for (int g = 0; g < k; g++) { if (g < (int)ctx.machine_info.prefer_non_model_filament.size() && ctx.machine_info.prefer_non_model_filament[g]) { for (int fidx : nozzles_filaments[g]) { if (ctx.model_info.filament_info[used_filaments[fidx]].usage_type == SupportOnly) prefer_level += SUPPORT_PREFER_REWARD; } } } // Build full map and evaluate std::vector full_map(ctx.group_info.total_filament_num, ctx.machine_info.master_extruder_id); for (int i = 0; i < n; ++i) full_map[used_filaments[i]] = used_labels[i]; int flush_vol = 0; double score = full_evaluate(used_filaments, full_map, ctx, get_custom_seq, &flush_vol); int master_ex_id = ctx.machine_info.master_extruder_id; if (master_ex_id < k && groups_count[master_ex_id] < (int)(used_filaments.size() + 1) / 2) score += ABSOLUTE_FLUSH_GAP_TOLERANCE; if (prefer_level > best_prefer_level || (prefer_level == best_prefer_level && score < best_score)) { best_score = score; best_prefer_level = prefer_level; best_full_map = full_map; best_flush = flush_vol; } MemoryedGroup mg(used_labels, score, prefer_level); update_memoryed_groups(mg, one_change_budget, ctx.group_info.max_gap_threshold, m_memoryed_heap); } if (cost) *cost = best_flush; return best_full_map; } std::vector FilamentGroup::calc_group_by_kmedoids( int k, const std::vector& used_filaments, const std::unordered_map>& unplaceable_limits, int* cost, int timeout_ms) { auto distance_evaluator = std::make_shared(ctx.model_info.flush_matrix, used_filaments, ctx.model_info.layer_filaments); 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) { std::pair, int> clusters; clusters.first = std::set(nozzles.begin(), nozzles.end()); clusters.second = ctx.machine_info.max_group_size.at(extruder_id); cluster_size_limit.emplace_back(clusters); } PAM.set_cluster_group_size(cluster_size_limit); if (!ctx.nozzle_info.per_nozzle_capacity.empty()) { const auto& cap = ctx.nozzle_info.per_nozzle_capacity; std::vector per_nozzle_max(k, DEFAULT_CLUSTER_SIZE); for (int nz = 0; nz < k; ++nz) per_nozzle_max[nz] = (nz < (int)cap.size()) ? cap[nz] : DEFAULT_CLUSTER_SIZE; PAM.set_max_cluster_size(per_nozzle_max); } PAM.do_clustering(ctx, timeout_ms, 30); m_memoryed_heap = PAM.get_memoryed_groups(); auto labels = PAM.get_cluster_labels(); std::vector full_map(ctx.group_info.total_filament_num, ctx.machine_info.master_extruder_id); for (int i = 0; i < (int)labels.size(); ++i) full_map[used_filaments[i]] = labels[i]; if (cost) { int flush_vol = 0; full_evaluate(used_filaments, full_map, ctx, get_custom_seq, &flush_vol); *cost = flush_vol; } return full_map; } /** * @brief Select the group that best fit the filaments in AMS * * Calculate the total color distance between the grouping results and the AMS filaments through * minimum cost maximum flow. Only those with a distance difference within the threshold are * considered valid. * * @param map_lists Group list with similar flush count * @param nozzle_lists nozzle_id -> extruder_id * @param used_filaments Idx of used filaments * @param used_filament_info Information of filaments used * @param machine_filament_info Information of filaments loaded in printer * @param color_threshold Threshold for considering colors to be similar * @return The group that best fits the filament distribution in AMS */ std::vector select_best_group_for_ams(const std::vector>& filament_to_nozzles, const std::vector& nozzle_list, const std::vector& used_filaments, const std::vector& used_filament_info, const std::vector>& machine_filament_info_, const bool has_filament_switcher, const double color_threshold) { using namespace FlushPredict; if (has_filament_switcher) return filament_to_nozzles.size() ? filament_to_nozzles.front() : std::vector(); const int fail_cost = 9999; // these code is to make we machine filament info size is 2 std::vector> machine_filament_info = machine_filament_info_; machine_filament_info.resize(2); // 设备侧完全没有耗材信息(未连接打印机 / 未同步 AMS)时,所有候选代价相同, // AMS 匹配没有参考价值,直接保留最小冲刷方案,避免结果由平局顺序决定。 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; for (auto &filament_to_nozzle : filament_to_nozzles) { std::vector> group_filaments(2); std::vector>group_colors(2); for (size_t i = 0; i < used_filaments.size(); ++i) { auto &nozzle = nozzle_list[filament_to_nozzle[used_filaments[i]]]; int target_group = nozzle.extruder_id == 0 ? 0 : 1; group_colors[target_group].emplace_back(used_filament_info[i].color); group_filaments[target_group].emplace_back(i); } int group_cost = 0; for (size_t i = 0; i < 2; ++i) { if (group_colors[i].empty()) continue; if (machine_filament_info[i].empty()) { // 按耗材根数计罚,与下方匹配分支保持同一尺度; // 若按分组数计罚,则"用的头越少越便宜",会把所有耗材压到同一个挤出机。 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())); // calculate color distance matrix for (size_t src = 0; src < group_colors[i].size(); ++src) { for (size_t dst = 0; dst < machine_filament_info[i].size(); ++dst) { distance_matrix[src][dst] = calc_color_distance( RGBColor(group_colors[i][src].r, group_colors[i][src].g, group_colors[i][src].b), RGBColor(machine_filament_info[i][dst].color.r, machine_filament_info[i][dst].color.g, machine_filament_info[i][dst].color.b) ); } } // get min cost by min cost max flow std::vectorl_nodes(group_colors[i].size()), r_nodes(machine_filament_info[i].size()); std::iota(l_nodes.begin(), l_nodes.end(), 0); std::iota(r_nodes.begin(), r_nodes.end(), 0); std::unordered_map>unlink_limits; for (size_t from = 0; from < group_filaments[i].size(); ++from) { for (size_t to = 0; to < machine_filament_info[i].size(); ++to) { if (used_filament_info[group_filaments[i][from]].type != machine_filament_info[i][to].type || used_filament_info[group_filaments[i][from]].is_support != machine_filament_info[i][to].is_support) { unlink_limits[from].emplace_back(to); } } } MatchModeGroupSolver mcmf(distance_matrix, l_nodes, r_nodes, std::vector(r_nodes.size(), l_nodes.size()), unlink_limits); auto ams_map = mcmf.solve(); for (size_t idx = 0; idx < ams_map.size(); ++idx) { if (ams_map[idx] == MaxFlowGraph::INVALID_ID || distance_matrix[idx][ams_map[idx]] > color_threshold) { group_cost += fail_cost; } else { group_cost += distance_matrix[idx][ams_map[idx]]; } } } if (best_map.empty() || group_cost < best_cost) { best_cost = group_cost; best_map = filament_to_nozzle; } } return best_map; } void FilamentGroupUtils::update_memoryed_groups(const MemoryedGroup& item, const double one_change_budget, const double gap_threshold, MemoryedGroupHeap& groups) { // 保留比最优多约五次换料代价的候选,让 select_best_group_for_ams 能优先选 // 匹配 AMS 的分组(如两个料都留在已装载的挤出机),而非纯最小冲刷的左右拆分。 // one_change_budget 随色对自适应;绝对/相对下限兜底退化情况(空/零冲刷矩阵、极小分数)。 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); }; if (groups.empty()) { groups.push(item); } else { auto top = groups.top(); // we only memory items with the highest prefer level if (top.prefer_level > item.prefer_level) return; else if (top.prefer_level == item.prefer_level) { if (top.cost <= item.cost) { emplace_if_accepatle(groups, item, top); } // find a group with lower cost, rebuild the heap else { MemoryedGroupHeap new_heap; new_heap.push(item); while (!groups.empty()) { auto top = groups.top(); groups.pop(); emplace_if_accepatle(new_heap, top, item); } groups = std::move(new_heap); } } // find a group with the higher prefer level, rebuild the heap else { groups = MemoryedGroupHeap(); groups.push(item); } } } std::vector collect_sorted_used_filaments(const std::vector>& layer_filaments) { std::setused_filaments_set; for (const auto& lf : layer_filaments) for (const auto& f : lf) used_filaments_set.insert(f); std::vectorused_filaments(used_filaments_set.begin(), used_filaments_set.end()); sort_remove_duplicates(used_filaments); return used_filaments; } FlushDistanceEvaluator::FlushDistanceEvaluator(const std::vector& flush_matrix, const std::vector& used_filaments, const std::vector>& layer_filaments, double p) { //calc pair counts std::vector>count_matrix(used_filaments.size(), std::vector(used_filaments.size())); for (const auto& lf : layer_filaments) { for (auto iter = lf.begin(); iter != lf.end(); ++iter) { auto id_iter1 = std::find(used_filaments.begin(), used_filaments.end(), *iter); if (id_iter1 == used_filaments.end()) continue; auto idx1 = id_iter1 - used_filaments.begin(); for (auto niter = std::next(iter); niter != lf.end(); ++niter) { auto id_iter2 = std::find(used_filaments.begin(), used_filaments.end(), *niter); if (id_iter2 == used_filaments.end()) continue; auto idx2 = id_iter2 - used_filaments.begin(); count_matrix[idx1][idx2] += 1; count_matrix[idx2][idx1] += 1; } } } m_distance_matrix.resize(flush_matrix.size(), std::vector>(used_filaments.size(), std::vector(used_filaments.size()))); for (size_t i = 0; i < used_filaments.size(); ++i) { for (size_t j = 0; j < used_filaments.size(); ++j) { for (size_t k = 0; k < flush_matrix.size(); k++) { if (i == j) m_distance_matrix[k][i][j] = 0; else { //TODO: check m_flush_matrix float max_val = std::max(flush_matrix[k][used_filaments[i]][used_filaments[j]], flush_matrix[k][used_filaments[j]][used_filaments[i]]); float min_val = std::min(flush_matrix[k][used_filaments[i]][used_filaments[j]], flush_matrix[k][used_filaments[j]][used_filaments[i]]); m_distance_matrix[k][i][j] = (max_val * p + min_val * (1 - p)) * (std::max(count_matrix[i][j], 1)); } } } } } double FlushDistanceEvaluator::get_distance(int idx_a, int idx_b, int extruder_id) const { assert(0 <= idx_a && idx_a < m_distance_matrix[extruder_id].size()); assert(0 <= idx_b && idx_b < m_distance_matrix[extruder_id].size()); return m_distance_matrix[extruder_id][idx_a][idx_b]; } double TimeEvaluator::get_estimated_time(const std::vector& filament_map) const { double time = 0; for(auto &elem : m_speed_info.filament_print_time){ int filament_idx = elem.first; auto extruder_time = elem.second; int filament_extruder_id = filament_map[filament_idx]; time += extruder_time[filament_extruder_id]; } return time; } void KMediods::set_cluster_group_size(const std::vector, int>> &cluster_group_size) { m_cluster_group_size = cluster_group_size; m_nozzle_to_extruder.resize(m_k, 0); for (int i = 0; i < m_cluster_group_size.size(); i++) { for (auto nozzle_id : m_cluster_group_size[i].first) m_nozzle_to_extruder[nozzle_id] = i; } } int KMediods::calc_cost(const std::vector& cluster_labels, const std::vector& cluster_centers,int cluster_id) { assert(m_evaluator); int total_cost = 0; std::vector> nozzle_cost(m_k,{0,0.0}); std::vector nozzle_filaments(m_k, 0); for (int i = 0; i < m_elem_count; ++i) { if (cluster_id != -1 && cluster_labels[i] != cluster_id) continue; if (cluster_centers[cluster_labels[i]] == -1) continue; nozzle_filaments[cluster_labels[i]]++; for (int j = i + 1; j < m_elem_count; ++j) { int nozzle_i = cluster_labels[i]; int nozzle_j = cluster_labels[j]; if (nozzle_i == nozzle_j) { nozzle_cost[nozzle_i].first++; nozzle_cost[nozzle_j].second += m_evaluator->get_distance(i, j, m_nozzle_to_extruder[nozzle_i]); } } } for (size_t i = 0; i < nozzle_cost.size(); ++i) { if (nozzle_filaments[i] > 0 && nozzle_cost[i].second > 0) total_cost += nozzle_cost[i].second / nozzle_cost[i].first * (nozzle_filaments[i] - 1); } return total_cost; } bool KMediods::have_enough_size(const std::vector& cluster_size, const std::vector, int>>& cluster_group_size,int elem_count) { bool have_enough_size = true; std::optionalcluster_sum; std::optionalcluster_group_sum; if (!cluster_size.empty()) cluster_sum = std::accumulate(cluster_size.begin(), cluster_size.end(), 0); if (!cluster_group_size.empty()) cluster_group_sum = std::accumulate(cluster_group_size.begin(), cluster_group_size.end(), 0, [](int a, const std::pair, int>& p) {return a + p.second; }); if (cluster_sum.has_value()) have_enough_size &= (cluster_sum >= elem_count); if (cluster_group_sum.has_value()) have_enough_size &= (cluster_group_sum >= elem_count); return have_enough_size; } // make sure each cluster at least have one elements std::vector KMediods::init_cluster_center(const std::unordered_map>& placeable_limits, const std::unordered_map>& unplaceable_limits,const std::vector& cluster_size,const std::vector,int>>& cluster_group_size, int seed) { // max flow network std::vector l_nodes(m_elem_count); // represent the filament idx, to be shuffled std::vector r_nodes(m_k); // represent the group idx std::iota(l_nodes.begin(), l_nodes.end(), 0); std::iota(r_nodes.begin(), r_nodes.end(), 0); std::unordered_map> shuffled_placeable_limits; std::unordered_map> shuffled_unplaceable_limits; // shuffle the filaments and transfer placeable,unplaceable limits { std::mt19937 rng(seed); std::shuffle(l_nodes.begin(), l_nodes.end(), rng); std::unordered_mapidx_transfer; for (size_t idx = 0; idx < l_nodes.size(); ++idx){ int new_idx = std::find(l_nodes.begin(),l_nodes.end(), idx) - l_nodes.begin(); idx_transfer[idx] = new_idx; } for (auto& elem : placeable_limits) shuffled_placeable_limits[idx_transfer[elem.first]] = elem.second; for (auto& elem : unplaceable_limits) shuffled_unplaceable_limits[idx_transfer[elem.first]] = elem.second; } MaxFlowSolver M(l_nodes, r_nodes, shuffled_placeable_limits, shuffled_unplaceable_limits); auto ret = M.solve(); // if still has -1,it means there has some filaments that cannot be placed under the limit. We neglect the -1 here since we // are deciding the cluster center, -1 can be handled in later steps std::vector cluster_center(m_k, -1); for (size_t idx = 0; idx < ret.size(); ++idx) { if (ret[idx] != -1) { cluster_center[ret[idx]] = l_nodes[idx]; } } return cluster_center; } std::vector KMediods::assign_cluster_label(const std::vector& center, const std::unordered_map>& placeable_limits, const std::unordered_map>& unplaceable_limits, const std::vector& cluster_size, const std::vector, int>>& cluster_group_size) { std::vector labels(m_elem_count, -1); std::vector l_nodes(m_elem_count); std::vector r_nodes(m_k); std::iota(l_nodes.begin(), l_nodes.end(), 0); std::iota(r_nodes.begin(), r_nodes.end(), 0); std::vector> distance_matrix(m_elem_count, std::vector(m_k)); for (int i = 0; i < m_elem_count; ++i) { for (int j = 0; j < m_k; ++j) { if (center[j] == -1) distance_matrix[i][j] = static_cast(MaxFlowGraph::MCMF_MAX_EDGE_COST); else distance_matrix[i][j] = m_evaluator->get_distance(i, center[j], m_nozzle_to_extruder[j]); } } // only consider the size limit if the group can contain all of the filaments std::vector r_nodes_capacity = {}; std::vector, int>> r_nodes_group_capacity = {}; if (have_enough_size(cluster_size, cluster_group_size, m_elem_count)) { r_nodes_capacity = cluster_size; r_nodes_group_capacity = cluster_group_size; } else { // TODO: xcr:throw exception here? // adjust group size to elem count if the group cannot contain all of the filamnts r_nodes_capacity = std::vector(m_k, m_elem_count); } std::vector l_nodes_capacity(l_nodes.size(),1); //for (size_t idx = 0; idx < center.size(); ++idx) // if (center[idx] != -1) // l_nodes_capacity[center[idx]] = 0; // Each group can receive up to m_elem_count materials at most, so the flow from r_nodes to sink is adjusted to m_elem_count. MinFlushFlowSolver M(distance_matrix, l_nodes, r_nodes, placeable_limits, unplaceable_limits, l_nodes_capacity, r_nodes_capacity, r_nodes_group_capacity); auto ret = M.solve(); for (size_t idx = 0; idx < ret.size(); ++idx) { if (ret[idx] != MaxFlowGraph::INVALID_ID) { labels[l_nodes[idx]] = r_nodes[ret[idx]]; } } for (size_t idx = 0; idx < center.size(); ++idx) if (center[idx] != -1) assert(labels[center[idx]] == idx); //for (size_t idx = 0; idx < center.size(); ++idx) { // if (center[idx] != -1) { // labels[center[idx]] = idx; // } //} // If there are materials that have not been grouped in the last step, assign them to a valid group. for (size_t idx = 0; idx < labels.size(); ++idx) { if (labels[idx] == -1) { int fallback = m_default_group_id; auto it = unplaceable_limits.find(static_cast(idx)); if (it != unplaceable_limits.end()) { for (int nid = 0; nid < m_k; ++nid) { if (std::find(it->second.begin(), it->second.end(), nid) == it->second.end()) { fallback = nid; break; } } } labels[idx] = fallback; } } return labels; } /* 1.Select initial medoids randomly 2.Iterate while the cost decreases: 2.1 In each cluster, make the point that minimizes the sum of distances within the cluster the medoid 2.2 Reassign each point to the cluster defined by the closest medoid determined in the previous step */ void KMediods::do_clustering(const FilamentGroupContext &context, int timeout_ms, int retry) { FlushTimeMachine T; T.time_machine_start(); const std::vector used_filaments = collect_sorted_used_filaments(context.model_info.layer_filaments); auto build_full_map = [&](const std::vector& labels) -> std::vector { std::vector full_map(context.group_info.total_filament_num, m_default_group_id); for (int i = 0; i < (int)labels.size(); ++i) full_map[used_filaments[i]] = labels[i]; return full_map; }; auto evaluate_labels = [&](const std::vector& labels) -> double { auto full_map = build_full_map(labels); return full_evaluate(used_filaments, full_map, context); }; std::vector best_cluster_centers = std::vector(m_k, 0); std::vector best_cluster_labels = std::vector(m_elem_count, m_default_group_id); double best_cluster_cost = std::numeric_limits::max(); int retry_count = 0; while (retry_count < retry && T.time_machine_end() < timeout_ms) { std::vector curr_cluster_centers = init_cluster_center(m_placeable_limits, m_unplaceable_limits, m_max_cluster_size, m_cluster_group_size, retry_count); std::vector curr_cluster_labels = assign_cluster_label(curr_cluster_centers, m_placeable_limits, m_unplaceable_limits, m_max_cluster_size, m_cluster_group_size); double curr_cluster_cost = evaluate_labels(curr_cluster_labels); MemoryedGroup g(curr_cluster_labels, curr_cluster_cost, 1); update_memoryed_groups(g, m_one_change_budget, memory_threshold, memoryed_groups); bool mediods_changed = true; while (mediods_changed && T.time_machine_end() < timeout_ms) { mediods_changed = false; double best_swap_cost = curr_cluster_cost; int best_swap_cluster = -1; int best_swap_elem = -1; for (size_t cluster_id = 0; cluster_id < m_k; ++cluster_id) { if (curr_cluster_centers[cluster_id] == -1) continue; for (int elem = 0; elem < m_elem_count; ++elem) { if (std::find(curr_cluster_centers.begin(), curr_cluster_centers.end(), elem) != curr_cluster_centers.end() || std::find(m_unplaceable_limits[cluster_id].begin(), m_unplaceable_limits[cluster_id].end(), elem) != m_unplaceable_limits[cluster_id].end()) continue; std::vector tmp_centers = curr_cluster_centers; tmp_centers[cluster_id] = elem; std::vector tmp_labels = assign_cluster_label(tmp_centers, m_placeable_limits, m_unplaceable_limits, m_max_cluster_size, m_cluster_group_size); double tmp_cost = evaluate_labels(tmp_labels); if (tmp_cost < best_swap_cost) { best_swap_cost = tmp_cost; best_swap_cluster = cluster_id; best_swap_elem = elem; mediods_changed = true; } } } if (mediods_changed) { curr_cluster_centers[best_swap_cluster] = best_swap_elem; curr_cluster_labels = assign_cluster_label(curr_cluster_centers, m_placeable_limits, m_unplaceable_limits, m_max_cluster_size, m_cluster_group_size); curr_cluster_cost = evaluate_labels(curr_cluster_labels); MemoryedGroup g(curr_cluster_labels, curr_cluster_cost, 1); update_memoryed_groups(g, m_one_change_budget, memory_threshold, memoryed_groups); } } if (curr_cluster_cost < best_cluster_cost) { best_cluster_centers = curr_cluster_centers; best_cluster_cost = curr_cluster_cost; best_cluster_labels = curr_cluster_labels; } retry_count += 1; } m_cluster_labels = best_cluster_labels; } FilamentGroupContext FilamentGroupContext::available_only(std::vector& full_nozzle_ids) const { full_nozzle_ids.clear(); FilamentGroupContext compact = *this; // 只保留已安装喷嘴,把 group_id 重编号成紧凑 [0,k);full_nozzle_ids 记录 紧凑id -> 原始id。 NozzleInfo compact_nozzle_info; for (const auto& nozzle : nozzle_info.nozzle_list) { const int full_id = nozzle.group_id; if (!nozzle.installed) continue; const int compact_id = (int)full_nozzle_ids.size(); full_nozzle_ids.emplace_back(full_id); MultiNozzleUtils::NozzleInfo compact_nozzle = nozzle; compact_nozzle.group_id = compact_id; compact_nozzle_info.nozzle_list.emplace_back(std::move(compact_nozzle)); compact_nozzle_info.per_nozzle_capacity.emplace_back(full_id >= 0 && full_id < (int)nozzle_info.per_nozzle_capacity.size() ? nozzle_info.per_nozzle_capacity[full_id] : 1); compact_nozzle_info.extruder_nozzle_list[nozzle.extruder_id].emplace_back(compact_id); if (auto it = nozzle_info.nozzle_status.find(full_id); it != nozzle_info.nozzle_status.end()) compact_nozzle_info.nozzle_status[compact_id] = it->second; } compact.nozzle_info = std::move(compact_nozzle_info); // master_extruder_id / prefer_non_model_filament 在 flush 算法里按喷嘴id 使用,需与 nozzle_info // 一并转到紧凑空间(master_extruder_id 兼作默认喷嘴槽位)。 auto& machine = compact.machine_info; machine.master_extruder_id = 0; for (int i = 0; i < (int)full_nozzle_ids.size(); ++i) if (full_nozzle_ids[i] == this->machine_info.master_extruder_id) { machine.master_extruder_id = i; break; } const auto& full_prefer = this->machine_info.prefer_non_model_filament; machine.prefer_non_model_filament.clear(); for (int full_id : full_nozzle_ids) machine.prefer_non_model_filament.push_back(full_id >= 0 && full_id < (int)full_prefer.size() && full_prefer[full_id]); return compact; } // 把耗材映射里的紧凑喷嘴id 还原回原始喷嘴id static void map_to_full_nozzle_ids(std::vector& filament_to_nozzle, const std::vector& full_nozzle_ids) { for (int& nozzle_id : filament_to_nozzle) if (nozzle_id >= 0 && nozzle_id < static_cast(full_nozzle_ids.size())) nozzle_id = full_nozzle_ids[nozzle_id]; } std::vector FilamentGroup::calc_min_flush_group(int* cost) { auto used_filaments = collect_sorted_used_filaments(ctx.model_info.layer_filaments); int n = (int)used_filaments.size(); // 分组只在可用喷嘴上进行:enum/kmedoids 把容量当软奖励,空槽位必须从候选里剔除(也缩小 k^n)。 // available_only 会把 nozzle_info 与按喷嘴id 使用的 machine 字段一并转到紧凑空间。 std::vector full_nozzle_ids; // 紧凑id -> 原始id FilamentGroupContext available_ctx = ctx.available_only(full_nozzle_ids); if (full_nozzle_ids.empty()) throw Slic3r::RuntimeError("No valid nozzle found. Please check nozzle count."); FilamentGroup available_group(available_ctx); available_group.get_custom_seq = get_custom_seq; int k = (int)available_ctx.nozzle_info.nozzle_list.size(); std::unordered_map> unplaceable_limits; extract_unprintable_limit_indices(available_ctx.model_info.unprintable_filaments, used_filaments, unplaceable_limits); unplaceable_limits = available_group.rebuild_nozzle_unprintables(used_filaments, unplaceable_limits, available_ctx.group_info.filament_volume_map); // 多口径模式下,显式指定了喷嘴口径的耗材若在所有可用喷嘴上均不可放置(如喷嘴架上无对应口径),直接报错,避免被软约束兜底分配到错误口径的喷嘴。 for (int fidx = 0; fidx < n; ++fidx) { const unsigned int filament_id = used_filaments[fidx]; if (filament_id >= available_ctx.model_info.selected_nozzle_diameters.size() || available_ctx.model_info.selected_nozzle_diameters[filament_id].empty()) continue; const auto it = unplaceable_limits.find(fidx); if (it != unplaceable_limits.end() && static_cast(it->second.size()) >= k) throw Slic3r::RuntimeError("Nozzle assignment error: no nozzle matches the diameter and flow selected for one of the filaments. Please check the nozzle setup."); } m_memoryed_heap = MemoryedGroupHeap(); std::vector result; long long estimated = estimate_dedup_enum_count(k, n, available_ctx); if (estimated < ENUM_THRESHOLD) result = available_group.calc_group_by_enum(k, used_filaments, unplaceable_limits, cost); else result = available_group.calc_group_by_kmedoids(k, used_filaments, unplaceable_limits, cost, 3000); map_to_full_nozzle_ids(result, full_nozzle_ids); change_memoryed_heaps_to_arrays(available_group.m_memoryed_heap, ctx.group_info.total_filament_num, used_filaments, m_memoryed_groups); for (auto& memoryed_group : m_memoryed_groups) map_to_full_nozzle_ids(memoryed_group, full_nozzle_ids); return result; } std::map FilamentGroup::rebuild_unprintables(const std::vector& used_filaments, const std::map& extruder_unprintables) { std::map ret; for (int f_idx = 0; f_idx < used_filaments.size(); f_idx++) { int unprintable_ext = -1; if (extruder_unprintables.find(f_idx) != extruder_unprintables.end()) { unprintable_ext = extruder_unprintables.at(f_idx); } bool multi_unprintable = false; auto unprintable_volumes = ctx.model_info.unprintable_volumes[used_filaments[f_idx]]; for (int nozzle_idx = 0; nozzle_idx != ctx.nozzle_info.nozzle_list.size(); nozzle_idx++) { auto nozzle_info = ctx.nozzle_info.nozzle_list[nozzle_idx]; if (unprintable_volumes.count(nozzle_info.volume_type)) { if (unprintable_ext == -1) unprintable_ext = nozzle_info.extruder_id; else if (unprintable_ext != nozzle_info.extruder_id) multi_unprintable = true; } } if (!multi_unprintable && unprintable_ext != -1) ret[f_idx] = unprintable_ext; } return ret; } std::unordered_map> FilamentGroup::try_merge_filaments() { std::unordered_map>merged_filaments; std::unordered_map> merge_filament_map; auto unprintable_stat_to_str = [unprintable_filaments = this->ctx.model_info.unprintable_filaments](int idx) { std::string str; for (size_t eid = 0; eid < unprintable_filaments.size(); ++eid) { if (unprintable_filaments[eid].count(idx)) { if (eid > 0) str += ','; str += std::to_string(idx); } } return str; }; for (size_t idx = 0; idx < ctx.model_info.filament_ids.size(); ++idx) { std::string id = ctx.model_info.filament_ids[idx]; Color color = ctx.model_info.filament_info[idx].color; std::string unprintable_str = unprintable_stat_to_str(idx); std::string key = id + "," + color.to_hex_str(true) + "," + unprintable_str; merge_filament_map[key].push_back(idx); } for (auto& elem : merge_filament_map) { if (elem.second.size() > 1) { merged_filaments[elem.second.front()] = elem.second; } } return merged_filaments; } std::vector FilamentGroup::seperate_merged_filaments(const std::vector& filament_map, const std::unordered_map>& merged_filaments) { std::vector ret_map = filament_map; for (auto& elem : merged_filaments) { int src = elem.first; for (auto f : elem.second) { ret_map[f] = ret_map[src]; } } return ret_map; } void FilamentGroup::rebuild_context(const std::unordered_map>& merged_filaments) { if (merged_filaments.empty()) return; FilamentGroupContext new_ctx = ctx; std::unordered_map filament_merge_map = get_merged_filament_map(merged_filaments); // modify layer filaments for (auto& layer_filament : new_ctx.model_info.layer_filaments) { for (auto& f : layer_filament) { if (auto iter = filament_merge_map.find((int)(f)); iter != filament_merge_map.end()) { f = iter->second; } } } for (auto& unprintables : new_ctx.model_info.unprintable_filaments) { std::set new_unprintables; for (auto f : unprintables) { if (auto iter = filament_merge_map.find((int)(f)); iter != filament_merge_map.end()) { new_unprintables.insert(iter->second); } else { new_unprintables.insert(f); } } } ctx = new_ctx; return; } std::vector FilamentGroup::calc_filament_group(int* cost) { /*auto extruder_variant_list = ctx.nozzle_info.extruder_nozzle_list; for (auto nozzle : ctx.nozzle_info.nozzle_list) if (nozzle.volume_type == NozzleVolumeType::nvtTPUHighFlow) return calc_filament_group_for_tpu(cost);*/ try { if (FGMode::MatchMode == ctx.group_info.mode) return calc_filament_group_for_match(cost); } catch (const FilamentGroupException&) { BOOST_LOG_TRIVIAL(warning) << current_exception_message(); } return calc_filament_group_for_flush(cost); } std::vector FilamentGroup::calc_filament_group_for_match(int* cost) { using namespace FlushPredict; constexpr int SupportPreferScore = 3; auto used_filaments = collect_sorted_used_filaments(ctx.model_info.layer_filaments); std::vector used_filament_list; for (auto f : used_filaments) used_filament_list.emplace_back(ctx.model_info.filament_info[f]); std::vector machine_filament_list; std::map> machine_filament_set; for (size_t eid = 0; eid < ctx.machine_info.machine_filament_info.size();++eid) { for (auto& filament : ctx.machine_info.machine_filament_info[eid]) { machine_filament_set[filament].insert(machine_filament_list.size()); machine_filament_list.emplace_back(filament); } } if (machine_filament_list.empty()) throw FilamentGroupException(FilamentGroupException::EmptyAmsFilaments,"Empty ams filament in For-Match mode."); std::map unprintable_limit_indices; // key stores filament idx in used_filament, value stores unprintable extruder extract_unprintable_limit_indices(ctx.model_info.unprintable_filaments, used_filaments, unprintable_limit_indices); unprintable_limit_indices = rebuild_unprintables(used_filaments, unprintable_limit_indices); // 行为工程耗材,列为设备耗材,成本越小越优先匹配。 std::vector> match_cost_matrix(used_filament_list.size(), std::vector(machine_filament_list.size())); for (size_t i = 0; i < used_filament_list.size(); ++i) { // 映射回工程耗材下标,读取表示耗材小类的 filament_id。 const auto model_filament_idx = used_filaments[i]; const std::string model_filament_id = model_filament_idx < ctx.model_info.filament_ids.size() ? ctx.model_info.filament_ids[model_filament_idx] : std::string(); for (size_t j = 0; j < machine_filament_list.size(); ++j) { const float color_dist = calc_color_distance( RGBColor(used_filament_list[i].color.r, used_filament_list[i].color.g, used_filament_list[i].color.b), RGBColor(machine_filament_list[j].color.r, machine_filament_list[j].color.g, machine_filament_list[j].color.b)); // 颜色优先;同色时优先匹配相同耗材小类。 match_cost_matrix[i][j] = calc_match_mode_cost(color_dist, model_filament_id, machine_filament_list[j].filament_id, static_cast(used_filament_list.size())); } } std::vectorl_nodes(used_filaments.size()); std::iota(l_nodes.begin(), l_nodes.end(), 0); std::vectorr_nodes(machine_filament_list.size()); std::iota(r_nodes.begin(), r_nodes.end(), 0); std::vectormachine_filament_capacity(machine_filament_list.size(),l_nodes.size()); std::vectorextruder_filament_count(2, 0); auto is_extruder_filament_compatible = [&unprintable_limit_indices](int filament_idx, int extruder_id) { auto iter = unprintable_limit_indices.find(filament_idx); if (iter != unprintable_limit_indices.end() && iter->second == extruder_id) return false; return true; }; auto build_unlink_limits = [](const std::vector& l_nodes, const std::vector& r_nodes, const std::function& can_link) { std::unordered_map> unlink_limits; for (size_t i = 0; i < l_nodes.size(); ++i) { std::vector unlink_filaments; for (size_t j = 0; j < r_nodes.size(); ++j) { if (!can_link(l_nodes[i], r_nodes[j])) unlink_filaments.emplace_back(j); } if (!unlink_filaments.empty()) unlink_limits.emplace(i, std::move(unlink_filaments)); } return unlink_limits; }; auto optimize_map_to_machine_filament = [&](const std::vector& map_to_machine_filament, const std::vector& l_nodes, const std::vector& r_nodes, std::vector& filament_map) { std::vector ungrouped_filaments; std::vector filaments_to_optimize; auto map_filament_to_machine_filament = [&](int filament_idx, int machine_filament_idx) { auto& machine_filament = machine_filament_list[machine_filament_idx]; filament_map[used_filaments[filament_idx]] = machine_filament.extruder_id; // set extruder id to filament map extruder_filament_count[machine_filament.extruder_id] += 1; // increase filament count in extruder }; auto unmap_filament_to_machine_filament = [&](int filament_idx, int machine_filament_idx) { auto& machine_filament = machine_filament_list[machine_filament_idx]; extruder_filament_count[machine_filament.extruder_id] -= 1; // increase filament count in extruder }; for (size_t idx = 0; idx < map_to_machine_filament.size(); ++idx) { if (map_to_machine_filament[idx] == MaxFlowGraph::INVALID_ID) { ungrouped_filaments.emplace_back(l_nodes[idx]); continue; } int used_filament_idx = l_nodes[idx]; int machine_filament_idx = r_nodes[map_to_machine_filament[idx]]; auto& machine_filament = machine_filament_list[machine_filament_idx]; if (machine_filament_set[machine_filament].size() > 1 && unprintable_limit_indices.count(used_filament_idx) == 0) filaments_to_optimize.emplace_back(idx); map_filament_to_machine_filament(used_filament_idx, machine_filament_idx); } // try to optimize the result for (auto idx : filaments_to_optimize) { int filament_idx = l_nodes[idx]; bool is_support_filament = used_filament_list[filament_idx].usage_type == FilamentUsageType::SupportOnly; int old_machine_filament_idx = r_nodes[map_to_machine_filament[idx]]; auto& old_machine_filament = machine_filament_list[old_machine_filament_idx]; unmap_filament_to_machine_filament(filament_idx, old_machine_filament_idx); auto optional_filaments = machine_filament_set[old_machine_filament]; // 第一阶段:找出所有满足容量约束的候选方案,并计算它们的偏好得分 std::vector> valid_candidates; // 存储可用的机器耗材idx与评分 for (auto machine_filament : optional_filaments) { int new_extruder_id = machine_filament_list[machine_filament].extruder_id; // 计算新分配的偏好得分 int preference_score = 0; bool new_extruder_prefer_support = ctx.machine_info.prefer_non_model_filament[new_extruder_id]; // 如果是支撑材料且分配给了偏好支撑的喷嘴,给予奖励 if (is_support_filament && new_extruder_prefer_support) { preference_score += SupportPreferScore; // 给予奖励 } valid_candidates.emplace_back(machine_filament, preference_score); } // 第二阶段:确定最佳偏好得分 int best_preference_score = 0; for (const auto& candidate : valid_candidates) { if (candidate.second >= best_preference_score) { best_preference_score = candidate.second; } } // 第三阶段:匹配成本优先,成本相同时选择负载更均衡的方案。 int best_candidate = -1; int best_gap = std::numeric_limits::max(); float best_match_cost = std::numeric_limits::max(); for (const auto& candidate : valid_candidates) { // 只考虑具有最佳偏好得分的候选方案 int machine_filament = candidate.first; int score = candidate.second; if (score == best_preference_score) { int new_extruder_id = machine_filament_list[machine_filament].extruder_id; int new_gap = std::abs(extruder_filament_count[new_extruder_id] + 1 - extruder_filament_count[1 - new_extruder_id]); float match_cost = match_cost_matrix[filament_idx][machine_filament]; // 优先选择匹配成本更低的候选,成本相同时选择负载更均衡的候选。 if (match_cost < best_match_cost || (match_cost == best_match_cost && new_gap < best_gap)) { best_match_cost = match_cost; best_gap = new_gap; best_candidate = machine_filament; } } } // 应用最佳选择 if (best_candidate != -1) { map_filament_to_machine_filament(filament_idx, best_candidate); } else { map_filament_to_machine_filament(filament_idx, old_machine_filament_idx); } } return ungrouped_filaments; }; std::vector group(ctx.group_info.total_filament_num, 0); std::vector ungrouped_filaments; auto unlink_limits_full = build_unlink_limits(l_nodes, r_nodes, [&used_filament_list, &machine_filament_list, is_extruder_filament_compatible](int used_filament_idx, int machine_filament_idx) { return used_filament_list[used_filament_idx].type == machine_filament_list[machine_filament_idx].type && used_filament_list[used_filament_idx].is_support == machine_filament_list[machine_filament_idx].is_support && is_extruder_filament_compatible(used_filament_idx, machine_filament_list[machine_filament_idx].extruder_id); }); { MatchModeGroupSolver s(match_cost_matrix, l_nodes, r_nodes, machine_filament_capacity, unlink_limits_full); ungrouped_filaments = optimize_map_to_machine_filament(s.solve(), l_nodes, r_nodes,group); if (ungrouped_filaments.empty()) return group; } // additionally remove type limits { l_nodes = ungrouped_filaments; auto unlink_limits = build_unlink_limits(l_nodes, r_nodes, [&machine_filament_list, is_extruder_filament_compatible](int used_filament_idx, int machine_filament_idx) { return is_extruder_filament_compatible(used_filament_idx, machine_filament_list[machine_filament_idx].extruder_id); }); MatchModeGroupSolver s(match_cost_matrix, l_nodes, r_nodes, machine_filament_capacity, unlink_limits); ungrouped_filaments = optimize_map_to_machine_filament(s.solve(), l_nodes, r_nodes, group); if (ungrouped_filaments.empty()) return group; } // remove all limits { l_nodes = ungrouped_filaments; MatchModeGroupSolver s(match_cost_matrix, l_nodes, r_nodes, machine_filament_capacity, {}); auto ret = optimize_map_to_machine_filament(s.solve(), l_nodes, r_nodes, group); for (size_t idx = 0; idx < ret.size(); ++idx) { if (ret[idx] == MaxFlowGraph::INVALID_ID) assert(false); else group[used_filaments[l_nodes[idx]]] = machine_filament_list[r_nodes[ret[idx]]].extruder_id; } } return group; } std::vector FilamentGroup::calc_filament_group_for_flush(int* cost) { auto used_filaments = collect_sorted_used_filaments(ctx.model_info.layer_filaments); std::vector ret = calc_min_flush_group(cost); std::vector> memoryed_maps = this->m_memoryed_groups; memoryed_maps.insert(memoryed_maps.begin(), ret); std::vector used_filament_info; for (auto f : used_filaments) { used_filament_info.emplace_back(ctx.model_info.filament_info[f]); } ret = select_best_group_for_ams(memoryed_maps, ctx.nozzle_info.nozzle_list, used_filaments, used_filament_info, ctx.machine_info.machine_filament_info, ctx.group_info.has_filament_switcher); return ret; } std::vector FilamentGroup::calc_filament_group_for_tpu(int *cost) { auto used_filaments = collect_sorted_used_filaments(ctx.model_info.layer_filaments); std::vector used_filament_list; for (auto f : used_filaments) used_filament_list.emplace_back(ctx.model_info.filament_info[f]); std::vector> print_time_matrix(used_filaments.size(), std::vector(ctx.nozzle_info.extruder_nozzle_list.size())); for (int i = 0; i < used_filaments.size(); ++i){ for (int j = 0; j < ctx.nozzle_info.extruder_nozzle_list.size(); ++j){ print_time_matrix[i][j] = ctx.speed_info.filament_print_time[used_filaments[i]][j]; if (ctx.nozzle_info.nozzle_list[j].volume_type == nvtTPUHighFlow) //同时存在TPU High Flow喷嘴和其他类型喷嘴时,优先将耗材分配至TPU High Flow喷嘴 print_time_matrix[i][j] *= 0.9; } } std::vector l_nodes(used_filaments.size()); std::iota(l_nodes.begin(), l_nodes.end(), 0); std::vector r_nodes(ctx.nozzle_info.extruder_nozzle_list.size()); std::iota(r_nodes.begin(), r_nodes.end(), 0); std::vector machine_filament_capacity({int(used_filaments.size()), int(used_filaments.size())}); std::map unprintable_limit_indices; // key stores filament idx in used_filament, value stores unprintable extruder extract_unprintable_limit_indices(ctx.model_info.unprintable_filaments, used_filaments, unprintable_limit_indices); unprintable_limit_indices = rebuild_unprintables(used_filaments, unprintable_limit_indices); std::unordered_map> unlink_limits(used_filaments.size()); for (int i = 0; i < used_filaments.size(); i++) { auto iter = unprintable_limit_indices.find(i); if (iter == unprintable_limit_indices.end() || iter->second < 0 || iter->second >= 2) continue; unlink_limits[i].emplace_back(iter->second); } MatchModeGroupSolver s(print_time_matrix, l_nodes, r_nodes, machine_filament_capacity, unlink_limits); auto ret = s.solve(); for (size_t idx = 0; idx < ret.size(); ++idx) { if (ret[idx] == MaxFlowGraph::INVALID_ID) { assert(false); ret[idx] = 1; } } std::vector group(ctx.group_info.total_filament_num, ctx.machine_info.master_extruder_id); for (int i = 0; i < ret.size(); ++i) group[used_filaments[i]] = ret[i]; return group; } // sorted used_filaments std::unordered_map> FilamentGroup::rebuild_nozzle_unprintables(const std::vector& used_filaments, const std::unordered_map>& extruder_unprintables, const std::vector& filament_volume_map) { std::unordered_map> nozzle_unprintables; for(size_t fidx = 0 ;fidx unexpected_extruders; if(extruder_unprintables.find(fidx) != extruder_unprintables.end()){ unexpected_extruders = extruder_unprintables.at(fidx); } auto unprintable_volumes = ctx.model_info.unprintable_volumes[used_filaments[fidx]]; std::vector unprintable_nozzles; for(size_t nozzle_idx =0 ;nozzle_idx < ctx.nozzle_info.nozzle_list.size(); ++nozzle_idx){ auto nozzle_info = ctx.nozzle_info.nozzle_list[nozzle_idx]; const unsigned int filament_id = used_filaments[fidx]; const bool diameter_mismatch = filament_id < ctx.model_info.selected_nozzle_diameters.size() && !ctx.model_info.selected_nozzle_diameters[filament_id].empty() && ctx.model_info.selected_nozzle_diameters[filament_id] != nozzle_info.diameter; if(std::find(unexpected_extruders.begin(), unexpected_extruders.end(), nozzle_info.extruder_id)!= unexpected_extruders.end() || (expected_volume!=nvtHybrid && expected_volume != nozzle_info.volume_type) || !filament_diameter_matches_nozzle_volume(ctx.model_info.filament_info[filament_id], nozzle_info.volume_type) || (unprintable_volumes.count(nozzle_info.volume_type) != 0) || diameter_mismatch) unprintable_nozzles.push_back(nozzle_idx); } if(unprintable_nozzles.empty()) continue; sort_remove_duplicates(unprintable_nozzles); nozzle_unprintables[fidx] = unprintable_nozzles; } return nozzle_unprintables; } std::vector calc_filament_group_for_match_multi_nozzle(const FilamentGroupContext& ctx) { FilamentGroup fg1(ctx); auto filament_extruder_map = fg1.calc_filament_group_for_match(); FilamentGroupContext new_ctx = ctx; auto used_filaments = collect_sorted_used_filaments(ctx.model_info.layer_filaments); for(size_t idx = 0; idx < used_filaments.size(); ++idx) new_ctx.model_info.unprintable_filaments[1 - filament_extruder_map[used_filaments[idx]]].insert(used_filaments[idx]); // Finite "no extra limit" value, see calc_filament_group_for_manual_multi_nozzle: INT_MAX // overflows have_enough_size() and disables the per-nozzle capacity that spreads fixed nozzles. int group_cap = std::max(1, new_ctx.group_info.total_filament_num); new_ctx.machine_info.max_group_size.assign(new_ctx.machine_info.max_group_size.size(), group_cap); FilamentGroup fg(new_ctx); return fg.calc_filament_group_for_flush(); } std::vector calc_filament_group_for_nozzle_match(FilamentGroupContext &ctx) { using namespace FlushPredict; auto used_filaments = collect_sorted_used_filaments(ctx.model_info.layer_filaments); struct LoadedNozzle { const NozzleLoadedFilamentInfo* filament; MultiNozzleUtils::NozzleInfo nozzle; }; // 1、收集当前设备侧已经确认“喷嘴内有料”的入口。 // 同一个真实喷嘴可能绑定多个可进退料槽,这里先按 nozzle_id 聚合,后面仍然作为多个候选材料参与匹配。 std::unordered_map> loaded_filament_map; for (const auto &loaded : ctx.machine_info.nozzle_loaded_filaments) { if (loaded.valid) loaded_filament_map[loaded.nozzle_id].emplace_back(&loaded); } std::vector loaded_nozzles; for (const auto &nozzle : ctx.nozzle_info.nozzle_list) { auto loaded = loaded_filament_map.find(nozzle.group_id); if (!nozzle.installed || loaded == loaded_filament_map.end()) continue; for (const auto* filament : loaded->second) loaded_nozzles.push_back({ filament, nozzle }); } // 没有工程耗材或没有设备已装料信息时,match 模式没有可参考目标,退回省冲刷分组。 if (used_filaments.empty() || loaded_nozzles.empty()) { FilamentGroup fg(ctx); return fg.calc_filament_group_for_flush(); } // 2、构建匹配图节点:左侧是工程实际使用的耗材,右侧是设备侧已装料入口。 // 右侧仍然只来自真实 nozzle_list;虚拟喷嘴不会在这里提前加入。 std::vector l_nodes(used_filaments.size()); std::iota(l_nodes.begin(), l_nodes.end(), 0); std::vector r_nodes(loaded_nozzles.size()); std::iota(r_nodes.begin(), r_nodes.end(), 0); // Multi-diameter hard constraint, shared by the loaded-nozzle matching and the unmatched // fallback: a filament may only sit on a nozzle whose diameter its preset works at. Type and // color alone carry no diameter information, so without this a 0.4-only filament can be // matched onto a loaded 0.2 nozzle just because both hold the same material. auto diameter_matches = [&ctx](int filament_id, const MultiNozzleUtils::NozzleInfo &nozzle) { if (filament_id < 0 || filament_id >= static_cast(ctx.model_info.selected_nozzle_diameters.size())) return true; const std::string &selected = ctx.model_info.selected_nozzle_diameters[filament_id]; return selected.empty() || selected == nozzle.diameter; }; // 3、定义硬约束:材料类型、支撑属性、不可打印限制、喷嘴口径和喷嘴流量类型都兼容时,才允许连边。 auto can_match = [&ctx, &used_filaments, &loaded_nozzles, &diameter_matches](int used_filament_idx, int loaded_idx) { int filament_id = used_filaments[used_filament_idx]; const auto &model = ctx.model_info.filament_info[filament_id]; const auto &loaded = *loaded_nozzles[loaded_idx].filament; const auto &nozzle = loaded_nozzles[loaded_idx].nozzle; if (model.type != loaded.type || model.is_support != loaded.is_support) return false; if (!diameter_matches(filament_id, nozzle)) return false; if (!filament_diameter_matches_nozzle_volume(model, nozzle.volume_type)) return false; if (nozzle.extruder_id >= 0 && nozzle.extruder_id < static_cast(ctx.model_info.unprintable_filaments.size()) && ctx.model_info.unprintable_filaments[nozzle.extruder_id].count(filament_id) != 0) return false; if (filament_id >= 0 && filament_id < static_cast(ctx.group_info.filament_volume_map.size())) { NozzleVolumeType expected_volume = static_cast(ctx.group_info.filament_volume_map[filament_id]); if (expected_volume != nvtHybrid && expected_volume != nozzle.volume_type) return false; } auto volume_iter = ctx.model_info.unprintable_volumes.find(filament_id); if (volume_iter != ctx.model_info.unprintable_volumes.end() && volume_iter->second.count(nozzle.volume_type) != 0) return false; return true; }; // 4、构造费用矩阵和禁连表:不兼容的边加入 unlink_limits,兼容边按颜色和耗材小类计算匹配成本。 // 若同一固定喷嘴存在多个候选耗材(如喷嘴内耗材 + 预装槽位/外挂耗材),后续候选增加微小代价偏置,优先保留喷嘴内当前耗材。 std::vector nozzle_secondary_tray_penalty(loaded_nozzles.size(), 0.0f); { std::unordered_set seen_fixed_nozzle_groups; for (size_t j = 0; j < loaded_nozzles.size(); ++j) { const int group_id = loaded_nozzles[j].nozzle.group_id; const int cap = (group_id >= 0 && group_id < static_cast(ctx.nozzle_info.per_nozzle_capacity.size())) ? ctx.nozzle_info.per_nozzle_capacity[group_id] : 1; if (cap <= 1 && !seen_fixed_nozzle_groups.insert(group_id).second) nozzle_secondary_tray_penalty[j] = 1.0f; } } std::vector> cost_matrix(used_filaments.size(), std::vector(loaded_nozzles.size(), 0.0f)); std::unordered_map> unlink_limits; for (size_t i = 0; i < used_filaments.size(); ++i) { const int filament_id = used_filaments[i]; const auto &model = ctx.model_info.filament_info[filament_id]; // 读取工程耗材小类,缺失时仅按颜色匹配。 const std::string model_filament_id = filament_id < ctx.model_info.filament_ids.size() ? ctx.model_info.filament_ids[filament_id] : std::string(); for (size_t j = 0; j < loaded_nozzles.size(); ++j) { if (!can_match(static_cast(i), static_cast(j))) { unlink_limits[static_cast(i)].emplace_back(static_cast(j)); continue; } const auto &loaded = *loaded_nozzles[j].filament; float cost = calc_color_distance(RGBColor(model.color.r, model.color.g, model.color.b), RGBColor(loaded.color.r, loaded.color.g, loaded.color.b)); cost_matrix[i][j] = calc_match_mode_cost(cost, model_filament_id, loaded.filament_id, static_cast(used_filaments.size())) + nozzle_secondary_tray_penalty[j]; } } // 5、把匹配结果转换成“工程耗材 -> nozzle group_id”。 // 真实喷嘴先消耗自身容量;如果同一个真实喷嘴匹配到多个工程耗材,超出容量的部分再按未匹配耗材策略分配。 auto build_match_result = [&ctx, &used_filaments, &loaded_nozzles, &diameter_matches, &cost_matrix, &nozzle_secondary_tray_penalty](const std::vector &match) { std::vector group(ctx.group_info.total_filament_num, ctx.machine_info.master_extruder_id); std::unordered_map remaining_capacity; // 5.1 初始化每个真实喷嘴的剩余容量。 // 这里不预留虚拟喷嘴容量,虚拟喷嘴只由真实匹配溢出触发。 for (const auto& nozzle : ctx.nozzle_info.nozzle_list) { int cap = 1; if (nozzle.group_id >= 0 && nozzle.group_id < static_cast(ctx.nozzle_info.per_nozzle_capacity.size())) cap = ctx.nozzle_info.per_nozzle_capacity[nozzle.group_id]; remaining_capacity[nozzle.group_id] = cap; } // 5.2 追加虚拟喷嘴:直接继承被溢出的真实喷嘴属性,只改成新的 group_id。 // 这样虚拟喷嘴和真实喷嘴保持相同的直径、流量类型和 extruder_id。 auto append_virtual_nozzle = [&ctx](const MultiNozzleUtils::NozzleInfo& source_nozzle) { const int group_id = static_cast(ctx.nozzle_info.nozzle_list.size()); MultiNozzleUtils::NozzleInfo virtual_nozzle = source_nozzle; virtual_nozzle.group_id = group_id; virtual_nozzle.installed = true; ctx.nozzle_info.nozzle_list.emplace_back(std::move(virtual_nozzle)); ctx.nozzle_info.per_nozzle_capacity.emplace_back(1); return group_id; }; // 5.3 兜底分配只处理“没有匹配到已装料入口”的工程耗材。 // 这类耗材没有颜色最优目标,但仍然要满足不可打印、喷嘴口径和流量类型约束。 auto can_place_unloaded = [&ctx, &diameter_matches](int filament_id, const MultiNozzleUtils::NozzleInfo& nozzle) { if (!nozzle.installed) return false; if (!diameter_matches(filament_id, nozzle)) return false; if (!filament_diameter_matches_nozzle_volume(ctx.model_info.filament_info[filament_id], nozzle.volume_type)) return false; if (nozzle.extruder_id >= 0 && nozzle.extruder_id < static_cast(ctx.model_info.unprintable_filaments.size()) && ctx.model_info.unprintable_filaments[nozzle.extruder_id].count(filament_id) != 0) return false; if (filament_id >= 0 && filament_id < static_cast(ctx.group_info.filament_volume_map.size())) { NozzleVolumeType expected_volume = static_cast(ctx.group_info.filament_volume_map[filament_id]); if (expected_volume != nvtHybrid && expected_volume != nozzle.volume_type) return false; } auto volume_iter = ctx.model_info.unprintable_volumes.find(filament_id); if (volume_iter != ctx.model_info.unprintable_volumes.end() && volume_iter->second.count(nozzle.volume_type) != 0) return false; return true; }; auto is_fixed_nozzle = [&ctx](const MultiNozzleUtils::NozzleInfo& nozzle) { if (nozzle.group_id >= 0 && nozzle.group_id < static_cast(ctx.nozzle_info.per_nozzle_capacity.size())) return ctx.nozzle_info.per_nozzle_capacity[nozzle.group_id] <= 1; return true; }; // 5.4 未匹配耗材没有可参考的已装料入口,按普通容量兜底: // 优先分配有剩余容量的固定喷嘴(2-9号),固定喷嘴无空余时再分配 AMS 喷嘴(1号头); // 如果兼容喷嘴容量均已满,则追加同类型虚拟喷嘴;没有兼容喷嘴则报错。 auto assign_unmatched = [&](int filament_id) { std::optional virtual_nozzle_source; for (bool prefer_fixed : { true, false }) { for (const auto& nozzle : ctx.nozzle_info.nozzle_list) { if (is_fixed_nozzle(nozzle) != prefer_fixed) continue; if (!can_place_unloaded(filament_id, nozzle)) continue; if (!virtual_nozzle_source) virtual_nozzle_source = nozzle; int& cap = remaining_capacity[nozzle.group_id]; if (cap <= 0) continue; --cap; return nozzle.group_id; } } // 有兼容喷嘴但真实容量已满时,追加同类型虚拟喷嘴,保持“一喷嘴一料”的分组语义。 if (virtual_nozzle_source) return append_virtual_nozzle(*virtual_nozzle_source); throw Slic3r::RuntimeError("Nozzle assignment error: no compatible nozzle is available for the unmatched filament. Please check the nozzle setup or regroup."); }; // 5.5 应用匹配结果:同一固定喷嘴优先保留喷嘴上当前已进料的耗材, // 多出的预装槽位耗材或未匹配耗材统一按固定喷嘴优先策略分配。 std::vector matched_indices; std::vector unmatched_indices; for (size_t idx = 0; idx < match.size(); ++idx) { if (match[idx] == MaxFlowGraph::INVALID_ID) unmatched_indices.push_back(idx); else matched_indices.push_back(idx); } std::stable_sort(matched_indices.begin(), matched_indices.end(), [&](size_t a, size_t b) { const float pen_a = nozzle_secondary_tray_penalty[match[a]]; const float pen_b = nozzle_secondary_tray_penalty[match[b]]; if (pen_a != pen_b) return pen_a < pen_b; const float cost_a = cost_matrix[a][match[a]]; const float cost_b = cost_matrix[b][match[b]]; if (cost_a != cost_b) return cost_a < cost_b; return match[a] < match[b]; }); for (size_t idx : matched_indices) { const int filament_id = used_filaments[idx]; const auto& matched_nozzle = loaded_nozzles[match[idx]].nozzle; int& cap = remaining_capacity[matched_nozzle.group_id]; if (cap > 0) { --cap; group[filament_id] = matched_nozzle.group_id; } else { unmatched_indices.push_back(idx); } } for (size_t idx : unmatched_indices) { const int filament_id = used_filaments[idx]; group[filament_id] = assign_unmatched(static_cast(filament_id)); } return group; }; // 6、执行匹配:每个已装料槽位节点自身容量为 1(一对一匹配),同一固定喷嘴的容量约束在应用匹配结果时完成二选一收敛。 std::vector v_capacity(loaded_nozzles.size(), 1); MatchModeGroupSolver solver(cost_matrix, l_nodes, r_nodes, v_capacity, unlink_limits); return build_match_result(solver.solve()); } std::vector plan_filament_nozzle_mapping_and_order(const FilamentGroupContext &ctx) { std::vector res; // 右节点:喷嘴 std::vector r_nodes(ctx.nozzle_info.nozzle_list.size(), -1); auto initial_nozzle = ctx.nozzle_info.nozzle_status; for (int r_id = 0; r_id < r_nodes.size(); r_id++) { if (initial_nozzle.count(r_id)) r_nodes[r_id] = initial_nozzle[r_id]; } std::vector r_nodes_group(ctx.nozzle_info.nozzle_list.size(), -1); for (auto &nozzle_info : ctx.nozzle_info.nozzle_list) { r_nodes_group[nozzle_info.group_id] = nozzle_info.extruder_id; } int layer_nums = ctx.model_info.layer_filaments.size(); auto &flush_matrix = ctx.model_info.flush_matrix; int prev_layer_last_nozzle_id = -1; bool used_prev_layer_last_nozzle = false; // 每一层,材料到喷嘴的匹配 filament->nozzle std::vector layer_fil_nozzle_match(ctx.model_info.filament_info.size(), 0); for (int i = 0; i < layer_nums; i++) { // 左节点:材料 - 使用 set 直接去重,避免 sort + unique const auto &layer_filaments = ctx.model_info.layer_filaments[i]; std::vector l_nodes(layer_filaments.begin(), layer_filaments.end()); std::sort(l_nodes.begin(), l_nodes.end()); l_nodes.erase(std::unique(l_nodes.begin(), l_nodes.end()), l_nodes.end()); if (l_nodes.empty()) { res.emplace_back(FilamentPlanRes{{}, {}}); continue; } // 每一层,喷嘴内使用的材料队列 std::vector> nozzle_fil_deq(r_nodes.size()); // 构建喷嘴状态到索引的反向映射,加速查找 O(n) -> O(1) std::unordered_map filament_to_nozzle; filament_to_nozzle.reserve(r_nodes.size()); for (size_t noz_id = 0; noz_id < r_nodes.size(); ++noz_id) { if (r_nodes[noz_id] >= 0) { filament_to_nozzle[r_nodes[noz_id]] = noz_id; } } const int epochs = std::ceil(double(l_nodes.size()) / r_nodes.size()); for (int j = 0; j < epochs; j++) { // 1、过滤掉材料与喷嘴内状态一致的节点 std::vector remaining_l_nodes; std::vector remaining_r_nodes; std::vector remaining_r_nodes_to_origin; std::vector used_r_nodes(r_nodes.size(), false); remaining_l_nodes.reserve(l_nodes.size()); remaining_r_nodes.reserve(r_nodes.size()); remaining_r_nodes_to_origin.reserve(r_nodes.size()); for (int f_id : l_nodes) { auto it = filament_to_nozzle.find(f_id); if (it != filament_to_nozzle.end()) { size_t noz_id = it->second; layer_fil_nozzle_match[f_id] = noz_id; nozzle_fil_deq[noz_id].push_back(f_id); used_prev_layer_last_nozzle = (noz_id == prev_layer_last_nozzle_id); used_r_nodes[noz_id] = true; } else { remaining_l_nodes.emplace_back(f_id); } } l_nodes = std::move(remaining_l_nodes); for (int r_id = 0; r_id < r_nodes.size(); r_id++) { if (!used_r_nodes[r_id]) { remaining_r_nodes.emplace_back(r_nodes[r_id]); remaining_r_nodes_to_origin.emplace_back(r_id); } } // 2、剩下的节点跑费用流 GroupMinCostFlowSolver s(flush_matrix, l_nodes, remaining_r_nodes, r_nodes_group); auto match = s.solve(); int write = 0; for (int l_id = 0; l_id < l_nodes.size(); l_id++) { if (match[l_id] >= 0 && match[l_id] < remaining_r_nodes.size()) { int noz_id = remaining_r_nodes_to_origin[match[l_id]]; int filament_id = l_nodes[l_id]; layer_fil_nozzle_match[filament_id] = noz_id; r_nodes[noz_id] = filament_id; nozzle_fil_deq[noz_id].push_back(filament_id); // 更新反向映射 filament_to_nozzle[filament_id] = noz_id; } else { l_nodes[write++] = l_nodes[l_id]; } } l_nodes.resize(write); } // 排序 int start_extruder = 0; int start_nozzle = 0; if (used_prev_layer_last_nozzle) { start_extruder = ctx.nozzle_info.nozzle_list[prev_layer_last_nozzle_id].extruder_id; start_nozzle = prev_layer_last_nozzle_id; } std::deque used_nozzle_deq; for (int m = 0; m < ctx.nozzle_info.extruder_nozzle_list.size(); m++) { int cur_extruder = (m + start_extruder) % ctx.nozzle_info.extruder_nozzle_list.size(); for (auto noz_id : ctx.nozzle_info.extruder_nozzle_list.at(cur_extruder)) { if (nozzle_fil_deq[noz_id].empty()) continue; if (noz_id == start_nozzle) used_nozzle_deq.push_front(noz_id); else used_nozzle_deq.push_back(noz_id); } } std::vector layer_fil_order; for (auto noz_id : used_nozzle_deq) { auto deq = nozzle_fil_deq[noz_id]; layer_fil_order.reserve(layer_fil_order.size() + deq.size()); layer_fil_order.insert(layer_fil_order.end(), deq.begin(), deq.end()); prev_layer_last_nozzle_id = noz_id; } FilamentPlanRes layer_pan{layer_fil_order, layer_fil_nozzle_match}; res.emplace_back(layer_pan); } return res; } std::vector calc_filament_group_for_manual_multi_nozzle(const std::vector& filament_map_manual, const FilamentGroupContext& ctx) { FilamentGroupContext new_ctx = ctx; auto used_filaments = collect_sorted_used_filaments(ctx.model_info.layer_filaments); for(size_t idx = 0; idx < used_filaments.size(); ++idx) new_ctx.model_info.unprintable_filaments[1 - filament_map_manual[used_filaments[idx]]].insert(used_filaments[idx]); int group_cap = std::max(1, new_ctx.group_info.total_filament_num); new_ctx.machine_info.max_group_size.assign(new_ctx.machine_info.max_group_size.size(), group_cap); FilamentGroup fg(new_ctx); return fg.calc_filament_group_for_flush(); } }