diff --git a/.github/workflows/build_orca.yml b/.github/workflows/build_orca.yml index 8c1b8134b7..9a4afb63a5 100644 --- a/.github/workflows/build_orca.yml +++ b/.github/workflows/build_orca.yml @@ -650,6 +650,9 @@ jobs: chmod +x "$appimage" "$appimage" --appimage-extract ./scripts/build_preset_cache.sh -b build build/package/resources/profiles squashfs-root/resources/profiles + # The runtime extracts every directory as 0700, and appimagetool (continuous + # build 333 onwards) refuses to pack a tree other users cannot read. + chmod -R a+rX squashfs-root appimagetool=$(find build -name "appimagetool.AppImage" | head -1) ARCH=$(uname -m) "$appimagetool" --appimage-extract-and-run squashfs-root "$appimage" rm -rf squashfs-root diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000000..b4e6ba27a7 --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,58 @@ +name: Stale issues and PRs + +on: + schedule: + - cron: "30 1 * * *" + workflow_dispatch: + +permissions: + actions: write # save the run state in the actions cache + issues: write + pull-requests: write + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v11 + with: + # Each new stale label costs about 2 operations. Runs that stop early + # continue from the same place the next day. + operations-per-run: 300 + ascending: true + stale-issue-label: stale + stale-pr-label: stale + remove-stale-when-updated: true + + # Issues + days-before-issue-stale: 90 + days-before-issue-close: 14 + close-issue-reason: not_planned + exempt-issue-labels: enhancement + exempt-all-issue-assignees: true + exempt-all-issue-milestones: true + stale-issue-message: | + This issue has had no activity for 90 days, so it will be closed in 14 days. + + If it still happens on the latest OrcaSlicer release, please leave a comment with the version you tested and it will stay open. + close-issue-message: | + This issue was closed because there was no activity after the reminder. + + If it still happens on the latest release, leave a comment here and a team member can reopen it, or open a new issue with the details. + + # PRs: only PRs where we asked the author for something + only-pr-labels: "wait for response" + days-before-pr-stale: 90 + days-before-pr-close: 14 + exempt-draft-pr: true + exempt-all-pr-assignees: true + exempt-all-pr-milestones: true + delete-branch: false + stale-pr-message: | + We asked for changes or more information on this PR, and there has been no activity for 90 days. It will be closed in 14 days. + + To keep it open, leave a comment. If you push new commits, please also leave a short comment, because a push alone does not reset this. If you no longer have time for it, that is fine, just let us know. + close-pr-message: | + This PR was closed because we did not hear back after the reminder. Thank you for the work you put into it. + + If you want to continue, push your changes and reopen it, or open a new PR. diff --git a/resources/profiles/Creality.json b/resources/profiles/Creality.json index e2fbd27dc1..e7ddd66e6b 100644 --- a/resources/profiles/Creality.json +++ b/resources/profiles/Creality.json @@ -1,6 +1,6 @@ { "name": "Creality", - "version": "02.03.02.87", + "version": "02.03.02.88", "force_update": "0", "description": "Creality configurations", "machine_model_list": [ diff --git a/resources/profiles/Creality/machine/Creality K1 Max (0.4 nozzle).json b/resources/profiles/Creality/machine/Creality K1 Max (0.4 nozzle).json index 037c48e64a..813ae4610c 100644 --- a/resources/profiles/Creality/machine/Creality K1 Max (0.4 nozzle).json +++ b/resources/profiles/Creality/machine/Creality K1 Max (0.4 nozzle).json @@ -150,7 +150,8 @@ "fan_speedup_overhangs": "1", "fan_speedup_time": "0", "high_current_on_filament_swap": "0", - "host_type": "octoprint", + "host_type": "crealityprint", + "printer_agent": "crealityprint", "layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]", "machine_LED_light_exist": "1", "machine_load_filament_time": "119", diff --git a/resources/profiles/Creality/machine/Creality K1 Max (0.6 nozzle).json b/resources/profiles/Creality/machine/Creality K1 Max (0.6 nozzle).json index 097777db73..9090da6325 100644 --- a/resources/profiles/Creality/machine/Creality K1 Max (0.6 nozzle).json +++ b/resources/profiles/Creality/machine/Creality K1 Max (0.6 nozzle).json @@ -152,7 +152,8 @@ "fan_speedup_overhangs": "1", "fan_speedup_time": "0", "high_current_on_filament_swap": "0", - "host_type": "octoprint", + "host_type": "crealityprint", + "printer_agent": "crealityprint", "layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]", "machine_LED_light_exist": "1", "machine_load_filament_time": "119", diff --git a/resources/profiles/Creality/machine/Creality K1 Max (0.8 nozzle).json b/resources/profiles/Creality/machine/Creality K1 Max (0.8 nozzle).json index e2ae32cae4..f55b6d9bdc 100644 --- a/resources/profiles/Creality/machine/Creality K1 Max (0.8 nozzle).json +++ b/resources/profiles/Creality/machine/Creality K1 Max (0.8 nozzle).json @@ -152,7 +152,8 @@ "fan_speedup_overhangs": "1", "fan_speedup_time": "0", "high_current_on_filament_swap": "0", - "host_type": "octoprint", + "host_type": "crealityprint", + "printer_agent": "crealityprint", "layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]", "machine_LED_light_exist": "1", "machine_load_filament_time": "119", diff --git a/resources/profiles/Creality/machine/Creality K1 Max_CFS-C 0.4 nozzle.json b/resources/profiles/Creality/machine/Creality K1 Max_CFS-C 0.4 nozzle.json index f30d670e49..2a5d929ac9 100644 --- a/resources/profiles/Creality/machine/Creality K1 Max_CFS-C 0.4 nozzle.json +++ b/resources/profiles/Creality/machine/Creality K1 Max_CFS-C 0.4 nozzle.json @@ -31,7 +31,8 @@ "fan_speedup_time": "0", "gcode_flavor": "klipper", "high_current_on_filament_swap": "0", - "host_type": "octoprint", + "host_type": "crealityprint", + "printer_agent": "crealityprint", "layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]", "machine_LED_light_exist": "1", "machine_end_gcode": "END_PRINT", diff --git a/resources/profiles/Creality/machine/Creality K1 SE_CFS-C 0.4 nozzle.json b/resources/profiles/Creality/machine/Creality K1 SE_CFS-C 0.4 nozzle.json index 1cce21a968..3b24a21259 100644 --- a/resources/profiles/Creality/machine/Creality K1 SE_CFS-C 0.4 nozzle.json +++ b/resources/profiles/Creality/machine/Creality K1 SE_CFS-C 0.4 nozzle.json @@ -31,7 +31,8 @@ "fan_speedup_time": "0", "gcode_flavor": "klipper", "high_current_on_filament_swap": "0", - "host_type": "octoprint", + "host_type": "crealityprint", + "printer_agent": "crealityprint", "layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]", "machine_LED_light_exist": "1", "machine_end_gcode": "END_PRINT", diff --git a/resources/profiles/Creality/machine/Creality K1C_CFS-C 0.4 nozzle.json b/resources/profiles/Creality/machine/Creality K1C_CFS-C 0.4 nozzle.json index 6d51a3cea8..7cb41ca271 100644 --- a/resources/profiles/Creality/machine/Creality K1C_CFS-C 0.4 nozzle.json +++ b/resources/profiles/Creality/machine/Creality K1C_CFS-C 0.4 nozzle.json @@ -31,7 +31,8 @@ "fan_speedup_time": "0", "gcode_flavor": "klipper", "high_current_on_filament_swap": "0", - "host_type": "octoprint", + "host_type": "crealityprint", + "printer_agent": "crealityprint", "layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]", "machine_LED_light_exist": "1", "machine_end_gcode": "END_PRINT", diff --git a/resources/profiles/Creality/machine/Creality K2 SE 0.4 nozzle.json b/resources/profiles/Creality/machine/Creality K2 SE 0.4 nozzle.json index 2005444a7b..d476760729 100644 --- a/resources/profiles/Creality/machine/Creality K2 SE 0.4 nozzle.json +++ b/resources/profiles/Creality/machine/Creality K2 SE 0.4 nozzle.json @@ -31,7 +31,8 @@ "fan_speedup_time": "0", "gcode_flavor": "klipper", "high_current_on_filament_swap": "0", - "host_type": "octoprint", + "host_type": "crealityprint", + "printer_agent": "crealityprint", "layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]", "machine_LED_light_exist": "1", "machine_end_gcode": "END_PRINT", diff --git a/src/libslic3r/Format/bbs_3mf.cpp b/src/libslic3r/Format/bbs_3mf.cpp index 1c809910e0..f693ac2d5a 100644 --- a/src/libslic3r/Format/bbs_3mf.cpp +++ b/src/libslic3r/Format/bbs_3mf.cpp @@ -8808,7 +8808,7 @@ bool _BBS_3MF_Exporter::_add_model_config_file_to_archive(mz_zip_archive& archiv if (plate_data->limit_filament_maps.size() > 0) { stream << " <" << METADATA_TAG << " " << KEY_ATTR << "=\"" << LIMIT_FILAMENT_MAP_ATTR << "\" " << VALUE_ATTR << "=\""; - add_vector(stream, plate_data->limit_filament_maps); + add_vector(stream, plate_data->limit_filament_maps); stream << "\"/>\n"; } diff --git a/src/libslic3r/Format/bbs_3mf.hpp b/src/libslic3r/Format/bbs_3mf.hpp index b9eea3251c..ca1819324a 100644 --- a/src/libslic3r/Format/bbs_3mf.hpp +++ b/src/libslic3r/Format/bbs_3mf.hpp @@ -8,6 +8,7 @@ #include "libslic3r/ProjectTask.hpp" #include "libslic3r/GCode/GCodeProcessor.hpp" #include +#include #include #include #include @@ -140,12 +141,8 @@ struct PlateData std::vector nozzles_info; std::optional nozzle_group_result; - // Hexadecimal number, - // the 0th digit corresponds to extruder 1 - // the 1th digit corresponds to extruder 2 - // ... and so on. - // 0 means can be print on this extruder, 1 means cannot - std::vector limit_filament_maps; + // Per filament, bit i is set when extruder i + 1 can't print it. + std::vector limit_filament_maps; std::vector warnings; diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index a12237d7c3..78a322e3f6 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -94,6 +94,7 @@ #include #include #include +#include #include #include #include @@ -1259,6 +1260,17 @@ static std::vector get_path_of_change_filament(const Print& print) end_filament_gcode_str = toolchange_retract_str + object_end_label_temp + end_filament_gcode_str; + // Lift to the layer Z so the toolchange can't hit taller printed parts. Only a custom macro or + // a switch to another physical extruder (whose firmware Tn may dock) can travel. The + // compacted_below_object descent below brings Z back down once over the tower. + const bool tool_may_travel = !change_filament_gcode.empty() + || (gcodegen.writer().filament() != nullptr && gcodegen.writer().filament()->extruder_id() != unsigned(new_extruder_id)); + std::string restore_layer_z_str; + if (compacted_below_object && tool_may_travel && gcodegen.writer().get_position().z() < current_z - EPSILON) { + restore_layer_z_str += gcodegen.writer().travel_to_z(current_z, "Restore layer Z before toolchange"); + check_add_eol(restore_layer_z_str); + } + std::string wipe_next_start_point_str; bool need_travel_after_change_filament_gcode = false; // travel need be after the filament changed to get the correct "m_curr_extruder_id" if (! change_filament_gcode.empty()) { @@ -1613,6 +1625,7 @@ static std::vector get_path_of_change_filament(const Print& print) // Insert the end filament, toolchange, and start filament gcode into the generated gcode. DynamicConfig config; config.set_key_value("filament_end_gcode", new ConfigOptionString(end_filament_gcode_str)); + config.set_key_value("restore_layer_z_before_toolchange", new ConfigOptionString(restore_layer_z_str)); config.set_key_value("change_filament_gcode", new ConfigOptionString(toolchange_gcode_str)); config.set_key_value("filament_start_gcode", new ConfigOptionString(start_filament_gcode_str)); std::string tcr_gcode, tcr_escaped_gcode = gcodegen.placeholder_parser_process("tcr_rotated_gcode", tcr_rotated_gcode, new_filament_id, &config); @@ -1746,6 +1759,7 @@ static std::vector get_path_of_change_filament(const Print& print) std::string toolchange_gcode_str; std::string deretraction_str; + std::string restore_layer_z_str; int toolchange_temp_override = -1; int interface_temp = -1; if (tcr.priming || (new_extruder_id >= 0 && needs_toolchange)) { @@ -1757,6 +1771,15 @@ static std::vector get_path_of_change_filament(const Print& print) interface_temp = gcodegen.config().nozzle_temperature_range_high.get_at(gcodegen.get_filament_config_index(new_extruder_id)); toolchange_temp_override = interface_temp; } + // Lift to the layer Z so the toolchange can't hit taller printed parts. Only a custom macro + // or a switch to another physical extruder (whose firmware Tn may dock) can travel. + const bool tool_may_travel = !gcodegen.config().change_filament_gcode.value.empty() + || (gcodegen.writer().filament() != nullptr + && gcodegen.writer().filament()->extruder_id() != get_extruder_index(*m_print_config, new_extruder_id)); + if (will_go_down && tool_may_travel && gcodegen.config().enable_prime_tower) { + restore_layer_z_str += gcodegen.writer().travel_to_z(current_z, "Restore layer Z before toolchange"); + check_add_eol(restore_layer_z_str); + } toolchange_gcode_str = gcodegen.set_extruder(new_extruder_id, tcr.print_z, false, toolchange_temp_override, WipeTower2::wait_for_temp_enabled(gcodegen.m_config)); // TODO: toolchange_z vs print_z if (!travel_to_tower_now && !tcr.priming && WipeTower2::use_gap_wall(gcodegen.m_config)) { @@ -1914,6 +1937,7 @@ static std::vector get_path_of_change_filament(const Print& print) DynamicConfig config; config.set_key_value("change_filament_gcode", new ConfigOptionString(toolchange_gcode_str)); config.set_key_value("deretraction_from_wipe_tower_generator", new ConfigOptionString(deretraction_str)); + config.set_key_value("restore_layer_z_before_toolchange", new ConfigOptionString(restore_layer_z_str)); config.set_key_value("layer_num", new ConfigOptionInt(gcodegen.m_layer_index)); config.set_key_value("layer_z", new ConfigOptionFloat(tcr.print_z)); config.set_key_value("toolchange_z", new ConfigOptionFloat(z)); @@ -3713,6 +3737,20 @@ void GCode::_do_export(Print& print, GCodeOutputStream &file, ThumbnailsGenerato this->placeholder_parser().set("first_filaments", new ConfigOptionInts(first_filaments)); this->placeholder_parser().set("initial_tool", initial_extruder_id); this->placeholder_parser().set("initial_extruder", initial_extruder_id); + // Orca: filament types really extruded on this plate, deduplicated, in filament id order. + // Joined with '_': safe in URLs and on print hosts, and unlike '-' it does not clash with + // types that already contain a hyphen (PLA-CF, TPU-95A). + std::string printing_filament_types; + { + std::vector types; + for (const Extruder &extruder : m_writer.extruders()) { + std::string type = m_config.filament_type.get_at(extruder.id()); + if (std::find(types.begin(), types.end(), type) == types.end()) + types.emplace_back(std::move(type)); + } + printing_filament_types = boost::algorithm::join(types, "_"); + } + this->placeholder_parser().set("printing_filament_types", printing_filament_types); //BBS match_physical_extruder_for_each_filament(first_non_support_filaments, m_config); @@ -4914,6 +4952,8 @@ void GCode::_do_export(Print& print, GCodeOutputStream &file, ThumbnailsGenerato print.tool_ordering())); print.m_print_statistics.initial_tool = initial_extruder_id; print.m_print_statistics.initial_no_support_tool = initial_non_support_extruder_id; + // Set again here: update_print_stats_and_format_filament_stats() above cleared the statistics. + print.m_print_statistics.printing_filament_types = printing_filament_types; if (!is_bbl_printers) { file.write_format("; total filament used [g] = %.2lf\n", print.m_print_statistics.total_weight); diff --git a/src/libslic3r/GCode/GCodeProcessor.cpp b/src/libslic3r/GCode/GCodeProcessor.cpp index 791d106da2..0157c8cdb4 100644 --- a/src/libslic3r/GCode/GCodeProcessor.cpp +++ b/src/libslic3r/GCode/GCodeProcessor.cpp @@ -37,6 +37,7 @@ #include #include +#include #include #include #include @@ -3022,11 +3023,11 @@ bool GCodeProcessor::check_multi_extruder_gcode_valid(const int auto unprintable_extruders = [&unprintable_areas, &unprintable_bboxes, &plate_offset](const BoundingBox &path_bbox) { BoundingBox bbox = path_bbox.inflated(SCALED_EPSILON); bbox.translate(-plate_offset); - int mask = 0; + uint64_t mask = 0; for (size_t i = 0; i < unprintable_areas.size(); ++i) if (!unprintable_areas[i].empty() && unprintable_bboxes[i].overlap(bbox) && !intersection(unprintable_areas[i], bbox.polygon()).empty()) - mask |= 1 << i; + mask |= uint64_t(1) << i; return mask; }; @@ -3084,9 +3085,9 @@ bool GCodeProcessor::check_multi_extruder_gcode_valid(const int //BoundingBox bbox_custom = path_poly_custom.bounding_box(); //bbox_custom.offset(-scale_(1.0)); // Narrow the range to provide a tolerance for the custom gcode //bbox.merge(bbox_custom); // merge the custom gcode pos with other pos*/ - const int unprintable_mask = unprintable_extruders(bbox); + const uint64_t unprintable_mask = unprintable_extruders(bbox); // check printable area - if ((extruder_id < unprintable_areas.size()) && (unprintable_mask & (1 << extruder_id))) { + if ((extruder_id < unprintable_areas.size()) && (unprintable_mask & (uint64_t(1) << extruder_id))) { m_result.gcode_check_result.error_code |= 1; std::pair filament_to_object_id; filament_to_object_id.first = iter->first; @@ -3102,7 +3103,7 @@ bool GCodeProcessor::check_multi_extruder_gcode_valid(const int filament_to_object_id.first = iter->first; filament_to_object_id.second = object_label_id; m_result.gcode_check_result.print_height_error_infos[extruder_id].push_back(filament_to_object_id); - m_result.limit_filament_maps[iter->first] |= (1 << extruder_id); + m_result.limit_filament_maps[iter->first] |= uint64_t(1) << extruder_id; valid = false; } @@ -3115,7 +3116,7 @@ bool GCodeProcessor::check_multi_extruder_gcode_valid(const int for (int extruder_id = 0; extruder_id < unprintable_filament_types.size(); ++extruder_id) { const std::set &filament_ids = unprintable_filament_types[extruder_id]; for (int filament_id : filament_ids) { - m_result.limit_filament_maps[filament_id] |= (1 << extruder_id); + m_result.limit_filament_maps[filament_id] |= uint64_t(1) << extruder_id; } }; diff --git a/src/libslic3r/GCode/GCodeProcessor.hpp b/src/libslic3r/GCode/GCodeProcessor.hpp index b99a5f2e86..8a53739b32 100644 --- a/src/libslic3r/GCode/GCodeProcessor.hpp +++ b/src/libslic3r/GCode/GCodeProcessor.hpp @@ -389,7 +389,8 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f; std::vector filament_costs; std::vector filament_vitrification_temperature; std::vector filament_maps; - std::vector limit_filament_maps; + // Per filament, bit i is set when extruder i + 1 can't print it. + std::vector limit_filament_maps; PrintEstimatedStatistics print_statistics; std::vector custom_gcode_per_print_z; bool spiral_vase_mode; diff --git a/src/libslic3r/GCode/WipeTower.cpp b/src/libslic3r/GCode/WipeTower.cpp index 9b29ba0b53..135600d6d7 100644 --- a/src/libslic3r/GCode/WipeTower.cpp +++ b/src/libslic3r/GCode/WipeTower.cpp @@ -2723,6 +2723,8 @@ void WipeTower::toolchange_Change( // This is where we want to place the custom gcodes. We will use placeholders for this. // These will be substituted by the actual gcodes when the gcode is generated. writer.append("[filament_end_gcode]\n"); + // Lift to the layer Z so change_filament_gcode can't hit taller printed parts. + writer.append("[restore_layer_z_before_toolchange]\n"); writer.append("[change_filament_gcode]\n"); // BBS: do travel in GCode::append_tcr() for lazy_lift diff --git a/src/libslic3r/GCode/WipeTower2.cpp b/src/libslic3r/GCode/WipeTower2.cpp index 83729a72a1..5e310e3bdd 100644 --- a/src/libslic3r/GCode/WipeTower2.cpp +++ b/src/libslic3r/GCode/WipeTower2.cpp @@ -1734,6 +1734,8 @@ void WipeTower2::toolchange_Change( // This is where we want to place the custom gcodes. We will use placeholders for this. // These will be substituted by the actual gcodes when the gcode is generated. //writer.append("[end_filament_gcode]\n"); + // Lift to the layer Z so change_filament_gcode can't hit taller printed parts. + writer.append("[restore_layer_z_before_toolchange]\n"); writer.append("[change_filament_gcode]\n"); if (m_is_mk4mmu3) diff --git a/src/libslic3r/IMEXZones.cpp b/src/libslic3r/IMEXZones.cpp index f5164f0500..3629ee065b 100644 --- a/src/libslic3r/IMEXZones.cpp +++ b/src/libslic3r/IMEXZones.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -376,4 +377,38 @@ ImexZoneLayout compute_imex_zone_layout(const DynamicPrintConfig& printer_cfg, return out; } +bool update_imex_layout_key(std::optional& key, const DynamicPrintConfig* printer_cfg, const std::string& mode) +{ + static const std::string no_mode; + static const std::vector no_strings; + const auto* is_imex = printer_cfg != nullptr ? printer_cfg->option("is_imex") : nullptr; + + ImexLayoutKey::Scalars s; + const ConfigOptionStrings* names = nullptr; + const ConfigOptionStrings* tools = nullptr; + if (is_imex != nullptr && is_imex->value) { + // The same accessors compute_imex_zone_layout() uses, so the key holds the values it lays + // out from. + s.imex = true; + s.gantry_count = imex_cfg_int(*printer_cfg, "imex_gantry_count"); + s.tools_per_gantry = imex_cfg_int(*printer_cfg, "imex_tools_per_gantry"); + s.tool_layout = int(imex_cfg_enum(*printer_cfg, "imex_tool_layout")); + s.clearance_x = imex_cfg_float(*printer_cfg, "imex_nozzle_clearance_x"); + s.clearance_y = imex_cfg_float(*printer_cfg, "imex_nozzle_clearance_y"); + s.carriage_margin = imex_cfg_float(*printer_cfg, "imex_carriage_margin"); + s.firmware_managed = imex_cfg_bool(*printer_cfg, "imex_firmware_managed_zones"); + names = printer_cfg->option("imex_mode_names"); + tools = printer_cfg->option("imex_mode_active_tools"); + } + const std::string& resolved_mode = s.imex ? mode : no_mode; + const std::vector& mode_names = names != nullptr ? names->values : no_strings; + const std::vector& mode_tools = tools != nullptr ? tools->values : no_strings; + + if (key.has_value() && key->s == s && key->mode == resolved_mode && key->mode_names == mode_names && + key->mode_active_tools == mode_tools) + return false; + key = ImexLayoutKey{ s, resolved_mode, mode_names, mode_tools }; + return true; +} + } // namespace Slic3r diff --git a/src/libslic3r/IMEXZones.hpp b/src/libslic3r/IMEXZones.hpp index 45bc959101..5896264f67 100644 --- a/src/libslic3r/IMEXZones.hpp +++ b/src/libslic3r/IMEXZones.hpp @@ -1,8 +1,10 @@ #pragma once +#include #include #include #include +#include #include #include "libslic3r/BoundingBox.hpp" @@ -91,4 +93,46 @@ ImexZoneLayout compute_imex_zone_layout(const DynamicPrintConfig& printer_cfg, const std::string& process_mode, const BoundingBoxf& bed_extents); +// Every config input to a plate's IMEX zones and ghosts: what compute_imex_zone_layout() reads from +// the printer preset, plus the plate's resolved mode and imex_firmware_managed_zones, which decides +// whether the plate draws ghosts. The bed is left out because a plate rebuilds its zones in +// set_shape(). An option that moves a zone or a ghost must be added here, or they go stale silently. +struct ImexLayoutKey +{ + // Every other field stays at its default while imex is false. + struct Scalars + { + bool imex = false; + int gantry_count = 0; + int tools_per_gantry = 0; + int tool_layout = -1; + double clearance_x = 0.0; + double clearance_y = 0.0; + double carriage_margin = 0.0; + bool firmware_managed = false; + + bool operator==(const Scalars& rhs) const + { + // A clearance field accepts "nan", so NaN equals itself here, or the key would change + // every frame. + auto same = [](double a, double b) { return a == b || (std::isnan(a) && std::isnan(b)); }; + return std::tie(imex, gantry_count, tools_per_gantry, tool_layout, firmware_managed) == + std::tie(rhs.imex, rhs.gantry_count, rhs.tools_per_gantry, rhs.tool_layout, rhs.firmware_managed) && + same(clearance_x, rhs.clearance_x) && same(clearance_y, rhs.clearance_y) && + same(carriage_margin, rhs.carriage_margin); + } + }; + Scalars s; + // The resolved mode and the printer's whole mode table. A name doesn't identify a roster: two + // presets can give one name different rosters, and editing a roster keeps its name. + std::string mode; + std::vector mode_names; + std::vector mode_active_tools; +}; + +// Brings `key` up to date with `printer_cfg` and the plate's resolved `mode`, and returns +// whether it changed. A null `printer_cfg` reads as IMEX off. Plates and the G-code preview call +// this every frame, so it compares against the live config and copies only when something changed. +bool update_imex_layout_key(std::optional& key, const DynamicPrintConfig* printer_cfg, const std::string& mode); + } // namespace Slic3r diff --git a/src/libslic3r/PresetBundle.cpp b/src/libslic3r/PresetBundle.cpp index d65c49972c..7ddfc983f3 100644 --- a/src/libslic3r/PresetBundle.cpp +++ b/src/libslic3r/PresetBundle.cpp @@ -4800,6 +4800,16 @@ unsigned int PresetBundle::sync_ams_list(std::vector std::string { + const Preset *current = filaments.find_preset(current_name, false); + const Preset *synced = filaments.find_preset(ams_name, false); + return current && synced && !current->is_system && current->is_compatible && + !synced->filament_id.empty() && current->filament_id == synced->filament_id ? current_name : ams_name; + }; + if (color_only) { auto get_map_index = [&ams_infos](const std::vector &infos, const AMSMapInfo &temp) { for (int i = 0; i < infos.size(); i++) { @@ -4912,7 +4922,7 @@ unsigned int PresetBundle::sync_ams_list(std::vector= 0 && valid_index < ams_filament_presets.size()) { exist_colors[i] = ams_filament_colors[valid_index]; exist_color_types[i] = ams_filament_color_types[valid_index]; - exist_filament_presets[i] = ams_filament_presets[valid_index]; + exist_filament_presets[i] = synced_preset_name(exist_filament_presets[i], ams_filament_presets[valid_index]); exist_multi_color_filment[i] = ams_multi_color_filment[valid_index]; } else { BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << "check error: array bound (mapping exist)"; @@ -4954,9 +4964,10 @@ unsigned int PresetBundle::sync_ams_list(std::vector 0 && enable_append) { BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "need_append_colors.size() > 0 && enable_append"; - auto get_idx_in_array = [](std::vector &presets, std::vector &colors, const std::string &preset, const std::string &color) -> int { + // A slot that kept a user preset for the tray's filament counts as that filament too. + auto get_idx_in_array = [&synced_preset_name](std::vector &presets, std::vector &colors, const std::string &preset, const std::string &color) -> int { for (size_t i = 0; i < presets.size(); i++) { - if (presets[i] == preset && colors[i] == color) { + if (synced_preset_name(presets[i], preset) == presets[i] && colors[i] == color) { return i; } } @@ -5007,7 +5018,11 @@ unsigned int PresetBundle::sync_ams_list(std::vector{ams_filament_colors[i]}); @@ -5041,6 +5056,10 @@ unsigned int PresetBundle::sync_ams_list(std::vectorvalues = ams_filament_colors; filament_color_type->values = ams_filament_color_types; + // Empty trays are left out of ams_filament_presets, so slot i may now hold a later tray. + // That is harmless here: a slot only keeps its preset when it is for the same filament. + for (size_t i = 0; i < std::min(ams_filament_presets.size(), this->filament_presets.size()); i++) + ams_filament_presets[i] = synced_preset_name(this->filament_presets[i], ams_filament_presets[i]); this->filament_presets = ams_filament_presets; filament_map->values.resize(ams_filament_colors.size(), 1); filament_volume_map->values.resize(ams_filament_colors.size(), static_cast(NozzleVolumeType::nvtStandard)); diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 59ede45165..953cb5f8f5 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -3015,10 +3015,12 @@ StringObjectException Print::validate(std::vector *warnin "adaptive_pressure_advance_model"); break; } - if (!AdaptivePAProcessor::validate_adaptive_pa_model(pa_model).empty()) { - warn(L("The Adaptive Pressure Advance model for one or more extruders may contain invalid values."), + const std::string pa_error = AdaptivePAProcessor::validate_adaptive_pa_model(pa_model); + if (!pa_error.empty()) { + // TRN %1% is the filament number as shown in the filament list, starting from 1; %2% names the invalid line. + // one warning per filament, the notifications stack + warn(Slic3r::format(L("The Adaptive Pressure Advance model of filament %1% contains invalid values.\n%2%"), filament_id + 1, pa_error), "adaptive_pressure_advance_model"); - break; } } } @@ -4951,7 +4953,8 @@ std::vector> Print::get_physical_unprintable_filaments(const std:: auto get_unprintable_extruder_id = [&](unsigned int filament_idx) -> int { // filament_printable may be shorter than the filament count; get_at() clamps. int status = m_config.filament_printable.get_at(filament_idx); - for (int i = 0; i < extruder_num; ++i) { + // An int has bits for the first 32 extruders only. + for (int i = 0; i < std::min(extruder_num, 32); ++i) { if (!(status >> i & 1)) { return i; } @@ -5872,6 +5875,7 @@ DynamicConfig PrintStatistics::config() const config.set_key_value("initial_tool", new ConfigOptionInt(static_cast(this->initial_tool))); config.set_key_value("initial_extruder", new ConfigOptionInt(static_cast(this->initial_tool))); config.set_key_value("initial_no_support_extruder", new ConfigOptionInt(static_cast(this->initial_no_support_tool))); + config.set_key_value("printing_filament_types", new ConfigOptionString(this->printing_filament_types)); return config; } @@ -5881,7 +5885,8 @@ DynamicConfig PrintStatistics::placeholders() for (const std::string key : { "print_time", "normal_print_time", "silent_print_time", "used_filament", "extruded_volume", "extruded_volume_total", "total_cost", "total_weight", "extruded_weight_total", - "initial_tool", "initial_extruder", "initial_no_support_extruder", "total_toolchanges", "total_wipe_tower_cost", "total_wipe_tower_filament"}) + "initial_tool", "initial_extruder", "initial_no_support_extruder", "total_toolchanges", "total_wipe_tower_cost", "total_wipe_tower_filament", + "printing_filament_types"}) config.set_key_value(key, new ConfigOptionString(std::string("{") + key + "}")); return config; } diff --git a/src/libslic3r/Print.hpp b/src/libslic3r/Print.hpp index b0fd8fd7cd..d9d7f801fe 100644 --- a/src/libslic3r/Print.hpp +++ b/src/libslic3r/Print.hpp @@ -965,6 +965,8 @@ struct PrintStatistics double total_wipe_tower_filament; unsigned int initial_tool; unsigned int initial_no_support_tool; + // Orca: underscore-separated list of the filament types really extruded on the plate. + std::string printing_filament_types; std::map filament_stats; // Config with the filled in print statistics. @@ -984,6 +986,7 @@ struct PrintStatistics total_wipe_tower_filament = 0.; initial_tool = 0; initial_no_support_tool = 0; + printing_filament_types.clear(); filament_stats.clear(); } static const std::string FilamentUsedG; diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 63d170c4ce..b12820c64a 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -13469,9 +13469,9 @@ PrintStatisticsConfigDef::PrintStatisticsConfigDef() def->label = L("Print time (normal mode)"); def->tooltip = L("Estimated print time when printed in normal mode (i.e. not in silent mode). Same as normal_print_time."); - //def = this->add("printing_filament_types", coString); - //def->label = L("Used filament types"); - //def->tooltip = L("Comma-separated list of all filament types used during the print."); + def = this->add("printing_filament_types", coString); + def->label = L("Used filament types"); + def->tooltip = L("Underscore-separated list of all filament types used during the print."); def = this->add("silent_print_time", coString); def->label = L("Print time (silent mode)"); diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 9a351ba47c..1a0147e945 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -981,6 +981,8 @@ if (APPLE) GUI/MacIME.mm GUI/MacIME.hpp GUI/Mcp/ScreenCapture_mac.mm + GUI/Accessibility/AccessibilityMac.mm + GUI/Accessibility/AccessibilityMac.h ) FIND_LIBRARY(DISKARBITRATION_LIBRARY DiskArbitration) endif () diff --git a/src/slic3r/GUI/Accessibility/AccessibilityMac.h b/src/slic3r/GUI/Accessibility/AccessibilityMac.h new file mode 100644 index 0000000000..be391ae559 --- /dev/null +++ b/src/slic3r/GUI/Accessibility/AccessibilityMac.h @@ -0,0 +1,62 @@ +#ifndef slic3r_GUI_AccessibilityMac_h_ +#define slic3r_GUI_AccessibilityMac_h_ + +#include +#include + +#ifdef __WXOSX__ + +class wxWindow; + +namespace Slic3r { +namespace GUI { + +// macOS accessibility (VoiceOver / Voice Control) for custom-drawn and native widgets. +// +// OrcaSlicer draws many controls with a plain NSView (backed by wxWindow), which +// assistive technologies neither name nor identify. This module configures the +// NSAccessibility metadata those views need so VoiceOver can focus, name and activate +// them and Voice Control can target them. The C++ API below is the only thing the rest +// of the codebase touches; every Cocoa and NSAccessibility detail stays in +// AccessibilityMac.mm. +namespace Accessibility { + +// The NSAccessibility role an element advertises. Add values here as more custom +// widgets are exposed. Keep in sync with role_string() in AccessibilityMac.mm. +enum class Role { + Button, // NSAccessibilityButtonRole + Checkbox, // NSAccessibilityCheckBoxRole +}; + +// How a wxWindow should be exposed to assistive technologies. +struct Descriptor { + Role role{ Role::Button }; + // Accessible name. When empty, the window's tooltip is used so icon-only controls + // still get a name. + wxString name; + // Default action invoked when the assistive technology activates the element. Stored + // as a block on the window's NSView (see detach()) and may capture the widget's + // `this`. Ignored for native controls, which have their own press action. + std::function press; +}; + +// Expose `win` to assistive technologies as described. Idempotent; call again whenever +// the name or enabled state changes (for example after a button's label is updated). +// +// The call is a no-op for a native control (an NSControl-backed wxWindow, e.g. a +// wxBitmapToggleButton): AppKit already exposes its role, value, enabled state and press +// action, so apply() only fills in the name and Voice Control identifier. Custom-drawn +// views are configured in full. +void apply(wxWindow* win, const Descriptor& desc); + +// Clear the press block apply() stored on the window's NSView. Call when the widget is +// destroyed so the view cannot outlive it with a press block capturing the freed widget. +void detach(wxWindow* win); + +} // namespace Accessibility +} // namespace GUI +} // namespace Slic3r + +#endif // __WXOSX__ + +#endif // !slic3r_GUI_AccessibilityMac_h_ diff --git a/src/slic3r/GUI/Accessibility/AccessibilityMac.mm b/src/slic3r/GUI/Accessibility/AccessibilityMac.mm new file mode 100644 index 0000000000..683af116aa --- /dev/null +++ b/src/slic3r/GUI/Accessibility/AccessibilityMac.mm @@ -0,0 +1,144 @@ +#include "AccessibilityMac.h" + +#include +#include +#include "wx/osx/core/cfstring.h" +#import + +// --------------------------------------------------------------------------- +// VoiceOver / Voice Control accessibility for custom-drawn controls. +// +// OrcaSlicer renders its dialog controls with a plain wxNSView (backed by wxWindow), +// which assistive technologies neither name nor identify. The NSAccessibility +// attributes of those views are configured through AppKit's instance-scoped setters +// (setAccessibilityRole:, setAccessibilityTitle:, setAccessibilityEnabled:, +// setAccessibilityIdentifier:, setAccessibilityElement:), which confines the change +// to the specific views we opt in. +// +// The press action has no setter, so accessibilityPerformPress is swizzled onto +// NSView once (install_press_action()). The replacement runs the press block stored +// on the view and otherwise forwards to the original implementation, so views that +// were never configured behave exactly as before. +// --------------------------------------------------------------------------- + +static const void* kOrcaAccessibilityPressKey = &kOrcaAccessibilityPressKey; + +// Swizzle accessibilityPerformPress on NSView, keeping the original implementation +// reachable through the captured IMP. dispatch_once makes this safe to trigger from +// every apply() call. +static void install_press_action() +{ + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + SEL sel = @selector(accessibilityPerformPress); + Method original = class_getInstanceMethod([NSView class], sel); + if (!original) + return; + + IMP original_imp = method_getImplementation(original); + IMP replacement = imp_implementationWithBlock(^BOOL(NSView* view) { + void (^handler)(void) = objc_getAssociatedObject(view, kOrcaAccessibilityPressKey); + if (handler) { + handler(); + return YES; + } + return ((BOOL (*)(id, SEL))original_imp)(view, sel); + }); + + const char* types = method_getTypeEncoding(original); + if (!class_addMethod([NSView class], sel, replacement, types)) { + // NSView implements the method itself rather than inheriting it, so adding + // failed; exchange the implementations instead. The captured original_imp + // stays valid and is called directly, so there is no recursion risk. + SEL stored = @selector(orca_accessibilityPerformPress); + if (class_addMethod([NSView class], stored, replacement, types)) + method_exchangeImplementations(original, class_getInstanceMethod([NSView class], stored)); + } + }); +} + +namespace Slic3r { +namespace GUI { +namespace Accessibility { + +namespace { + +// Maps a Role to its NSAccessibility role string. Keep in sync with Role in +// AccessibilityMac.h: every enumerator needs a case here, otherwise it falls through to +// NSAccessibilityUnknownRole. +NSString* role_string(Role role) +{ + switch (role) { + case Role::Button: return NSAccessibilityButtonRole; + case Role::Checkbox: return NSAccessibilityCheckBoxRole; + } + return NSAccessibilityUnknownRole; +} + +// Voice Control identifier. wxWindow::GetId() is stable for the window's lifetime but +// can be recycled once a window is destroyed; Voice Control's spoken-number overlay +// only needs the mapping to stay stable while the element is on screen. +wxString default_identifier(const wxWindow* win) +{ + return wxString::Format("wxID_%d", (int)win->GetId()); +} + +} // namespace + +void apply(wxWindow* win, const Descriptor& desc) +{ + if (!win) + return; + + NSView* view = (NSView*)win->GetHandle(); + if (!view) + return; + + // A native control (an NSControl-backed wxWindow such as a wxBitmapToggleButton) + // already exposes its role, value, enabled state and press action through AppKit, so + // we only fill in the two pieces AppKit cannot derive for our controls: the name and + // the Voice Control identifier. A custom-drawn view (a plain wxNSView) exposes none + // of this, so it is configured in full below. + const bool native = [view isKindOfClass:[NSControl class]]; + + // The element's name. Fall back to the tooltip so icon-only controls get a name. + wxString name = desc.name; + if (name.empty()) + name = win->GetToolTipText(); + [view setAccessibilityTitle:name.empty() ? nil : wxCFStringRef(name).AsNSString()]; + + // A stable id Voice Control uses to map spoken commands back to the element. + [view setAccessibilityIdentifier:wxCFStringRef(default_identifier(win)).AsNSString()]; + + if (native) + return; + + install_press_action(); + + [view setAccessibilityRole:role_string(desc.role)]; + + // wxWindow::IsEnabled() includes disabled ancestors; kept current by re-calling + // apply() from the widget's DoEnable() (wx cascades DoEnable to children). + [view setAccessibilityEnabled:win->IsEnabled()]; + + if (desc.press) { + auto press = desc.press; // copy the std::function into the stored block + objc_setAssociatedObject(view, kOrcaAccessibilityPressKey, ^{ press(); }, OBJC_ASSOCIATION_COPY_NONATOMIC); + } else { + objc_setAssociatedObject(view, kOrcaAccessibilityPressKey, nil, OBJC_ASSOCIATION_COPY_NONATOMIC); + } + + // Opt this view into the accessibility tree. + [view setAccessibilityElement:YES]; +} + +void detach(wxWindow* win) +{ + NSView* view = win ? (NSView*)win->GetHandle() : nil; + if (view) + objc_setAssociatedObject(view, kOrcaAccessibilityPressKey, nil, OBJC_ASSOCIATION_COPY_NONATOMIC); +} + +} // namespace Accessibility +} // namespace GUI +} // namespace Slic3r diff --git a/src/slic3r/GUI/BackgroundSlicingProcess.cpp b/src/slic3r/GUI/BackgroundSlicingProcess.cpp index 602464bb86..e1dc565874 100644 --- a/src/slic3r/GUI/BackgroundSlicingProcess.cpp +++ b/src/slic3r/GUI/BackgroundSlicingProcess.cpp @@ -807,6 +807,10 @@ void BackgroundSlicingProcess::reset_export() if (!this->running()) { m_export_path.clear(); m_export_path_on_removable_media = false; + // A scheduled upload only leaves m_upload_job when prepare_upload() hands it to the print host + // job queue. If the run ended before that (a post-processing script or plugin failure, or a + // cancel), the job must not survive into the next plain slice, which would upload again. + m_upload_job = PrintHostJob(); // invalidate_step expects the mutex to be locked. std::scoped_lock lock(m_print->state_mutex()); this->invalidate_step(bspsGCodeFinalize); diff --git a/src/slic3r/GUI/BackgroundSlicingProcess.hpp b/src/slic3r/GUI/BackgroundSlicingProcess.hpp index 231bee811e..1ccd821190 100644 --- a/src/slic3r/GUI/BackgroundSlicingProcess.hpp +++ b/src/slic3r/GUI/BackgroundSlicingProcess.hpp @@ -166,7 +166,7 @@ public: // Set print host upload job data to be enqueued to the PrintHostJobQueue // after current print slicing is complete void schedule_upload(Slic3r::PrintHostJob upload_job); - // Clear m_export_path. + // Clear m_export_path and drop a scheduled upload that was not handed to the print host job queue. void reset_export(); // Once the G-code export is scheduled, the apply() methods will do nothing. bool is_export_scheduled() const { return ! m_export_path.empty(); } diff --git a/src/slic3r/GUI/GCodeViewer.cpp b/src/slic3r/GUI/GCodeViewer.cpp index 0c18e2c5b3..07cc49df65 100644 --- a/src/slic3r/GUI/GCodeViewer.cpp +++ b/src/slic3r/GUI/GCodeViewer.cpp @@ -2288,34 +2288,17 @@ void GCodeViewer::render_markers(int canvas_width, int canvas_height) // Cache guard. The marker plan below is resolved from preset/plate state only, // so it is rebuilt when that state moves and reused otherwise — the sequential // slider is sticky, and re-resolving the zone layout on every frame of the rest - // of the session showed up as a measurable per-frame cost. The comparison is - // deliberately made against the live config rather than against a freshly built - // key, so an unchanged frame allocates nothing at all. - static const std::vector s_no_strings; - auto* names_opt = printer_cfg.opt("imex_mode_names"); - auto* tools_opt = printer_cfg.opt("imex_mode_active_tools"); - const std::vector& mode_names = names_opt ? names_opt->values : s_no_strings; - const std::vector& active_tools = tools_opt ? tools_opt->values : s_no_strings; + // of the session showed up as a measurable per-frame cost. + ImexMarkerKey::Plate plate; + plate.plate_index = plate_list.get_curr_plate_index(); + plate.bed_min_x = bed_extents.min.x(); + plate.bed_min_y = bed_extents.min.y(); + plate.bed_max_x = bed_extents.max.x(); + plate.bed_max_y = bed_extents.max.y(); - ImexMarkerKey::Scalars key; - key.plate_index = plate_list.get_curr_plate_index(); - // Same accessor the plan is built from: a key holding a different fallback than - // the value actually laid out would compare equal across a real change. - key.gantry_count = imex_cfg_int(printer_cfg, "imex_gantry_count"); - key.tools_per_gantry = imex_cfg_int(printer_cfg, "imex_tools_per_gantry"); - key.tool_layout = (int)imex_cfg_enum(printer_cfg, "imex_tool_layout"); - key.clearance_x = imex_cfg_float(printer_cfg, "imex_nozzle_clearance_x"); - key.clearance_y = imex_cfg_float(printer_cfg, "imex_nozzle_clearance_y"); - key.firmware_managed = imex_cfg_bool(printer_cfg, "imex_firmware_managed_zones"); - key.bed_min_x = bed_extents.min.x(); - key.bed_min_y = bed_extents.min.y(); - key.bed_max_x = bed_extents.max.x(); - key.bed_max_y = bed_extents.max.y(); - - if (!(m_imex_marker_key.s == key) || m_imex_marker_key.mode != mode || - m_imex_marker_key.mode_names != mode_names || - m_imex_marker_key.mode_active_tools != active_tools) { - m_imex_marker_key = ImexMarkerKey{ key, mode, mode_names, active_tools }; + const bool layout_changed = update_imex_layout_key(m_imex_marker_key.layout, &printer_cfg, mode); + if (layout_changed || !(m_imex_marker_key.plate == plate)) { + m_imex_marker_key.plate = plate; m_imex_marker_plan = resolve_imex_marker_plan(printer_cfg, mode, bed_extents); // The carriage roster — and with it the marker count — can change with any // of those inputs, so drop the markers and let the lazy init below rebuild diff --git a/src/slic3r/GUI/GCodeViewer.hpp b/src/slic3r/GUI/GCodeViewer.hpp index b011bd4e9e..e4e16aa492 100644 --- a/src/slic3r/GUI/GCodeViewer.hpp +++ b/src/slic3r/GUI/GCodeViewer.hpp @@ -19,8 +19,10 @@ #include "libslic3r/BoundingBox.hpp" #include #include "libslic3r/Config.hpp" +#include "libslic3r/IMEXZones.hpp" #include "libvgcode/include/GCodeInputData.hpp" #include +#include #include "libvgcode/include/PathVertex.hpp" #include @@ -271,50 +273,23 @@ private: // Invalidation key for the plan above: every input the plan is derived from, and // nothing that changes between frames. A stale plan would put the preview markers // somewhere the plate's own zones and ghosts do not agree with, which is exactly the - // drift the shared layout call exists to prevent -- so this deliberately mirrors - // PartPlate::build_imex_cache_key(). The two keys are not field-for-field identical, and - // the differences are deliberate rather than incidental: - // - bed extents and plate_index are here and not there. Zone centres scale with the - // extents, and one preview serves every plate, so the preview must key what the plate - // gets for free -- it re-bakes on set_shape() and is keyed by being that plate. - // - mode_names / mode_active_tools hold the printer's WHOLE mode table; the plate resolves - // one active mode and keys that roster plus its primary head. Same information reached - // two ways, so a change to the active mode moves both keys. - // - imex_carriage_margin is there and not here: it only sizes the plate's advisory bands, - // which the preview never draws. - // imex_tool_layout is in both, which the plate's key gained for the reason this one has it: - // the T0-corner flip moves every zone rectangle while nothing else keyed changes. + // drift the shared layout call exists to prevent -- so the layout half is the plate's own + // key. The preview adds the plate index and bed extents, which a plate gets for free: zone + // centers scale with the bed, and one preview serves every plate, while each plate rebuilds + // its zones in set_shape(). The layout key also holds imex_carriage_margin, which only sizes + // the plate's advisory bands, so a margin change re-resolves the plan needlessly. struct ImexMarkerKey { - // Scalar half. Built fresh on the stack each frame -- it allocates nothing -- and - // compared as a tuple. - struct Scalars + std::optional layout; + struct Plate { - int plate_index = -1; - int gantry_count = 0; - int tools_per_gantry = 0; - int tool_layout = -1; - double clearance_x = 0.0; - double clearance_y = 0.0; - bool firmware_managed = false; + int plate_index = -1; double bed_min_x = 0.0, bed_min_y = 0.0, bed_max_x = 0.0, bed_max_y = 0.0; - auto tied() const { - return std::tie(plate_index, gantry_count, tools_per_gantry, tool_layout, - clearance_x, clearance_y, firmware_managed, - bed_min_x, bed_min_y, bed_max_x, bed_max_y); - } - bool operator==(const Scalars& rhs) const { return tied() == rhs.tied(); } + auto tied() const { return std::tie(plate_index, bed_min_x, bed_min_y, bed_max_x, bed_max_y); } + bool operator==(const Plate& rhs) const { return tied() == rhs.tied(); } }; - Scalars s; - // Resolved active mode (the plate's mode beats the process preset), plus the printer - // preset's whole mode table. The name alone is not identity: two presets can carry - // the same mode name over different tool rosters, and editing a roster in place - // moves neither the name nor any scalar above. Compared by value, never copied - // unless something actually changed. - std::string mode; - std::vector mode_names; - std::vector mode_active_tools; + Plate plate; }; ImexMarkerKey m_imex_marker_key; ImexMarkerPlan m_imex_marker_plan; diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index 6ae113abd5..4ed43d1583 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -2660,6 +2660,7 @@ void GLCanvas3D::_render_frame(bool scene_dirty, bool only_init) // Automation records ImGui items per canvas (ImGuiWrapper::set_item_recording). wxGetApp().imgui()->set_frame_owner(this); + const ImGuiID active_id = ImGui::GetActiveID(); wxGetApp().imgui()->new_frame(); if (_update_inactive_plates_visibility()) @@ -2814,6 +2815,7 @@ void GLCanvas3D::_render_frame(bool scene_dirty, bool only_init) m_frame_profiler.mark("notifications"); ImDrawData* draw_data = wxGetApp().imgui()->end_frame(); + m_overlay_dirty |= active_id != ImGui::GetActiveID(); std::optional signature; if (_is_frame_skipping_enabled()) @@ -3473,9 +3475,14 @@ void GLCanvas3D::reload_scene(bool refresh_immediately, bool force_full_scene_re volume->is_modifier = !mvs->model_volume->is_model_part(); volume->set_color(color_from_model_volume(*mvs->model_volume)); + const ModelInstance& instance = *mvs->model_volume->get_object()->instances[mvs->composite_id.instance_id]; + // Follow the instance's printable flag on every reload; the assemble view never shows it. + if (m_canvas_type != ECanvasType::CanvasAssembleView) + volume->printable = instance.printable; + // updates volumes transformations if (m_canvas_type != ECanvasType::CanvasAssembleView) { - volume->set_instance_transformation(mvs->model_volume->get_object()->instances[mvs->composite_id.instance_id]->get_transformation()); + volume->set_instance_transformation(instance.get_transformation()); volume->set_volume_transformation(mvs->model_volume->get_transformation()); // updates volumes convex hull if (mvs->model_volume->is_model_part() && ! volume->convex_hull()) @@ -3485,14 +3492,14 @@ void GLCanvas3D::reload_scene(bool refresh_immediately, bool force_full_scene_re volume->set_offset_to_assembly(Vec3d(0, 0, 0)); } else { - volume->set_instance_transformation(mvs->model_volume->get_object()->instances[mvs->composite_id.instance_id]->get_assemble_transformation()); + volume->set_instance_transformation(instance.get_assemble_transformation()); volume->set_volume_transformation(mvs->model_volume->get_transformation()); // updates volumes convex hull if (mvs->model_volume->is_model_part() && ! volume->convex_hull()) // Model volume was likely changed from modifier or support blocker / enforcer to a model part. // Only model parts require convex hulls. volume->set_convex_hull(mvs->model_volume->get_convex_hull_shared_ptr()); - volume->set_offset_to_assembly(mvs->model_volume->get_object()->instances[mvs->composite_id.instance_id]->get_offset_to_assembly()); + volume->set_offset_to_assembly(instance.get_offset_to_assembly()); } } } @@ -3562,6 +3569,8 @@ void GLCanvas3D::reload_scene(bool refresh_immediately, bool force_full_scene_re it->volume_idx = m_volumes.volumes.size(); m_volumes.load_object_volume(&model_object, obj_idx, volume_idx, instance_idx, m_color_by, m_initialized, m_canvas_type == ECanvasType::CanvasAssembleView); m_volumes.volumes.back()->geometry_id = key.geometry_id; + if (m_canvas_type != ECanvasType::CanvasAssembleView) + m_volumes.volumes.back()->printable = model_instance.printable; update_object_list = true; } else { // Recycling an old GLVolume. @@ -4160,8 +4169,10 @@ void GLCanvas3D::on_idle(wxIdleEvent& evt) if (m_extra_frame_requested || mouse3d_controller_applied) { m_dirty = true; m_extra_frame_requested = false; - evt.RequestMore(); } + + if (m_dirty) + evt.RequestMore(); #if ENABLE_ENHANCED_IMGUI_SLIDER_FLOAT else if (imgui_requires_extra_frame || wxGetApp().imgui()->requires_extra_frame()) { // ImGui settling a window or fading a tooltip. diff --git a/src/slic3r/GUI/IdleScheduler.cpp b/src/slic3r/GUI/IdleScheduler.cpp index bd40288678..309ffcb194 100644 --- a/src/slic3r/GUI/IdleScheduler.cpp +++ b/src/slic3r/GUI/IdleScheduler.cpp @@ -45,11 +45,13 @@ bool input_pending() #endif } -// True inside a wxYield(), where a slice would build pages in the middle of the code that yielded. -bool yielding() +// True inside a wxYield() or a nested loop such as a modal dialog's, where a slice would build pages in +// the middle of the code that is waiting. A new web view waits for WebKit in a yield loop; if the dialog +// closes meanwhile, macOS aborts its modal session, the reply never arrives and the app hangs. +bool in_nested_loop() { const wxEventLoopBase* loop = wxEventLoopBase::GetActive(); - return loop != nullptr && loop->IsYielding(); + return loop != nullptr && (loop->IsYielding() || !loop->IsMain()); } } // namespace @@ -79,7 +81,7 @@ void IdleScheduler::tick() stop(); return; } - if (m_input_idle_ms() < quiet_ms || input_pending() || yielding()) { + if (m_input_idle_ms() < quiet_ms || input_pending() || in_nested_loop()) { start(); return; } diff --git a/src/slic3r/GUI/PartPlate.cpp b/src/slic3r/GUI/PartPlate.cpp index b3a7ffa389..fb768574f2 100644 --- a/src/slic3r/GUI/PartPlate.cpp +++ b/src/slic3r/GUI/PartPlate.cpp @@ -472,7 +472,7 @@ std::string PartPlate::get_effective_imex_mode() const std::string mode = get_imex_mode(); if (mode != kImexPrimaryMode) return mode; - // wxGetApp() is not available headless -- see build_imex_cache_key, which guards on the + // wxGetApp() is not available headless -- see refresh_imex_layout_key, which guards on the // same thing. Nothing calls this from the CLI today; this keeps that from being fatal. if (!m_plater) return mode; @@ -492,16 +492,14 @@ void PartPlate::set_imex_mode(const std::string& mode) m_config.set_key_value("imex_parallel_mode", new ConfigOptionString(mode)); } update_slice_result_valid_state(false); - m_imex_zones_mode_cache = "\x01"; // force zone rebuild - m_imex_ghost_cache_key = "\x01"; // force ghost rebuild + m_imex_layout_key.reset(); // force zone and ghost rebuild } void PartPlate::reset_imex_mode() { m_config.erase("imex_parallel_mode"); update_slice_result_valid_state(false); - m_imex_zones_mode_cache = "\x01"; - m_imex_ghost_cache_key = "\x01"; + m_imex_layout_key.reset(); } std::map PartPlate::get_imex_head_filament_map() const @@ -678,7 +676,6 @@ void PartPlate::calc_imex_zones() m_imex_margin_overlay.clear(); m_imex_primary_zone_box = std::nullopt; m_imex_head_zone_centers.clear(); - m_imex_primary_head = -1; if (!wxGetApp().preset_bundle) return; @@ -695,7 +692,6 @@ void PartPlate::calc_imex_zones() const ImexZoneLayout layout = compute_imex_zone_layout(printer_cfg, get_imex_mode(), process_mode, get_extents(m_shape)); - m_imex_primary_head = layout.primary_head; m_imex_head_zone_centers = layout.head_zone_centers; m_imex_primary_zone_box = layout.primary_zone_box; m_imex_secondary_zone_boxes = layout.secondary_zone_boxes; @@ -737,62 +733,32 @@ void PartPlate::calc_imex_zones() push_zone_fill(m_imex_margin_overlay, b.min.x(), b.max.x(), b.min.y(), b.max.y()); } -// Build a cache key from the current IDEX/IQEX config options, or "" if IDEX/IQEX is off. -// Reads per-plate mode from m_config first, falling back to the process preset. -// -// Inputs that contribute to the key (any change must invalidate the IMEX zone cache): -// - active_mode (per-plate or process-preset fallback) -// - imex_tools_per_gantry, imex_gantry_count (grid shape) -// - imex_tool_layout (which corner tool 0 occupies) -// - imex_nozzle_clearance_x, imex_nozzle_clearance_y (zone widths / collision strips) -// - imex_carriage_margin (zone shrink) -// - the active mode's tool roster and its Primary head (same name, different roster) -// - imex_firmware_managed_zones (suppresses ghost generation) -// -// IMPORTANT: if you add a printer config option that affects zone geometry, ghost transforms, -// or collision strips, it MUST be incorporated here — otherwise ghost meshes and zone overlays -// will go stale silently after a config change. Float values are scaled by 10 before integer -// cast so 0.1 mm steps invalidate the cache; if you add a float option needing finer precision, -// adjust the scale. -std::string PartPlate::build_imex_cache_key() const +void PartPlate::refresh_imex_layout_key() { // CLI / headless slice: no GUI_App is initialized, so `wxGetApp()` returns // memory that segfaults on member access. `m_plater` is set only by the GUI - // construction path; treat its absence as "no IMEX state to compute" and - // return an empty key. Same guard pattern used by calc_imex_ghosts. - if (!m_plater || !wxGetApp().preset_bundle) - return ""; - const DynamicPrintConfig& printer_cfg = wxGetApp().preset_bundle->printers.get_edited_preset().config; - auto* is_imex_opt = printer_cfg.option("is_imex"); - if (!is_imex_opt || !is_imex_opt->value) - return ""; - std::string active_mode = get_effective_imex_mode(); - // Mode NAME alone is not printer identity: two presets can define the same mode - // name with different tool rosters/primary, and imex_firmware_managed_zones - // suppresses ghost generation entirely. Both shape the baked zone/ghost set, so - // key them directly (previously caught only incidentally, via the ghost key's - // since-removed pem entry). - std::string active_tools; - int primary_phys = -1; - resolve_active_mode_tools(active_tools, primary_phys); // empty on failure — keyed as such - // imex_tool_layout decides which physical corner tool 0 occupies (flip_x / flip_y inside - // compute_imex_zone_layout), so every zone rectangle, collision strip and ghost offset moves - // when it changes while every other keyed field stays put. Without it the key is identical - // across a layout change and the baked zones go stale; that this currently appears to work is - // incidental -- some other path happens to rebuild -- not something to rely on. - // Geometry values go through imex_cfg_* so the key is built from the same numbers - // compute_imex_zone_layout() lays out with; a literal here could key on a value the layout - // never used. - return active_mode - + "|" + std::to_string(imex_cfg_int(printer_cfg, "imex_tools_per_gantry")) - + "x" + std::to_string(imex_cfg_int(printer_cfg, "imex_gantry_count")) - + "|ly" + std::to_string((int)imex_cfg_enum(printer_cfg, "imex_tool_layout")) - + "|cw" + std::to_string((int)(imex_cfg_float(printer_cfg, "imex_nozzle_clearance_x") * 10)) - + "|ch" + std::to_string((int)(imex_cfg_float(printer_cfg, "imex_nozzle_clearance_y") * 10)) - + "|mg" + std::to_string((int)(imex_cfg_float(printer_cfg, "imex_carriage_margin") * 10)) - + "|t" + active_tools - + "|p" + std::to_string(primary_phys) - + "|fw" + (imex_cfg_bool(printer_cfg, "imex_firmware_managed_zones") ? "1" : "0"); + // construction path; treat its absence as "IMEX off". Same guard pattern used + // by calc_imex_ghosts. + const DynamicPrintConfig* printer_cfg = nullptr; + if (m_plater && wxGetApp().preset_bundle) { + const DynamicPrintConfig& cfg = wxGetApp().preset_bundle->printers.get_edited_preset().config; + const auto* is_imex = cfg.option("is_imex"); + if (is_imex != nullptr && is_imex->value) + printer_cfg = &cfg; + } + // With IMEX off the key ignores the mode, so don't resolve it. + if (!update_imex_layout_key(m_imex_layout_key, printer_cfg, printer_cfg != nullptr ? get_effective_imex_mode() : std::string())) + return; + + ++m_imex_layout_key_version; + m_imex_zones_stale = true; + m_imex_active_mode = {}; + if (m_imex_layout_key->s.imex && m_imex_layout_key->mode != kImexPrimaryMode) { + // A mode missing from the table, or past the end of a short imex_mode_active_tools, gets + // empty tools, which declare no Primary, so the mode stays unresolved. + m_imex_active_mode.tools = find_imex_mode(*printer_cfg, m_imex_layout_key->mode).active_tools; + m_imex_active_mode.primary = imex_primary_tool_for_mode(m_imex_active_mode.tools); + } } // Reposition the IMEX mode icon without requiring a full set_shape() rebuild. @@ -824,66 +790,36 @@ void PartPlate::refresh_imex_icon() } // Ensure zone geometry (secondary boxes, collision strips, visual meshes) is up to date. -// Called before any collision check AND before rendering so both paths share the same data. void PartPlate::ensure_imex_zones() { // CLI / headless slice: no GUI_App, no plater, no IMEX state to track. Bail out // before touching `wxGetApp()` (which segfaults without a GUI_App) — placement // checks reach this from the headless 3MF-load path through `check_outside`. if (!m_plater) return; - std::string cache_key = build_imex_cache_key(); - if (cache_key != m_imex_zones_mode_cache) { - m_imex_zones_mode_cache = cache_key; - calc_imex_zones(); - } + refresh_imex_layout_key(); + rebuild_stale_imex_zones(); } -std::string PartPlate::build_imex_ghost_cache_key() const +void PartPlate::rebuild_stale_imex_zones() { - // Ghost shape depends on: mode topology (same inputs as zone key) + set of - // objects on plate + each primary instance's transform. Filament routing and - // colors are deliberately NOT keyed: ghost RGB is restamped live every frame - // by update_imex_ghost_colors, so color-only changes never need a mesh rebuild. - std::string k = build_imex_cache_key(); - if (k.empty()) return ""; // ghost-off when zones-off - - k += "|obj"; - for (const auto& oi : obj_to_instance_set) - k += std::to_string(oi.first) + "." + std::to_string(oi.second) + ","; - return k; + if (!m_plater || !m_imex_zones_stale) return; + m_imex_zones_stale = false; + calc_imex_zones(); } void PartPlate::ensure_imex_ghosts() { - std::string key = build_imex_ghost_cache_key(); - if (key != m_imex_ghost_cache_key) { - m_imex_ghost_cache_key = key; - calc_imex_ghosts(); - } -} - -bool PartPlate::resolve_active_mode_tools(std::string& out_tools_str, int& out_primary_phys) const -{ - if (!wxGetApp().preset_bundle) return false; - const DynamicPrintConfig& printer_cfg = wxGetApp().preset_bundle->printers.get_edited_preset().config; - auto* is_imex_opt = printer_cfg.option("is_imex"); - if (!is_imex_opt || !is_imex_opt->value) return false; - - const std::string active_mode = get_effective_imex_mode(); - if (active_mode == kImexPrimaryMode) return false; - - const ImexMode mode = find_imex_mode(printer_cfg, active_mode); - if (!mode.found()) return false; - - // Also the ragged case: a tools array too short to reach this row hands back an empty - // string, which has no declared primary, which is the same "no zones here" answer the - // explicit bounds check used to give. - const int primary_phys = imex_primary_tool_for_mode(mode.active_tools); - if (primary_phys < 0) return false; - - out_tools_str = mode.active_tools; - out_primary_phys = primary_phys; - return true; + // Ghost meshes depend on: mode topology (the layout key) + set of objects on + // plate. Instance transforms are applied live by update_imex_ghost_transforms. + // Filament routing and colors are deliberately NOT keyed: ghost RGB is restamped + // live every frame by update_imex_ghost_colors, so color-only changes never need + // a mesh rebuild. With IMEX off there are no ghosts, whatever the plate holds. + if (m_imex_ghost_layout_version == m_imex_layout_key_version && + (!m_imex_layout_key || !m_imex_layout_key->s.imex || m_imex_ghost_objects == obj_to_instance_set)) + return; + m_imex_ghost_layout_version = m_imex_layout_key_version; + m_imex_ghost_objects = obj_to_instance_set; + calc_imex_ghosts(); } // Ghost opacity, stamped together with RGB by update_imex_ghost_colors every @@ -896,9 +832,10 @@ void PartPlate::calc_imex_ghosts() if (!m_plater || !m_model) return; if (obj_to_instance_set.empty()) return; - std::string active_tools_str; - int primary_phys = -1; - if (!resolve_active_mode_tools(active_tools_str, primary_phys)) return; + const ImexActiveMode& active = m_imex_active_mode; + if (!active.resolved()) return; + const std::string& active_tools_str = active.tools; + const int primary_phys = active.primary; // IMEX firmware-managed zones: the slicer emits a centered single-half slice and the // firmware fans copies/mirrors out from there — placement is not slicer-authoritative. @@ -911,9 +848,8 @@ void PartPlate::calc_imex_ghosts() return; // Zone centers are the basis for ghost placement; make sure they exist before - // we read them. render_imex_zones already ensures this, but ghost rebuild can - // also be driven from mode/preset invalidation paths that don't touch zones. - ensure_imex_zones(); + // we read them. + rebuild_stale_imex_zones(); const auto heads = parse_imex_active_tools(active_tools_str); @@ -1051,13 +987,13 @@ void PartPlate::update_imex_ghost_transforms( { if (m_imex_ghost_volumes.empty() || !m_plater || !m_model) return; - std::string active_tools_str; - int primary_phys = -1; - if (!resolve_active_mode_tools(active_tools_str, primary_phys)) return; - // Reuse zone-center-derived offsets (same source calc_imex_ghosts uses), so // update and rebuild paths always agree on where each ghost belongs. ensure_imex_zones(); + const ImexActiveMode& active = m_imex_active_mode; + if (!active.resolved()) return; + const std::string& active_tools_str = active.tools; + const int primary_phys = active.primary; auto center_for = [&](int phys) -> Vec2d { auto it = m_imex_head_zone_centers.find(phys); return (it == m_imex_head_zone_centers.end()) ? Vec2d::Zero() : it->second; @@ -1294,11 +1230,11 @@ bool PartPlate::has_imex_multimaterial_conflict() const // which the raw key's single default entry does not describe. const ConfigOptionInts pem = effective_physical_extruder_map(*pb); - // Resolve the active mode's tools string from the printer config. Print::validate() + // The active mode's roster, as refresh_imex_layout_key() resolved it. Print::validate() // resolves the same name the same way and keeps going on an empty result -- the mixed // filament rule below does not depend on the roster -- so this must too, or the badge // goes quiet on exactly the plates the slicer refuses. - const std::string active_tools_str = find_imex_mode(printer_cfg, mode).active_tools; + const std::string& active_tools_str = m_imex_active_mode.tools; // Convert PartPlate's 1-based extruder list to the 0-based form the helper expects. // @@ -1330,7 +1266,7 @@ void PartPlate::render_imex_zones(bool force_default_color) if (force_default_color) return; - ensure_imex_zones(); + rebuild_stale_imex_zones(); ensure_imex_ghosts(); // Read visualization theme from printer config. @@ -2673,11 +2609,8 @@ void PartPlate::render_icons(bool bottom, bool only_name, int hover_id) auto* is_imex_opt = pb ? pb->printers.get_edited_preset().config.option("is_imex") : nullptr; if (is_imex_opt && is_imex_opt->value) { // The icon shows the mode the plate slices as, the one its ghosts follow. - std::string active_tools; - int primary_phys = -1; - const size_t kind = size_t(resolve_active_mode_tools(active_tools, primary_phys) ? - imex_mode_kind(active_tools) : - ImexModeKind::Primary); + const ImexActiveMode& active = m_imex_active_mode; + const size_t kind = size_t(active.resolved() ? imex_mode_kind(active.tools) : ImexModeKind::Primary); // Both the mode name and the conflict warning describe the same hovered icon, // and set_hover_tooltip records one string per frame, so they are composed here. std::string hover_tip; @@ -5222,7 +5155,7 @@ bool PartPlate::set_shape(const Pointfs& shape, const Pointfs& exclude_areas, co const BoundingBox& pp_bbox = poly.contour.bounding_box(); calc_gridlines(poly, pp_bbox); - m_imex_zones_mode_cache = "\x01"; // force rebuild on next render + m_imex_zones_stale = true; // force rebuild on next render calc_imex_zones(); calc_vertex_for_icons(0, m_del_icon); @@ -5340,6 +5273,8 @@ bool PartPlate::intersects(const BoundingBoxf3& bb) const void PartPlate::render(const Transform3d& view_matrix, const Transform3d& projection_matrix, bool bottom, bool only_body, bool force_background_color, HeightLimitMode mode, int hover_id, bool render_cali, bool show_grid, bool hide_chrome) { + refresh_imex_layout_key(); + glsafe(::glEnable(GL_DEPTH_TEST)); GLShaderProgram *shader = wxGetApp().get_shader("flat"); diff --git a/src/slic3r/GUI/PartPlate.hpp b/src/slic3r/GUI/PartPlate.hpp index bfaf9c0318..7ae0ce2d3a 100644 --- a/src/slic3r/GUI/PartPlate.hpp +++ b/src/slic3r/GUI/PartPlate.hpp @@ -32,6 +32,7 @@ #include "libslic3r/ObjectID.hpp" #include "libslic3r/GCode/GCodeProcessor.hpp" #include "libslic3r/Format/bbs_3mf.hpp" +#include "libslic3r/IMEXZones.hpp" #include "libslic3r/Slicing.hpp" #include "libslic3r/GCode/WipeTowerEstimate.hpp" #include "libslic3r/Arrange.hpp" @@ -181,10 +182,23 @@ private: std::vector m_imex_margin_overlay; // amber advisory bands just inside collision strips std::optional m_imex_primary_zone_box; // primary zone extents in mm; empty when IDEX/IQEX is off/primary-only std::map m_imex_head_zone_centers; // physical-head → zone-center (mm); populated by calc_imex_zones - int m_imex_primary_head{ -1 }; // physical-head index of the primary tool in the active mode; -1 when no mode - std::string m_imex_zones_mode_cache{ "\x01" }; // cached mode+topology key; sentinel = unbuilt + // What the zones, the ghosts and m_imex_active_mode were last built from; nullopt rebuilds all three. + std::optional m_imex_layout_key; + unsigned m_imex_layout_key_version{ 0 }; // bumped whenever m_imex_layout_key changes + bool m_imex_zones_stale{ true }; // set when the key changes, cleared by the zone rebuild + // Resolved only when m_imex_layout_key changes, because find_imex_mode() copies the whole + // mode, G-code included. + struct ImexActiveMode + { + std::string tools; // the mode's imex_mode_active_tools entry; empty if there's none + int primary = -1; // physical head of the mode's Primary tool + bool resolved() const { return primary >= 0; } + }; + ImexActiveMode m_imex_active_mode; std::vector> m_imex_ghost_volumes; - std::string m_imex_ghost_cache_key{ "\x01" }; // sentinel = unbuilt + // The layout key version and the objects the ghosts were built from; nullopt = unbuilt. + std::optional m_imex_ghost_layout_version; + std::set> m_imex_ghost_objects; GLModel m_height_limit_common; GLModel m_height_limit_bottom; GLModel m_height_limit_top; @@ -233,16 +247,14 @@ private: void calc_gridlines(const ExPolygon& poly, const BoundingBox& pp_bbox); void calc_height_limit(); void calc_imex_zones(); - void ensure_imex_zones(); - std::string build_imex_cache_key() const; + void ensure_imex_zones(); // checks the layout key, then rebuild_stale_imex_zones() + void rebuild_stale_imex_zones(); // rebuilds the zones if they're stale; doesn't refresh the key + // Brings m_imex_layout_key up to date; when it changes, re-resolves m_imex_active_mode and + // marks the zones stale. Reads per-plate mode first, falling back to the process preset. + // render() calls it once a frame, and ensure_imex_zones() for callers outside render(). + void refresh_imex_layout_key(); void calc_imex_ghosts(); // full rebuild void ensure_imex_ghosts(); // cached rebuild on key change - std::string build_imex_ghost_cache_key() const; - // Resolves the currently-active IMEX mode's tools string + primary physical head. - // Plate override wins; else falls back to process preset `imex_parallel_mode`. - // Returns false (and leaves outputs untouched) if IMEX is off, mode is empty/"primary", - // mode config is missing, the mode isn't listed, or no primary is found. - bool resolve_active_mode_tools(std::string& out_tools_str, int& out_primary_phys) const; void render_imex_zones(bool force_default_color); void refresh_imex_icon(); float icon_scale_factor() const; @@ -273,6 +285,9 @@ private: void render_icon_texture(GLModel &buffer, GLTexture &texture); void set_hover_tooltip(const std::string& tooltip); void render_icons(bool bottom, bool only_name = false, int hover_id = -1); + // Returns true when IMEX parallel mode is active (non-primary) AND the plate + // has objects assigned to more than one filament — a combination that warrants caution. + bool has_imex_multimaterial_conflict() const; void render_only_numbers(bool bottom); void render_plate_name_texture(); void invalidate_plate_name_texture(); @@ -419,7 +434,7 @@ public: void update_imex_ghost_colors(); // Invalidate the ghost cache so the next render_imex_zones() call rebuilds fully. - void invalidate_imex_ghosts() { m_imex_ghost_cache_key = "\x01"; } + void invalidate_imex_ghosts() { m_imex_ghost_layout_version.reset(); } std::vector get_plate_wrapping_detection_area() const; @@ -635,9 +650,6 @@ public: // Footprint of the prime tower as the scene draws it, in scaled plate-list coords. // Empty when the plate has no tower. Polygon imex_wipe_tower_hull() const; - // Returns true when IMEX parallel mode is active (non-primary) AND the plate - // has objects assigned to more than one filament — a combination that warrants caution. - bool has_imex_multimaterial_conflict() const; // Returns the primary-zone bounding box in mm when an IDEX/IQEX parallel mode is active. // Empty (nullopt) when IDEX/IQEX is off or the mode is "primary" (full-bed). std::optional imex_primary_zone() { ensure_imex_zones(); return m_imex_primary_zone_box; } diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 1f4d41a686..4a9411294d 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -6305,6 +6305,14 @@ void Sidebar::sync_ams_list(bool is_from_big_sync_btn) auto & list = wxGetApp().preset_bundle->filament_ams_list; if (list.empty()) { + // Only an unreachable printer is "not connected". One that is online and has + // delivered at least one status push answered the request without listing any + // filament slot, and the message then names the machine that answered. + if (obj->is_connected() && obj->m_push_count > 0) { + p->plater->pop_warning_and_go_to_device_page(from_u8(obj->get_dev_name()), Plater::PrinterWarningType::NO_FILAMENT_SYSTEM, + _L("Sync printer information")); + return; + } auto printer_name = p->plater->get_selected_printer_name_in_combox(); p->plater->pop_warning_and_go_to_device_page(printer_name, Plater::PrinterWarningType::NOT_CONNECTED, _L("Sync printer information")); return; @@ -22561,6 +22569,9 @@ void Plater::pop_warning_and_go_to_device_page(wxString printer_name, PrinterWar content = _L("There are no filaments on the printer. Please load the filaments on the printer first."); } else if (type == PrinterWarningType::EMPTY_FILAMENT) { content = _L("The filaments on the printer are all unknown types. Please go to the printer screen or software device page to set the filament type."); + } else if (type == PrinterWarningType::NO_FILAMENT_SYSTEM) { + // TRN %s is the connected printer's name. + content = wxString::Format(_L("%s is connected, but no filament system (AMS, CFS or other multi-material unit) was found on it, so there are no filaments to synchronize."), printer_name); } MessageDialog dlg(this, content, title, wxOK | wxFORWARD | wxICON_WARNING, _L("Device Page")); auto result = dlg.ShowModal(); diff --git a/src/slic3r/GUI/Plater.hpp b/src/slic3r/GUI/Plater.hpp index 29e1723035..7f2ecc5205 100644 --- a/src/slic3r/GUI/Plater.hpp +++ b/src/slic3r/GUI/Plater.hpp @@ -715,7 +715,8 @@ public: NOT_CONNECTED, INCONSISTENT, UNINSTALL_FILAMENT, - EMPTY_FILAMENT + EMPTY_FILAMENT, + NO_FILAMENT_SYSTEM }; void pop_warning_and_go_to_device_page(wxString printer_name, PrinterWarningType type, const wxString &title); bool check_printer_initialized(MachineObject *obj, bool only_warning = false,bool popup_warning = true); diff --git a/src/slic3r/GUI/Preferences.cpp b/src/slic3r/GUI/Preferences.cpp index 4e502ac4ee..956f6dd41e 100644 --- a/src/slic3r/GUI/Preferences.cpp +++ b/src/slic3r/GUI/Preferences.cpp @@ -429,6 +429,7 @@ wxBoxSizer *PreferencesDialog::create_item_language_combobox(wxString title, wxS wxLANGUAGE_TURKISH, wxLANGUAGE_POLISH, wxLANGUAGE_CATALAN, + wxLANGUAGE_BASQUE, wxLANGUAGE_PORTUGUESE_BRAZILIAN, wxLANGUAGE_LITHUANIAN, wxLANGUAGE_VIETNAMESE, @@ -523,6 +524,9 @@ wxBoxSizer *PreferencesDialog::create_item_language_combobox(wxString title, wxS else if (vlist[i] == wxLocale::GetLanguageInfo(wxLANGUAGE_CATALAN)) { language_name = wxString::FromUTF8("Catalan"); } + else if (vlist[i] == wxLocale::GetLanguageInfo(wxLANGUAGE_BASQUE)) { + language_name = wxString::FromUTF8("Euskara"); + } else if (vlist[i] == wxLocale::GetLanguageInfo(wxLANGUAGE_PORTUGUESE_BRAZILIAN)) { language_name = wxString::FromUTF8("Português (Brasil)"); } diff --git a/src/slic3r/GUI/Widgets/Button.cpp b/src/slic3r/GUI/Widgets/Button.cpp index 63558245c8..2405ea23f5 100644 --- a/src/slic3r/GUI/Widgets/Button.cpp +++ b/src/slic3r/GUI/Widgets/Button.cpp @@ -16,11 +16,106 @@ #include #include #include +#include #include "slic3r/GUI/Widgets/StateColor.hpp" #include "slic3r/GUI/wxExtensions.hpp" #ifdef __APPLE__ #include "libslic3r/MacUtils.hpp" #endif +#include +#if wxUSE_ACCESSIBILITY +#include +#endif +#ifdef __WXOSX__ +#include "slic3r/GUI/Accessibility/AccessibilityMac.h" +#endif + +#if wxUSE_ACCESSIBILITY + +namespace { + +// Exposes the custom-drawn Button to screen readers. On Windows the base +// wxWindowAccessible reports every window as a generic client area, so NVDA and +// Narrator announce the label but not the button role. Overriding these +// callbacks reports the button as a push button with its name and state, and +// lets the screen reader activate it through DoDefaultAction. +class ButtonAccessible : public wxWindowAccessible +{ +public: + explicit ButtonAccessible(Button* btn) + : wxWindowAccessible(btn) + , m_btn(btn) + { + } + + wxAccStatus GetName(int childId, wxString* name) override + { + if (childId != wxACC_SELF) + return wxACC_NOT_IMPLEMENTED; + + *name = m_btn->GetLabel(); + if (name->empty()) + *name = m_btn->GetToolTipText(); + return name->empty() ? wxACC_NOT_IMPLEMENTED : wxACC_OK; + } + + wxAccStatus GetRole(int childId, wxAccRole* role) override + { + if (childId != wxACC_SELF) + return wxACC_NOT_IMPLEMENTED; + + *role = wxROLE_SYSTEM_PUSHBUTTON; + return wxACC_OK; + } + + wxAccStatus GetValue(int childId, wxString* strValue) override + { + if (childId != wxACC_SELF) + return wxACC_NOT_IMPLEMENTED; + + // A push button carries no value; expose an explicit empty one. + strValue->clear(); + return wxACC_OK; + } + + wxAccStatus GetState(int childId, long* state) override + { + if (childId != wxACC_SELF) + return wxACC_NOT_IMPLEMENTED; + + long st = 0; + if (!m_btn->IsEnabled()) + st |= wxACC_STATE_SYSTEM_UNAVAILABLE; + if (!m_btn->IsShown()) + st |= wxACC_STATE_SYSTEM_INVISIBLE; + if (m_btn->IsFocusable()) + st |= wxACC_STATE_SYSTEM_FOCUSABLE; + if (m_btn->HasFocus()) + st |= wxACC_STATE_SYSTEM_FOCUSED; + if (m_btn->GetValue()) + st |= wxACC_STATE_SYSTEM_PRESSED; + + *state = st; + return wxACC_OK; + } + + wxAccStatus DoDefaultAction(int childId) override + { + if (childId != wxACC_SELF) + return wxACC_NOT_IMPLEMENTED; + + m_btn->Click(); + return wxACC_OK; + } + +private: + Button* m_btn; +}; + +} // anonymous namespace + +#endif // wxUSE_ACCESSIBILITY + BEGIN_EVENT_TABLE(Button, StaticBox) EVT_LEFT_DOWN(Button::mouseDown) @@ -66,6 +161,10 @@ bool Button::Create(wxWindow* parent, wxString text, wxString icon, long style, this->active_icon = ScalableBitmap(this, icon.ToStdString(), iconSize > 0 ? iconSize : 20); } messureSize(); +#ifdef __WXOSX__ + applyAccessibility(); + Bind(wxEVT_DESTROY, [this](wxWindowDestroyEvent&) { Slic3r::GUI::Accessibility::detach(this); }); +#endif return true; } @@ -75,6 +174,10 @@ void Button::SetLabel(const wxString& label) wxWindow::SetLabel(label); messureSize(); Refresh(); +#ifdef __WXOSX__ + // Keep the accessible name in sync with the visible label. + applyAccessibility(); +#endif } } @@ -510,6 +613,45 @@ void Button::sendButtonEvent() GetEventHandler()->ProcessEvent(event); } +void Button::Click() +{ + if (IsEnabled()) + sendButtonEvent(); +} + +#ifdef __WXOSX__ +void Button::DoSetToolTipText(const wxString& tip) +{ + wxWindow::DoSetToolTipText(tip); + // Icon-only buttons are named by their tooltip, which callers set after Create(). + applyAccessibility(); +} + +void Button::DoEnable(bool enable) +{ + wxWindow::DoEnable(enable); + // Keep the accessibility enabled state in sync; wx cascades DoEnable to children + // when an ancestor is (re)enabled, and apply() reads the ancestor-aware IsEnabled(). + applyAccessibility(); +} + +void Button::applyAccessibility() +{ + Slic3r::GUI::Accessibility::Descriptor desc; + desc.role = Slic3r::GUI::Accessibility::Role::Button; + desc.name = GetLabel(); + desc.press = [this] { Click(); }; + Slic3r::GUI::Accessibility::apply(this, desc); +} +#endif + +#if wxUSE_ACCESSIBILITY +wxAccessible* Button::CreateAccessible() +{ + return new ButtonAccessible(this); +} +#endif + #ifdef __WIN32__ WXLRESULT Button::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam) diff --git a/src/slic3r/GUI/Widgets/Button.hpp b/src/slic3r/GUI/Widgets/Button.hpp index f5f675051f..dfd3738aa3 100644 --- a/src/slic3r/GUI/Widgets/Button.hpp +++ b/src/slic3r/GUI/Widgets/Button.hpp @@ -12,6 +12,7 @@ #include #include #include +#include class ButtonProps { @@ -113,11 +114,26 @@ public: void Rescale(); + // Programmatically activate the button, as if it had been clicked. Used by the + // accessibility layer to trigger the button from a screen reader. + void Click(); + +#if wxUSE_ACCESSIBILITY + // Return the accessible object that exposes this button's accessible name, role + // and state to screen readers. See ButtonAccessible in Button.cpp. + wxAccessible* CreateAccessible() override; +#endif + protected: #ifdef __WIN32__ WXLRESULT MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam) override; #endif +#ifdef __WXOSX__ + void DoSetToolTipText(const wxString& tip) override; + void DoEnable(bool enable) override; +#endif + bool AcceptsFocus() const override; private: @@ -140,6 +156,11 @@ private: // void sendButtonEvent(); +#ifdef __WXOSX__ + // (Re)expose this button to VoiceOver using its current label as the accessible name. + void applyAccessibility(); +#endif + // parent motion void OnParentMotion(wxMouseEvent& event); void OnParentLeave(wxMouseEvent& event); diff --git a/src/slic3r/GUI/Widgets/CheckBox.cpp b/src/slic3r/GUI/Widgets/CheckBox.cpp index c36a53d8af..f9461a1eaa 100644 --- a/src/slic3r/GUI/Widgets/CheckBox.cpp +++ b/src/slic3r/GUI/Widgets/CheckBox.cpp @@ -9,6 +9,9 @@ #ifdef __WXGTK__ #include "../GUI_Utils.hpp" #endif +#ifdef __WXOSX__ +#include "slic3r/GUI/Accessibility/AccessibilityMac.h" +#endif CheckBox::CheckBox(wxWindow *parent, int id) : wxBitmapToggleButton(parent, id, wxNullBitmap, wxDefaultPosition, wxDefaultSize, wxBORDER_NONE) @@ -38,6 +41,9 @@ CheckBox::CheckBox(wxWindow *parent, int id) #endif Rescale(); +#ifdef __WXOSX__ + applyAccessibility(); +#endif } void CheckBox::SetValue(bool value) @@ -135,5 +141,22 @@ void CheckBox::updateBitmap(wxEvent & evt) OnLeaveWindow(e); } } + +void CheckBox::DoSetToolTipText(const wxString& tip) +{ + wxWindow::DoSetToolTipText(tip); + // The accessible name comes from the tooltip, which callers set after construction. + applyAccessibility(); +} + +void CheckBox::applyAccessibility() +{ + // This is an NSButton-backed control, so apply() only fills in the accessible name + // and Voice Control identifier; the checkbox role, checked value and press action + // are already reported natively by AppKit. + Slic3r::GUI::Accessibility::Descriptor desc; + desc.role = Slic3r::GUI::Accessibility::Role::Checkbox; + Slic3r::GUI::Accessibility::apply(this, desc); +} #endif diff --git a/src/slic3r/GUI/Widgets/CheckBox.hpp b/src/slic3r/GUI/Widgets/CheckBox.hpp index bab691eb53..8b7e5acd9a 100644 --- a/src/slic3r/GUI/Widgets/CheckBox.hpp +++ b/src/slic3r/GUI/Widgets/CheckBox.hpp @@ -33,7 +33,9 @@ protected: #ifdef __WXOSX__ virtual wxBitmap DoGetBitmap(State which) const wxOVERRIDE; - + + virtual void DoSetToolTipText(const wxString& tip) wxOVERRIDE; + void updateBitmap(wxEvent & evt); bool m_disable = false; @@ -44,6 +46,13 @@ protected: private: void update(); +#ifdef __WXOSX__ + // Expose this checkbox to VoiceOver / Voice Control. Native NSButton-backed controls + // already report their role, value and press action, so this only supplies the + // accessible name and Voice Control identifier. + void applyAccessibility(); +#endif + private: ScalableBitmap m_on; ScalableBitmap m_half; diff --git a/src/slic3r/Utils/CrealityHostDiscovery.hpp b/src/slic3r/Utils/CrealityHostDiscovery.hpp index be9b85faa1..f441cef350 100644 --- a/src/slic3r/Utils/CrealityHostDiscovery.hpp +++ b/src/slic3r/Utils/CrealityHostDiscovery.hpp @@ -12,10 +12,10 @@ struct CrealityHost std::string ip; // dotted-quad IPv4 std::string service_name; // raw mDNS service type, e.g. "_Creality-543324280CDB19._udp.local." std::string hostname; // e.g. "K2-DB19" (derived from service-name suffix) - std::string model_code; // "F008" / "F012" / "F021" (empty if /info probe failed) - std::string model_name; // "K2 Plus" / "K2 Pro" / "K2" (empty if model not in our table) + std::string model_code; // "F008" / "F012" / "F021" on K2, literal name (e.g. "K1 Max") on K1-family (empty if /info probe failed) + std::string model_name; // display name from the CFS table, e.g. "K2 Plus" / "K1 Max" (empty if model not in our table) std::string mac; // from /info if probed - bool cfs_capable = false; // true when model_code is in the K2 family + bool cfs_capable = false; // true when model_code is in the CFS-capable table }; // Synchronous LAN discovery for Creality K-series printers via DNS-SD mDNS. @@ -28,10 +28,10 @@ struct CrealityHost // reliable way to find them. // // When probe_info is true, each discovered host is followed up with an HTTP -// GET http:///info call to fetch the printer's model code (F008/F012/F021) -// and MAC. The probe step adds ~2-4 seconds per host but yields enriched -// results that let the UI display "K2" / "K2 Plus" / "K2 Pro" instead of -// just an IP. +// GET http:///info call to fetch the printer's model code (F008/F012/F021 +// on K2, a literal model name on K1-family) and MAC. The probe step adds +// ~2-4 seconds per host but yields enriched results that let the UI display +// "K2 Plus" / "K1 Max" instead of just an IP. // // Call from a background thread -- the function blocks for at least 5 seconds. class CrealityHostDiscovery diff --git a/src/slic3r/Utils/CrealityPrint.cpp b/src/slic3r/Utils/CrealityPrint.cpp index ae52facc33..0d5eff4e5c 100644 --- a/src/slic3r/Utils/CrealityPrint.cpp +++ b/src/slic3r/Utils/CrealityPrint.cpp @@ -294,13 +294,18 @@ static void ws_close(net::io_context& ioc, websocket::stream& } // K1-family firmware stores gcodes under /usr/data and uses a stricter WebSocket -// protocol (TEXT frames, heartbeat acks). Add verified K1-family model IDs here. +// protocol (TEXT frames, heartbeat acks). The /info model is the literal name on +// K1-family, including the *_CFS-C bundle variants. Add verified model IDs here. static bool is_k1_family(const std::string& model) { static const std::unordered_set k1_models = { "K1", + "K1 Max", + "K1 Max_CFS-C", "K1 SE", + "K1 SE_CFS-C", "K1C", + "K1C_CFS-C", "K1_CFS-C", }; return k1_models.count(model) > 0; @@ -322,11 +327,16 @@ static const std::map& cfs_capable_models() static const std::map models = { {"F008", "K2 Plus"}, {"F012", "K2 Pro"}, + {"F016", "K2 SE"}, {"F021", "K2"}, {"F022", "SPARKX i7"}, {"K1", "K1"}, + {"K1 Max", "K1 Max"}, + {"K1 Max_CFS-C", "K1 Max_CFS-C"}, {"K1 SE", "K1 SE"}, + {"K1 SE_CFS-C", "K1 SE_CFS-C"}, {"K1C", "K1C"}, + {"K1C_CFS-C", "K1C_CFS-C"}, {"K1_CFS-C", "K1_CFS-C"}, }; return models; diff --git a/tests/fff_print/test_adaptive_pressure_advance.cpp b/tests/fff_print/test_adaptive_pressure_advance.cpp index 4383b8030c..ca852b3a52 100644 --- a/tests/fff_print/test_adaptive_pressure_advance.cpp +++ b/tests/fff_print/test_adaptive_pressure_advance.cpp @@ -95,18 +95,24 @@ TEST_CASE("The default adaptive pressure advance model holds no measurements", " CHECK(AdaptivePAProcessor::adaptive_pa_model_has_measurements("0.04,3.96,3000")); } -// The warnings Print::validate raises about the adaptive pressure advance model. -static std::vector adaptive_pa_model_warnings(const std::string &model) +// The warnings Print::validate raises about the adaptive pressure advance models, one per filament, +// when a cube is printed with the given filament. +static std::vector adaptive_pa_model_warnings(const std::vector &models, int filament = 1) { DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); config.set_deserialize_strict({ - { "enable_pressure_advance", "1" }, - { "adaptive_pressure_advance", "1" }, // the default config fails validation on relative extrusion without a G92 E0 at each layer { "use_relative_e_distances", "0" }, }); + for (const char *key : { "enable_pressure_advance", "adaptive_pressure_advance" }) + config.option(key)->values.assign(models.size(), true); + // the filament count is the number of filament diameters + config.option("filament_diameter")->values.assign(models.size(), 1.75); // set as a value so that an empty model stays one filament column, as a preset holds it - config.option("adaptive_pressure_advance_model")->values = { model }; + config.option("adaptive_pressure_advance_model")->values = models; + for (const char *key : { "outer_wall_filament_id", "inner_wall_filament_id", "sparse_infill_filament_id", + "internal_solid_filament_id", "top_surface_filament_id", "bottom_surface_filament_id" }) + config.option(key)->value = filament; Print print; Model model_instance; init_print({ cube(20) }, print, model_instance, config); @@ -121,6 +127,11 @@ static std::vector adaptive_pa_model_warnings(const std::string &mo return texts; } +static std::vector adaptive_pa_model_warnings(const std::string &model) +{ + return adaptive_pa_model_warnings(std::vector{ model }); +} + TEST_CASE("Slicing warns when adaptive pressure advance is enabled without a model", "[AdaptivePressureAdvance]") { const std::string default_model = DynamicPrintConfig::full_print_config().opt_string("adaptive_pressure_advance_model", 0u); @@ -141,3 +152,20 @@ TEST_CASE("Slicing warns about an adaptive pressure advance model whose flow is REQUIRE(warnings.size() == 1); CHECK(warnings.front().find("invalid values") != std::string::npos); } + +TEST_CASE("Slicing names the filament and the line of an invalid adaptive pressure advance model", "[AdaptivePressureAdvance]") +{ + // a period where the comma belongs leaves the second line with two values + const std::vector warnings = adaptive_pa_model_warnings("0.07,4.71,500\n0.04.7.53,1000\n0.035,9.41,1000"); + REQUIRE(warnings.size() == 1); + CHECK(warnings.front().find("filament 1") != std::string::npos); + CHECK(warnings.front().find("Line 2") != std::string::npos); +} + +TEST_CASE("Slicing names the second filament when its adaptive pressure advance model is invalid", "[AdaptivePressureAdvance]") +{ + const std::vector warnings = adaptive_pa_model_warnings({ "0.07,4.71,500\n0.035,9.41,1000", "0.07,4.71,500\n0.04.7.53,1000" }, 2); + REQUIRE(warnings.size() == 1); + CHECK(warnings.front().find("filament 2") != std::string::npos); + CHECK(warnings.front().find("Line 2") != std::string::npos); +} diff --git a/tests/fff_print/test_gcodeprocessor.cpp b/tests/fff_print/test_gcodeprocessor.cpp index 0bb0b33e3b..9653ef07d2 100644 --- a/tests/fff_print/test_gcodeprocessor.cpp +++ b/tests/fff_print/test_gcodeprocessor.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include "libslic3r/libslic3r.h" #include "libslic3r/BeltTransform.hpp" #include "libslic3r/BoundingBox.hpp" @@ -24,10 +25,12 @@ #include #include +#include #include #include #include "libslic3r/PrintConfig.hpp" #include "libslic3r/Point.hpp" +#include #include #include #include @@ -658,36 +661,57 @@ TEST_CASE("Each extrusion weighs its filament's density", "[GCodeProcessor]") namespace { -// Two nozzles over a 200 mm square bed: nozzle 1 reaches only `nozzle_1_area`, nozzle 2 the whole bed. -// A 20 mm cube centered on `center` prints with filament 1, mapped to nozzle 1. -void slice_cube_in_nozzle_area(const Vec2ds &nozzle_1_area, const Vec2d ¢er, GCodeProcessorResult &result) +// A printer with `nozzles` nozzles over a 200 mm square bed: nozzle `filament_1_nozzle` reaches only +// `nozzle_area`, the others the whole bed. A 20 mm cube centered on `center` prints with filament 1, +// mapped to that nozzle and printable on every nozzle. +void slice_cube_in_nozzle_area(const Vec2ds &nozzle_area, const Vec2d ¢er, GCodeProcessorResult &result, int nozzles = 2, + int filament_1_nozzle = 1) { + const auto per_nozzle = [nozzles](const std::string &value) { + std::string values = value; + for (int i = 1; i < nozzles; ++i) + values += "," + value; + return values; + }; + std::string extruder_ids = "1"; + for (int i = 2; i <= nozzles; ++i) + extruder_ids += "," + std::to_string(i); DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); config.set_deserialize_strict({ - { "nozzle_diameter", "0.4,0.4" }, - { "printer_extruder_id", "1,2" }, - { "printer_extruder_variant", "Direct Drive Standard,Direct Drive Standard" }, - { "extruder_offset", "0x0,0x0" }, + { "nozzle_diameter", per_nozzle("0.4") }, + { "printer_extruder_id", extruder_ids }, + { "printer_extruder_variant", per_nozzle("Direct Drive Standard") }, + { "extruder_offset", per_nozzle("0x0") }, { "printable_area", "0x0,200x0,200x200,0x200" }, { "printable_height", 100 }, - { "extruder_printable_height", "100,100" }, + { "extruder_printable_height", per_nozzle("100") }, + // One filament, so one purge volume per nozzle, as the GUI and the CLI size it. + { "flush_volumes_matrix", per_nozzle("0") }, { "skirt_loops", 0 }, { "brim_type", "no_brim" }, + { "layer_change_gcode", "G92 E0\n" }, // validate() relative-E reset { "filament_map_mode", "Manual" }, - { "filament_map", "1" }, + { "filament_map", filament_1_nozzle }, + { "filament_printable", -1 }, }); + // Other per-nozzle printer options, at their defaults. + for (const char *key : { "extruder_type", "nozzle_volume_type", "min_layer_height", "max_layer_height", "extruder_max_nozzle_count" }) + dynamic_cast(config.option(key))->resize(nozzles); const Vec2ds bed { Vec2d(0., 0.), Vec2d(200., 0.), Vec2d(200., 200.), Vec2d(0., 200.) }; - config.set_key_value("extruder_printable_area", new ConfigOptionPointsGroups(std::vector{ nozzle_1_area, bed })); + std::vector areas(nozzles, bed); + areas[filament_1_nozzle - 1] = nozzle_area; + config.set_key_value("extruder_printable_area", new ConfigOptionPointsGroups(areas)); TriangleMesh mesh = Test::cube(20); mesh.translate(float(center.x() - 10.), float(center.y() - 10.), 0.f); Print print; Model model; Test::init_print(std::vector{ std::move(mesh) }, print, model, config, nullptr, false); + REQUIRE_THAT(print.validate().string, Catch::Matchers::Equals(std::string())); Test::gcode(print, &result); } -// Nozzle 1's area inset from the bed on one side, on two adjacent sides (leaving an L-shaped +// A nozzle's area inset from the bed on one side, on two adjacent sides (leaving an L-shaped // unprintable region), on three (a U) and on all four (a frame). Each contains the bed center and // has an X 150 edge; all but the first also have a Y 50 edge, meeting it in an inner corner. Vec2ds inset_nozzle_area(int sides) @@ -802,3 +826,63 @@ TEST_CASE("A filament mapped to no nozzle has no errors listed under a nozzle", CHECK(result.gcode_check_result.print_area_error_infos.count(-1) == 0); } + +TEST_CASE("Nozzles up to the 64th are marked as unable to print a filament they can't", "[GCodeProcessor][Regression]") +{ + // 64 nozzles over a 200 mm square bed. Filament 1 maps to one of them and prints a 20 mm square + // at X 160-180, Y 100-120, Z 10, which that nozzle alone can't print. + const int nozzle = GENERATE(1, 31, 32, 63); // 0-based + CAPTURE(nozzle); + const Vec2ds bed { Vec2d(0., 0.), Vec2d(200., 0.), Vec2d(200., 200.), Vec2d(0., 200.) }; + std::vector unprintable_areas(MAXIMUM_EXTRUDER_NUMBER); + std::vector printable_heights(MAXIMUM_EXTRUDER_NUMBER, 100.); + std::vector> unprintable_filament_types(MAXIMUM_EXTRUDER_NUMBER); + int expected_error = 0; + SECTION("it can't reach the square") + { + const Vec2ds nozzle_area { Vec2d(0., 0.), Vec2d(150., 0.), Vec2d(150., 200.), Vec2d(0., 200.) }; + unprintable_areas[nozzle] = diff(Polygon::new_scale(bed), Polygon::new_scale(nozzle_area)); + expected_error = 1; + } + SECTION("the square is above its printable height") + { + printable_heights[nozzle] = 5.; + expected_error = 1 << 1; + } + SECTION("it can't print the filament's type") { unprintable_filament_types[nozzle] = { 0 }; } + + GCodeProcessor processor; + for (const Vec2d &point : { Vec2d(160., 100.), Vec2d(180., 100.), Vec2d(180., 120.), Vec2d(160., 120.) }) { + GCodeProcessorResult::MoveVertex move; + move.type = EMoveType::Extrude; + move.extrusion_role = erExternalPerimeter; + move.extruder_id = 0; // filament 1 + move.object_label_id = 1; + move.position = Vec3f(float(point.x()), float(point.y()), 10.f); + move.print_z = 10.f; + processor.result().moves.emplace_back(move); + } + processor.check_multi_extruder_gcode_valid(int(MAXIMUM_EXTRUDER_NUMBER), bed, 100., {}, unprintable_areas, printable_heights, + { nozzle + 1 }, unprintable_filament_types); + const GCodeProcessorResult &result = processor.result(); + + CHECK(result.gcode_check_result.error_code == expected_error); + REQUIRE(result.limit_filament_maps.size() == 1); + CHECK(result.limit_filament_maps[0] == uint64_t(1) << nozzle); +} + +TEST_CASE("A cube on the 64th nozzle of a 64-nozzle printer slices, and fails the area check only outside that nozzle's area", "[GCodeProcessor][Regression]") +{ + // Filament 1 maps to nozzle 64, which reaches X 0-150. The cube sits at the bed center, or at X 165-185. + const int nozzles = 64; + const bool outside = GENERATE(false, true); + INFO("cube " << (outside ? "outside" : "inside") << " nozzle 64's area"); + GCodeProcessorResult result; + slice_cube_in_nozzle_area(inset_nozzle_area(1), outside ? Vec2d(175., 100.) : Vec2d(100., 100.), result, nozzles, nozzles); + + const int expected = outside ? 1 : 0; + CHECK((result.gcode_check_result.error_code & 1) == expected); + CHECK(result.gcode_check_result.print_area_error_infos.count(nozzles - 1) == size_t(expected)); + REQUIRE(result.limit_filament_maps.size() == 1); + CHECK(result.limit_filament_maps[0] == uint64_t(expected) << (nozzles - 1)); +} diff --git a/tests/fff_print/test_print.cpp b/tests/fff_print/test_print.cpp index d8bfd7c533..d960334d0f 100644 --- a/tests/fff_print/test_print.cpp +++ b/tests/fff_print/test_print.cpp @@ -561,6 +561,40 @@ TEST_CASE("Print: {first_object_name} is not replaced by the saved-project file CHECK(resolved_output_name(model, "{first_object_name}", "SavedProject") == "WidgetPart.gcode"); } +TEST_CASE("{printing_filament_types} lists the filament types really printed", "[Print]") +{ + // Two filaments of different types. The start G-code uses the placeholder too: it has to + // resolve there as well as in the file name. + DynamicPrintConfig config = multifilament_config(2, { + { "filament_type", "ABS;PLA" }, + { "enable_prime_tower", 0 }, + { "filename_format", "{printing_filament_types}-{filament_type[initial_tool]}" }, + { "machine_start_gcode", "; printing types: {printing_filament_types}" }, + }); + + SECTION("only the filament the object is printed with, not filament 1") { + const std::vector> overrides{ { { "extruder", 2 } } }; + Print print; + Model model; + init_print({ cube(20) }, print, model, config, &overrides); + const std::string gcode = Slic3r::Test::gcode(print); + + CHECK(gcode.find("; printing types: PLA\n") != std::string::npos); + CHECK(print.output_filename() == "PLA-PLA.gcode"); + } + + SECTION("every type printed, joined with an underscore") { + const std::vector> overrides{ { { "extruder", 1 } }, { { "extruder", 2 } } }; + Print print; + Model model; + init_print({ cube(20), cube(20) }, print, model, config, &overrides); + const std::string gcode = Slic3r::Test::gcode(print); + + CHECK(gcode.find("; printing types: ABS_PLA\n") != std::string::npos); + CHECK(print.output_filename() == "ABS_PLA-ABS.gcode"); + } +} + TEST_CASE("Print::validate stacks independent warnings", "[Print][validate]") { // Two unrelated checks (region precise-wall + machine acceleration) must each diff --git a/tests/fff_print/test_wipe_tower.cpp b/tests/fff_print/test_wipe_tower.cpp index 20b6ef373c..86d6f2a6dc 100644 --- a/tests/fff_print/test_wipe_tower.cpp +++ b/tests/fff_print/test_wipe_tower.cpp @@ -10,6 +10,7 @@ #include "libslic3r/Print.hpp" #include #include +#include #include #include @@ -23,6 +24,7 @@ #include "libslic3r/BoundingBox.hpp" #include "libslic3r/ClipperUtils.hpp" #include "libslic3r/GCode/GCodeProcessor.hpp" +#include "libslic3r/GCodeReader.hpp" #include "libslic3r/GCode/WipeTower.hpp" #include "libslic3r/LocalesUtils.hpp" #include "libslic3r/PrintConfig.hpp" @@ -573,3 +575,101 @@ TEST_CASE("Only a cone wall gives the tower a stabilization cone", "[WipeTower]" CHECK_FALSE(print.get_conflict_result().has_value()); } } + +TEST_CASE("Without sparse layers the filament change starts at the tallest printed layer", "[WipeTower]") +{ + // Filament 2 on top surfaces only, so the layers between the short cube's top and the tall + // cube's top have no toolchange and the tower skips them: at the tall cube's top it is still + // about 2 mm high. A custom change_filament_gcode may travel anywhere, and so may the firmware + // Tn of a switch to another physical extruder, so neither may start that low. + const std::string tower_type = GENERATE("type1", "type2"); + const bool two_nozzles = GENERATE(false, true); + const bool custom_macro = GENERATE(true, false); + DynamicPrintConfig config = multifilament_config(2, { + { "top_surface_filament_id", 2 }, + { "enable_prime_tower", true }, + { "wipe_tower_type", tower_type }, + { "wipe_tower_no_sparse_layers", true }, + { "wipe_tower_x", 30 }, + { "wipe_tower_y", 30 }, + { "layer_height", 0.2 }, + { "change_filament_gcode", custom_macro ? "; TOOLCHANGE_MARK\n" : "" }, + { "gcode_comments", true }, + { "timelapse_type", "0" }, + { "enable_wrapping_detection", false }, + { "raft_layers", "0" } }); + if (two_nozzles) { + config.set_num_extruders(2); + config.set_deserialize_strict({ + { "single_extruder_multi_material", false }, + { "nozzle_diameter", "0.4,0.4" }, + { "printer_extruder_id", "1,2" }, + { "printer_extruder_variant", "Direct Drive Standard,Direct Drive Standard" }, + { "extruder_printable_height", "0,0" }, + { "filament_map_mode", "Manual" }, + { "filament_map", "1,2" } }); + size_flush_to_nozzles(config); + } + + const double short_height = 2., tall_height = 10.; + TriangleMesh tall = make_cube(10., 10., tall_height); + tall.translate(120.f, 120.f, 0.f); + TriangleMesh low = make_cube(10., 10., short_height); + low.translate(150.f, 120.f, 0.f); + + Print print; + Model model; + init_print({ std::move(tall), std::move(low) }, print, model, config, nullptr, false); + print.apply(model, config); + const std::string gcode = Slic3r::Test::gcode(print); + + // Z where each change_filament_gcode or Tn starts, next to the highest Z of the objects + // extruded before it; and the Z of each tower extrusion once the objects pass the short cube. + std::vector> changes; + std::vector> tower_extrusions; + double object_z = 0.; + bool in_tower = false; + size_t lifts = 0; + GCodeReader parser; + parser.parse_buffer(gcode, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) { + const std::string_view raw = line.raw(); + // Objects are tagged with the processor's ;TYPE:, the tower with its own ; FEATURE:. + if (raw.rfind(";TYPE:", 0) == 0 || raw.rfind("; FEATURE: ", 0) == 0) + in_tower = raw.find("Prime tower") != std::string_view::npos; + else if (line.extruding(self) && (line.has_x() || line.has_y())) { // not an unretract + if (!in_tower) + object_z = std::max(object_z, double(self.z())); + // Above the tall cube is the final unload, printed over the finished parts on purpose. + else if (object_z > short_height + EPSILON && self.z() <= tall_height + EPSILON) + tower_extrusions.emplace_back(self.z(), object_z); + } else if (raw.find("; TOOLCHANGE_MARK") != std::string_view::npos + || (raw.size() > 1 && raw[0] == 'T' && raw[1] >= '0' && raw[1] <= '9')) + changes.emplace_back(self.z(), object_z); + if (raw.find("Restore layer Z before toolchange") != std::string_view::npos) + ++lifts; + }); + INFO(tower_type << (two_nozzles ? ", two nozzles" : ", one nozzle") << (custom_macro ? ", custom macro" : ", empty macro")); + + if (!custom_macro && !two_nozzles) { + // Nothing travels during the change, so the toolhead stays down at the tower. + CHECK(lifts == 0); + } else { + size_t above_short = 0; + for (const auto &[change_z, printed_z] : changes) { + if (printed_z <= short_height + EPSILON) + continue; + ++above_short; + INFO("toolchange at Z " << change_z << ", printed up to Z " << printed_z); + CHECK(change_z >= printed_z - EPSILON); + } + // The tall cube's top surface needs at least one change above the short cube. + CHECK(above_short > 0); + } + + // Every lift has to come back down: the tower keeps printing at its compacted height. + REQUIRE_FALSE(tower_extrusions.empty()); + for (const auto &[tower_z, printed_z] : tower_extrusions) { + INFO("tower extrusion at Z " << tower_z << ", printed up to Z " << printed_z); + CHECK(tower_z < printed_z - EPSILON); + } +} diff --git a/tests/libslic3r/test_imex_zones.cpp b/tests/libslic3r/test_imex_zones.cpp index 67123854e8..a2f2bac22f 100644 --- a/tests/libslic3r/test_imex_zones.cpp +++ b/tests/libslic3r/test_imex_zones.cpp @@ -2,6 +2,8 @@ #include #include +#include +#include #include #include @@ -577,3 +579,85 @@ TEST_CASE("an aggregated gantry raises its collision strip from the zone it pain } } } + +TEST_CASE("a plate's IMEX layout key changes with each input of its zones and ghosts", "[IMEXZones]") +{ + PrinterCfg p; + p.active_tools = "0:P,1:M"; + DynamicPrintConfig cfg = make_cfg(p); + cfg.set_key_value("imex_firmware_managed_zones", new ConfigOptionBool(false)); + std::string mode = kMode; + const DynamicPrintConfig* cfg_ptr = &cfg; + + std::optional key; + REQUIRE(update_imex_layout_key(key, cfg_ptr, mode)); + REQUIRE_FALSE(update_imex_layout_key(key, cfg_ptr, mode)); + + SECTION("imex_gantry_count") { cfg.set_key_value("imex_gantry_count", new ConfigOptionInt(2)); } + SECTION("imex_tools_per_gantry") { cfg.set_key_value("imex_tools_per_gantry", new ConfigOptionInt(3)); } + SECTION("imex_tool_layout") + { + cfg.set_deserialize_strict("imex_tool_layout", ConfigOptionEnum(ImexToolLayout::RearRight).serialize()); + } + // Clearances and the margin are compared exactly, so even 0.05 mm counts. + SECTION("imex_nozzle_clearance_x") { cfg.set_key_value("imex_nozzle_clearance_x", new ConfigOptionFloat(0.05)); } + SECTION("imex_nozzle_clearance_y") { cfg.set_key_value("imex_nozzle_clearance_y", new ConfigOptionFloat(0.05)); } + SECTION("imex_carriage_margin") { cfg.set_key_value("imex_carriage_margin", new ConfigOptionFloat(0.05)); } + SECTION("imex_firmware_managed_zones") { cfg.set_key_value("imex_firmware_managed_zones", new ConfigOptionBool(true)); } + SECTION("the plate's mode") { mode = kImexPrimaryMode; } + SECTION("the printer config going away") { cfg_ptr = nullptr; } + SECTION("the mode's roster, under the same name") { cfg.option("imex_mode_active_tools")->values[1] = "0:P,1:C"; } + // The plate's mode no longer names a row, so it has no zones. + SECTION("the mode's name in the table") { cfg.option("imex_mode_names")->values[1] = "renamed"; } + SECTION("another mode in the table") + { + cfg.option("imex_mode_names")->values.emplace_back("other"); + cfg.option("imex_mode_active_tools")->values.emplace_back("0:P,1:C"); + } + + CHECK(update_imex_layout_key(key, cfg_ptr, mode)); + CHECK_FALSE(update_imex_layout_key(key, cfg_ptr, mode)); +} + +TEST_CASE("a plate's IMEX layout key ignores a mode's G-code and settles on a NaN clearance", "[IMEXZones]") +{ + PrinterCfg p; + p.active_tools = "0:P,1:M"; + DynamicPrintConfig cfg = make_cfg(p); + cfg.set_key_value("imex_mode_gcodes", new ConfigOptionStrings(std::vector{ std::string(), "M400" })); + + std::optional key; + REQUIRE(update_imex_layout_key(key, &cfg, kMode)); + + SECTION("a mode's G-code, which moves no zone") + { + cfg.option("imex_mode_gcodes")->values[1] = "G28"; + CHECK_FALSE(update_imex_layout_key(key, &cfg, kMode)); + } + // A clearance field accepts "nan". Setting it changes the key once, then the key holds still. + SECTION("a NaN clearance") + { + cfg.set_key_value("imex_nozzle_clearance_x", new ConfigOptionFloat(std::nan(""))); + CHECK(update_imex_layout_key(key, &cfg, kMode)); + CHECK_FALSE(update_imex_layout_key(key, &cfg, kMode)); + } +} + +TEST_CASE("a plate's IMEX layout key ignores the IMEX inputs while IMEX is off", "[IMEXZones]") +{ + PrinterCfg p; + p.is_imex = false; + p.active_tools = "0:P,1:M"; + DynamicPrintConfig cfg = make_cfg(p); + + std::optional key; + REQUIRE(update_imex_layout_key(key, &cfg, kMode)); + cfg.set_key_value("imex_nozzle_clearance_x", new ConfigOptionFloat(5.0)); + cfg.option("imex_mode_active_tools")->values[1] = "0:P,1:C"; + CHECK_FALSE(update_imex_layout_key(key, &cfg, "other")); + // No printer config at all reads the same as IMEX off. + CHECK_FALSE(update_imex_layout_key(key, nullptr, kMode)); + + cfg.set_key_value("is_imex", new ConfigOptionBool(true)); + CHECK(update_imex_layout_key(key, &cfg, kMode)); +} diff --git a/tests/libslic3r/test_preset_bundle_loading.cpp b/tests/libslic3r/test_preset_bundle_loading.cpp index dc5325d725..c36299c8ba 100644 --- a/tests/libslic3r/test_preset_bundle_loading.cpp +++ b/tests/libslic3r/test_preset_bundle_loading.cpp @@ -5691,6 +5691,58 @@ TEST_CASE("An empty AMS slot between loaded single-colour slots keeps every slot CHECK(multi[i] == colours[i]); } +// A user preset carries its system parent's filament_id, so a slot holding one for the filament a +// tray reports keeps it through a sync; a slot whose tray holds another filament takes that filament. +TEST_CASE("Syncing the AMS keeps a slot's user preset for the tray's filament", "[Preset][Bundle][AMS]") +{ + PresetBundle bundle; + auto add_filament = [&](const std::string &name, const std::string &inherits, const std::string &filament_id, bool is_system) { + Preset &preset = add_inmemory_preset(bundle.filaments, name, inherits); + preset.is_system = is_system; + preset.filament_id = filament_id; + }; + add_filament("System PLA", "", "GFA00", true); + add_filament("System PETG", "", "GFG00", true); + add_filament("My PLA", "System PLA", "GFA00", false); + bundle.set_num_filaments(2u, std::string("#111111")); + + auto add_tray = [&](int slot, const std::string &filament_id, const std::string &type, const std::string &colour) { + DynamicPrintConfig config; + config.set_key_value("filament_id", new ConfigOptionStrings{filament_id}); + config.set_key_value("filament_colour", new ConfigOptionStrings{colour}); + config.set_key_value("filament_colour_type", new ConfigOptionStrings{"1"}); + config.set_key_value("filament_multi_colour", new ConfigOptionStrings{}); + config.set_key_value("ams_id", new ConfigOptionStrings{"0"}); + config.set_key_value("slot_id", new ConfigOptionStrings{std::to_string(slot)}); + config.set_key_value("filament_type", new ConfigOptionStrings{type}); + bundle.filament_ams_list.emplace(slot, std::move(config)); + }; + std::vector> unknowns; + MergeFilamentInfo merge_info; + + SECTION("overriding the project, with an empty tray among the loaded ones") { + bundle.filament_presets = {"My PLA", "My PLA"}; + add_tray(0, "GFA00", "PLA", "#FF0000"); + add_tray(1, "GFG00", "PETG", "#00FF00"); + add_tray(2, "", "", ""); + std::map maps; + REQUIRE(bundle.sync_ams_list(unknowns, false, maps, true, merge_info) == 2); + CHECK(bundle.filament_presets == std::vector{"My PLA", "System PETG"}); + } + + // Slots pair with trays through the map, not by position: slot 1 holds the PLA in tray 0. + // Tray 2 is an unmapped backup spool of the same PLA and colour, so it is not appended. + SECTION("mapping project slots to trays") { + bundle.filament_presets = {"System PETG", "My PLA"}; + add_tray(0, "GFA00", "PLA", "#FF0000"); + add_tray(1, "GFG00", "PETG", "#00FF00"); + add_tray(2, "GFA00", "PLA", "#FF0000"); + std::map maps{{0, {"0", "1"}}, {1, {"0", "0"}}}; + REQUIRE(bundle.sync_ams_list(unknowns, true, maps, true, merge_info) == 2); + CHECK(bundle.filament_presets == std::vector{"System PETG", "My PLA"}); + } +} + TEST_CASE("Loading incomplete mixed metadata normalizes slots before adding a filament", "[Preset][Bundle][FilamentMixer]") { DynamicPrintConfig config = DynamicPrintConfig::full_print_config();