diff --git a/docs/HLSD/center-of-mass.md b/docs/HLSD/center-of-mass.md index 40f866e8e4..0c2cb6af62 100644 --- a/docs/HLSD/center-of-mass.md +++ b/docs/HLSD/center-of-mass.md @@ -164,12 +164,13 @@ The markers drawn last are kept, and a left click is tested against them before center and a point a radius to its right are projected to the screen, and the click hits a marker within that distance. The solid markers are tested before the faded ones and the smaller kinds before the larger, the order in which they cover each other. A hit opens the details of that marker -and keeps the click from changing the selection; a click anywhere else, or Esc, closes them. The box is an +and keeps the click from changing the selection; a left or right click anywhere else, or Esc, closes them. The box is an ImGui window beside the marker, redrawn with the overlay from the markers of the last scene, so it follows a dragged object, and in Preview the layer slider. It closes when its marker is gone, or when the number of markers of its kind changes, as then it may stand for something else. As it moves with the view, zooming toward the cursor can bring it under the mouse, so the wheel zooms over it rather -than going to ImGui. +than going to ImGui. It also covers the model, so a drag that starts on it, off its close button, +turns or pans the view as one over empty space would. Its title says what the marker stands for: the plate, an object, an assembly or a part, the body of an assembly. The G-code export lists the object instances for the processor, marking assemblies, as diff --git a/src/OrcaSlicer.cpp b/src/OrcaSlicer.cpp index db81911722..8c2766b33d 100644 --- a/src/OrcaSlicer.cpp +++ b/src/OrcaSlicer.cpp @@ -3223,6 +3223,29 @@ int CLI::run(int argc, char **argv) std::vector& inherits_group = m_print_config.option("inherits_group", true)->values; inherits_group.resize(filament_count + 2, std::string()); different_settings.resize(filament_count + 2, std::string()); + // More filaments loaded than the project defines: the project grows to the loaded count, so + // every per-filament table from here on covers the loaded slots. The two slot lists above and + // compatible_machine_expression_group keep the printer in their last slot, so the new filament + // slots go in before it. + const int project_defined_filament_count = filament_count; + if (filament_count < load_filament_count) { + // An empty --load-filaments entry keeps the project's filament in that slot, so past the project's count + // it has nothing to keep; only --load-defaultfila fills such a slot, and then it is in load_filaments_index. + for (int slot = filament_count + 1; slot <= load_filament_count; slot++) { + if (std::find(load_filaments_index.begin(), load_filaments_index.end(), slot) == load_filaments_index.end()) { + boost::nowide::cerr << boost::format("--load-filaments slot %1% is empty, but the project defines only %2% filaments, so there is none to keep in it") % slot % filament_count << std::endl; + record_exit_reson(outfile_dir, CLI_INVALID_PARAMS, 0, cli_errors[CLI_INVALID_PARAMS], sliced_info); + flush_and_exit(CLI_INVALID_PARAMS); + } + } + BOOST_LOG_TRIVIAL(info) << boost::format("%1% filaments loaded on a project with %2%, growing the project to %1%") % load_filament_count % filament_count; + inherits_group.insert(inherits_group.begin() + filament_count + 1, load_filament_count - filament_count, std::string()); + different_settings.insert(different_settings.begin() + filament_count + 1, load_filament_count - filament_count, std::string()); + if (auto *machine_expressions = m_print_config.option("compatible_machine_expression_group"); + machine_expressions != nullptr && machine_expressions->values.size() == size_t(filament_count + 2)) + machine_expressions->values.insert(machine_expressions->values.begin() + filament_count + 1, load_filament_count - filament_count, std::string()); + filament_count = load_filament_count; + } if (!is_bbl_3mf && !different_process_setting.empty()) { different_settings[0] = different_process_setting; } @@ -3546,26 +3569,31 @@ int CLI::run(int argc, char **argv) max_self_index = std::max(max_self_index, v); min_self_index = std::min(min_self_index, v); } - // And a project saved with FEWER filaments than are now loaded (a - // one-filament project sliced with two --load-filaments) leaves the tables half filled: - // the variant matching below then reads past filament_extruder_variant and - // set_with_restore_2 throws an uncaught size error. Regenerate in that case too. - if (max_self_index > filament_count || min_self_index < 1 || max_self_index < filament_count - || (int) filament_self_index_opt->values.size() < filament_count) { + // A project saved with fewer filaments than are now loaded has grown to the loaded + // count above; its own layout is checked against the count it was saved with, and + // the loaded filaments are appended below. + if (max_self_index > project_defined_filament_count || min_self_index < 1 || max_self_index < project_defined_filament_count + || (int) filament_self_index_opt->values.size() < project_defined_filament_count) { BOOST_LOG_TRIVIAL(warning) << boost::format("filament_self_index range [%1%, %2%] (size %4%) is invalid for filament_count %3%, regenerating") - % min_self_index % max_self_index % filament_count % filament_self_index_opt->values.size(); + % min_self_index % max_self_index % project_defined_filament_count % filament_self_index_opt->values.size(); need_regenerate_self_index = true; } } if (need_regenerate_self_index) { filament_self_index_opt = m_print_config.option("filament_self_index", true); std::vector& filament_self_indice = filament_self_index_opt->values; - filament_self_indice.resize(filament_count); - for (int index = 0; index < filament_count; index++) + filament_self_indice.resize(project_defined_filament_count); + for (int index = 0; index < project_defined_filament_count; index++) filament_self_indice[index] = index + 1; } std::vector old_self_indice= filament_self_index_opt->values; + // A filament loaded beyond the project's count gets one variant of its own, appended after + // the project's layout so the project's filaments keep their variant groups. Only this copy + // grows: normalize_filament_values_to_variants below lays the project's per-variant values + // out by its own filament_self_index, and the config's index is rebuilt after the loop. + for (int index = project_defined_filament_count + 1; index <= filament_count; index++) + old_self_indice.push_back(index); int old_self_indice_size = old_self_indice.size(); int k = -1, current_filament = 0; for (size_t i = 0; i < old_self_indice_size; i++) { diff --git a/src/libslic3r/AppConfig.cpp b/src/libslic3r/AppConfig.cpp index 19142e3d97..68ad793545 100644 --- a/src/libslic3r/AppConfig.cpp +++ b/src/libslic3r/AppConfig.cpp @@ -996,8 +996,15 @@ std::string AppConfig::load(bool read_only) local_machine.printer_type = p["printer_type"].get(); if (p.contains("printer_agent_id")) local_machine.printer_agent_id = p["printer_agent_id"].get(); + // Entries saved before agents were recorded have none. Bambu printers are keyed by + // serial number; the other agents used the address, which is the IP or has a '.' or ':'. + if (local_machine.printer_agent_id.empty() && local_machine.dev_id != local_machine.dev_ip && + local_machine.dev_id.find_first_of(".:") == std::string::npos) + local_machine.printer_agent_id = "bbl"; if (p.contains("access_code")) local_machine.access_code = p["access_code"].get(); + if (p.contains("ca_file")) + local_machine.ca_file = p["ca_file"].get(); m_local_machines[local_machine.dev_id] = local_machine; } } else { @@ -1211,6 +1218,8 @@ void AppConfig::save() m_json["printer_type"] = local_machine.second.printer_type; m_json["printer_agent_id"] = local_machine.second.printer_agent_id; m_json["access_code"] = local_machine.second.access_code; + if (!local_machine.second.ca_file.empty()) + m_json["ca_file"] = local_machine.second.ca_file; j["local_machines"][local_machine.first] = m_json; } diff --git a/src/libslic3r/AppConfig.hpp b/src/libslic3r/AppConfig.hpp index 852080c50c..d2294313cf 100644 --- a/src/libslic3r/AppConfig.hpp +++ b/src/libslic3r/AppConfig.hpp @@ -82,7 +82,7 @@ struct BBLocalMachine std::string dev_ip; std::string dev_id; /* serial number */ std::string printer_type; /* model_id */ - std::string printer_agent_id; /* id of the IPrinterAgent that discovered/bound this device, e.g. "bbl"; empty for entries persisted before this field existed */ + std::string printer_agent_id; /* id of the IPrinterAgent that discovered/bound this device, e.g. "bbl"; empty for non-Bambu entries persisted before this field existed */ // Access code, scoped to printer_agent_id above - so a code saved while bound under one // printer agent isn't treated as valid for a different, independent agent talking to the // same physical dev_id. Empty for entries persisted before this field existed; those fall @@ -90,11 +90,14 @@ struct BBLocalMachine // since BBL was the only agent when they were saved) - see // get_access_code_with_legacy_fallback() in DevManager.cpp. std::string access_code; + // Path of a CA certificate the user chose in the connect dialog, for a printer behind a proxy + // with its own CA. Kept per device, never taken from a printer preset. + std::string ca_file; bool operator==(const BBLocalMachine& other) const { return dev_name == other.dev_name && dev_ip == other.dev_ip && dev_id == other.dev_id && printer_type == other.printer_type && - printer_agent_id == other.printer_agent_id && access_code == other.access_code; + printer_agent_id == other.printer_agent_id && access_code == other.access_code && ca_file == other.ca_file; } bool operator!=(const BBLocalMachine& other) const { return !operator==(other); } }; diff --git a/src/libslic3r/CutUtils.cpp b/src/libslic3r/CutUtils.cpp index 71833e4a45..3796696cdb 100644 --- a/src/libslic3r/CutUtils.cpp +++ b/src/libslic3r/CutUtils.cpp @@ -1,5 +1,6 @@ #include "CutUtils.hpp" +#include "Config.hpp" #include "Geometry.hpp" #include "Point.hpp" #include "TriangleMesh.hpp" @@ -70,7 +71,10 @@ static void add_cut_volume(TriangleMesh& mesh, ModelObject* object, const ModelV vol->config.assign_config(src_volume->config); assert(vol->config.id().valid()); assert(vol->config.id() != src_volume->config.id()); - vol->set_material(src_volume->material_id(), *src_volume->material()); + // The id is all that needs carrying: the cut model carries no material settings, and the id resolves + // against the material of the model the result is added to. Copying the material here would replace + // the source object's own entry, which Model::add_material deletes before copying from it. + vol->set_material_id(src_volume->material_id()); vol->cut_info = src_volume->cut_info; } @@ -437,30 +441,96 @@ static void distribute_modifiers_from_object(ModelObject* from_obj, const int in } } +// The identity that decides how a solid part is sliced and colored: filament, material and the +// per-part process overrides. A part inherits the object's config, so a value is read from the volume +// when it sets it and from the object otherwise: restating the object's value does not split the part. +static std::string part_group_key(const ModelVolume& mv) +{ + // The material id and the serialized values are length-prefixed, so a value containing ';' or '=' + // cannot make two different parts share a key. + std::string key = std::to_string(std::max(1, mv.extruder_id())) + "|"; + key += std::to_string(mv.material_id().size()) + ":" + mv.material_id() + "|"; + const ModelObject& object = *mv.get_object(); + t_config_option_keys opt_keys = object.config.keys(); + for (const std::string& opt_key : mv.config.keys()) + if (!object.config.has(opt_key)) + opt_keys.push_back(opt_key); + std::sort(opt_keys.begin(), opt_keys.end()); + for (const std::string& opt_key : opt_keys) { + if (opt_key == "extruder") + continue; + const std::string value = mv.config.has(opt_key) ? mv.config.opt_serialize(opt_key) : object.config.opt_serialize(opt_key); + key += opt_key + "=" + std::to_string(value.size()) + ":" + value + ";"; + } + return key; +} + static void merge_solid_parts_inside_object(ModelObjectPtrs& objects) { + struct Group + { + std::string key; + TriangleMesh mesh; + const ModelVolume* representative = nullptr; + }; + for (ModelObject* mo : objects) { - TriangleMesh mesh; - // Merge all SolidPart but not Connectors - for (const ModelVolume* mv : mo->volumes) { - if (mv->is_model_part() && !mv->is_cut_connector()) { - TriangleMesh m = mv->mesh(); - m.transform(mv->get_matrix()); - mesh.merge(m); + // Merge all SolidPart but not Connectors, keeping parts with a different slicing identity apart. + std::vector originals; + std::vector groups; + for (ModelVolume* mv : mo->volumes) { + if (!mv->is_model_part() || mv->is_cut_connector()) + continue; + originals.push_back(mv); + const std::string key = part_group_key(*mv); + auto group = std::find_if(groups.begin(), groups.end(), [&key](const Group& g) { return g.key == key; }); + if (group == groups.end()) { + groups.push_back({key, TriangleMesh(), mv}); + group = groups.end() - 1; } + TriangleMesh m = mv->mesh(); + m.transform(mv->get_matrix()); + group->mesh.merge(m); } - if (!mesh.empty()) { - ModelVolume* new_volume = mo->add_volume(mesh); - new_volume->name = mo->name; - // Delete all merged SolidPart but not Connectors - for (int i = int(mo->volumes.size()) - 2; i >= 0; --i) { - const ModelVolume* mv = mo->volumes[i]; - if (mv->is_model_part() && !mv->is_cut_connector()) - mo->delete_volume(i); + + bool created = false; + for (Group& group : groups) { + if (group.mesh.empty()) + continue; + + ModelVolume* new_volume = mo->add_volume(std::move(group.mesh)); + if (!created) { + new_volume->name = mo->name; + } else { + // Number the extra parts as splitting a mesh into parts does; the first part keeps the object's name. + const auto name_taken = [mo](const std::string& n) { + return std::any_of(mo->volumes.begin(), mo->volumes.end(), [&n](const ModelVolume* v) { return v->name == n; }); + }; + std::string name; + int suffix = 2; + do + name = mo->name + "_" + std::to_string(suffix++); + while (name_taken(name)); + new_volume->name = name; } - // Ensuring that volumes start with solid parts for proper slicing - mo->sort_volumes(true); + // Don't copy the config's ID. + new_volume->config.assign_config(group.representative->config); + // Only the material id is carried; the cut model has no material table for its settings. + new_volume->set_material_id(group.representative->material_id()); + created = true; } + + if (!created) + continue; + + // Delete the merged SolidPart but not Connectors, matched by pointer. + for (size_t i = mo->volumes.size(); i > 0; --i) { + const ModelVolume* mv = mo->volumes[i - 1]; + if (std::find(originals.begin(), originals.end(), mv) != originals.end()) + mo->delete_volume(i - 1); + } + // Ensuring that volumes start with solid parts for proper slicing + mo->sort_volumes(true); } } diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index ae63ee16b5..f9532718c4 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -11023,6 +11023,27 @@ std::string GCode::set_extruder(unsigned int new_filament_id, double print_z, bo } std::string gcode; + + // Same suppression as the long multi-extruder path: at print-start in IMEX + // parallel modes the user's mode_gcode + machine_start_gcode is responsible + // for tool selection, so the slicer's bare T would be a duplicate. Mid- + // print toolchanges (count > 1) emit normally — Print::validate() blocks + // multi-color in configurations where mid-print T wouldn't make sense + // (see imex_multicolor_block_reason). + const std::string toolchange_command = m_writer.toolchange(new_filament_id, new_extruder_id); + const bool emit_toolchange = !toolchange_command.empty() && !imex_suppresses_bare_toolchange(m_imex_parallel_mode, m_toolchange_count); + if (emit_toolchange) + gcode += toolchange_command; + if (Extruder *fil = m_writer.filament()) + fil->set_config_index((int)get_filament_config_index((int)fil->id())); + // Firmware can change the temperature on a T command, so set it again here, as the multi-extruder path below does. + if (emit_toolchange && m_config.single_extruder_multi_material && !m_config.enable_prime_tower) { + size_t new_fi = get_filament_config_index(new_filament_id); + int temp = (m_layer_index <= 0 ? m_config.nozzle_temperature_initial_layer.get_at(new_fi) : + m_config.nozzle_temperature.get_at(new_fi)); + gcode += m_writer.set_temperature(temp, false); + } + // Append the filament start G-code. const std::string &filament_start_gcode = m_config.filament_start_gcode.get_at(new_filament_id); if (! filament_start_gcode.empty()) { @@ -11048,17 +11069,6 @@ std::string GCode::set_extruder(unsigned int new_filament_id, double print_z, bo gcode += set_filament_pressure_advance(new_filament_id, imex_pem_tool_for((int) new_filament_id, m_imex_parallel_mode, m_config.physical_extruder_map)); - // Same suppression as the long multi-extruder path: at print-start in IMEX - // parallel modes the user's mode_gcode + machine_start_gcode is responsible - // for tool selection, so the slicer's bare T would be a duplicate. Mid- - // print toolchanges (count > 1) emit normally — Print::validate() blocks - // multi-color in configurations where mid-print T wouldn't make sense - // (see imex_multicolor_block_reason). - const std::string toolchange_command = m_writer.toolchange(new_filament_id, new_extruder_id); - if (!imex_suppresses_bare_toolchange(m_imex_parallel_mode, m_toolchange_count)) - gcode += toolchange_command; - if (Extruder *fil = m_writer.filament()) - fil->set_config_index((int)get_filament_config_index((int)fil->id())); if (position_before_toolchange) this->synchronize_toolchange_position(*position_before_toolchange, gcode); return gcode; diff --git a/src/libslic3r/GCode/GCodeProcessor.cpp b/src/libslic3r/GCode/GCodeProcessor.cpp index 6c0a770069..f306100afd 100644 --- a/src/libslic3r/GCode/GCodeProcessor.cpp +++ b/src/libslic3r/GCode/GCodeProcessor.cpp @@ -2844,7 +2844,7 @@ void GCodeProcessor::register_commands() {"G3", [this](const GCodeReader::GCodeLine& line) { process_G2_G3(line, false); }}, // Move {"G4", [this](const GCodeReader::GCodeLine& line) { process_G4(line); }}, // Delay - {"G10", [this](const GCodeReader::GCodeLine& line) { process_G10(line); }}, // Retract + {"G10", [this](const GCodeReader::GCodeLine& line) { process_G10(line); }}, // Retract, or set tool temperature on RepRapFirmware {"G11", [this](const GCodeReader::GCodeLine& line) { process_G11(line); }}, // Unretract {"G20", [this](const GCodeReader::GCodeLine& line) { process_G20(line); }}, // Set Units to Inches @@ -6405,6 +6405,20 @@ void GCodeProcessor::process_G29(const GCodeReader::GCodeLine& line) void GCodeProcessor::process_G10(const GCodeReader::GCodeLine& line) { + // Orca: RepRapFirmware's G10 with parameters sets tool temperatures, offsets or workplaces, only a bare G10 retracts + if (m_flavor == gcfRepRapFirmware && + (line.has('P') || line.has('R') || line.has('S') || line.has('L') || line.has_x() || line.has_y() || line.has_z())) { + float new_temp; + if (line.has_value('S', new_temp)) { + float tool; + const int filament_id = line.has_value('P', tool) ? static_cast(tool) : get_filament_id(); + // Orca: RRF turns a heater off with a negative temperature + if (filament_id >= 0 && filament_id < static_cast(m_extruder_temps.size())) + m_extruder_temps[filament_id] = std::max(new_temp, 0.f); + } + return; + } + // Emulate G1 retract, decrement G1 count as it's will be incremented in process_G1, but it's fake G1 GCodeReader::GCodeLine g10; g10.set(Axis::E, -this->m_parser.config().retraction_length.get_at(m_extruder_id)); diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index 7c6e14638f..ba03c9bc71 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -1309,24 +1309,6 @@ bool Model::is_fuzzy_skin_painted() const return std::any_of(this->objects.cbegin(), this->objects.cend(), [](const ModelObject *mo) { return mo->is_fuzzy_skin_painted(); }); } -static void add_cut_volume(TriangleMesh& mesh, ModelObject* object, const ModelVolume* src_volume, const Transform3d& cut_matrix, const std::string& suffix = {}, ModelVolumeType type = ModelVolumeType::MODEL_PART) -{ - if (mesh.empty()) - return; - - mesh.transform(cut_matrix); - ModelVolume* vol = object->add_volume(mesh); - vol->set_type(type); - - vol->name = src_volume->name + suffix; - // Don't copy the config's ID. - vol->config.assign_config(src_volume->config); - assert(vol->config.id().valid()); - assert(vol->config.id() != src_volume->config.id()); - vol->set_material(src_volume->material_id(), *src_volume->material()); - vol->cut_info = src_volume->cut_info; -} - ModelObject::~ModelObject() { this->clear_volumes(); @@ -2125,7 +2107,11 @@ void ModelObject::convert_units(ModelObjectPtrs& new_objects, ConversionType con vol->config.assign_config(volume->config); assert(vol->config.id().valid()); assert(vol->config.id() != volume->config.id()); - vol->set_material(volume->material_id(), *volume->material()); + // The clone is detached while it is rebuilt; point it at the source model so set_material_id() + // can record the entry, and detach it again. + new_object->set_model(this->get_model()); + vol->set_material_id(volume->material_id()); + new_object->set_model(nullptr); vol->source.input_file = volume->source.input_file; vol->source.object_idx = (int)new_objects.size(); vol->source.volume_idx = vol_idx; @@ -2778,13 +2764,6 @@ ModelMaterial* ModelVolume::material() const return this->object->get_model()->get_material(m_material_id); } -void ModelVolume::set_material(t_model_material_id material_id, const ModelMaterial &material) -{ - m_material_id = material_id; - if (! material_id.empty()) - this->object->get_model()->add_material(material_id, material); -} - // Extract the current extruder ID based on this ModelVolume's config and the parent ModelObject's config. int ModelVolume::extruder_id() const { diff --git a/src/libslic3r/Model.hpp b/src/libslic3r/Model.hpp index 5f7220cd93..c59ec6db75 100644 --- a/src/libslic3r/Model.hpp +++ b/src/libslic3r/Model.hpp @@ -1053,7 +1053,6 @@ public: void set_material_id(t_model_material_id material_id); void reset_extra_facets(); ModelMaterial* material() const; - void set_material(t_model_material_id material_id, const ModelMaterial &material); // Extract the current extruder ID based on this ModelVolume's config and the parent ModelObject's config. // Extruder ID is only valid for FFF. Returns -1 for SLA or if the extruder ID is not applicable (support volumes). int extruder_id() const; diff --git a/src/libslic3r/Preset.cpp b/src/libslic3r/Preset.cpp index 6742e63f23..e26ca52ab6 100644 --- a/src/libslic3r/Preset.cpp +++ b/src/libslic3r/Preset.cpp @@ -3990,13 +3990,13 @@ size_t PresetCollection::first_visible_idx_by_type(const std::string& filament_t return idx; } - // 3. Any visible preset - return first_visible_idx(); + return size_t(-1); } std::string PresetCollection::filament_id_by_type(const std::string& filament_type) const { - return preset(first_visible_idx_by_type(filament_type)).filament_id; + const size_t idx = first_visible_idx_by_type(filament_type); + return idx == size_t(-1) ? std::string() : preset(idx).filament_id; } std::vector PresetCollection::diameters_of_selected_printer() diff --git a/src/libslic3r/Preset.hpp b/src/libslic3r/Preset.hpp index fbdd00dd86..f0f0190d84 100644 --- a/src/libslic3r/Preset.hpp +++ b/src/libslic3r/Preset.hpp @@ -825,9 +825,9 @@ public: size_t first_visible_idx() const; // Return the index of the first visible, compatible, system base preset - // matching the given filament_type. Falls back to base type, then any visible. + // matching the given filament_type, falling back to its base type; size_t(-1) when neither is found. size_t first_visible_idx_by_type(const std::string& filament_type) const; - // Return the filament_id of the best-matching visible preset for the given filament type. + // Return the filament_id of the best-matching visible preset for the given filament type; empty when none. std::string filament_id_by_type(const std::string& filament_type) const; // Return index of the first compatible preset. Certainly at least the '- default -' preset shall be compatible. // If one of the prefered_alternates is compatible, select it. diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 28d2ea324e..1c90f33458 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -907,7 +907,7 @@ StringObjectException Print::sequential_print_clearance_valid(const Print &print // Place of the instance in print.model()'s object and instance lists. Copies of one object get // one PrintObject per distinct transformation, so print.objects() does not list them in order. std::pair model_position; - double height; // top above the bed, raft included (object_top below) + double height; // top above the bed, raft included (PrintObject::print_z_max) // Whether the instance reaches above extruder_clearance_height_to_rod, and the Y extent of it // the rod can hit while a later instance prints (see above_rod_y_range). bool has_above_rod = false; @@ -928,17 +928,9 @@ StringObjectException Print::sequential_print_clearance_valid(const Print &print } const bool skirt_reaches_rod = print.has_infinite_skirt() || (print.config().skirt_loops > 0 && print.config().skirt_height * max_layer_height > rod_height); - // Top of an instance above the bed, scaled. object_print_z_max includes the raft and the Z shrinkage - // compensation, like the printable-height check in validate(). On a belt printer it is the height in the - // tilted slicing frame, so there the model's own top is used, as that check does; a raft is refused there. - const bool belt_printer = print.config().belt_printer.value; - auto object_top = [belt_printer](const PrintInstance &instance) -> double { - return belt_printer ? instance.print_object->max_z() - : scale_(instance.print_object->slicing_parameters().object_print_z_max); - }; - auto above_rod_y_range = [rod_height, &object_top](const PrintInstance &instance, coord_t &min_y, coord_t &max_y) -> bool { + auto above_rod_y_range = [rod_height](const PrintInstance &instance, coord_t &min_y, coord_t &max_y) -> bool { // Skip the mesh walk for the common case of an object whose top, raft included, doesn't reach the rod. - if (object_top(instance) <= scale_(rod_height)) + if (instance.print_object->print_z_max() <= scale_(rod_height)) return false; // Mesh Z this far below the rod prints above it once the raft lifts the object. const double rod_z = rod_height - instance.print_object->slicing_parameters().object_print_z_min; @@ -1074,7 +1066,7 @@ StringObjectException Print::sequential_print_clearance_valid(const Print &print } } struct print_instance_info print_info {&instance, convex_hull.bounding_box(), convex_hull}; - print_info.height = object_top(instance); + print_info.height = instance.print_object->print_z_max(); print_info.model_position = model_position_of(print.model(), instance.model_instance); print_info.has_above_rod = above_rod_y_range(instance, print_info.rod_min_y, print_info.rod_max_y); const BoundingBox footprint = print_info.bounding_box.inflated(-scale_(0.5 * print.config().extruder_clearance_radius.value + object_skirt_offset)); @@ -1534,7 +1526,7 @@ StringObjectException Print::compacted_wipe_tower_clearance_valid(const Print &p Polygons offenders; bool body_tier_used = false; for (const PrintObject *object : print.objects()) { - const double object_top = unscaled(object->max_z()); + const double object_top = unscaled(object->print_z_max()); for (const PrintInstance &instance : object->instances()) { const Polygon inst_hull = compacted_tower_print_instance_hull(*object, instance); if (inst_hull.points.empty()) @@ -1648,7 +1640,7 @@ void Print::validate_compacted_wipe_tower_clearance() const return; for (const PrintObject *object : m_objects) { - const double object_top = unscaled(object->max_z()); + const double object_top = unscaled(object->print_z_max()); for (const PrintInstance &instance : object->instances()) { const Polygon inst_hull = compacted_tower_print_instance_hull(*object, instance); if (inst_hull.points.empty()) @@ -5694,8 +5686,8 @@ void Print::_make_wipe_tower() // Lets go through the wipe tower layers and determine pairs of extruder changes for each // to pass to wipe_tower (so that it can use it for planning the layout of the tower) + unsigned int current_extruder_id = m_wipe_tower_data.tool_ordering.all_extruders().back(); { - unsigned int current_extruder_id = m_wipe_tower_data.tool_ordering.all_extruders().back(); for (auto &layer_tools : m_wipe_tower_data.tool_ordering.layer_tools()) { // for all layers if (!layer_tools.has_wipe_tower) continue; @@ -5756,10 +5748,13 @@ void Print::_make_wipe_tower() } else { // There is yet enough space at this layer of the wipe tower for the final purge. } + } else if (m_config.single_extruder_multi_material || m_config.filament_multitool_ramming.get_at(current_extruder_id)) { + // The tower stops below the last print layer, but the last filament has to ram out. Unload at the + // object's top layer so the nozzle doesn't descend into the part on its way to the tower. + wipe_tower.set_layer(float(m_wipe_tower_data.tool_ordering.back().print_z), float(layer_height), 0, false, true); } else { - // The wipe tower does not reach the last print layer. + // The wipe tower does not reach the last print layer and nothing needs ramming. // Skip final purge to avoid generating purge lines in mid-air. - assert(m_wipe_tower_data.tool_ordering.back().wipe_tower_partitions == 0); generate_final_purge = false; } m_wipe_tower_data.final_purge = generate_final_purge diff --git a/src/libslic3r/Print.hpp b/src/libslic3r/Print.hpp index 38627daeea..be4fe4df33 100644 --- a/src/libslic3r/Print.hpp +++ b/src/libslic3r/Print.hpp @@ -405,6 +405,10 @@ public: // The height is snug. coord_t height() const { return m_size.z(); } double max_z() const { return m_max_z; } + // Top of the printed object above the bed, scaled: object_print_z_max of the slicing parameters, so the + // raft and the Z shrinkage compensation count, as in the printable-height check of Print::validate(). + // On a belt printer that is the height in the tilted slicing frame, so the model's own top is used there. + double print_z_max() const; // Centering offset of the sliced mesh from the scaled and rotated mesh of the model. const Point& center_offset() const { return m_center_offset; } const AdaptiveInfillField* adaptive_infill_field(AdaptiveInfillMode mode) const { return m_adaptive_infill_fields[size_t(mode)].get(); } @@ -1398,7 +1402,7 @@ public: static int get_compatible_filament_type(const std::set& types); bool is_all_objects_are_short() const { - return std::all_of(this->objects().begin(), this->objects().end(), [&](PrintObject* obj) { return obj->height() < scale_(this->config().nozzle_height.value); }); + return std::all_of(this->objects().begin(), this->objects().end(), [&](PrintObject* obj) { return obj->print_z_max() < scale_(this->config().nozzle_height.value); }); } // Post-slicing config-slot resolvers: map a (filament, layer) pair to the index of its diff --git a/src/libslic3r/PrintObject.cpp b/src/libslic3r/PrintObject.cpp index 81001c06cb..1265b0856b 100644 --- a/src/libslic3r/PrintObject.cpp +++ b/src/libslic3r/PrintObject.cpp @@ -4433,8 +4433,8 @@ PrintRegionConfig region_config_from_model_volume(const PrintRegionConfig &defau // default_or_parent_region_config contains parent PrintRegion config, which already contains ModelVolume's config. } apply_to_print_region_config(config, volume.config.get(), feature_overrides, variant_index); - if (! volume.material_id().empty()) - apply_to_print_region_config(config, volume.material()->config.get(), feature_overrides, variant_index); + if (const ModelMaterial* material = volume.material(); material != nullptr) + apply_to_print_region_config(config, material->config.get(), feature_overrides, variant_index); if (layer_range_config != nullptr) { // Not applicable to modifiers. assert(volume.is_model_part()); @@ -4478,6 +4478,11 @@ void PrintObject::generate_support_preview() profiler.duration2 = (ts3 - ts2).total_milliseconds(); } +double PrintObject::print_z_max() const +{ + return this->print()->config().belt_printer.value ? m_max_z : scale_(m_slicing_params.object_print_z_max); +} + void PrintObject::update_slicing_parameters() { // Orca: updated function call for XYZ shrinkage compensation diff --git a/src/slic3r/GUI/DeviceCore/DevManager.cpp b/src/slic3r/GUI/DeviceCore/DevManager.cpp index b84e5bf533..be59142997 100644 --- a/src/slic3r/GUI/DeviceCore/DevManager.cpp +++ b/src/slic3r/GUI/DeviceCore/DevManager.cpp @@ -66,6 +66,14 @@ namespace { } return ""; } + + // Scoped to the agent like the access code above; there is no legacy flat key to fall back to. + std::string get_stored_ca_file(Slic3r::AppConfig* config, const std::string& dev_id, const std::string& agent_id) + { + const auto& machines = config->get_local_machines(); + auto it = machines.find(dev_id); + return it != machines.end() && it->second.printer_agent_id == agent_id ? it->second.ca_file : ""; + } } namespace Slic3r @@ -110,6 +118,7 @@ namespace Slic3r obj->m_is_online = true; obj->last_alive = Slic3r::Utils::get_current_time_utc(); obj->set_access_code(get_access_code_with_legacy_fallback(config, m.dev_id, obj->printer_agent_id), false); + obj->set_ca_file(m.ca_file, false); if (obj->has_access_right()) { localMachineList.insert(std::make_pair(m.dev_id, obj)); } else { @@ -131,6 +140,7 @@ namespace Slic3r local_machine.printer_type = m.printer_type; local_machine.printer_agent_id = m.printer_agent_id; local_machine.access_code = m.get_access_code(); + local_machine.ca_file = m.get_ca_file(); config->update_local_machine(local_machine); } } else { @@ -446,6 +456,7 @@ namespace Slic3r //load access code if (config) { obj->set_access_code(get_access_code_with_legacy_fallback(config, dev_id, obj->printer_agent_id), false); + obj->set_ca_file(get_stored_ca_file(config, dev_id, obj->printer_agent_id), false); } localMachineList.insert(std::make_pair(dev_id, obj)); @@ -478,11 +489,13 @@ namespace Slic3r std::string version, std::string access_code) { MachineObject* obj; - auto it = localMachineList.find(machine.dev_id); + bool agent_changed = false; + auto it = localMachineList.find(machine.dev_id); if (it != localMachineList.end()) { obj = it->second; // insert_local_device is called by the active agent, so a reused entry must follow // that agent as well; otherwise the agent-scoped printer list hides it. + agent_changed = obj->printer_agent_id != get_current_printer_agent_id(); obj->printer_agent_id = get_current_printer_agent_id(); } else { obj = new MachineObject(this, m_agent, machine.dev_name, machine.dev_id, machine.dev_ip); @@ -500,6 +513,8 @@ namespace Slic3r obj->m_is_online = true; obj->last_alive = Slic3r::Utils::get_current_time_utc(); obj->set_access_code(access_code, false); + if ((agent_changed || obj->get_ca_file().empty()) && get_app_config()) + obj->set_ca_file(get_stored_ca_file(get_app_config(), machine.dev_id, obj->printer_agent_id), false); update_local_machine(*obj, get_app_config()); diff --git a/src/slic3r/GUI/DeviceManager.cpp b/src/slic3r/GUI/DeviceManager.cpp index 31fe6e6438..9fe22c8c80 100644 --- a/src/slic3r/GUI/DeviceManager.cpp +++ b/src/slic3r/GUI/DeviceManager.cpp @@ -579,6 +579,15 @@ void MachineObject::set_access_code(std::string code, bool only_refresh) } } +void MachineObject::set_ca_file(std::string path, bool only_refresh) +{ + ca_file = std::move(path); + if (only_refresh && is_lan_mode_printer() && has_access_right()) { + if (AppConfig* config = m_manager ? m_manager->get_app_config() : GUI::wxGetApp().app_config) + DeviceManager::update_local_machine(*this, config); + } +} + std::string MachineObject::get_show_printer_type() const { std::string printer_type = this->printer_type; @@ -1200,12 +1209,14 @@ void MachineObject::parse_home_flag(int flag) m_fila_system->GetAmsSystemSetting().SetAutoRefillEnabled(((flag >> 10) & 0x1) != 0); } - is_support_flow_calibration = ((flag >> 15) & 0x1) != 0; - if (this->is_series_o()) { is_support_flow_calibration = false; } // todo: Temp modification due to incorrect machine push message for H2D - - is_support_pa_calibration = ((flag >> 16) & 0x1) != 0; - if (this->is_series_p()) { is_support_pa_calibration = false; } // todo: Temp modification due to incorrect machine push message for P + if (!((is_support_flow_calibration || is_support_pa_calibration) && this->is_series_n())) { // modification: Protect A1/A1 mini legacy firmware capability reporting. If either capability is already reported as supported, preserve it; otherwise, fall back to home_flag bits for newer firmware. + is_support_flow_calibration = ((flag >> 15) & 0x1) != 0; + if (this->is_series_o()) { is_support_flow_calibration = false; } // todo: Temp modification due to incorrect machine push message for H2D + is_support_pa_calibration = ((flag >> 16) & 0x1) != 0; + if (this->is_series_p()) { is_support_pa_calibration = false; } // todo: Temp modification due to incorrect machine push message for P + } + if (time(nullptr) - xcam_prompt_sound_hold_start > HOLD_TIME_3SEC) { xcam_allow_prompt_sound = ((flag >> 17) & 0x1) != 0; } @@ -2706,13 +2717,20 @@ int MachineObject::connect() // bare IP as dev_ip, so take the port from the dev_id rather than falling back to port 80. if (port.empty() && connects_through_moonraker_agent(printer_agent_id)) Http::get_host_from_url(get_dev_id(), &port); - std::string ca_file; + // A Bambu printer's CA is chosen per device in the connect dialog. Never take it from the + // selected preset: it may belong to another printer, or come from an imported profile. + // A local machine saved before agent ids existed belongs to the agent that connects it now. + const std::string agent_id = !printer_agent_id.empty() ? printer_agent_id : + m_manager ? m_manager->get_current_printer_agent_id() : std::string(); + const bool is_bbl = agent_id == BBL_PRINTER_AGENT_ID; + std::string ca_file = is_bbl ? get_ca_file() : std::string(); if (wxTheApp && GUI::wxGetApp().preset_bundle) { const auto& config = GUI::wxGetApp().preset_bundle->printers.get_edited_preset().config; if (port.empty()) port = config.opt_string("printhost_port"); - ca_file = config.opt_string("printhost_cafile"); + if (!is_bbl) + ca_file = config.opt_string("printhost_cafile"); // Refresh credentials from the matching preset for connections that bypass GUI_App::select_machine(). const std::string print_host = config.opt_string("print_host"); diff --git a/src/slic3r/GUI/DeviceManager.hpp b/src/slic3r/GUI/DeviceManager.hpp index 455d37fe49..8944a769d0 100644 --- a/src/slic3r/GUI/DeviceManager.hpp +++ b/src/slic3r/GUI/DeviceManager.hpp @@ -119,6 +119,7 @@ private: std::string dev_name; std::string dev_ip; std::string access_code; + std::string ca_file; bool m_access_revoked = false; // type, time stamp, delay @@ -234,6 +235,9 @@ public: void revoke_access(); std::string get_access_code() const; void set_access_code(std::string code, bool only_refresh = true); + // CA certificate the user chose for this LAN printer (see BBLocalMachine::ca_file). + std::string get_ca_file() const { return ca_file; } + void set_ca_file(std::string path, bool only_refresh = true); //PRINTER_TYPE printer_type = PRINTER_3DPrinter_UKNOWN; std::string printer_type; /* model_id */ diff --git a/src/slic3r/GUI/FilamentBitmapUtils.cpp b/src/slic3r/GUI/FilamentBitmapUtils.cpp index 0e6370e50c..db0ee3f71f 100644 --- a/src/slic3r/GUI/FilamentBitmapUtils.cpp +++ b/src/slic3r/GUI/FilamentBitmapUtils.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -28,6 +29,7 @@ #include #include #include +#include #include "FilamentBitmapUtils.hpp" #include "GUI_App.hpp" @@ -73,10 +75,19 @@ void tri_barycentric(TriPoint p, TriPoint v0, TriPoint v1, TriPoint v2, TriPoint tri_clamp(TriPoint p, TriPoint v0, TriPoint v1, TriPoint v2) { - double w0, w1, w2; - tri_barycentric(p, v0, v1, v2, w0, w1, w2); - return {w0 * v0.x + w1 * v1.x + w2 * v2.x, - w0 * v0.y + w1 * v1.y + w2 * v2.y}; + if (tri_contains(p, v0, v1, v2)) + return p; + // Snap a point outside to the nearest point on the outline. + auto closest_on_edge = [p](TriPoint a, TriPoint b) { + const double dx = b.x - a.x, dy = b.y - a.y; + const double len2 = dx * dx + dy * dy; + const double t = len2 > 0 ? std::clamp(((p.x - a.x) * dx + (p.y - a.y) * dy) / len2, 0.0, 1.0) : 0.0; + return TriPoint{a.x + t * dx, a.y + t * dy}; + }; + auto dist2 = [p](TriPoint q) { return (q.x - p.x) * (q.x - p.x) + (q.y - p.y) * (q.y - p.y); }; + const std::array candidates{closest_on_edge(v0, v1), closest_on_edge(v1, v2), closest_on_edge(v2, v0)}; + return *std::min_element(candidates.begin(), candidates.end(), + [&dist2](TriPoint a, TriPoint b) { return dist2(a) < dist2(b); }); } static void fill_gradient_rect_east(wxDC& dc, const wxRect& rect, const wxColour* colors, size_t count) @@ -529,7 +540,7 @@ constexpr double kPlotLeftRatio = 0.0316; constexpr double kPlotRightRatio = 0.6766; constexpr double kPlotTopRatio = 0.1529; constexpr double kPlotBottomRatio = 0.8474; -constexpr int kGridDivisions = 9; // 10 grid lines including the outer borders. +constexpr int kGridDivisions = 10; // 10% steps, 11 grid lines including the outer borders. constexpr int kStrokeAxis = 2; // axis line width (px, no DPI scaling) constexpr int kAxisArrowHalf = 5; // half-base of the axis arrow triangle (DIP) constexpr int kAxisArrowLen = 10; // length of the axis arrow triangle (DIP) @@ -552,6 +563,58 @@ wxColour lerp_blend(const wxColour& a, const wxColour& b, double ratio_a) // window parameter explicitly; nullptr picks the app's default DPI like the Publish dialog does. int dip_px(int v) { return wxWindow::FromDIP(v, nullptr); } +using Dash = std::pair; + +// Splits the line a -> b into 1 DIP dashes separated by 2 DIP gaps. The line gets a whole number +// of dash + gap periods, so the dashes meet both ends evenly. +void add_dashes(std::vector& dashes, TriPoint a, TriPoint b) +{ + const double dash = dip_px(1); + const double period = dash + dip_px(2); + const int count = std::max(1, int(std::lround(std::hypot(b.x - a.x, b.y - a.y) / period))); + auto at = [&a, &b](double t) { return TriPoint{a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)}; }; + for (int j = 0; j < count; ++j) + dashes.emplace_back(at(double(j) / count), at((j + dash / period) / count)); +} + +// Dark dashes over a light fill, white ones over a dark fill. +wxColour dash_colour(double luminance) { return luminance > 0.5 ? wxColour(38, 46, 48) : *wxWHITE; } + +// The anti-aliased graphics context of `dc`, or one created over it and kept alive by `owned`. +// Null when wx cannot wrap the dc. Drop `owned` before drawing on the dc again. +wxGraphicsContext* graphics_context(wxDC& dc, std::unique_ptr& owned) +{ + wxGraphicsContext* gc = dc.GetGraphicsContext(); + if (!gc) { + owned.reset(wxGraphicsContext::CreateFromUnknownDC(dc)); + gc = owned.get(); + } + if (gc) + gc->SetAntialiasMode(wxANTIALIAS_DEFAULT); + return gc; +} + +// Strokes the dashes at sub-pixel positions through `gc`, so all dashes of one line stay +// collinear. Without a graphics context they are drawn on `dc`, rounded to whole pixels. +void stroke_dashes(wxDC& dc, wxGraphicsContext* gc, const std::vector& dashes, const wxColour& colour) +{ + if (gc) { + gc->SetPen(gc->CreatePen(wxGraphicsPenInfo(colour, dip_px(1)).Cap(wxCAP_BUTT))); + wxGraphicsPath path = gc->CreatePath(); + for (const auto& [p0, p1] : dashes) { + path.MoveToPoint(p0.x, p0.y); + path.AddLineToPoint(p1.x, p1.y); + } + gc->StrokePath(path); + } else { + wxPen pen(colour, dip_px(1)); + pen.SetCap(wxCAP_BUTT); + dc.SetPen(pen); + for (const auto& [p0, p1] : dashes) + dc.DrawLine(wxRound(p0.x), wxRound(p0.y), wxRound(p1.x), wxRound(p1.y)); + } +} + } // namespace wxRect mixed_gradient_plot_rect(const wxSize& sz) @@ -567,7 +630,8 @@ wxRect mixed_gradient_plot_rect(const wxSize& sz) void draw_mixed_gradient_plot(wxDC& raw_dc, const wxSize& canvas, const std::vector& curves, const std::vector& anchors, - const MixedGradientTheme& theme) + const MixedGradientTheme& theme, + double min_ratio) { // Draw into an internal opaque buffer so wxGCDC text/curves anti-alias against a solid // background (never a transparent one), then blit the finished image onto the caller's @@ -586,7 +650,7 @@ void draw_mixed_gradient_plot(wxDC& raw_dc, const wxSize& canvas, wxGCDC dc(memdc); wxGraphicsContext* gc = dc.GetGraphicsContext(); - // 10x10 light grid (10 lines including outer borders, 9 equal divisions). + // 10x10 light grid (11 lines including outer borders, 10 equal divisions). dc.SetPen(wxPen(theme.grid, 1)); for (int i = 0; i <= kGridDivisions; ++i) { const int x = rc.x + rc.width * i / kGridDivisions; @@ -671,6 +735,17 @@ void draw_mixed_gradient_plot(wxDC& raw_dc, const wxSize& canvas, if (!gc) return; + if (min_ratio > 0.0) { + std::vector dashes; + for (const double ratio : {min_ratio, 1.0 - min_ratio}) { + // Floored like the grid lines so the dashes sit on them; the epsilon keeps a ratio such + // as 1 - 0.9 from landing a pixel short. + const double y = rc.y + std::floor((1.0 - ratio) * rc.height + 1e-6); + add_dashes(dashes, {double(rc.x), y}, {double(rc.x + rc.width), y}); + } + stroke_dashes(dc, gc, dashes, dash_colour(theme.background.GetLuminance())); + } + // Outline only when the curve colour is perceptually close to the background; otherwise the // plain filament colour reads fine and the extra stroke would look heavy. auto needs_outline = [&](const wxColour& c) { @@ -708,7 +783,7 @@ void draw_mixed_gradient_plot(wxDC& raw_dc, const wxSize& canvas, } void draw_mixed_ratio_blend_bar(wxDC& dc, const wxRect& rect, const wxColour& first, - const wxColour& second, double second_fraction) + const wxColour& second, double second_fraction, double min_ratio) { if (rect.width <= 0 || rect.height <= 0) return; @@ -719,6 +794,18 @@ void draw_mixed_ratio_blend_bar(wxDC& dc, const wxRect& rect, const wxColour& fi dc.DrawLine(rect.x + x, rect.y, rect.x + x, rect.y + rect.height); } + // Each dashed line is dark or light to suit the fill under it. + if (min_ratio > 0.0) { + std::unique_ptr owned_gc; + wxGraphicsContext* gc = graphics_context(dc, owned_gc); + for (const double t : {min_ratio, 1.0 - min_ratio}) { + const double x = rect.x + std::floor(t * rect.width); + std::vector dashes; + add_dashes(dashes, {x, double(rect.y)}, {x, double(rect.y + rect.height)}); + stroke_dashes(dc, gc, dashes, dash_colour(lerp_blend(first, second, 1.0 - t).GetLuminance())); + } + } + // Fixed in both themes, like the triangle picker's drag handle: the divider is drawn over // blended filament colour, so it has to keep its contrast against data rather than chrome. const int div_x = rect.x + static_cast(second_fraction * rect.width); @@ -782,6 +869,17 @@ std::map& tri_cache() return cache; } +// The blended colour of the picker fill at barycentric weights (w0, w1, w2). +wxColour tri_mix_colour(const wxColour& c0, const wxColour& c1, const wxColour& c2, double w0, double w1, double w2) +{ + unsigned char mr = c2.Red(), mg = c2.Green(), mb = c2.Blue(); + if (w0 + w1 > 1e-6) { + Slic3r::filament_mixer_lerp(c0.Red(), c0.Green(), c0.Blue(), c1.Red(), c1.Green(), c1.Blue(), float(w1 / (w0 + w1)), &mr, &mg, &mb); + Slic3r::filament_mixer_lerp(mr, mg, mb, c2.Red(), c2.Green(), c2.Blue(), float(w2), &mr, &mg, &mb); + } + return wxColour(mr, mg, mb); +} + } // namespace std::array mixed_triangle_vertices(const wxSize& size, double margin_dip) @@ -797,7 +895,8 @@ std::array mixed_triangle_vertices(const wxSize& size, double margi } void draw_mixed_triangle_picker(wxDC& dc, const wxSize& size, const std::array& colours, - const std::array& weights, const MixedTriangleTheme& theme) + const std::array& weights, const MixedTriangleTheme& theme, + double min_weight) { if (size.GetWidth() <= 0 || size.GetHeight() <= 0) return; @@ -836,15 +935,7 @@ void draw_mixed_triangle_picker(wxDC& dc, const wxSize& size, const std::array 1e-6) { - float t01 = float(w1 / (w0 + w1)); - Slic3r::filament_mixer_lerp(c0.Red(), c0.Green(), c0.Blue(), c1.Red(), c1.Green(), c1.Blue(), t01, &mr, &mg, &mb); - Slic3r::filament_mixer_lerp(mr, mg, mb, c2.Red(), c2.Green(), c2.Blue(), float(w2), &mr, &mg, &mb); - } else { - mr = c2.Red(); mg = c2.Green(); mb = c2.Blue(); - } - mdc.SetPen(wxPen(wxColour(mr, mg, mb))); + mdc.SetPen(wxPen(tri_mix_colour(c0, c1, c2, w0, w1, w2))); mdc.DrawPoint(px, py); } } @@ -863,13 +954,46 @@ void draw_mixed_triangle_picker(wxDC& dc, const wxSize& size, const std::array owned_gc; + wxGraphicsContext* gc = graphics_context(dc, owned_gc); + + // Dashed outline of the area where every weight is at least `min_weight`. It is dark or light + // depending on how light the fill under the line is on average, so it stays visible over most blends. + if (min_weight > 0.0) { + const double k = 1.0 - 2.0 * min_weight; + std::array inner; + for (size_t i = 0; i < 3; ++i) { + const TriPoint& a = v[i]; + const TriPoint& b = v[(i + 1) % 3]; + const TriPoint& c = v[(i + 2) % 3]; + inner[i] = {k * a.x + min_weight * (b.x + c.x), k * a.y + min_weight * (b.y + c.y)}; + } + std::vector dashes; + for (size_t i = 0; i < 3; ++i) + add_dashes(dashes, inner[i], inner[(i + 1) % 3]); + double luminance = 0.0; + for (const auto& [p0, p1] : dashes) { + double w0, w1, w2; + tri_barycentric({(p0.x + p1.x) / 2, (p0.y + p1.y) / 2}, v[0], v[1], v[2], w0, w1, w2); + luminance += tri_mix_colour(c0, c1, c2, w0, w1, w2).GetLuminance(); + } + stroke_dashes(dc, gc, dashes, dash_colour(luminance / dashes.size())); + } + + // Drag handle, anti-aliased at its sub-pixel position when a graphics context is available. const double w0 = weights[0], w1 = weights[1], w2 = weights[2]; - const int hx = int(w0 * v[0].x + w1 * v[1].x + w2 * v[2].x); - const int hy = int(w0 * v[0].y + w1 * v[1].y + w2 * v[2].y); - dc.SetBrush(*wxWHITE_BRUSH); - dc.SetPen(wxPen(theme.ring, dip_px(2))); - dc.DrawCircle(hx, hy, dip_px(5)); + const double hx = w0 * v[0].x + w1 * v[1].x + w2 * v[2].x; + const double hy = w0 * v[0].y + w1 * v[1].y + w2 * v[2].y; + const double r = dip_px(5); + if (gc) { + gc->SetBrush(*wxWHITE_BRUSH); + gc->SetPen(gc->CreatePen(wxGraphicsPenInfo(theme.ring, dip_px(2)))); + gc->DrawEllipse(hx - r, hy - r, 2 * r, 2 * r); + } else { + dc.SetBrush(*wxWHITE_BRUSH); + dc.SetPen(wxPen(theme.ring, dip_px(2))); + dc.DrawCircle(wxRound(hx), wxRound(hy), wxRound(r)); + } } void draw_mixed_triangle_labels(wxDC& dc, const wxSize& size, const std::array& weights, diff --git a/src/slic3r/GUI/FilamentBitmapUtils.hpp b/src/slic3r/GUI/FilamentBitmapUtils.hpp index 9db9da73bc..48f870b06d 100644 --- a/src/slic3r/GUI/FilamentBitmapUtils.hpp +++ b/src/slic3r/GUI/FilamentBitmapUtils.hpp @@ -123,17 +123,21 @@ wxRect mixed_gradient_plot_rect(const wxSize& canvas); // Draw the whole plot (grid, axes + arrowheads, axis labels, each curve with an optional // near-background outline, and anchor circles). `anchors` are empty when the caller has // none to show. `dc` is the caller's buffered paint DC; a wxGCDC is created inside so the -// geometry gets anti-aliased. +// geometry gets anti-aliased. A positive `min_ratio` draws dashed lines at the `min_ratio` and +// `1 - min_ratio` ratios. void draw_mixed_gradient_plot(wxDC& dc, const wxSize& canvas, const std::vector& curves, const std::vector& anchors, - const MixedGradientTheme& theme); + const MixedGradientTheme& theme, + double min_ratio = 0.0); // --- Ratio bar (2-component continuous blend + divider, matching MixedFilamentDialog). // Colours blend first->second across the rect; the divider marks `second_fraction` of the -// rect's width (the second component's share, 0..1). +// rect's width (the second component's share, 0..1). A positive `min_ratio` draws dashed lines +// where either share reaches `min_ratio`. void draw_mixed_ratio_blend_bar(wxDC& dc, const wxRect& rect, const wxColour& first, - const wxColour& second, double second_fraction); + const wxColour& second, double second_fraction, + double min_ratio = 0.0); // Fallback ratio bar for N>2 non-gradient slots: one solid segment per component, // widths proportional to shares. Label text (the "NN%" inside wide-enough segments) is @@ -157,9 +161,11 @@ std::array mixed_triangle_vertices(const wxSize& size, double margi // Draw background, the cached barycentric fill, the outline and the drag-handle marker. // `weights` are the three barycentric shares (sum 1). The "Ratio" title and per-vertex // percentage labels are drawn by the caller so the interactive editor can keep its own -// live child labels while the read-only preview draws them as text. +// live child labels while the read-only preview draws them as text. A positive `min_weight` +// draws a dashed outline around the area where every weight is at least `min_weight`. void draw_mixed_triangle_picker(wxDC& dc, const wxSize& size, const std::array& colours, - const std::array& weights, const MixedTriangleTheme& theme); + const std::array& weights, const MixedTriangleTheme& theme, + double min_weight = 0.0); // Draw the "Ratio" title plus one "NN%" label per vertex (used by the read-only preview; // the interactive editor positions its own live labels instead). diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index 0c14497562..26c4ca334f 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -1350,6 +1350,27 @@ bool GLCanvas3D::CenterOfMass::details_hovered() const return m_picked && hovered != nullptr && hovered == ImGui::FindWindowByName(details_window); } +bool GLCanvas3D::CenterOfMass::details_contain(const Vec2d& point) const +{ + const ImGuiWindow* window = ImGui::FindWindowByName(details_window); + return m_picked && window != nullptr && window->Rect().Contains(ImVec2(float(point.x()), float(point.y()))); +} + +bool GLCanvas3D::CenterOfMass::details_pressed() const +{ + if (!details_hovered()) + return false; + const ImGuiContext& g = *ImGui::GetCurrentContext(); + const ImGuiWindow* window = g.HoveredWindow; + // The close button is active after a press on it, the window's move id after a press elsewhere on the window. + if (g.ActiveIdWindow == window && g.ActiveId != window->MoveId) + return false; + for (int button = 0; button < IM_ARRAYSIZE(g.IO.MouseDown); ++button) + if (g.IO.MouseDown[button] && window->Rect().Contains(g.IO.MouseClickedPos[button])) + return true; + return false; +} + bool GLCanvas3D::CenterOfMass::hide_details(GLCanvas3D& canvas) { if (!m_picked) @@ -2611,7 +2632,13 @@ void GLCanvas3D::_render_frame(bool scene_dirty, bool only_init) return; // ensures this canvas is current and initialized - if (!_is_shown_on_screen() || !_set_current() || !wxGetApp().init_opengl()) + if (!_is_shown_on_screen()) + return; + if (!_set_current()) { + wxGetApp().get_opengl_manager().report_make_current_failure(*m_canvas, m_context); + return; + } + if (!wxGetApp().init_opengl()) return; if (!is_initialized() && !init()) @@ -4003,6 +4030,10 @@ void GLCanvas3D::load_gcode_preview(const GCodeProcessorResult& gcode_result, co const std::vector& exclude_bounding_box = plate->get_exclude_areas(); _set_shown_canvas_current(); + // The viewer uploads to the GPU from here on. Without a context the driver lets us make + // current, the OpenGL functions were never loaded and there is nothing to draw it with. + if (!wxGetApp().init_opengl()) + return; //BBS: init is called in GLCanvas3D.render() //when load gcode directly, it is too late @@ -4975,7 +5006,21 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) // that incorrectly suppresses the active drag's tooltip and can interrupt its processing. The active drag always takes priority. const bool other_drag_active = m_gizmos.is_dragging() || m_mouse.dragging || m_rectangle_selection.is_dragging() || m_layers_editing.state == LayersEditing::Editing; - if (imgui->update_mouse_data(evt) && !other_drag_active) { + // A drag that starts on a marker's details moves the view, as over empty space. Checked on the first drag event only, + // while ImGui still hovers what was under the press. After that, m_mouse.dragging keeps the drag on the canvas. + const bool camera_drag = evt.Dragging() && !other_drag_active && m_center_of_mass.details_pressed(); + if (camera_drag) { + // Else the object under the details keeps a left drag from turning the view. + m_hover_volume_idxs.clear(); + // From the press, as the canvas does, which went to the ImGui branch below and left its position in m_mouse.position. + m_mouse.drag.start_position_2D = Point(m_mouse.position.x(), m_mouse.position.y()); + // Its release is no right click on the canvas, also when the view has not turned yet, as that takes a second drag event. + m_mouse.ignore_right_up = true; + } + // A click that closes a context menu has no move before it, so ImGui may not yet hover the details. + const bool click_on_details = (evt.ButtonDown() || evt.ButtonUp()) && m_center_of_mass.details_contain(pos.cast()); + + if ((imgui->update_mouse_data(evt) || click_on_details) && !other_drag_active && !camera_drag) { if ((evt.LeftDown() || (evt.Moving() && (evt.AltDown() || evt.ShiftDown()))) && m_canvas != nullptr) m_canvas->SetFocus(); m_mouse.position = evt.Leaving() ? Vec2d(-1.0, -1.0) : pos.cast(); @@ -5191,6 +5236,9 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) m_mouse.ignore_left_up = true; return; } + // A right click off the details hides them, as a left one does. + if (evt.RightDown() && !mouse_in_layer_editing) + m_center_of_mass.hide_details(*this); bool any_gizmo_active = m_gizmos.get_current() != nullptr; diff --git a/src/slic3r/GUI/GLCanvas3D.hpp b/src/slic3r/GUI/GLCanvas3D.hpp index 3ea1a879b0..c9833d8fd6 100644 --- a/src/slic3r/GUI/GLCanvas3D.hpp +++ b/src/slic3r/GUI/GLCanvas3D.hpp @@ -549,6 +549,10 @@ class GLCanvas3D void render_details(GLCanvas3D& canvas); // Whether the mouse is over the details. bool details_hovered() const; + // Whether the details cover a point, also when ImGui has not seen the mouse move there. + bool details_contain(const Vec2d& point) const; + // Whether a button held down was pressed on the details, off their close button. + bool details_pressed() const; // Whether there were details to hide. bool hide_details(GLCanvas3D& canvas); }; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp b/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp index 81eea83308..d8d21001a8 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp @@ -263,9 +263,8 @@ bool GLGizmoMeasure::on_mouse(const wxMouseEvent &mouse_event) if (mouse_event.CmdDown()) return false; - if (m_hover_id != -1) { + if (can_pick()) { m_mouse_left_down = true; - m_mouse_left_down_mesh_deal = true; auto detect_current_item = [this]() { SelectedFeatures::Item item; if (m_hover_id == SEL_SPHERE_1_ID) { @@ -361,6 +360,7 @@ bool GLGizmoMeasure::on_mouse(const wxMouseEvent &mouse_event) else { // 2nd feature selection m_selected_features.second = item; + record_hit_volume(item, true); if (requires_sphere_raycaster_for_picking(item)) { auto pick = std::make_shared(SEL_SPHERE_2_ID, *m_sphere.mesh_raycaster); m_gripper_id_raycast_map[GripperType::SPHERE_2] = pick; @@ -393,6 +393,7 @@ bool GLGizmoMeasure::on_mouse(const wxMouseEvent &mouse_event) } m_selected_wrong_feature_waring_tip = false; m_selected_features.first = item; + record_hit_volume(item, false); if (requires_sphere_raycaster_for_picking(item)) { auto pick = std::make_shared(SEL_SPHERE_1_ID, *m_sphere.mesh_raycaster); m_gripper_id_raycast_map[GripperType::SPHERE_1] = pick; @@ -404,15 +405,12 @@ bool GLGizmoMeasure::on_mouse(const wxMouseEvent &mouse_event) m_imgui->set_requires_extra_frame(); return true; } - else + else { + m_hover_id = -1; // if the mouse pointer is on any volume, filter out the event to prevent the user to move it // equivalent tp: return (m_parent.get_first_hover_volume_idx() != -1); return m_curr_feature.has_value(); - - // fix: prevent restart gizmo when reselect object - // take responsibility for left up - if (m_parent.get_first_hover_volume_idx() >= 0) - m_mouse_left_down = true; + } } else if (mouse_event.LeftUp()) { if (m_mouse_left_down) { @@ -453,7 +451,8 @@ void GLGizmoMeasure::data_changed(bool is_serializing) register_single_mesh_pick(); reset_all_feature(); } - m_last_inv_zoom = 0.0f; + // reset_all_pick() drops the hovered circle's gripper, and rebuilding the circle adds it back. + m_curr_circle.last_circle_feature.reset(); m_last_plane_idx = -1; m_editing_distance = false; m_is_editing_distance_first_frame = true; @@ -569,26 +568,26 @@ bool GLGizmoMeasure::on_is_activable() const void GLGizmoMeasure::init_circle_glmodel(GripperType gripper_type, const Measure::SurfaceFeature &feature, CircleGLModel &circle_gl_model,float inv_zoom) { const auto [center, radius, normal] = feature.get_circle(); - auto cur_feature =const_cast(&feature); - if (circle_gl_model.inv_zoom != inv_zoom) { - if (circle_gl_model.last_circle_feature) { - const auto [last_center, last_radius, last_normal] = circle_gl_model.last_circle_feature->get_circle(); - float eps = 1e-2; - if ((last_center - center).norm() < eps && (last_normal - normal).norm() < eps && abs(last_radius - radius) < eps){ - return; - } + if (circle_gl_model.inv_zoom == inv_zoom && circle_gl_model.last_circle_feature) { + const auto [last_center, last_radius, last_normal] = circle_gl_model.last_circle_feature->get_circle(); + float eps = 1e-2; + if ((last_center - center).norm() < eps && (last_normal - normal).norm() < eps && abs(last_radius - radius) < eps){ + return; } - reset_gripper_pick(gripper_type); - circle_gl_model.circle.reset(); - GLModel::Geometry circle_geometry = init_torus_data(64, 16, center.cast(), float(radius), 5.0f * inv_zoom, normal.cast(), Transform3f::Identity()); - circle_gl_model.circle.mesh_raycaster = std::make_unique(std::make_shared(circle_geometry.get_as_indexed_triangle_set())); - circle_gl_model.circle.model.init_from(std::move(circle_geometry)); - if (circle_gl_model.circle.model.is_initialized()) { - m_gripper_id_raycast_map[gripper_type] = std::make_shared(CIRCLE_ID, *m_curr_circle.circle.mesh_raycaster); - } - circle_gl_model.last_circle_feature = cur_feature; - circle_gl_model.inv_zoom = inv_zoom; } + const bool pickable = gripper_type != GripperType::UNDEFINE; + if (pickable) + reset_gripper_pick(gripper_type); + circle_gl_model.circle.reset(); + GLModel::Geometry circle_geometry = init_torus_data(64, 16, center.cast(), float(radius), 5.0f * inv_zoom, normal.cast(), Transform3f::Identity()); + if (pickable) + circle_gl_model.circle.mesh_raycaster = std::make_unique(std::make_shared(circle_geometry.get_as_indexed_triangle_set())); + circle_gl_model.circle.model.init_from(std::move(circle_geometry)); + if (pickable && circle_gl_model.circle.model.is_initialized()) { + m_gripper_id_raycast_map[gripper_type] = std::make_shared(CIRCLE_ID, *circle_gl_model.circle.mesh_raycaster); + } + circle_gl_model.last_circle_feature = feature; + circle_gl_model.inv_zoom = inv_zoom; } const float MEASURE_PLNE_NORMAL_OFFSET = 0.05; void GLGizmoMeasure::init_plane_glmodel(GripperType gripper_type, const Measure::SurfaceFeature &feature, PlaneGLModel &plane_gl_model) @@ -604,12 +603,15 @@ void GLGizmoMeasure::init_plane_glmodel(GripperType gripper_type, const Measure: plane_gl_model.plane.reset(); } if (!plane_gl_model.plane.model.is_initialized()) { + const bool pickable = gripper_type != GripperType::UNDEFINE; plane_gl_model.plane_idx = idx; - reset_gripper_pick(gripper_type); + if (pickable) + reset_gripper_pick(gripper_type); GLModel::Geometry init_data = init_plane_data(mesh->its, *feature.plane_indices, MEASURE_PLNE_NORMAL_OFFSET); - plane_gl_model.plane.mesh_raycaster = std::make_unique(std::make_shared(init_data.get_as_indexed_triangle_set())); + if (pickable) + plane_gl_model.plane.mesh_raycaster = std::make_unique(std::make_shared(init_data.get_as_indexed_triangle_set())); plane_gl_model.plane.model.init_from(std::move(init_data)); - if (plane_gl_model.plane.model.is_initialized()) { + if (pickable && plane_gl_model.plane.model.is_initialized()) { m_gripper_id_raycast_map[gripper_type] = std::make_shared(PLANE_ID, *plane_gl_model.plane.mesh_raycaster, feature.world_tran); } } @@ -652,23 +654,22 @@ void GLGizmoMeasure::on_render() bool mouse_on_object =false; { if (!m_editing_distance) { - Vec3f hit = Vec3f::Zero(); + // m_hover_id is the closest gripper hit of this frame, or the earlier one on a tie. + m_hover_id = -1; double closest_hit_squared_distance = std::numeric_limits::max(); - for (auto item : m_gripper_id_raycast_map) { - - auto world_tran = item.second->get_transform(); + for (const auto &item : m_gripper_id_raycast_map) { + const Transform3d &world_tran = item.second->get_transform(); + Vec3f hit = Vec3f::Zero(); Vec3f normal_on_gripper; - if (item.second->get_raycaster()->closest_hit(mouse_position, item.second->get_transform(), camera, hit, normal_on_gripper)) { - double hit_squared_distance = (camera.get_position() - world_tran * hit.cast()).squaredNorm(); + if (item.second->get_id() > 0 && item.second->get_raycaster()->closest_hit(mouse_position, world_tran, camera, hit, normal_on_gripper)) { + const double hit_squared_distance = (camera.get_position() - world_tran * hit.cast()).squaredNorm(); if (hit_squared_distance < closest_hit_squared_distance) { closest_hit_squared_distance = hit_squared_distance; - if (item.second->get_id() > 0) { - m_hover_id = item.second->get_id(); - mouse_on_gripper = true; - } + m_hover_id = item.second->get_id(); } } } + mouse_on_gripper = m_hover_id != -1; } } Vec3d position_on_model; @@ -703,44 +704,8 @@ void GLGizmoMeasure::on_render() reset_gripper_pick(GripperType::PLANE); reset_gripper_pick(GripperType::CIRCLE); } - if (m_mouse_left_down_mesh_deal && m_hover_id >= 0) { - m_mouse_left_down_mesh_deal = false; - if (m_selected_features.second.feature.has_value()) { - if (m_hit_order_volumes.size() == 1) { - m_hit_order_volumes.push_back(m_last_hit_volume); - } else { - m_hit_order_volumes[1] = m_last_hit_volume; - } - // deal hit_different_volumes - if (m_hit_different_volumes.size() >= 1) { - if (m_last_hit_volume == m_hit_different_volumes[0]) { - if (m_hit_different_volumes.size() == 2) {//hit same volume - m_hit_different_volumes.erase(m_hit_different_volumes.begin() + 1); - } - } else { - if (m_hit_different_volumes.size() == 2) { - m_hit_different_volumes[1] = m_last_hit_volume; - } else { - m_hit_different_volumes.push_back(m_last_hit_volume); - } - } - } - } - else if (m_selected_features.first.feature.has_value()) { - if (m_hit_order_volumes.size() == 0) { - m_hit_order_volumes.push_back(m_last_hit_volume); - } else { - m_hit_order_volumes[0] = m_last_hit_volume; - } - //deal hit_different_volumes - if (m_hit_different_volumes.size() == 0) { - m_hit_different_volumes.push_back(m_last_hit_volume); - } - } - } } //const bool mouse_on_object = m_raycaster->unproject_on_mesh(mouse_position, Transform3d::Identity(), camera, position_on_model, normal_on_model, nullptr, &model_facet_idx); - const bool is_hovering_on_feature = m_mode == EMode::PointSelection && m_hover_id != -1; if (m_mode == EMode::FeatureSelection || m_mode == EMode::PointSelection) { if (m_hover_id == SEL_SPHERE_1_ID || m_hover_id == SEL_SPHERE_2_ID) { @@ -770,11 +735,11 @@ void GLGizmoMeasure::on_render() } } } - if (m_curr_feature != curr_feature || - (curr_feature.has_value() && curr_feature->get_type() == Measure::SurfaceFeatureType::Circle && (m_curr_feature != curr_feature || m_last_inv_zoom != inv_zoom))) { - reset_gripper_pick(GripperType::UNDEFINE, true); + if (m_curr_feature != curr_feature) { + reset_hover_gripper_pick(); m_curr_feature = curr_feature; + m_curr_point_on_feature_position.reset(); // The selected features are drawn below whether or not one is hovered. if (m_curr_feature.has_value()) { m_curr_feature->volume = m_last_hit_volume; @@ -793,7 +758,7 @@ void GLGizmoMeasure::on_render() break; } case Measure::SurfaceFeatureType::Circle: { - m_curr_circle.last_circle_feature = nullptr; + m_curr_circle.last_circle_feature.reset(); m_curr_circle.inv_zoom = 0; init_circle_glmodel(GripperType::CIRCLE, *m_curr_feature, m_curr_circle,inv_zoom); break; @@ -813,8 +778,8 @@ void GLGizmoMeasure::on_render() if (m_mode != EMode::PointSelection) { m_curr_point_on_feature_position.reset(); } - else if (is_hovering_on_feature) { - auto position_on_feature = [this, &mouse_position](int feature_type_id, const Camera &camera, std::function callback = nullptr) -> Vec3d { + else { + auto position_on_feature = [this, &mouse_position](int feature_type_id, const Camera &camera, std::function callback = nullptr) -> std::optional { auto it = m_gripper_id_raycast_map.find((GripperType) feature_type_id); // m_raycasters.find(feature_type_id); if (it != m_gripper_id_raycast_map.end() && it->second != nullptr) { Vec3f p; @@ -827,7 +792,7 @@ void GLGizmoMeasure::on_render() return trafo * p.cast(); } } - return Vec3d(DBL_MAX, DBL_MAX, DBL_MAX); + return std::nullopt; }; if (m_curr_feature.has_value()) { switch (m_curr_feature->get_type()) @@ -840,31 +805,23 @@ void GLGizmoMeasure::on_render() } case Measure::SurfaceFeatureType::Edge: { - const std::optional extra = m_curr_feature->get_extra_point(); - if (extra.has_value() && m_hover_id == GripperType::POINT) - m_curr_point_on_feature_position = *extra; - else { - const Vec3d pos = position_on_feature(GripperType::EDGE, camera, [](const Vec3f &v) { return Vec3f(0.0f, 0.0f, v.z()); }); - if (!pos.isApprox(Vec3d(DBL_MAX, DBL_MAX, DBL_MAX))) - m_curr_point_on_feature_position = pos; - } + if (const std::optional pos = position_on_feature(GripperType::EDGE, camera, [](const Vec3f &v) { return Vec3f(0.0f, 0.0f, v.z()); })) + m_curr_point_on_feature_position = pos; break; } case Measure::SurfaceFeatureType::Plane: { - m_curr_point_on_feature_position = position_on_feature(GripperType::PLANE, camera); + if (const std::optional pos = position_on_feature(GripperType::PLANE, camera)) + m_curr_point_on_feature_position = pos; break; } case Measure::SurfaceFeatureType::Circle: { const auto [center, radius, normal] = m_curr_feature->get_circle(); - if (m_hover_id == POINT_ID) - m_curr_point_on_feature_position = center; - else { - const Vec3d world_pof = position_on_feature(GripperType::CIRCLE, camera, [](const Vec3f &v) { return v; }); + if (const std::optional world_pof = position_on_feature(GripperType::CIRCLE, camera, [](const Vec3f &v) { return v; })) { const Eigen::Hyperplane plane(normal, center); const Transform3d local_to_model_matrix = Geometry::translation_transform(center) * Eigen::Quaternion::FromTwoVectors(Vec3d::UnitZ(), normal); - const Vec3d local_proj = local_to_model_matrix.inverse() * plane.projection(world_pof); + const Vec3d local_proj = local_to_model_matrix.inverse() * plane.projection(*world_pof); double angle = std::atan2(local_proj.y(), local_proj.x()); if (angle < 0.0) angle += 2.0 * double(M_PI); @@ -877,9 +834,9 @@ void GLGizmoMeasure::on_render() } } } - else { - m_curr_point_on_feature_position.reset(); - } + + if (!can_pick()) + m_hover_id = -1; if (!m_curr_feature.has_value() && !m_selected_features.first.feature.has_value()) { return; @@ -949,21 +906,16 @@ void GLGizmoMeasure::on_render() } // render plane feature1 or feature2 if (featura_index == 0) { // feature1 - init_circle_glmodel(GripperType::CIRCLE_1, feature, m_feature_circle_first, inv_zoom); + init_circle_glmodel(GripperType::UNDEFINE, feature, m_feature_circle_first, inv_zoom); render_glmodel(m_feature_circle_first.circle, colors.front(), tran.get_matrix(), hover); } else if (featura_index == 1) { // feature2 - init_circle_glmodel(GripperType::CIRCLE_2, feature, m_feature_circle_second, inv_zoom); + init_circle_glmodel(GripperType::UNDEFINE, feature, m_feature_circle_second, inv_zoom); render_glmodel(m_feature_circle_second.circle, colors.front(), tran.get_matrix(), hover); } // render center if (colors.size() > 1) { const Transform3d center_matrix = Geometry::translation_transform(center) * Geometry::scale_transform(inv_zoom); render_glmodel(m_sphere, colors.back(), center_matrix, hover); - - Geometry::Transformation tran(center_matrix); - auto it = m_gripper_id_raycast_map.find(GripperType::POINT); - if (it != m_gripper_id_raycast_map.end() && it->second != nullptr) - it->second->set_transform(center_matrix); } break; } @@ -990,11 +942,6 @@ void GLGizmoMeasure::on_render() const Transform3d point_matrix = Geometry::translation_transform(*extra) * Geometry::scale_transform(inv_zoom); Geometry::Transformation tran(point_matrix); render_glmodel(m_sphere, colors.back(), tran.get_matrix(), hover); - - auto it = m_gripper_id_raycast_map.find(GripperType::POINT); - if (it != m_gripper_id_raycast_map.end() && it->second != nullptr) { - it->second->set_transform(point_matrix); - } } } break; @@ -1006,10 +953,10 @@ void GLGizmoMeasure::on_render() } //render plane feature1 or feature2 if (featura_index == 0) {//feature1 - init_plane_glmodel(GripperType::PLANE_1, feature, m_feature_plane_first); + init_plane_glmodel(GripperType::UNDEFINE, feature, m_feature_plane_first); render_glmodel(m_feature_plane_first.plane, colors.back(), feature.world_tran, hover); } else if (featura_index == 1) {//feature2 - init_plane_glmodel(GripperType::PLANE_2, feature, m_feature_plane_second); + init_plane_glmodel(GripperType::UNDEFINE, feature, m_feature_plane_second); render_glmodel(m_feature_plane_second.plane, colors.back(), feature.world_tran, hover); } break; @@ -1151,7 +1098,7 @@ void GLGizmoMeasure::on_render() } } - if (is_hovering_on_feature && m_curr_point_on_feature_position.has_value()) { + if (m_mode == EMode::PointSelection && m_curr_point_on_feature_position.has_value()) { if (m_hover_id != POINT_ID) { // render point on feature while SHIFT is pressed const Transform3d matrix = Geometry::translation_transform(*m_curr_point_on_feature_position) * Geometry::scale_transform(inv_zoom); @@ -2323,24 +2270,72 @@ void GLGizmoMeasure::update_measurement_result() void GLGizmoMeasure::reset_all_pick() { std::map>().swap(m_mesh_raycaster_map); - reset_gripper_pick(GripperType::UNDEFINE,true); + reset_hover_gripper_pick(); } -void GLGizmoMeasure::reset_gripper_pick(GripperType id, bool is_all) +void GLGizmoMeasure::reset_gripper_pick(GripperType id) { if (m_gripper_id_raycast_map.find(id) != m_gripper_id_raycast_map.end()) { m_gripper_id_raycast_map[id].reset(); m_gripper_id_raycast_map.erase(id); } - if (id == GripperType ::UNDEFINE && is_all) { - reset_gripper_pick(GripperType::POINT); - reset_gripper_pick(GripperType::EDGE); - reset_gripper_pick(GripperType::PLANE); - reset_gripper_pick(GripperType::PLANE_1); - reset_gripper_pick(GripperType::PLANE_2); - reset_gripper_pick(GripperType::CIRCLE); - reset_gripper_pick(GripperType::CIRCLE_1); - reset_gripper_pick(GripperType::CIRCLE_2); +} + +void GLGizmoMeasure::reset_hover_gripper_pick() +{ + reset_gripper_pick(GripperType::POINT); + reset_gripper_pick(GripperType::EDGE); + reset_gripper_pick(GripperType::PLANE); + reset_gripper_pick(GripperType::CIRCLE); +} + +bool GLGizmoMeasure::can_pick() const +{ + if (m_hover_id == SEL_SPHERE_1_ID) + return m_selected_features.first.feature.has_value() && m_gripper_id_raycast_map.count(GripperType::SPHERE_1) > 0; + if (m_hover_id == SEL_SPHERE_2_ID) + return m_selected_features.second.feature.has_value() && m_gripper_id_raycast_map.count(GripperType::SPHERE_2) > 0; + return m_curr_feature.has_value() && (m_mode != EMode::PointSelection || m_curr_point_on_feature_position.has_value()); +} + +void GLGizmoMeasure::record_hit_volume(const SelectedFeatures::Item &item, bool is_second) +{ + // A center item's feature is a new point with no volume, so the volume comes from the feature it is the center of. + GLVolume *volume = static_cast(item.feature->volume); + if (volume == nullptr && item.source.has_value()) + volume = static_cast(item.source->volume); + if (volume == nullptr) + volume = m_last_hit_volume; + + if (is_second) { + if (m_hit_order_volumes.size() == 1) { + m_hit_order_volumes.push_back(volume); + } else { + m_hit_order_volumes[1] = volume; + } + if (m_hit_different_volumes.size() >= 1) { + if (volume == m_hit_different_volumes[0]) { + if (m_hit_different_volumes.size() == 2) { + m_hit_different_volumes.erase(m_hit_different_volumes.begin() + 1); + } + } else { + if (m_hit_different_volumes.size() == 2) { + m_hit_different_volumes[1] = volume; + } else { + m_hit_different_volumes.push_back(volume); + } + } + } + } + else { + if (m_hit_order_volumes.size() == 0) { + m_hit_order_volumes.push_back(volume); + } else { + m_hit_order_volumes[0] = volume; + } + if (m_hit_different_volumes.size() == 0) { + m_hit_different_volumes.push_back(volume); + } } } @@ -2391,7 +2386,7 @@ void GLGizmoMeasure::reset_feature1_render() } if (m_feature_circle_first.circle.model.is_initialized()) { m_feature_circle_first.circle.model.reset(); - m_feature_circle_first.last_circle_feature = nullptr; + m_feature_circle_first.last_circle_feature.reset(); m_feature_circle_first.inv_zoom = 0; } } @@ -2404,7 +2399,7 @@ void GLGizmoMeasure::reset_feature2_render() } if (m_feature_circle_second.circle.model.is_initialized()) { m_feature_circle_second.circle.model.reset(); - m_feature_circle_second.last_circle_feature = nullptr; + m_feature_circle_second.last_circle_feature.reset(); m_feature_circle_second.inv_zoom = 0; } } @@ -2433,8 +2428,6 @@ void GLGizmoMeasure::reset_feature1() if (m_hit_order_volumes.size() == 1) { m_hit_order_volumes.clear(); } - reset_gripper_pick(GripperType::PLANE_1); - reset_gripper_pick(GripperType::CIRCLE_1); reset_gripper_pick(GripperType::SPHERE_1); } update_measurement_result(); @@ -2453,8 +2446,6 @@ void GLGizmoMeasure::reset_feature2() m_selected_features.second.reset(); m_show_reset_first_tip = false; m_selected_wrong_feature_waring_tip = false; - reset_gripper_pick(GripperType::PLANE_2); - reset_gripper_pick(GripperType::CIRCLE_2); reset_gripper_pick(GripperType::SPHERE_2); update_measurement_result(); @@ -2514,9 +2505,9 @@ void GLGizmoMeasure::update_feature_by_tran(Measure::SurfaceFeature &feature) feature.clone(*feature.origin_surface_feature); feature.translate(feature.world_tran); if (feature.get_type() == Measure::SurfaceFeatureType::Circle) { - m_feature_circle_first.last_circle_feature = nullptr; + m_feature_circle_first.last_circle_feature.reset(); m_feature_circle_first.inv_zoom = 0; - m_feature_circle_second.last_circle_feature = nullptr; + m_feature_circle_second.last_circle_feature.reset(); m_feature_circle_second.inv_zoom = 0; } if (feature.get_type() == Measure::SurfaceFeatureType::Plane) { diff --git a/src/slic3r/GUI/Gizmos/GLGizmoMeasure.hpp b/src/slic3r/GUI/Gizmos/GLGizmoMeasure.hpp index 7035c07e39..33d0998cea 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoMeasure.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoMeasure.hpp @@ -96,11 +96,7 @@ protected: POINT, EDGE, CIRCLE, - CIRCLE_1, - CIRCLE_2, PLANE, - PLANE_1, - PLANE_2, SPHERE_1, SPHERE_2, }; @@ -179,12 +175,13 @@ protected: struct CircleGLModel { PickingModel circle; - Measure::SurfaceFeature *last_circle_feature{nullptr}; + std::optional last_circle_feature; float inv_zoom{0}; }; CircleGLModel m_curr_circle; CircleGLModel m_feature_circle_first; CircleGLModel m_feature_circle_second; + // GripperType::UNDEFINE builds the circle without a gripper, for the selected circles. void init_circle_glmodel(GripperType gripper_type, const Measure::SurfaceFeature &feature, CircleGLModel &circle_gl_model, float inv_zoom); struct PlaneGLModel { @@ -194,6 +191,7 @@ protected: PlaneGLModel m_curr_plane; PlaneGLModel m_feature_plane_first; PlaneGLModel m_feature_plane_second; + // GripperType::UNDEFINE builds the plane without a gripper, for the selected planes. void init_plane_glmodel(GripperType gripper_type, const Measure::SurfaceFeature &feature, PlaneGLModel &plane_gl_model); struct Dimensioning @@ -221,12 +219,10 @@ protected: std::optional m_curr_point_on_feature_position; // These hold information to decide whether recalculation is necessary: - float m_last_inv_zoom{ 0.0f }; std::optional m_last_circle_feature; int m_last_plane_idx{ -1 }; bool m_mouse_left_down{ false }; // for detection left_up of this gizmo - bool m_mouse_left_down_mesh_deal{false};//for pick mesh KeyAutoRepeatFilter m_shift_kar_filter; @@ -292,7 +288,13 @@ protected: void update_measurement_result(); void reset_all_pick(); - void reset_gripper_pick(GripperType id,bool is_all = false); + void reset_gripper_pick(GripperType id); + void reset_hover_gripper_pick(); + // Returns true when a click can select a live selection sphere under the cursor, or else the hovered feature + // and, in point selection, the point on it. The hovered feature needs no gripper hit, since its highlight can be thinner than its hover band. + bool can_pick() const; + // Records the volume of a newly selected feature, as the first or the second selection. + void record_hit_volume(const SelectedFeatures::Item &item, bool is_second); void register_single_mesh_pick(); //void update_single_mesh_pick(GLVolume* v); diff --git a/src/slic3r/GUI/GradientCurveEditor.cpp b/src/slic3r/GUI/GradientCurveEditor.cpp index b18bfe0480..d4c1f05801 100644 --- a/src/slic3r/GUI/GradientCurveEditor.cpp +++ b/src/slic3r/GUI/GradientCurveEditor.cpp @@ -362,7 +362,7 @@ void GradientCurveEditor::on_paint(wxPaintEvent& /*evt*/) } const MixedGradientTheme theme{bg, grid_color, axis_color, label_muted, label_strong, outline_color, point_fill}; - draw_mixed_gradient_plot(raw_dc, GetClientSize(), curves, anchors, theme); + draw_mixed_gradient_plot(raw_dc, GetClientSize(), curves, anchors, theme, kGradientMinRatio); } void GradientCurveEditor::on_left_down(wxMouseEvent& evt) diff --git a/src/slic3r/GUI/HintNotification.cpp b/src/slic3r/GUI/HintNotification.cpp index 1ad5903dea..2a7c9fb380 100644 --- a/src/slic3r/GUI/HintNotification.cpp +++ b/src/slic3r/GUI/HintNotification.cpp @@ -850,6 +850,9 @@ void NotificationManager::HintNotification::init() // Do not init closing notification if (is_finished()) return; + // No font before the first ImGui frame, see PopNotification::init(). + if (ImGui::GetFont() == nullptr) + return; count_spaces(); count_lines(); diff --git a/src/slic3r/GUI/MixedFilamentDialog.cpp b/src/slic3r/GUI/MixedFilamentDialog.cpp index 443562bd05..d15d14c74d 100644 --- a/src/slic3r/GUI/MixedFilamentDialog.cpp +++ b/src/slic3r/GUI/MixedFilamentDialog.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -199,8 +200,7 @@ MixedFilamentDialog::MixedFilamentDialog(wxWindow* parent, void MixedFilamentDialog::on_dpi_changed(const wxRect&) { - int h = (num_components() >= 3) ? FromDIP(680) : FromDIP(580); - SetSize(FromDIP(439), h); + resize_keeping_centre(); Refresh(); } @@ -631,15 +631,16 @@ void MixedFilamentDialog::build_ui() m_right_sizer->Add(create_material_selection(), 0, wxEXPAND); m_right_sizer->Add(create_gradient_section(), 0, wxEXPAND | wxTOP, FromDIP(7)); - m_ratio_sizer = create_ratio_slider(); - m_right_sizer->Add(m_ratio_sizer, 0, wxEXPAND | wxTOP, FromDIP(7)); - m_triangle_sizer = create_triangle_picker(); m_right_sizer->Add(m_triangle_sizer, 0, wxALIGN_CENTER_HORIZONTAL | wxTOP, FromDIP(7)); top_sizer->Add(m_right_sizer, 1, wxTOP | wxRIGHT | wxBOTTOM, FromDIP(20)); main_sizer->Add(top_sizer, 0, wxEXPAND); + // The ratio bar spans the full dialog width, using the space below the preview too. + m_ratio_sizer = create_ratio_slider(); + main_sizer->Add(m_ratio_sizer, 0, wxEXPAND | wxLEFT | wxRIGHT | wxBOTTOM, FromDIP(25)); + main_sizer->Add(create_recommendation_grid(), 1, wxEXPAND | wxLEFT | wxRIGHT, FromDIP(25)); // Warning panel: red bordered box with exclamation icon + text @@ -866,7 +867,7 @@ wxBoxSizer* MixedFilamentDialog::create_ratio_slider() wxBufferedPaintDC dc(m_ratio_bar); wxSize sz = m_ratio_bar->GetClientSize(); draw_mixed_ratio_blend_bar(dc, wxRect(0, 0, sz.GetWidth(), sz.GetHeight()), - comp_colour(0), comp_colour(1), ratio(1) / 100.0); + comp_colour(0), comp_colour(1), ratio(1) / 100.0, MIN_COMPONENT_RATIO / 100.0); }); m_ratio_bar->Bind(wxEVT_LEFT_DOWN, [this](wxMouseEvent& e) { @@ -965,7 +966,8 @@ wxBoxSizer* MixedFilamentDialog::create_triangle_picker() {StateColor::darkModeColorFor(*wxWHITE), StateColor::darkModeColorFor(wxColour("#CECECE")), StateColor::darkModeColorFor(wxColour("#262E30")), - StateColor::darkModeColorFor(COLOR_LABEL_MUTED)}); + StateColor::darkModeColorFor(COLOR_LABEL_MUTED)}, + MIN_COMPONENT_RATIO / 100.0); if (m_result.ratios.size() >= 3) { dc.SetFont(::Label::Body_10); @@ -1395,15 +1397,7 @@ void MixedFilamentDialog::on_gradient_toggled() // Toggling the curve editor changes the right column height (and width when // turning gradient on), so the dialog must follow or the recommendation list // gets squeezed off-screen. Same trick as 2-color -> 3-color switching. - const wxSize new_size = compute_dialog_size(); - if (GetSize() != new_size) { - const wxRect old_rect = GetRect(); - const wxPoint center(old_rect.x + old_rect.width / 2, - old_rect.y + old_rect.height / 2); - SetSize(new_size); - SetPosition(wxPoint(center.x - new_size.x / 2, - center.y - new_size.y / 2)); - } + resize_keeping_centre(); Layout(); Refresh(); @@ -1836,15 +1830,26 @@ void MixedFilamentDialog::update_component_count_ui() m_btn_remove_material->SetToolTip(is_three ? _L("Remove the third material") : wxString()); } - const wxSize new_size = compute_dialog_size(); - const wxRect old_rect = GetRect(); - const wxPoint center(old_rect.x + old_rect.width / 2, - old_rect.y + old_rect.height / 2); - SetSize(new_size); - SetPosition(wxPoint(center.x - new_size.x / 2, - center.y - new_size.y / 2)); + resize_keeping_centre(); Layout(); } +void MixedFilamentDialog::resize_keeping_centre() +{ + // Until it is shown the dialog has no display of its own (on Wayland none at all), so use + // the parent's, which is also where CentreOnParent() places it. + const wxRect area = wxDisplay(IsShown() ? static_cast(this) : GetParent()).GetClientArea(); + wxSize new_size = compute_dialog_size(); + new_size.DecTo(area.GetSize()); // never larger than the display + if (GetSize() == new_size) + return; + // Grow or shrink around the current centre, but keep the whole dialog inside its display + // so the buttons don't end up under the taskbar. + const wxPoint centre = GetPosition() + GetSize() / 2; + const int x = std::max(area.x, std::min(centre.x - new_size.x / 2, area.GetRight() + 1 - new_size.x)); + const int y = std::max(area.y, std::min(centre.y - new_size.y / 2, area.GetBottom() + 1 - new_size.y)); + SetSize(x, y, new_size.x, new_size.y, wxSIZE_ALLOW_MINUS_ONE); +} + } // namespace GUI } // namespace Slic3r diff --git a/src/slic3r/GUI/MixedFilamentDialog.hpp b/src/slic3r/GUI/MixedFilamentDialog.hpp index 2e94b0c6e7..7d275a5c74 100644 --- a/src/slic3r/GUI/MixedFilamentDialog.hpp +++ b/src/slic3r/GUI/MixedFilamentDialog.hpp @@ -101,6 +101,8 @@ private: // Picks dialog (width, height) based on current state so the gradient curve // editor and the recommendation list stay visible at the same time. wxSize compute_dialog_size() const; + // Resizes the dialog to compute_dialog_size() around its centre, clamped to its display. + void resize_keeping_centre(); void rebuild_all_combos(); void rebuild_recommendation_items(); void refresh_curve_editor_colors(); diff --git a/src/slic3r/GUI/NotificationManager.cpp b/src/slic3r/GUI/NotificationManager.cpp index 31f1cfc6d6..f0aa8ac1d0 100644 --- a/src/slic3r/GUI/NotificationManager.cpp +++ b/src/slic3r/GUI/NotificationManager.cpp @@ -627,6 +627,10 @@ void NotificationManager::PopNotification::init() // Do not init closing notification if (is_finished()) return; + // Text is measured with the ImGui font, which the first ImGui frame sets up. Without a + // working OpenGL context that frame never comes, so stay Unknown and let render() init. + if (ImGui::GetFont() == nullptr) + return; // Text is measured with the font ImGuiWrapper::new_frame() builds on the first ImGui frame. A // notification pushed or updated before that (the app starts on Home, and slicing or arranging diff --git a/src/slic3r/GUI/OpenGLManager.cpp b/src/slic3r/GUI/OpenGLManager.cpp index cd882847e8..06aab8893f 100644 --- a/src/slic3r/GUI/OpenGLManager.cpp +++ b/src/slic3r/GUI/OpenGLManager.cpp @@ -3,6 +3,7 @@ #include "GUI.hpp" #include "I18N.hpp" +#include "format.hpp" #include "3DScene.hpp" #include "libslic3r/AppConfig.hpp" @@ -38,6 +39,12 @@ #include "../Utils/MacDarkMode.hpp" #endif // __APPLE__ +#ifdef _WIN32 +#include +#include +#include +#endif // _WIN32 + #ifdef __WXGTK__ #include "LinuxDisplayBackend.hpp" #ifdef wxHAS_EGL @@ -427,6 +434,96 @@ wxGLContext* OpenGLManager::init_glcontext(wxGLCanvas& canvas, const std::pairGetGLRC() == nullptr) + out << "no OpenGL context was created"; + else if (::wglMakeCurrent(hdc, context->GetGLRC()) != FALSE) { + retry_succeeded = true; + out << "wglMakeCurrent succeeded on retry"; + } else { + const DWORD error = ::GetLastError(); + out << "wglMakeCurrent failed with error " << error << " (" << std::system_category().message(static_cast(error)) << ")"; + } + + PIXELFORMATDESCRIPTOR pfd{}; + if (const int pixel_format = ::GetPixelFormat(hdc); pixel_format > 0 && ::DescribePixelFormat(hdc, pixel_format, sizeof(pfd), &pfd) > 0) + out << ", pixel format " << pixel_format << " (flags 0x" << std::hex << pfd.dwFlags << std::dec << ", color " + << static_cast(pfd.cColorBits) << ", depth " << static_cast(pfd.cDepthBits) << ", stencil " + << static_cast(pfd.cStencilBits) << ")"; + else + out << ", no pixel format on the canvas"; + + if (!display.device.empty()) + out << ", " << into_u8(display.device) << " on " << (display.adapter.empty() ? "an unknown adapter" : into_u8(display.adapter)); + return out.str(); +} +#endif // _WIN32 + +void OpenGLManager::report_make_current_failure([[maybe_unused]] const wxGLCanvas& canvas, [[maybe_unused]] const wxGLContext* context) +{ + if (m_make_current_failure_reported) + return; + m_make_current_failure_reported = true; +#ifdef _WIN32 + const CanvasDisplay display = canvas_display(canvas); + bool retry_succeeded = false; + BOOST_LOG_TRIVIAL(error) << "Cannot make the OpenGL context current on a shown canvas: " + << describe_make_current_failure(canvas, context, display, retry_succeeded); + // A failure after OpenGL came up, or one a retry clears, does not leave the 3D view empty. + if (m_gl_initialized || retry_succeeded) + return; + // The cause varies (no OpenGL driver behind the display, a disabled or broken driver, an overlay), + // so name the adapter Windows reports for the window's display instead of guessing one. + // TRN The OpenGL context could not be made current, so nothing can be drawn in the 3D view. + wxString message = _L("OpenGL could not be activated for the 3D view, so it cannot be shown."); + if (!display.adapter.empty()) { + message += "\n\n"; + // TRN %1% is the name of a graphics card or display adapter as Windows reports it, such as "Microsoft Basic Display Adapter". + message += format_wxstr(_L("The window is on a display driven by \"%1%\"."), display.adapter); + } + message += "\n\n"; + message += _L("Make sure the display adapter driving this window's display is enabled and its driver is installed and up to date."); + message += "\n"; + message += _L("If the computer has more than one graphics card, connecting the monitor to another one may help."); + message += "\n"; + message += _L("If the problem remains, close any overlay or screen capture software and try again."); + // show_error() defers the dialog, so it does not open inside the paint handler drawing the canvas. + show_error(nullptr, message); +#endif // _WIN32 +} + static const char* const SCENE_CANVAS_NAME = "OrcaSceneCanvas"; wxGLCanvas* OpenGLManager::create_wxglcanvas(wxWindow& parent) diff --git a/src/slic3r/GUI/OpenGLManager.hpp b/src/slic3r/GUI/OpenGLManager.hpp index 979e7cb2ec..3b7487a92d 100644 --- a/src/slic3r/GUI/OpenGLManager.hpp +++ b/src/slic3r/GUI/OpenGLManager.hpp @@ -77,6 +77,7 @@ private: }; bool m_gl_initialized{ false }; + bool m_make_current_failure_reported{ false }; wxGLContext* m_context{ nullptr }; GLShadersManager m_shaders_manager; static GLInfo s_gl_info; @@ -92,6 +93,10 @@ public: bool init_gl(bool popup_error = true); wxGLContext* init_glcontext(wxGLCanvas& canvas, const std::pair& required_opengl_version, bool enable_compatibility_profile, bool enable_debug); + // Called when the context cannot be made current on a shown canvas, which then stays empty. + // On Windows, logs why once per session and, if OpenGL never came up, tells the user. Elsewhere + // this does nothing: a GTK canvas can fail transiently until its surface is mapped. + void report_make_current_failure(const wxGLCanvas& canvas, const wxGLContext* context); GLShaderProgram* get_shader(const std::string& shader_name) { return m_shaders_manager.get_shader(shader_name); } GLShaderProgram* get_current_shader() { return m_shaders_manager.get_current_shader(); } diff --git a/src/slic3r/GUI/ReleaseNote.cpp b/src/slic3r/GUI/ReleaseNote.cpp index 9af36b676e..d8dfa1c049 100644 --- a/src/slic3r/GUI/ReleaseNote.cpp +++ b/src/slic3r/GUI/ReleaseNote.cpp @@ -73,7 +73,9 @@ #include "slic3r/GUI/DeviceManager.hpp" #include "slic3r/GUI/HMS.hpp" #include "slic3r/GUI/Widgets/ComboBox.hpp" +#include "slic3r/Utils/BBLPrinterAgent.hpp" #include "slic3r/Utils/NetworkAgent.hpp" +#include "slic3r/Utils/NetworkAgentFactory.hpp" #include #include @@ -1538,19 +1540,7 @@ InputIpAddressDialog::InputIpAddressDialog(wxWindow *parent) m_input_top_sizer->Add(m_tips_cafile, 0, wxTOP | wxEXPAND, FromDIP(10)); m_input_top_sizer->Add(cafile_input_sizer, 0, wxTOP | wxEXPAND, FromDIP(4)); m_input_top_sizer->Add(m_cafile_hint, 0, wxTOP | wxEXPAND, FromDIP(4)); - - if (!Http::ca_file_supported()) { - m_input_cafile->Disable(); - m_button_cafile->Disable(); - m_cafile_hint->SetLabel(_L("This system uses HTTPS certificates from the system Certificate Store or Keychain. To use a custom CA file, import it there.")); - m_cafile_hint->Wrap(FromDIP(352)); - } - - if (wxGetApp().preset_bundle) { - const auto& config = wxGetApp().preset_bundle->printers.get_edited_preset().config; - if (config.has("printhost_cafile")) - m_input_cafile->SetValue(from_u8(config.opt_string("printhost_cafile"))); - } + init_cafile_input(); ip_input_top_panel->SetSizer(m_input_top_sizer); ip_input_top_panel->Layout(); @@ -1818,6 +1808,7 @@ void InputIpAddressDialog::set_machine_obj(MachineObject* obj) m_input_ip->GetTextCtrl()->ChangeValue(m_obj->get_dev_ip()); m_input_access_code->GetTextCtrl()->ChangeValue(m_obj->get_access_code()); m_input_printer_name->GetTextCtrl()->ChangeValue(m_obj->get_dev_name()); + init_cafile_input(); // m_obj may use another agent than the current one std::string img_str = DevPrinterConfigUtil::get_printer_connect_help_img(m_obj->printer_type); if (img_str.empty()) { img_str = "input_access_code_x1"; } @@ -1931,12 +1922,47 @@ void InputIpAddressDialog::on_ok(wxMouseEvent& evt) config.opt_string("print_host") = str_ip; if (!port.empty()) config.opt_string("printhost_port") = port; - if (Http::ca_file_supported()) + if (!is_bbl_agent() && Http::ca_file_supported()) config.opt_string("printhost_cafile") = m_input_cafile->GetValue().ToStdString(); } + std::string str_ca_file = is_bbl_agent() ? into_u8(m_input_cafile->GetValue().Strip(wxString::both)) : std::string(); token_.reset(this, nop_deleter); - m_thread = new boost::thread(boost::bind(&InputIpAddressDialog::workerThreadFunc, this, str_ip, str_access_code, str_sn, str_model_id, str_name)); + m_thread = new boost::thread(boost::bind(&InputIpAddressDialog::workerThreadFunc, this, str_ip, str_access_code, str_sn, str_model_id, str_name, str_ca_file)); +} + +// Bambu printers check certificates in the network plug-in and keep their CA per device; other +// printers use curl and the printer preset's CA. +void InputIpAddressDialog::init_cafile_input() +{ + const bool bbl_agent = is_bbl_agent(); + const bool editable = bbl_agent || Http::ca_file_supported(); + m_input_cafile->Enable(editable); + m_button_cafile->Enable(editable); + m_cafile_hint->SetLabel(editable ? _L("HTTPS CA file is optional. It is only needed if you use HTTPS with a self-signed certificate.") : + _L("This system uses HTTPS certificates from the system Certificate Store or Keychain. To use a custom CA file, import it there.")); + m_cafile_hint->Wrap(FromDIP(352)); + + wxString ca_file; + if (bbl_agent) { + if (m_obj) + ca_file = from_u8(m_obj->get_ca_file()); + } else if (wxGetApp().preset_bundle) { + const auto& config = wxGetApp().preset_bundle->printers.get_edited_preset().config; + if (config.has("printhost_cafile")) + ca_file = from_u8(config.opt_string("printhost_cafile")); + } + m_input_cafile->ChangeValue(ca_file); +} + +bool InputIpAddressDialog::is_bbl_agent() const +{ + // Like MachineObject::connect: a printer without an agent id belongs to the current agent. + std::string agent_id = m_obj ? m_obj->printer_agent_id : std::string(); + if (agent_id.empty()) + if (DeviceManager* dev = wxGetApp().getDeviceManager()) + agent_id = dev->get_current_printer_agent_id(); + return agent_id.empty() || agent_id == BBL_PRINTER_AGENT_ID; } void InputIpAddressDialog::on_send_retry() @@ -1955,7 +1981,11 @@ void InputIpAddressDialog::on_send_retry() // check support function if (!m_obj) return; + const bool bbl_agent = is_bbl_agent(); + const std::string ca_file = into_u8(m_input_cafile->GetValue().Strip(wxString::both)); if (!m_obj->is_support_send_to_sdcard) { + if (bbl_agent) + m_obj->set_ca_file(ca_file); wxString input_str = wxString::Format("%s|%s", ip, str_access_code); auto event = wxCommandEvent(EVT_ENTER_IP_ADDRESS); event.SetString(input_str); @@ -1997,20 +2027,34 @@ void InputIpAddressDialog::on_send_retry() m_send_job->has_sdcard = m_obj->GetStorage()->get_sdcard_state() == DevStorage::SdcardState::HAS_SDCARD_NORMAL; m_send_job->set_check_mode(); m_send_job->set_project_name("verify_job"); + // The check connects before the CA is saved. + if (bbl_agent) + BBLPrinterAgent::trust_ca_file(m_obj->get_dev_id(), ca_file); m_send_job->on_check_ip_address_fail([this](int result) { this->check_ip_address_failed(result); }); - m_send_job->on_check_ip_address_success([this, ip, str_access_code]() { + // Runs on the job's worker thread. + m_send_job->on_check_ip_address_success([this, ip, str_access_code, bbl_agent, ca_file, dev_id = m_obj->get_dev_id()]() { + if (bbl_agent) { + wxGetApp().CallAfter([dev_id, ca_file]() { + if (DeviceManager* dev = wxGetApp().getDeviceManager()) + if (MachineObject* obj = dev->get_my_machine(dev_id)) + obj->set_ca_file(ca_file); + wxGetApp().app_config->save(); + }); + } wxString input_str = wxString::Format("%s|%s", ip, str_access_code); auto event = wxCommandEvent(EVT_ENTER_IP_ADDRESS); event.SetString(input_str); event.SetEventObject(this); wxPostEvent(this, event); - m_result = 0; - update_test_msg(_L("IP and Access Code Verified! You may close the window"), true); + CallAfter([this]() { + m_result = 0; + update_test_msg(_L("IP and Access Code Verified! You may close the window"), true); + }); }); replace_job(*m_worker, std::move(m_send_job)); @@ -2036,7 +2080,7 @@ void InputIpAddressDialog::post_update_test_msg(std::weak_ptr w = std::weak_ptr(token_); @@ -2093,7 +2137,7 @@ void InputIpAddressDialog::workerThreadFunc(std::string str_ip, std::string str_ } if (w.expired()) return; - CallAfter([this, detectData, str_ip, str_access_code, w]() { + CallAfter([this, detectData, str_ip, str_access_code, ca_file, w]() { DeviceManager* dev = wxGetApp().getDeviceManager(); BBLocalMachine machine; machine.dev_name = detectData.dev_name; @@ -2108,6 +2152,7 @@ void InputIpAddressDialog::workerThreadFunc(std::string str_ip, std::string str_ if (w.expired()) return; if (m_obj) { + m_obj->set_ca_file(ca_file, false); // saved together with the access code below m_obj->set_access_code(str_access_code); wxGetApp().getDeviceManager()->set_selected_machine(m_obj->get_dev_id()); } diff --git a/src/slic3r/GUI/ReleaseNote.hpp b/src/slic3r/GUI/ReleaseNote.hpp index fbb01ac0ee..71159feada 100644 --- a/src/slic3r/GUI/ReleaseNote.hpp +++ b/src/slic3r/GUI/ReleaseNote.hpp @@ -364,7 +364,9 @@ public: void on_send_retry(); void update_test_msg_event(wxCommandEvent &evt); void post_update_test_msg(std::weak_ptr w, wxString text, bool beconnect); - void workerThreadFunc(std::string str_ip, std::string str_access_code, std::string sn, std::string model_id, std::string name); + void workerThreadFunc(std::string str_ip, std::string str_access_code, std::string sn, std::string model_id, std::string name, std::string ca_file); + bool is_bbl_agent() const; + void init_cafile_input(); void OnTimer(wxTimerEvent& event); void on_text(wxCommandEvent& evt); void on_dpi_changed(const wxRect& suggested_rect) override; diff --git a/src/slic3r/Utils/BBLPrinterAgent.cpp b/src/slic3r/Utils/BBLPrinterAgent.cpp index fbf4826184..b71d6cd768 100644 --- a/src/slic3r/Utils/BBLPrinterAgent.cpp +++ b/src/slic3r/Utils/BBLPrinterAgent.cpp @@ -9,16 +9,31 @@ #include #include +#include +#include +#include +#include #include #include #include #include #include +#include +#include #include +#include +#include +#include +#include +#include +#include #include +#include +#include #include #include #include +#include #include #include using json = nlohmann::json; @@ -123,8 +138,84 @@ To as_abi(From fn) return reinterpret_cast(reinterpret_cast(fn)); } +// The certificates in pem, re-encoded, when there is at least one and every one is a CA; else "". +// Only what OpenSSL parsed ends up in printer.cer, never the rest of the file. +std::string ca_certificates_pem(const std::string& pem) +{ + std::unique_ptr in(BIO_new_mem_buf(pem.data(), int(pem.size())), &BIO_free); + std::unique_ptr out(BIO_new(BIO_s_mem()), &BIO_free); + if (!in || !out) + return {}; + + ERR_clear_error(); + int count = 0; + bool ok = true; + // Never prompt for a passphrase: an encrypted block counts as broken. + pem_password_cb* const no_passphrase = [](char*, int, int, void*) { return 0; }; + while (X509* cert = PEM_read_bio_X509(in.get(), nullptr, no_passphrase, nullptr)) { + ok = ok && X509_check_ca(cert) >= 1 && PEM_write_bio_X509(out.get(), cert) == 1; + X509_free(cert); + ++count; + } + // Reading ends with "no start line" at the end of the input; any other error is a broken certificate. + const unsigned long err = ERR_peek_last_error(); + ok = ok && count > 0 && ERR_GET_LIB(err) == ERR_LIB_PEM && ERR_GET_REASON(err) == PEM_R_NO_START_LINE; + ERR_clear_error(); + if (!ok) + return {}; + + char* data = nullptr; + const long size = BIO_get_mem_data(out.get(), &data); + return std::string(data, size_t(size)); +} + +// Replaces path in one step and only when its content changes: the plug-in may read it at any time. +void replace_file(const boost::filesystem::path& path, const std::string& content) +{ + if (boost::filesystem::exists(path)) { + std::string current; + load_string_file(path, current); + if (current == content) + return; + } + const boost::filesystem::path tmp = path.string() + ".tmp"; + save_string_file(tmp, content); + if (const std::error_code ec = rename_file(tmp.string(), path.string())) + throw std::system_error(ec, "Cannot replace " + path.string()); +} + } // namespace +// The plug-in has one cert folder for all printers, and multi-printer sending talks to several at +// once, so the folder trusts the CA file of every printer connected this session. It is rebuilt and +// re-pointed on every connect: restarting networking points the plug-in back at the bundled folder +// (GUI_App), and a renewed, changed or cleared CA file is picked up. Re-pointing after start() +// takes effect on the next connection. +void BBLPrinterAgent::trust_ca_file(const std::string& dev_id, const std::string& ca_file) +{ + static std::mutex mutex; + static std::map ca_file_by_dev; + + auto& plugin = BBLNetworkPlugin::instance(); + auto agent = plugin.get_agent(); + auto set_cert_file = plugin.get_set_cert_file(); + if (!agent || !set_cert_file) + return; + + std::lock_guard lock(mutex); + if (ca_file.empty() && ca_file_by_dev.erase(dev_id) == 0) + return; // a printer without a CA leaves the folder as it is + if (!ca_file.empty()) + ca_file_by_dev[dev_id] = ca_file; + + std::set ca_files; + for (const auto& [id, file] : ca_file_by_dev) + ca_files.insert(file); + const std::string cert_dir = cert_dir_with_cas(resources_dir() + "/cert", data_dir() + "/cert", ca_files); + if (const int ret = set_cert_file(agent, cert_dir, "slicer_base64.cer"); ret != 0) + BOOST_LOG_TRIVIAL(warning) << "BBLPrinterAgent: set_cert_file(" << cert_dir << ") failed, ret = " << ret; +} + std::string BBLPrinterAgent::to_orca_filament_id(const std::string& printer_filament_id) const { const auto& map = bambu_filament_id_map().to_orca; @@ -296,11 +387,57 @@ int BBLPrinterAgent::connect_printer(const PrinterConnectionParams& params) } #endif if (func && agent) { + trust_ca_file(params.dev_id, params.ca_file); return func(agent, params.dev_id, params.host, params.username, params.password, use_ssl_for_mqtt); } return -1; } +std::string BBLPrinterAgent::cert_dir_with_cas(const std::string& bundled_dir, const std::string& out_dir, const std::set& extra_cas) +{ + namespace fs = boost::filesystem; + + std::string extra; + for (const std::string& ca_file : extra_cas) { + std::string pem; + try { + load_string_file(ca_file, pem); + } catch (const std::exception&) { + pem.clear(); + } + const std::string certs = ca_certificates_pem(pem); + if (certs.empty()) { + BOOST_LOG_TRIVIAL(warning) << "Ignoring CA file, it holds no readable CA certificate: " << ca_file; + continue; + } + extra += certs; + } + if (extra.empty()) + return bundled_dir; + + try { + std::string bundle; + load_string_file(fs::path(bundled_dir) / "printer.cer", bundle); + if (!bundle.empty() && bundle.back() != '\n') + bundle += '\n'; + + const fs::path out(out_dir); + fs::create_directories(out); + for (const fs::directory_entry& entry : fs::directory_iterator(bundled_dir)) { + if (!fs::is_regular_file(entry.status()) || entry.path().filename() == "printer.cer") + continue; + std::string content; + load_string_file(entry.path(), content); + replace_file(out / entry.path().filename(), content); + } + replace_file(out / "printer.cer", bundle + extra); + } catch (const std::exception& e) { + BOOST_LOG_TRIVIAL(error) << "Cannot build cert folder with custom CAs, using the bundled one: " << e.what(); + return bundled_dir; + } + return out_dir; +} + int BBLPrinterAgent::disconnect_printer() { auto& plugin = BBLNetworkPlugin::instance(); diff --git a/src/slic3r/Utils/BBLPrinterAgent.hpp b/src/slic3r/Utils/BBLPrinterAgent.hpp index 02e45276b6..73c20ee7c9 100644 --- a/src/slic3r/Utils/BBLPrinterAgent.hpp +++ b/src/slic3r/Utils/BBLPrinterAgent.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include namespace Slic3r { class ICloudServiceAgent; } @@ -112,6 +113,16 @@ public: static std::string to_orca_payload(std::string json_text); static std::string from_orca_payload(std::string json_text); + // The plug-in checks LAN MQTT and FTPS certificates against /printer.cer. A printer + // behind a proxy with its own CA (the "HTTPS CA File" of the connect dialog) needs that CA there + // too. Writes out_dir/printer.cer as bundled_dir/printer.cer plus the certificates of every file + // in extra_cas that holds only CA certificates, copies the other files of bundled_dir, and + // returns out_dir. Files are replaced in one step, and only when their content changes. + // Returns bundled_dir when no extra CA is usable or out_dir cannot be written. + static std::string cert_dir_with_cas(const std::string& bundled_dir, const std::string& out_dir, const std::set& extra_cas); + // Sets the CA file the plug-in's cert folder trusts for dev_id; an empty ca_file removes it. + static void trust_ca_file(const std::string& dev_id, const std::string& ca_file); + private: int publish(const std::string& dev_id, const nlohmann::json& j, bool lan_mode); }; diff --git a/src/slic3r/Utils/CrealityPrintAgent.cpp b/src/slic3r/Utils/CrealityPrintAgent.cpp index d1b106cce2..cba3cde126 100644 --- a/src/slic3r/Utils/CrealityPrintAgent.cpp +++ b/src/slic3r/Utils/CrealityPrintAgent.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -34,17 +35,6 @@ std::string to_lower(std::string s) return s; } -bool has_visible_base_preset(const PresetCollection& filaments, const std::string& filament_id) -{ - for (const auto& p : filaments.get_presets()) { - if (p.is_visible && p.is_compatible - && filaments.get_preset_base(p) == &p - && p.filament_id == filament_id) - return true; - } - return false; -} - // Lower-case words of a preset name with the "@scope" suffix dropped: // "Generic PLA Matte @Creality K2-all" -> {"generic", "pla", "matte"}. std::vector name_words(const std::string& name) @@ -150,12 +140,11 @@ std::string CrealityPrintAgent::match_filament_preset(const PresetCollection& fi } if (matches.empty()) { - // first_visible_idx_by_type() returns any visible preset when no base of this - // type exists. Never sync an unrelated material to the CFS. - const auto& fallback_preset = filaments.preset(filaments.first_visible_idx_by_type(base_type)); - const std::string fallback = fallback_preset.filament_id; - const bool fallback_ok = fallback_preset.config.opt_string("filament_type", 0u) == base_type && - has_visible_base_preset(filaments, fallback); + // Only a visible base of exactly this type; never sync another material to the CFS. + const size_t fallback_idx = filaments.first_visible_idx_by_type(base_type); + const Preset* fallback_preset = fallback_idx == size_t(-1) ? nullptr : &filaments.preset(fallback_idx); + const std::string fallback = fallback_preset ? fallback_preset->filament_id : std::string(); + const bool fallback_ok = fallback_preset && fallback_preset->config.opt_string("filament_type", 0u) == base_type; BOOST_LOG_TRIVIAL(info) << "CrealityPrintAgent: no preset scored for spool {" << vendor << " " << brand_name << " (" << base_type << ")} after considering " << considered diff --git a/src/slic3r/Utils/MoonrakerPrinterAgent.cpp b/src/slic3r/Utils/MoonrakerPrinterAgent.cpp index 5ed453b853..0e17a1f35b 100644 --- a/src/slic3r/Utils/MoonrakerPrinterAgent.cpp +++ b/src/slic3r/Utils/MoonrakerPrinterAgent.cpp @@ -801,7 +801,11 @@ std::string MoonrakerPrinterAgent::map_filament_type_to_generic_id(const std::st static const std::map type_to_ofl_family = { // PLA variants {"PLA", "PLA"}, + {"PLA+", "PLA"}, + {"PLA PRO", "PLA"}, {"PLA-CF", "PLA-CF"}, + {"PLA MATTE", "PLA Matte"}, + {"PLA-MATTE", "PLA Matte"}, {"PLA SILK", "PLA Silk"}, {"PLA-SILK", "PLA Silk"}, {"PLA HIGH SPEED", "PLA High Speed"}, @@ -810,11 +814,16 @@ std::string MoonrakerPrinterAgent::map_filament_type_to_generic_id(const std::st // ABS/ASA variants {"ABS", "ABS"}, + {"ABS+", "ABS"}, {"ASA", "ASA"}, // PETG/PET variants {"PETG", "PETG"}, + {"PETG+", "PETG"}, {"PET", "PETG"}, + {"PETG HF", "PETG HF"}, + {"PETG-HF", "PETG HF"}, + {"PETG-CF", "PETG-CF"}, {"PCTG", "PCTG"}, // PA/Nylon variants @@ -830,7 +839,10 @@ std::string MoonrakerPrinterAgent::map_filament_type_to_generic_id(const std::st // PP/PE variants {"PE", "PE"}, + {"PE-CF", "PE-CF"}, {"PP", "PP"}, + {"PP-CF", "PP-CF"}, + {"PP-GF", "PP-GF"}, // Support materials {"PVA", "PVA"}, @@ -888,8 +900,9 @@ bool MoonrakerPrinterAgent::fetch_creality_cfs_data(std::vector& tr data.tray_type = slot.material_type; data.tray_color = slot.color; data.has_filament = true; - data.tray_info_idx = bundle ? bundle->filaments.filament_id_by_type(data.tray_type) - : map_filament_type_to_generic_id(data.tray_type); + data.tray_info_idx = bundle ? bundle->filaments.filament_id_by_type(data.tray_type) : std::string(); + if (data.tray_info_idx.empty()) + data.tray_info_idx = map_filament_type_to_generic_id(data.tray_type); max_lane_index = std::max(max_lane_index, data.slot_index); trays.push_back(std::move(data)); } @@ -1049,10 +1062,10 @@ bool MoonrakerPrinterAgent::fetch_moonraker_filament_data(std::vectorfilaments.filament_id_by_type(tray.tray_type); if (tray.tray_info_idx.empty()) - tray.tray_info_idx = bundle - ? bundle->filaments.filament_id_by_type(tray.tray_type) - : map_filament_type_to_generic_id(tray.tray_type); + tray.tray_info_idx = map_filament_type_to_generic_id(tray.tray_type); max_lane_index = std::max(max_lane_index, lane_index); trays.push_back(tray); @@ -1178,9 +1191,9 @@ bool MoonrakerPrinterAgent::fetch_hh_filament_info(std::vector& tra tray.has_filament = true; auto* bundle = GUI::wxGetApp().preset_bundle; - tray.tray_info_idx = bundle - ? bundle->filaments.filament_id_by_type(tray.tray_type) - : map_filament_type_to_generic_id(tray.tray_type); + tray.tray_info_idx = bundle ? bundle->filaments.filament_id_by_type(tray.tray_type) : std::string(); + if (tray.tray_info_idx.empty()) + tray.tray_info_idx = map_filament_type_to_generic_id(tray.tray_type); max_lane_index = std::max(max_lane_index, gate_idx); trays.push_back(tray); diff --git a/src/slic3r/Utils/QidiPrinterAgent.cpp b/src/slic3r/Utils/QidiPrinterAgent.cpp index bf1a14ee95..93f3c1bca8 100644 --- a/src/slic3r/Utils/QidiPrinterAgent.cpp +++ b/src/slic3r/Utils/QidiPrinterAgent.cpp @@ -267,6 +267,8 @@ bool QidiPrinterAgent::fetch_slot_info(const std::string& base_url, tray.tray_info_idx = setting_id; } else { tray.tray_info_idx = bundle->filaments.filament_id_by_type(tray.tray_type); + if (tray.tray_info_idx.empty()) + tray.tray_info_idx = map_filament_type_to_generic_id(tray.tray_type); } // Look up color from dictionary diff --git a/src/slic3r/Utils/SnapmakerPrinterAgent.cpp b/src/slic3r/Utils/SnapmakerPrinterAgent.cpp index 4a66646963..9f42b64d08 100644 --- a/src/slic3r/Utils/SnapmakerPrinterAgent.cpp +++ b/src/slic3r/Utils/SnapmakerPrinterAgent.cpp @@ -13,6 +13,8 @@ #include "libslic3r/Preset.hpp" #include #include +#include +#include namespace Slic3r { @@ -20,6 +22,14 @@ namespace { constexpr const char* SNAPMAKER_AGENT_VERSION = "0.0.1"; +// Ranks a candidate that declares no usable colour behind every candidate that does, while +// still leaving it ahead of no match at all. The largest real distance is 3 * 255^2 = 195075. +constexpr unsigned int UNRANKED_COLOR_DISTANCE = 0xfffffffeu; + +// filament_vendor of the presets Orca ships in OrcaFilamentLibrary, set in that library's own +// filament/base/fdm_filament_common.json, so every "Generic ..." preset inherits it. +constexpr const char* GENERIC_FILAMENT_VENDOR = "Generic"; + // Safely access a parallel array by index, returning a fallback if out of bounds. template T safe_at(const std::vector& vec, int index, const T& fallback) @@ -27,44 +37,154 @@ T safe_at(const std::vector& vec, int index, const T& fallback) return (index >= 0 && index < static_cast(vec.size())) ? vec[index] : fallback; } -std::string find_closest_color_preset_by_vendor_and_type(const PresetCollection& filaments, - const std::string& vendor_name, - const std::string& filament_type, - const std::string& color_rgba) +// Parse the RRGGBB part of a colour into 0xRRGGBB, skipping a leading '#' and +// dropping any alpha channel. Returns false rather than letting std::stoul throw +// on an empty or malformed value. +bool parse_rgb(const std::string& value, unsigned int& out) { - std::string best_match_id = ""; - int best_color_distance = 0xffffffff; + const size_t hash_pos = value.find('#'); + std::string digits = value.substr(hash_pos != std::string::npos ? hash_pos + 1 : 0); + if (digits.size() > 6) + digits.resize(6); + if (digits.size() != 6) + return false; + for (char c : digits) { + if (!std::isxdigit(static_cast(c))) + return false; + } + out = static_cast(std::stoul(digits, nullptr, 16)); + return true; +} + +// Case-insensitive whole-word search. The needle must not be flanked by alphanumeric +// characters, so "CF" matches "PETG-CF" and "PLA CF" but not "Scaffold" or "CF10". +bool contains_word_ci(const std::string& haystack, const std::string& needle) +{ + if (needle.empty() || needle.size() > haystack.size()) + return false; + + const auto equal_ci = [](unsigned char a, unsigned char b) { return std::toupper(a) == std::toupper(b); }; + const auto is_word = [](char c) { return std::isalnum(static_cast(c)) != 0; }; + + for (auto it = haystack.begin(); it != haystack.end(); ++it) { + it = std::search(it, haystack.end(), needle.begin(), needle.end(), equal_ci); + if (it == haystack.end()) + return false; + + const auto after = it + static_cast(needle.size()); + const bool left_ok = it == haystack.begin() || !is_word(*(it - 1)); + const bool right_ok = after == haystack.end() || !is_word(*after); + if (left_ok && right_ok) + return true; + } + return false; +} + +// A tag reports the fibre loading in its sub type ("CF10", "GF30"), while the material types in +// MaterialType::all() and the profile names only ever say CF or GF. Expects upper case input. +std::string normalize_fibre_sub_type(const std::string& sub) +{ + for (const char* fibre : {"CF", "GF"}) { + const std::string prefix = fibre; + if (sub.size() >= prefix.size() && sub.compare(0, prefix.size(), prefix) == 0 && + std::all_of(sub.begin() + static_cast(prefix.size()), sub.end(), + [](char c) { return std::isdigit(static_cast(c)) != 0; })) + return prefix; + } + return sub; +} + +// Like contains_word_ci, but a trailing digit run belongs to the same word, so a CF sub type +// matches a "PA12-CF10" preset as well as "PA12-CF". A trailing letter does not: "CFX" is +// a different product. +bool contains_sub_type_ci(const std::string& haystack, const std::string& needle) +{ + if (needle.empty() || needle.size() > haystack.size()) + return false; + + const auto equal_ci = [](unsigned char a, unsigned char b) { return std::toupper(a) == std::toupper(b); }; + const auto is_word = [](char c) { return std::isalnum(static_cast(c)) != 0; }; + + for (auto it = haystack.begin(); it != haystack.end(); ++it) { + it = std::search(it, haystack.end(), needle.begin(), needle.end(), equal_ci); + if (it == haystack.end()) + return false; + + auto after = it + static_cast(needle.size()); + while (after != haystack.end() && std::isdigit(static_cast(*after)) != 0) + ++after; + + const bool left_ok = it == haystack.begin() || !is_word(*(it - 1)); + const bool right_ok = after == haystack.end() || !is_word(*after); + if (left_ok && right_ok) + return true; + } + return false; +} + +// Tags written by older tools (or as a workaround) carry the full product name in the vendor +// field, e.g. vendor "Anycubic PLA Basic" with an empty sub type, while profiles may use either +// "Anycubic" or "Anycubic PLA Basic". Treat the vendors as matching when they are equal or when +// either contains the other as whole words, ignoring case. +bool vendor_matches(const std::string& tag_vendor, const std::string& profile_vendor) +{ + if (tag_vendor.empty() || profile_vendor.empty()) + return false; + return contains_word_ci(tag_vendor, profile_vendor) || contains_word_ci(profile_vendor, tag_vendor); +} +// Rank the visible, compatible base presets of one filament type by colour distance, preferring a +// name that carries the spool's sub type. Candidates are limited to vendor_filter, which nothing +// matches when it is empty; tag_vendor is the tag's own vendor field, which a legacy tag uses to +// name the variant. +std::string closest_preset_by_colour(const PresetCollection& filaments, const std::string& vendor_filter, + const std::string& tag_vendor, const std::string& filament_type, + const std::string& sub_wanted, unsigned int target_color_value) +{ + std::string best_match_id = ""; + unsigned int best_color_distance = 0xffffffffu; + bool best_matches_sub = false; for (const auto& p : filaments.get_presets()) { - if (p.is_visible && p.is_compatible && - // Filament profile must be detached from parent to be considered for matching - filaments.get_preset_base(p) == &p && p.config.opt_string("filament_vendor", 0u) == vendor_name && + // Only a base preset can be loaded: sync_ams_list() resolves a filament_id to the first + // base preset carrying it, so a derived copy never loads and could outrank its parent. + if (p.is_visible && p.is_compatible && filaments.get_preset_base(p) == &p && !p.filament_id.empty() && + vendor_matches(vendor_filter, p.config.opt_string("filament_vendor", 0u)) && p.config.opt_string("filament_type", 0u) == filament_type) { - // The printer returns RGBA in the format RRGGBBAA, but profiles store color as #RRGGBB, - // so we must remove # and ignore alpha channel for distance calculation - unsigned int target_color_value = std::stoul(color_rgba.substr(0, color_rgba.length() - 2), nullptr, 16); - - std::string p_color = p.config.opt_string("default_filament_colour", 0u); - unsigned int p_color_value; - if (!p_color.empty()) { - size_t hash_pos = p_color.find("#"); - p_color_value = std::stoul(p_color.substr(hash_pos != std::string::npos ? hash_pos + 1 : 0), nullptr, 16); - } else { - // Default to black if no color specified in profile. Assume other profiles might be a closer color match. - // Could be a problem if the target color is also black and there exist a specific profile for that type, vendor and color - // combination. - p_color_value = 0; + // A profile that specifies no colour, or one that cannot be parsed, is unranked: it + // is kept as a last resort rather than scored as black, which would otherwise let a + // colourless profile win every dark spool and beat profiles that do declare a colour. + std::string p_color = p.config.opt_string("default_filament_colour", 0u); + unsigned int p_color_value = 0; + unsigned int distance = UNRANKED_COLOR_DISTANCE; + if (parse_rgb(p_color, p_color_value)) { + // Euclidean colour distance in RGB space + const int dr = ((target_color_value & 0xff) - (p_color_value & 0xff)); + const int dg = (((target_color_value >> 8) & 0xff) - ((p_color_value >> 8) & 0xff)); + const int db = (((target_color_value >> 16) & 0xff) - ((p_color_value >> 16) & 0xff)); + distance = static_cast(dr * dr + dg * dg + db * db); } - // Calculate Euclidean color distance in RGB space - int dr = ((target_color_value & 0xff) - (p_color_value & 0xff)); - int dg = (((target_color_value >> 8) & 0xff) - ((p_color_value >> 8) & 0xff)); - int db = (((target_color_value >> 16) & 0xff) - ((p_color_value >> 16) & 0xff)); - unsigned int distance = dr * dr + dg * dg + db * db; + // Variants (Matte, Silk, Basic, Eco, ...) are not filament_type values -- the + // profiles carry them in the preset name, so "Snapmaker PLA Matte" and + // "Snapmaker PLA Basic" are both vendor Snapmaker, type PLA. Prefer a candidate + // whose name mentions the spool's sub type, and rank by colour within that + // preference, so a matte spool stops resolving to whichever variant happens to + // sit nearest in colour. + // A profile's own filament_subtype counts too. When the tag has no sub type, a + // legacy tag may still name the variant in its vendor field ("Anycubic PLA Silk"), + // so look for the profile's subtype, or the whole tag vendor, there instead. + const std::string p_sub = p.config.has("filament_subtype") ? p.config.opt_string("filament_subtype", 0u) : std::string(); + const bool matches_sub = !sub_wanted.empty() ? + (contains_sub_type_ci(p.name, sub_wanted) || contains_sub_type_ci(p_sub, sub_wanted)) : + (contains_word_ci(tag_vendor, p_sub) || contains_word_ci(p.name, tag_vendor) || + contains_word_ci(tag_vendor, p.name)); + if (best_matches_sub && !matches_sub) + continue; - if (distance < best_color_distance) { + if ((matches_sub && !best_matches_sub) || distance < best_color_distance) { best_color_distance = distance; best_match_id = p.filament_id; + best_matches_sub = matches_sub; } } } @@ -73,6 +193,38 @@ std::string find_closest_color_preset_by_vendor_and_type(const PresetCollection& } // anonymous namespace +std::string SnapmakerPrinterAgent::find_closest_color_preset_by_vendor_and_type(const PresetCollection& filaments, + const std::string& vendor_name, + const std::string& filament_type, + const std::string& sub_type, + const std::string& color_rgba) +{ + // The printer returns RGBA in the format RRGGBBAA, but profiles store color as #RRGGBB, + // so we must remove # and ignore alpha channel for distance calculation. + // An unusable colour cannot rank candidates; leave the match to the type-only lookup. + unsigned int target_color_value = 0; + if (!parse_rgb(color_rgba, target_color_value)) + return {}; + + const std::string sub_wanted = normalize_fibre_sub_type(trim_and_upper(sub_type)); + + // The spool's own vendor first, with the sub type as a preference. A tag that reports no + // vendor matches no profile's filament_vendor, so such a spool finds nothing in this pass. + const std::string vendor_match = closest_preset_by_colour(filaments, vendor_name, vendor_name, filament_type, + sub_wanted, target_color_value); + if (!vendor_match.empty()) + return vendor_match; + + // Orca ships no preset for this spool's vendor, so fall back to its own Generic presets: they + // cover the sub types the U1 sees (Generic PLA Silk @U1, Generic PLA High Speed @U1, + // Generic PETG HF @U1) and carry no other brand's temperatures or flow. That beats another + // brand's preset of the same finish, and it beats the caller's fallback, + // filament_id_by_type(), which takes the first visible preset of the type whatever its vendor + // and finish. + return closest_preset_by_colour(filaments, GENERIC_FILAMENT_VENDOR, vendor_name, filament_type, sub_wanted, + target_color_value); +} + SnapmakerPrinterAgent::SnapmakerPrinterAgent(std::string log_dir) : MoonrakerPrinterAgent(std::move(log_dir)) {} AgentInfo SnapmakerPrinterAgent::get_agent_info_static() @@ -91,22 +243,17 @@ std::string SnapmakerPrinterAgent::combine_filament_type(const std::string& type if (sub.empty() || sub == "NONE") return base; - if (sub == "CF") - return base + "-CF"; - if (sub == "GF") - return base + "-GF"; - if (sub == "SNAPSPEED" || sub == "HS") - return base + " HIGH SPEED"; - if (sub == "SILK") - return base + " SILK"; - if (sub == "WOOD") - return base + " WOOD"; - if (sub == "MATTE") - return base + " MATTE"; - if (sub == "MARBLE") - return base + " MARBLE"; + // Only CF and GF are material types, whatever fibre loading the tag reports ("CF10"); skip + // the suffix when the base already carries it. + const std::string fibre = normalize_fibre_sub_type(sub); + if (fibre == "CF" || fibre == "GF") { + const std::string suffix = "-" + fibre; + const bool has_suffix = base.size() >= suffix.size() && + base.compare(base.size() - suffix.size(), suffix.size(), suffix) == 0; + return has_suffix ? base : base + suffix; + } - // Unrecognized sub-type (brand names like Polylite, Basic, etc.) -- use base type only + // Every other sub type is a finish or a brand name, not a material type. return base; } @@ -192,24 +339,31 @@ bool SnapmakerPrinterAgent::fetch_filament_info(std::string dev_id, FilamentSync tray.has_filament = filament_exist[i]; if (tray.has_filament) { - tray.tray_type = combine_filament_type(safe_at(filament_type, i, empty_str), - safe_at(filament_sub_type, i, empty_str)); - tray.tray_color = safe_at(filament_color, i, default_color); + const std::string raw_sub_type = safe_at(filament_sub_type, i, empty_str); + tray.tray_type = combine_filament_type(safe_at(filament_type, i, empty_str), raw_sub_type); + tray.tray_color = safe_at(filament_color, i, empty_str); + if (tray.tray_color.empty()) + tray.tray_color = default_color; auto* bundle = GUI::wxGetApp().preset_bundle; // Try to find a matching preset for this filament based on vendor, type and color. // If not found, default to traditional search by type only or generic type mapping. if (bundle) { - std::string vendor = safe_at(filament_vendor, i, empty_str); + std::string vendor = safe_at(filament_vendor, i, empty_str); + std::string sub_type = raw_sub_type; + if (trim_and_upper(sub_type) == "NONE") + sub_type.clear(); std::string filament_id = find_closest_color_preset_by_vendor_and_type(bundle->filaments, vendor, tray.tray_type, - tray.tray_color); + sub_type, tray.tray_color); if (!filament_id.empty()) { tray.tray_info_idx = filament_id; - BOOST_LOG_TRIVIAL(warning) << "Filament sync: Found manufacturer-specific profile for slot " << i << ": " + BOOST_LOG_TRIVIAL(warning) << "Filament sync: Found profile for slot " << i << ": " << filament_id; } else { tray.tray_info_idx = bundle->filaments.filament_id_by_type(tray.tray_type); + if (tray.tray_info_idx.empty()) + tray.tray_info_idx = map_filament_type_to_generic_id(tray.tray_type); } } else { tray.tray_info_idx = map_filament_type_to_generic_id(tray.tray_type); @@ -218,11 +372,9 @@ bool SnapmakerPrinterAgent::fetch_filament_info(std::string dev_id, FilamentSync // Extract NFC temperature data if available if (nfc_info.is_array() && i < static_cast(nfc_info.size()) && nfc_info[i].is_object()) { auto& nfc_slot = nfc_info[i]; - std::string vendor = nfc_slot.value("VENDOR", "NONE"); - if (vendor != "NONE" && !vendor.empty()) { - tray.bed_temp = nfc_slot.value("BED_TEMP", 0); - tray.nozzle_temp = nfc_slot.value("FIRST_LAYER_TEMP", 0); - } + tray.bed_temp = safe_json_int(nfc_slot, "BED_TEMP"); + // build_ams_payload publishes this as `nozzle_temp_max`, and FIRST_LAYER_TEMP is 0 for external tags. + tray.nozzle_temp = safe_json_int(nfc_slot, "HOTEND_MAX_TEMP"); } } diff --git a/src/slic3r/Utils/SnapmakerPrinterAgent.hpp b/src/slic3r/Utils/SnapmakerPrinterAgent.hpp index 39b642081b..11fcda7a74 100644 --- a/src/slic3r/Utils/SnapmakerPrinterAgent.hpp +++ b/src/slic3r/Utils/SnapmakerPrinterAgent.hpp @@ -7,6 +7,8 @@ namespace Slic3r { +class PresetCollection; + class SnapmakerPrinterAgent final : public MoonrakerPrinterAgent { public: @@ -18,7 +20,14 @@ public: bool fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode = FilamentSyncMode::pull) override; -private: + // Pick the filament_id of the closest visible base preset for a spool's vendor, type, sub type + // and colour. Static so the matcher can be exercised without a printer. + static std::string find_closest_color_preset_by_vendor_and_type(const PresetCollection& filaments, + const std::string& vendor_name, + const std::string& filament_type, + const std::string& sub_type, + const std::string& color_rgba); + // Combine filament_type + filament_sub_type into a unified type string static std::string combine_filament_type(const std::string& type, const std::string& sub_type); }; diff --git a/src/slic3r/plugin/PluginHooks.cpp b/src/slic3r/plugin/PluginHooks.cpp index 0088bc1477..347687a20b 100644 --- a/src/slic3r/plugin/PluginHooks.cpp +++ b/src/slic3r/plugin/PluginHooks.cpp @@ -1,6 +1,7 @@ #include "PluginHooks.hpp" #include "PluginManager.hpp" +#include "PluginResolver.hpp" #include "PythonInterpreter.hpp" #include "PythonPluginInterface.hpp" #include "pluginTypes/slicingPipeline/SlicingPipelinePluginCapability.hpp" @@ -33,24 +34,8 @@ namespace { void install_capability_resolver() { ConfigBase::set_resolve_capability_fn([](const std::string& cap_name, const std::string& cap_type) { - PluginManager& plugin_mgr = PluginManager::instance(); - const PluginCapabilityType type = plugin_capability_type_from_string(cap_type); - // only_enabled = false: this resolves the reference a preset STORES, which must stay - // resolvable whether or not the user currently has the capability enabled. Filtering on - // the enable flag here would quietly drop the reference out of the preset's manifest. - auto plugin_cap = plugin_mgr.get_plugin_capability(cap_name, type, /*only_enabled=*/false); - if (!plugin_cap) - return std::string(); - - PluginDescriptor descriptor; - if (!plugin_mgr.try_get_plugin_descriptor_for_capability(cap_name, type, descriptor)) - return std::string(); - - // Cloud plugins are resolved at runtime via the UUID in the middle field, so the first - // field keeps the friendly display name. Local plugins are looked up by plugin_key (the - // first field, with an empty UUID), so emit the plugin_key to keep them resolvable. - const std::string identity = descriptor.is_cloud_plugin() ? descriptor.name : descriptor.plugin_key; - return identity + ';' + descriptor.cloud_uuid() + ';' + cap_name; + const auto ref = PluginManager::instance().resolve_capability_ref(cap_name, plugin_capability_type_from_string(cap_type)); + return ref ? create_full_ref(*ref) : std::string(); }); } diff --git a/src/slic3r/plugin/PluginManager.cpp b/src/slic3r/plugin/PluginManager.cpp index b5bd92e8b5..447e7e3943 100644 --- a/src/slic3r/plugin/PluginManager.cpp +++ b/src/slic3r/plugin/PluginManager.cpp @@ -5,6 +5,7 @@ #include #include #include +#include "libslic3r/Config.hpp" #include "libslic3r/LifecycleEvents.hpp" #include #include @@ -586,6 +587,24 @@ bool PluginManager::try_get_plugin_descriptor_for_capability(const std::string& return false; } +std::optional PluginManager::resolve_capability_ref(const std::string& capability_name, + PluginCapabilityType type) const +{ + // only_enabled = false: a stored reference must stay resolvable whether or not the user + // currently has the capability enabled; the dispatchers report "disabled" separately. + if (!get_plugin_capability(capability_name, type, /*only_enabled=*/false)) + return std::nullopt; + + PluginDescriptor descriptor; + if (!try_get_plugin_descriptor_for_capability(capability_name, type, descriptor)) + return std::nullopt; + + // Cloud plugins are resolved at runtime via the UUID, so the name field keeps the friendly + // display name. Local plugins are looked up by plugin_key with an empty UUID. + const std::string identity = descriptor.is_cloud_plugin() ? descriptor.name : descriptor.plugin_key; + return PluginCapabilityRef{identity, capability_name, descriptor.cloud_uuid()}; +} + std::string PluginManager::get_storage_dir(const std::string& plugin_key) const { namespace fs = boost::filesystem; diff --git a/src/slic3r/plugin/PluginManager.hpp b/src/slic3r/plugin/PluginManager.hpp index e8769e3afd..58db6a996d 100644 --- a/src/slic3r/plugin/PluginManager.hpp +++ b/src/slic3r/plugin/PluginManager.hpp @@ -190,6 +190,9 @@ public: bool try_get_plugin_descriptor_for_capability(const std::string& capability_name, PluginCapabilityType type, PluginDescriptor& out) const; + // The "name;uuid;capability" reference for a loaded capability, as stored in a preset's + // "plugins" manifest; std::nullopt when no loaded package provides it. + std::optional resolve_capability_ref(const std::string& capability_name, PluginCapabilityType type) const; // Per-plugin storage directory under orca_plugins/plugin_data, created if missing. Throws // std::runtime_error if the plugin is unregistered, the key is invalid, or (cloud plugins) // no user is logged in yet. @@ -489,6 +492,15 @@ void execute_capabilities_from_refs(const ConfigOptionStrings& capabilities, } } + // The manifest is derived from the picker value only when that value changes, so it can be + // stale or empty (e.g. derived before the plugin finished loading) even though the + // capability is loaded now. Resolve it by name instead of silently skipping the step. + if (!ref) { + ref = plugin_mgr.resolve_capability_ref(capability, type); + if (ref) + BOOST_LOG_TRIVIAL(warning) << tag << ": capability '" << capability << "' missing from the plugins manifest; resolved by name"; + } + if (!ref) { BOOST_LOG_TRIVIAL(warning) << tag << ": no plugin reference found for capability '" << capability << "'; skipping"; continue; diff --git a/tests/cli/CMakeLists.txt b/tests/cli/CMakeLists.txt index 2c9ad769c5..b108599aca 100644 --- a/tests/cli/CMakeLists.txt +++ b/tests/cli/CMakeLists.txt @@ -55,6 +55,14 @@ set_tests_properties(cli_filament_colour_count PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) +add_test(NAME cli_load_filaments_count + COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/test_cli_load_filaments_count.sh $ ${ORCA_CLI_TEST_PYTHON} + ${CMAKE_SOURCE_DIR}/resources/profiles/BBL) +set_tests_properties(cli_load_filaments_count PROPERTIES + LABELS "CLI;RequiresApp" + SKIP_RETURN_CODE 77 + TIMEOUT 300) + add_test(NAME cli_malformed_input COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/test_cli_malformed_input.sh $ ${ORCA_CLI_TEST_PYTHON}) set_tests_properties(cli_malformed_input PROPERTIES diff --git a/tests/cli/test_cli_load_filaments_count.sh b/tests/cli/test_cli_load_filaments_count.sh new file mode 100755 index 0000000000..80d101f256 --- /dev/null +++ b/tests/cli/test_cli_load_filaments_count.sh @@ -0,0 +1,161 @@ +#!/usr/bin/env bash +# End-to-end check that --load-filaments with more presets than the project defines grows the project +# without disturbing its own filaments or the printer's slot, and that an empty slot past the project's +# count is rejected unless --load-defaultfila fills it. +# +# A one-filament project is exported from the shipped Bambu Lab H2D presets, where a filament has one +# value per extruder variant. Its per-variant filament_max_volumetric_speed is changed and listed as +# different, and the printer's name and a compatibility condition are put in the printer's slot of +# inherits_group and compatible_machine_expression_group, the last one. The project is +# sliced with as many filaments as it has variant entries, the one empty slot per project filament +# refreshing it and every slot beyond it a loaded preset: the kept values must survive at their variant +# positions (a loaded count that equals the variant count used to be mistaken for one value per +# filament), and the printer must still hold the last slot of both lists, after the new filaments. The same count +# with an empty slot beyond the project's filament has nothing to keep in that slot: the run must fail +# with CLI_INVALID_PARAMS, unless --load-defaultfila fills the slot with the first loaded preset. +# +# usage: test_cli_load_filaments_count.sh +set -u + +BIN="${1:-}" +PY="${2:-python3}" +PROFILES="${3:-}" +# 77 is the test's SKIP_RETURN_CODE. +[ -x "$BIN" ] || { echo "SKIP: orca-slicer binary not found: $BIN"; exit 77; } +[ -d "$PROFILES" ] || { echo "FAIL: profiles directory not found: $PROFILES"; exit 1; } + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/orca-cli-load-filaments-count.XXXXXX")" +trap 'rm -rf "$WORK"' EXIT + +"$PY" - "$WORK/cube.stl" <<'EOF' +import sys + +v = [(x, y, z) for z in (0, 10) for y in (0, 10) for x in (0, 10)] +with open(sys.argv[1], "w") as f: + f.write("solid cube\n") + for a, b, c, d in ((0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)): + for tri in ((v[a], v[b], v[c]), (v[a], v[c], v[d])): + f.write("facet normal 0 0 0\nouter loop\n") + for p in tri: + f.write("vertex %g %g %g\n" % p) + f.write("endloop\nendfacet\n") + f.write("endsolid cube\n") +EOF + +# run [option...]: slice into $WORK//out.3mf with a fresh data directory; prints the exit status. +run() { + local out="$WORK/$1" input="$2"; shift 2 + mkdir -p "$out" + timeout 300 "$BIN" --datadir "$out/datadir" "$@" --slice 0 --outputdir "$out" --export-3mf out.3mf "$input" > "$out/log" 2>&1 + echo $? +} + +# slice [option...]: the run must succeed. +slice() { + local rc; rc="$(run "$@")" + [ "$rc" = 0 ] || { echo "FAIL: $1: orca-slicer exited $rc"; tail -n 40 "$WORK/$1/log"; exit 1; } +} + +# reject [option...]: the run must fail with CLI_INVALID_PARAMS (-2) and record it in result.json. +reject() { + local rc; rc="$(run "$@")" + [ "$rc" = 254 ] || { echo "FAIL: $1: orca-slicer exited $rc, want 254 (CLI_INVALID_PARAMS)"; tail -n 40 "$WORK/$1/log"; exit 1; } + "$PY" - "$WORK/$1/result.json" <<'EOF' || { echo "FAIL: $1: result.json"; exit 1; } +import json, sys + +with open(sys.argv[1]) as f: + result = json.load(f) +if result.get("return_code") != -2 or not result.get("error_string"): + sys.exit("return_code %r, error_string %r, want -2 with a message" % (result.get("return_code"), result.get("error_string"))) +EOF +} + +slice base "$WORK/cube.stl" \ + --load-settings "$PROFILES/machine/Bambu Lab H2D 0.4 nozzle.json;$PROFILES/process/0.20mm Standard @BBL H2D.json" \ + --load-filaments "$PROFILES/filament/Bambu PLA Basic @BBL H2D.json" + +# Prints the number of filaments to load: one per variant entry of the project's filament. +LOADED="$("$PY" - "$WORK/base/out.3mf" "$WORK/old.3mf" <<'EOF' +import json, sys, zipfile + +src, dst = sys.argv[1], sys.argv[2] +with zipfile.ZipFile(src) as zin, zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED) as zout: + for item in zin.infolist(): + data = zin.read(item.filename) + if item.filename == "Metadata/project_settings.config": + config = json.loads(data) + variants = len(config["filament_self_index"]) + if variants < 2: + print("SKIP: the project's filament has one variant, so the loaded count cannot equal the variant count", file=sys.stderr) + sys.exit(77) + # A different value per variant, none of them the system preset's. + config["filament_max_volumetric_speed"] = ["%g" % (float(v) + i + 1) for i, v in enumerate(config["filament_max_volumetric_speed"])] + # One entry for the process, one per filament, one for the printer. + config["different_settings_to_system"][1] = "filament_max_volumetric_speed" + config["inherits_group"][-1] = config["printer_settings_id"] + config["compatible_machine_expression_group"][-1] = "printer_notes=~/.*/" + expected = {key: config[key] for key in ("filament_max_volumetric_speed", "filament_self_index", "inherits_group", "compatible_machine_expression_group")} + with open(dst + ".expected.json", "w") as f: + json.dump(expected, f) + print(variants) + data = json.dumps(config, indent=4) + zout.writestr(item, data) +EOF +)" || { rc=$?; [ "$rc" = 77 ] && exit 77; exit "$rc"; } + +MATTE="$PROFILES/filament/Bambu PLA Matte @BBL H2D.json" +# Slot 1 stays the project's filament; every slot beyond it loads a preset. +FILAMENTS="" +for ((i = 1; i < LOADED; i++)); do FILAMENTS="$FILAMENTS;$MATTE"; done +slice grown "$WORK/old.3mf" --load-filaments "$FILAMENTS" + +"$PY" - "$WORK/grown/out.3mf" "$WORK/old.3mf.expected.json" "$LOADED" <<'EOF' || { tail -n 40 "$WORK/grown/log"; exit 1; } +import json, sys, zipfile + +with zipfile.ZipFile(sys.argv[1]) as z: + config = json.loads(z.read("Metadata/project_settings.config")) +with open(sys.argv[2]) as f: + expected = json.load(f) +loaded = int(sys.argv[3]) +errors = [] +# The project's filament keeps its variant entries, at the front of the per-variant lists. +for key in ("filament_max_volumetric_speed", "filament_self_index"): + want = expected[key] + if config.get(key, [])[:len(want)] != want: + errors.append("%s is %r, want it to start with %r" % (key, config.get(key), want)) +ids = config.get("filament_settings_id", []) +if len(ids) != loaded or ids[1:] != ["Bambu PLA Matte @BBL H2D"] * (loaded - 1): + errors.append("filament_settings_id is %r, want %d entries with the loaded preset after the project's" % (ids, loaded)) +# One entry for the process, one per loaded filament, one for the printer. +inherits = config.get("inherits_group", []) +if len(inherits) != loaded + 2 or inherits[-1] != expected["inherits_group"][-1]: + errors.append("inherits_group is %r, want %d entries with the printer %r last" % (inherits, loaded + 2, expected["inherits_group"][-1])) +expressions = config.get("compatible_machine_expression_group", []) +if len(expressions) != loaded + 2 or expressions[-1] != expected["compatible_machine_expression_group"][-1]: + errors.append("compatible_machine_expression_group is %r, want %d entries with the printer's condition %r last" % (expressions, loaded + 2, expected["compatible_machine_expression_group"][-1])) +different = config.get("different_settings_to_system", []) +if len(different) != loaded + 2 or "filament_max_volumetric_speed" not in different[1].split(";"): + errors.append("different_settings_to_system is %r, want %d entries with the kept key in the first filament's" % (different, loaded + 2)) +for e in errors: + print("FAIL: " + e) +sys.exit(1 if errors else 0) +EOF + +# Only the last slot loads a preset: the empty slots between the project's filament and it have nothing to keep. +EMPTY_SLOTS="" +for ((i = 1; i < LOADED; i++)); do EMPTY_SLOTS="$EMPTY_SLOTS;"; done +reject empty_slot "$WORK/old.3mf" --load-filaments "$EMPTY_SLOTS$MATTE" +grep -qF -- "--load-filaments slot 2 is empty" "$WORK/empty_slot/log" || { echo "FAIL: empty_slot: log does not name the empty slot"; tail -n 40 "$WORK/empty_slot/log"; exit 1; } + +# With --load-defaultfila the same empty slots take the first loaded preset instead. +slice default_filled "$WORK/old.3mf" --load-defaultfila --load-filaments "$EMPTY_SLOTS$MATTE" +"$PY" - "$WORK/default_filled/out.3mf" "$LOADED" <<'EOF' || { tail -n 40 "$WORK/default_filled/log"; exit 1; } +import json, sys, zipfile + +with zipfile.ZipFile(sys.argv[1]) as z: + config = json.loads(z.read("Metadata/project_settings.config")) +ids = config.get("filament_settings_id", []) +if ids != ["Bambu PLA Matte @BBL H2D"] * int(sys.argv[2]): + sys.exit("FAIL: filament_settings_id is %r, want every slot filled with the loaded preset" % ids) +EOF +echo "PASS" diff --git a/tests/fff_print/test_multifilament.cpp b/tests/fff_print/test_multifilament.cpp index 2e11470d34..6f98ca423d 100644 --- a/tests/fff_print/test_multifilament.cpp +++ b/tests/fff_print/test_multifilament.cpp @@ -2293,3 +2293,100 @@ TEST_CASE("Nozzle change ramming is symmetric for identical filaments", "[MultiF } CHECK_THAT(medians[0], Catch::Matchers::WithinRel(medians[1], 0.01)); } + +// Regression for #14753: emit M104 after T0 in single-extruder MM to override firmware/CFS reset. +TEST_CASE("Single-extruder MM emits M104 after T0 toolchange", "[MultiFilament]") +{ + const int expected_temp = 240; + const std::string gcode = slice({ cube(20) }, + multifilament_config(2, { + { "nozzle_temperature", std::to_string(expected_temp) + "," + std::to_string(expected_temp) }, + { "nozzle_temperature_initial_layer", std::to_string(expected_temp) + "," + std::to_string(expected_temp) }, + { "machine_start_gcode", "" }, + { "enable_prime_tower", "0" }, + })); + + bool found_t0 = false; + std::string first_cmd_after_t0; + int first_temp_after_t0 = -1; + GCodeReader reader; + reader.parse_buffer(gcode, [&](GCodeReader& self, const GCodeReader::GCodeLine& line) { + const std::string cmd(line.cmd()); + if (cmd.empty()) + return; + if (!found_t0) { + if (cmd == "T0") + found_t0 = true; + } else { + first_cmd_after_t0 = cmd; + float s_val = 0; + if (line.has_value('S', s_val)) + first_temp_after_t0 = int(s_val); + self.quit_parsing(); + } + }); + + REQUIRE(found_t0); + REQUIRE(first_cmd_after_t0 == "M104"); + REQUIRE(first_temp_after_t0 == expected_temp); +} + +// Single-filament prints must not get an M104 after start G-code when no T command was written. +TEST_CASE("Single-filament print does not emit M104 after start G-code", "[MultiFilament]") +{ + const std::string gcode = slice({ cube(20) }, + multifilament_config(1, { + { "machine_start_gcode", "; START_GCODE_END\n" }, + { "enable_prime_tower", "0" }, + })); + + const size_t start_pos = gcode.find("; START_GCODE_END"); + REQUIRE(start_pos != std::string::npos); + const size_t layer_pos = gcode.find(";LAYER_CHANGE", start_pos); + REQUIRE(layer_pos != std::string::npos); + + const std::string between = gcode.substr(start_pos, layer_pos - start_pos); + CHECK(between.find("M104") == std::string::npos); + CHECK(between.find("M109") == std::string::npos); + CHECK(between.find("T0") == std::string::npos); +} + +// A custom M104 in filament start G-code must be preserved after T0 and the slicer's default M104. +TEST_CASE("Custom M104 in filament start G-code wins on a T0-only print", "[MultiFilament]") +{ + const int slicer_temp = 240; + const int custom_temp = 255; + const std::string gcode = slice({ cube(20) }, + multifilament_config(2, { + { "nozzle_temperature", std::to_string(slicer_temp) + "," + std::to_string(slicer_temp) }, + { "nozzle_temperature_initial_layer", std::to_string(slicer_temp) + "," + std::to_string(slicer_temp) }, + { "filament_start_gcode", std::string("M104 S") + std::to_string(custom_temp) + "\n" }, + { "machine_start_gcode", "" }, + { "enable_prime_tower", "0" }, + })); + + bool found_t0 = false; + std::vector temps_after_t0; + GCodeReader reader; + reader.parse_buffer(gcode, [&](GCodeReader& self, const GCodeReader::GCodeLine& line) { + const std::string cmd(line.cmd()); + if (cmd == ";LAYER_CHANGE" || line.comment() == "LAYER_CHANGE") { + if (found_t0) + self.quit_parsing(); + return; + } + if (!found_t0) { + if (cmd == "T0") + found_t0 = true; + } else if (cmd == "M104" || cmd == "M109") { + float s_val = 0; + if (line.has_value('S', s_val)) + temps_after_t0.push_back(int(s_val)); + } + }); + + REQUIRE(found_t0); + REQUIRE(temps_after_t0.size() >= 2); + CHECK(temps_after_t0.front() == slicer_temp); + CHECK(temps_after_t0.back() == custom_temp); +} diff --git a/tests/fff_print/test_print.cpp b/tests/fff_print/test_print.cpp index cb5f27c0b6..d7a064ad88 100644 --- a/tests/fff_print/test_print.cpp +++ b/tests/fff_print/test_print.cpp @@ -1888,6 +1888,43 @@ TEST_CASE("Sequential printing counts a raft toward the height checked against t CHECK(error.find("too tall") != std::string::npos); } +TEST_CASE("Sequential printing counts a raft toward whether an object is short", "[Print]") +{ + // Objects below nozzle_height only need to clear the nozzle cone, so they may stand close together, + // and their skirt is kept at its full distance. A raft lifts a 2 mm slab past the 2.5 mm nozzle_height, + // so the slabs need the toolhead radius between them and the skirt offset of a tall object. + const bool raft = GENERATE(false, true); + std::vector meshes; + for (size_t i = 0; i < 2; ++i) { + TriangleMesh slab = make_cube(20, 20, 2); + slab.translate(float(80 + 30 * i), 80.f, 0.f); // 10 mm apart, within the 40 mm toolhead radius + meshes.push_back(std::move(slab)); + } + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ + { "print_sequence", "by object" }, + { "nozzle_height", 2.5 }, + { "extruder_clearance_radius", 40 }, + { "skirt_loops", 1 }, + { "skirt_type", "perobject" }, + { "raft_layers", raft ? 3 : 0 }, + { "layer_change_gcode", "G92 E0\n" } // validate() relative-E reset + }); + Print print; + Model model; + Test::init_print(std::move(meshes), print, model, config, nullptr, /*arrange=*/false); + REQUIRE((2. + print.objects().front()->slicing_parameters().object_print_z_min > 2.5) == raft); + + CHECK(print.is_all_objects_are_short() == ! raft); + CHECK((std::get<0>(print.object_skirt_offset()) > 0.f) == ! raft); + const std::string error = print.validate().string; + INFO(error); + if (raft) + CHECK(error.find("too close to others") != std::string::npos); + else + CHECK(error.empty()); +} + TEST_CASE("Sequential printing measures objects on a belt printer by the model's top", "[Print][belt]") { // On a belt printer object_print_z_max is the height in the tilted slicing frame: at 45 degrees a 30 mm @@ -3217,6 +3254,39 @@ TEST_CASE("No sparse layers still refuses an object that rises past the lid clea REQUIRE_THROWS_WITH(print.process(), Catch::Matchers::ContainsSubstring("No sparse layers")); } +// Only the layers below an object's top count toward its rise above the compacted tower, and a raft lifts that +// top. The 20 mm cube shares the tower's Y band and may rise 20 mm above it. The tower starts on the first layer +// above 19.6 mm, where the taller object's second part changes filament, and keeps pace from there, so without a +// raft the cube rises 19.6 mm at most. The raft lifts the cube's top with every layer, and it is refused. +TEST_CASE("No sparse layers counts a raft toward an object's rise above the compacted tower", "[Print][PrimeTower]") +{ + const bool raft = GENERATE(false, true); + Model model; + add_object(model, make_cube(20., 20., 20.), 20., 140.); + ModelObject *tall = add_object(model, make_cube(20., 20., 19.6), 60., 20.); + TriangleMesh upper = make_cube(20., 20., 20.4); + upper.translate(0.f, 0.f, 19.6f); + tall->add_volume(std::move(upper))->config.set_key_value("extruder", new ConfigOptionInt(2)); + Print print; + print.apply(model, prime_tower_config({ + { "wipe_tower_no_sparse_layers", 1 }, + { "wipe_tower_x", 120 }, // with its rib wall the tower is over 40 mm across + { "wipe_tower_y", 140 }, + { "extruder_clearance_height_to_lid", 30 }, // the taller cube, away from the rod's band, rises as much + { "extruder_clearance_height_to_rod", 20 }, + { "raft_layers", raft ? 3 : 0 }, + })); + REQUIRE((print.objects().front()->slicing_parameters().object_print_z_min > 0.4) == raft); + + const std::string error = print.validate().string; + INFO(error); + CHECK(error.empty()); + if (raft) + REQUIRE_THROWS_WITH(print.process(), Catch::Matchers::ContainsSubstring("No sparse layers")); + else + REQUIRE_NOTHROW(print.process()); +} + // Within the toolhead radius of the tower the head body limits an object to nozzle_height, however tall the tower // grows, so validate() refuses it before slicing. TEST_CASE("No sparse layers refuses before slicing an object that rises within the toolhead radius of the tower", "[Print][PrimeTower]") @@ -3231,6 +3301,31 @@ TEST_CASE("No sparse layers refuses before slicing an object that rises within t CHECK_THAT(print.validate().string, Catch::Matchers::ContainsSubstring("No sparse layers")); } +// The head body passes over an object that stays below nozzle_height however close to the tower it stands. A +// raft lifts a 2 mm slab past the 2.5 mm nozzle_height, so the same slab within the toolhead radius is refused +// before slicing once it stands on one. +TEST_CASE("No sparse layers counts a raft toward whether an object near the tower is short", "[Print][PrimeTower]") +{ + const bool raft = GENERATE(false, true); + Model model; + add_object(model, make_cube(10., 10., 2.), 140., 140.); // 10 mm from the tower in X and in Y + add_object(model, make_cube(20., 20., 10.), 20., 20.)->config.set_key_value("extruder", new ConfigOptionInt(2)); + Print print; + print.apply(model, prime_tower_config({ + { "wipe_tower_no_sparse_layers", 1 }, + { "nozzle_height", 2.5 }, + { "raft_layers", raft ? 3 : 0 }, + })); + REQUIRE((2. + print.objects().front()->slicing_parameters().object_print_z_min > 2.5) == raft); + + const std::string error = print.validate().string; + INFO(error); + if (raft) + CHECK(error.find("No sparse layers") != std::string::npos); + else + CHECK(error.empty()); +} + TEST_CASE("An object takes the layer height limits of the extruder of its own filament", "[Print]") { CHECK_THAT(slicing_parameters_on_filament(1).max_layer_height, Catch::Matchers::WithinAbs(0.32, EPSILON)); diff --git a/tests/fff_print/test_wipe_tower.cpp b/tests/fff_print/test_wipe_tower.cpp index 7811a2ffb1..ece5c4a87d 100644 --- a/tests/fff_print/test_wipe_tower.cpp +++ b/tests/fff_print/test_wipe_tower.cpp @@ -7,6 +7,7 @@ #include "libslic3r/Point.hpp" #include "libslic3r/Polygon.hpp" #include +#include #include "libslic3r/Model.hpp" #include "libslic3r/Print.hpp" #include @@ -29,6 +30,7 @@ #include "libslic3r/GCode/ToolOrdering.hpp" #include "libslic3r/GCode/WipeTower.hpp" #include "libslic3r/LocalesUtils.hpp" +#include "libslic3r/ModelArrange.hpp" #include "libslic3r/PrintConfig.hpp" #include "libslic3r/Utils.hpp" @@ -641,6 +643,111 @@ TEST_CASE("A merged tower layer declares its own height to the G-code processor" CHECK(count_height_tags(combined.gcode, "0.4") - count_height_tags(plain.gcode, "0.4") == combined.folded); } +// Filament 2 only for the bottom 2mm of a 10mm cube, nothing changes for the remaining ~8mm, so the +// wipe tower's last active layer sits well below the object's last printed layer. +static std::string slice_short_tower_cube(Print &print, const DynamicPrintConfig &config) +{ + Model model; + auto *obj = model.add_object(); + obj->add_volume(cube(10)); + obj->add_instance(); + DynamicPrintConfig range_config; + range_config.set_key_value("extruder", new ConfigOptionInt(2)); + range_config.set_key_value("layer_height", new ConfigOptionFloat(0.3)); + obj->layer_config_ranges[{0.0, 2.0}].assign_config(std::move(range_config)); + + arrange_objects(model, InfiniteBed{}, ArrangeParams{ scaled(min_object_distance(config)) }); + for (auto *mo : model.objects) { + mo->ensure_on_bed(); + print.auto_assign_extruders(mo); + } + print.apply(model, config); + print.apply(model, config); // second apply, same reason as slice_with_prime_tower + print.validate(); + print.set_status_silent(); + print.process(); + return Slic3r::Test::gcode(print); +} + +static DynamicPrintConfig short_tower_config(bool ramming) +{ + return multifilament_config(2, { + { "enable_prime_tower", true }, + { "wipe_tower_x", 50 }, + { "wipe_tower_y", 50 }, + { "layer_height", 0.3 }, + { "gcode_flavor", "marlin" }, + { "single_extruder_multi_material", ramming ? "1" : "0" }, + { "enable_filament_ramming", ramming ? "1" : "0" }, + { "purge_in_prime_tower", "1" }, + }); +} + +// A SEMM/MMU print with ramming must still ram+unload the last filament at print end even when +// the tower's last real toolchange isn't on the object's very last layer (the common case). +TEST_CASE("The final unload ramming still prints when the wipe tower stops growing before the last layer", "[WipeTower]") +{ + Print print; + const std::string g = slice_short_tower_cube(print, short_tower_config(true)); + REQUIRE(print.wipe_tower_data(2).tool_ordering.back().wipe_tower_partitions == 0); + + // One ramming block for the mid-print toolchange, one more for the final end-of-print unload. + const size_t first_ramming = g.find("Ramming start"); + REQUIRE(first_ramming != std::string::npos); + const size_t final_ramming = g.find("Ramming start", first_ramming + 1); + REQUIRE(final_ramming != std::string::npos); + CHECK(g.find("Ramming start", final_ramming + 1) == std::string::npos); + + // The final unload comes after every per-layer "current Z" comment, i.e. after the object has + // finished printing, not interleaved with it. + const size_t last_layer_z_comment = g.rfind(";Z:"); + REQUIRE(last_layer_z_comment != std::string::npos); + CHECK(last_layer_z_comment < final_ramming); + + // The unload is done at the object's top layer over the tower: the head must not descend + // below it on the way there, which would cut through the part. + const double top_z = std::stod(g.substr(last_layer_z_comment + 3)); + // The ";Z:" comment precedes the move up to that layer, so only measure once the head is there. + double min_z_since_top_layer = std::numeric_limits::max(); + bool at_top_layer = false; + GCodeReader reader; + reader.parse_buffer(g, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) { + if (line.raw().rfind(";Z:", 0) == 0) { + at_top_layer = false; + min_z_since_top_layer = std::numeric_limits::max(); + } else { + at_top_layer = at_top_layer || self.z() >= top_z - EPSILON; + if (at_top_layer) + min_z_since_top_layer = std::min(min_z_since_top_layer, double(self.z())); + } + }); + REQUIRE(at_top_layer); + CHECK(min_z_since_top_layer >= top_z - EPSILON); +} + +// Without ramming nothing needs the final unload, and it would only add a move down to a tower +// that stopped below the top of the object. +TEST_CASE("No final unload is generated when the tower stops short and nothing rams", "[WipeTower]") +{ + Print print; + slice_short_tower_cube(print, short_tower_config(false)); + REQUIRE(print.wipe_tower_data(2).tool_ordering.back().wipe_tower_partitions == 0); + REQUIRE(print.wipe_tower_data(2).final_purge); + CHECK(print.wipe_tower_data(2).final_purge->gcode.empty()); +} + +// The other ramming condition: a multi-tool printer whose last filament rams on the tower. +TEST_CASE("The final unload is generated for a short tower when the last filament rams without SEMM", "[WipeTower]") +{ + DynamicPrintConfig config = short_tower_config(false); + config.set_deserialize_strict({ { "filament_multitool_ramming", "1,1" } }); + Print print; + slice_short_tower_cube(print, config); + REQUIRE(print.wipe_tower_data(2).tool_ordering.back().wipe_tower_partitions == 0); + REQUIRE(print.wipe_tower_data(2).final_purge); + CHECK_FALSE(print.wipe_tower_data(2).final_purge->gcode.empty()); +} + TEST_CASE("A tower printed without a tool change is still validated against the bed", "[WipeTower]") { // Wrapping detection prints a tower on a plate that purges one filament. Neither the old diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index 98f7b17c7a..6c878026e8 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -28,6 +28,7 @@ add_executable(${_TEST_NAME}_tests test_clipper_offset.cpp test_clipper_utils.cpp test_cut_connectors.cpp + test_cut.cpp test_config.cpp test_config_variant_expansion.cpp test_locales_utils.cpp @@ -36,6 +37,7 @@ add_executable(${_TEST_NAME}_tests test_toolordering_nozzle_group.cpp test_parallel_resolve.cpp test_preset_bundle_loading.cpp + test_preset_collection.cpp test_preset_setting_id.cpp test_preset_diff.cpp test_publish_settings.cpp diff --git a/tests/libslic3r/test_appconfig.cpp b/tests/libslic3r/test_appconfig.cpp index 17c1bc268c..a57aea3885 100644 --- a/tests/libslic3r/test_appconfig.cpp +++ b/tests/libslic3r/test_appconfig.cpp @@ -117,6 +117,7 @@ TEST_CASE("Local machine agent replacements survive save and reload", "[AppConfi saved.printer_type = "test-model"; saved.printer_agent_id = "orca"; saved.access_code = "old-key"; + saved.ca_file = "old-ca.crt"; config.update_local_machine(saved); config.save(); REQUIRE_FALSE(config.dirty()); @@ -124,6 +125,7 @@ TEST_CASE("Local machine agent replacements survive save and reload", "[AppConfi BBLocalMachine replacement = saved; replacement.printer_agent_id = "moonraker"; replacement.access_code = GENERATE("", "new-key", "88888888"); + replacement.ca_file = GENERATE("", "new-ca.crt"); config.update_local_machine(replacement); REQUIRE(config.dirty()); REQUIRE(config.get_local_machines().at(saved.dev_id) == replacement); @@ -137,6 +139,29 @@ TEST_CASE("Local machine agent replacements survive save and reload", "[AppConfi REQUIRE_FALSE(reloaded.dirty()); } +TEST_CASE("Local machines saved without an agent load as Bambu printers unless keyed by address", "[AppConfig]") +{ + ScopedDataDir data_dir("local-machine-legacy"); + save_main_thread_id(); + const std::string agent_field = GENERATE("", R"("printer_agent_id": "",)"); + AppConfig config; + std::ofstream(config.config_path()) << R"({"local_machines": {)" + << R"("01P00A000000001": {)" << agent_field << R"("dev_ip": "192.168.1.20"},)" + << R"("192.168.1.30:7125": {)" << agent_field << R"("dev_ip": "192.168.1.30:7125"},)" + << R"("192.168.1.31:7125": {)" << agent_field << R"("dev_ip": "192.168.1.32"},)" + << R"("voron": {)" << agent_field << R"("dev_ip": "voron"},)" + << R"("01P00A000000002": {"printer_agent_id": "moonraker", "dev_ip": "192.168.1.40"})" + << "}}"; + + REQUIRE(config.load().empty()); + const auto& machines = config.get_local_machines(); + CHECK(machines.at("01P00A000000001").printer_agent_id == "bbl"); + CHECK(machines.at("192.168.1.30:7125").printer_agent_id.empty()); + CHECK(machines.at("192.168.1.31:7125").printer_agent_id.empty()); + CHECK(machines.at("voron").printer_agent_id.empty()); + CHECK(machines.at("01P00A000000002").printer_agent_id == "moonraker"); +} + TEST_CASE("Clearing local credentials preserves another agent's record", "[AppConfig]") { AppConfig config; diff --git a/tests/libslic3r/test_cut.cpp b/tests/libslic3r/test_cut.cpp new file mode 100644 index 0000000000..19f7a5b382 --- /dev/null +++ b/tests/libslic3r/test_cut.cpp @@ -0,0 +1,337 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include "libslic3r/Config.hpp" +#include "libslic3r/CutUtils.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/TriangleSelector.hpp" + +using namespace Slic3r; + +namespace { + +// A 25 mm cube split into two 12.5 mm wide halves that butt together on the plane x = 0, +// so a groove cut at the origin crosses both of them. +struct TwoPartBox +{ + ModelObject* object = nullptr; + ModelVolume* part_a = nullptr; + ModelVolume* part_b = nullptr; +}; + +ModelVolume* add_half(ModelObject* object, float min_x) +{ + TriangleMesh cube = make_cube(12.5, 25., 25.); + cube.translate(min_x + 6.25f, -12.5f, -12.5f); + return object->add_volume(std::move(cube)); +} + +TwoPartBox add_two_part_box(Model& model) +{ + TwoPartBox box; + box.object = model.add_object(); + box.part_a = add_half(box.object, -12.5f); + box.part_b = add_half(box.object, 0.f); + box.object->add_instance(); + return box; +} + +ModelObject* add_single_part_box(Model& model) +{ + ModelObject* object = model.add_object(); + TriangleMesh cube = make_cube(25., 25., 25.); + cube.translate(-12.5f, -12.5f, -12.5f); + object->add_volume(std::move(cube)); + object->add_instance(); + return object; +} + +std::vector model_parts(const ModelObject& object) +{ + std::vector parts; + for (const ModelVolume* volume : object.volumes) + if (volume->is_model_part() && !volume->is_cut_connector()) + parts.push_back(volume); + return parts; +} + +// Runs the dovetail cut the cut gizmo runs, with the groove at the origin. +const ModelObjectPtrs& run_dovetail(Cut& cut) +{ + Cut::Groove groove; + groove.depth = 3.f; + groove.width = 2.f; + groove.flaps_angle = 0.5235988f; // 30 degrees + groove.angle = 0.0872665f; // 5 degrees + groove.depth_tolerance = 0.1f; + groove.width_tolerance = 0.1f; + return cut.perform_with_groove(groove, Transform3d::Identity(), 1, 0.f, 0.f); +} + +// Painting is remapped by surface overlap, so facets touching the joint would paint the neighbour as +// well: paint the outer face of the part, away from x = 0. +void paint_away_from_joint(ModelVolume* volume) +{ + const indexed_triangle_set& its = volume->mesh().its; + float min_x = std::numeric_limits::max(); + for (const Vec3f& vertex : its.vertices) + min_x = std::min(min_x, vertex.x()); + + const auto on_outer_face = [min_x](const Vec3f& vertex) { return vertex.x() < min_x + 0.01f; }; + + TriangleSelector selector(volume->mesh()); + int painted = 0; + for (size_t i = 0; i < its.indices.size(); ++i) { + const auto& facet = its.indices[i]; + if (on_outer_face(its.vertices[facet(0)]) && on_outer_face(its.vertices[facet(1)]) && on_outer_face(its.vertices[facet(2)])) { + selector.set_facet(int(i), EnforcerBlockerType::Extruder2); + ++painted; + } + } + REQUIRE(painted > 0); + REQUIRE(volume->mmu_segmentation_facets.set(selector)); +} + +} // namespace + +TEST_CASE("A dovetail cut keeps each part's filament", "[Cut]") +{ + Model model; + const TwoPartBox box = add_two_part_box(model); + box.part_b->config.set("extruder", 2); + + Cut cut(box.object, 0, Transform3d::Identity(), + ModelObjectCutAttribute::KeepUpper | ModelObjectCutAttribute::KeepLower); + const ModelObjectPtrs& objects = run_dovetail(cut); + + REQUIRE(objects.size() == 2); + for (const ModelObject* object : objects) { + std::vector filaments; + std::vector names; + for (const ModelVolume* part : model_parts(*object)) { + filaments.push_back(part->extruder_id()); + names.push_back(part->name); + } + std::sort(filaments.begin(), filaments.end()); + std::sort(names.begin(), names.end()); + REQUIRE(filaments == std::vector{ 1, 2 }); + REQUIRE(names == std::vector{ object->name, object->name + "_2" }); + } +} + +TEST_CASE("A dovetail cut of a single-part object still leaves one part", "[Cut]") +{ + Model model; + ModelObject* object = add_single_part_box(model); + + Cut cut(object, 0, Transform3d::Identity(), + ModelObjectCutAttribute::KeepUpper | ModelObjectCutAttribute::KeepLower); + const ModelObjectPtrs& objects = run_dovetail(cut); + + REQUIRE(objects.size() == 2); + for (const ModelObject* result : objects) { + const std::vector parts = model_parts(*result); + REQUIRE(parts.size() == 1); + REQUIRE(parts.front()->name == result->name); + } +} + +TEST_CASE("A part that restates the object's filament merges with a part that leaves it implicit", "[Cut]") +{ + Model model; + const TwoPartBox box = add_two_part_box(model); + box.object->config.set("extruder", 1); + box.part_b->config.set("extruder", 1); + + Cut cut(box.object, 0, Transform3d::Identity(), + ModelObjectCutAttribute::KeepUpper | ModelObjectCutAttribute::KeepLower); + const ModelObjectPtrs& objects = run_dovetail(cut); + + REQUIRE(objects.size() == 2); + for (const ModelObject* object : objects) + REQUIRE(model_parts(*object).size() == 1); +} + +TEST_CASE("A part that restates the object's infill merges with a part that leaves it implicit", "[Cut]") +{ + Model model; + const TwoPartBox box = add_two_part_box(model); + box.object->config.set_key_value("sparse_infill_density", new ConfigOptionPercent(50.)); + box.part_b->config.set_key_value("sparse_infill_density", new ConfigOptionPercent(50.)); + + Cut cut(box.object, 0, Transform3d::Identity(), + ModelObjectCutAttribute::KeepUpper | ModelObjectCutAttribute::KeepLower); + const ModelObjectPtrs& objects = run_dovetail(cut); + + REQUIRE(objects.size() == 2); + for (const ModelObject* object : objects) + REQUIRE(model_parts(*object).size() == 1); +} + +TEST_CASE("A dovetail cut keeps the filament of a single-part object", "[Cut]") +{ + Model model; + ModelObject* object = add_single_part_box(model); + object->volumes.front()->config.set("extruder", 2); + + Cut cut(object, 0, Transform3d::Identity(), + ModelObjectCutAttribute::KeepUpper | ModelObjectCutAttribute::KeepLower); + const ModelObjectPtrs& objects = run_dovetail(cut); + + REQUIRE(objects.size() == 2); + for (const ModelObject* result : objects) { + const std::vector parts = model_parts(*result); + REQUIRE(parts.size() == 1); + REQUIRE(parts.front()->extruder_id() == 2); + } +} + +TEST_CASE("A dovetail cut keeps modifier volumes", "[Cut]") +{ + Model model; + const TwoPartBox box = add_two_part_box(model); + box.part_b->config.set("extruder", 2); + + TriangleMesh cube = make_cube(5., 5., 5.); + cube.translate(-2.5f, -2.5f, -2.5f); + ModelVolume* modifier = box.object->add_volume(std::move(cube)); + modifier->set_type(ModelVolumeType::PARAMETER_MODIFIER); + + Cut cut(box.object, 0, Transform3d::Identity(), + ModelObjectCutAttribute::KeepUpper | ModelObjectCutAttribute::KeepLower); + const ModelObjectPtrs& objects = run_dovetail(cut); + + REQUIRE(objects.size() == 2); + for (const ModelObject* object : objects) { + std::vector filaments; + size_t others = 0; + for (const ModelVolume* volume : object->volumes) { + if (volume->is_model_part() && !volume->is_cut_connector()) + filaments.push_back(volume->extruder_id()); + else + ++others; + } + std::sort(filaments.begin(), filaments.end()); + REQUIRE(filaments == std::vector{ 1, 2 }); + REQUIRE(others == 1); + } +} + +TEST_CASE("A dovetail cut keeps per-part process settings", "[Cut]") +{ + Model model; + const TwoPartBox box = add_two_part_box(model); + box.part_b->config.set_key_value("sparse_infill_density", new ConfigOptionPercent(50.)); + + Cut cut(box.object, 0, Transform3d::Identity(), + ModelObjectCutAttribute::KeepUpper | ModelObjectCutAttribute::KeepLower); + const ModelObjectPtrs& objects = run_dovetail(cut); + + REQUIRE(objects.size() == 2); + for (const ModelObject* object : objects) { + const std::vector parts = model_parts(*object); + REQUIRE(parts.size() == 2); + std::vector densities; + for (const ModelVolume* part : parts) + if (part->config.has("sparse_infill_density")) + densities.push_back(part->config.opt_serialize("sparse_infill_density")); + REQUIRE(densities.size() == 1); + REQUIRE(densities.front() == "50%"); + } +} + +TEST_CASE("Paint stays on its own part after a dovetail cut", "[Cut]") +{ + Model model; + const TwoPartBox box = add_two_part_box(model); + paint_away_from_joint(box.part_a); + box.part_b->config.set("extruder", 2); + + Cut cut(box.object, 0, Transform3d::Identity(), + ModelObjectCutAttribute::KeepUpper | ModelObjectCutAttribute::KeepLower | ModelObjectCutAttribute::KeepPaint); + const ModelObjectPtrs& objects = run_dovetail(cut); + + REQUIRE(objects.size() == 2); + for (const ModelObject* object : objects) { + const std::vector parts = model_parts(*object); + REQUIRE(parts.size() == 2); + std::vector painted_filaments; + for (const ModelVolume* part : parts) + if (part->mmu_segmentation_facets.has_facets(*part, EnforcerBlockerType::Extruder2)) + painted_filaments.push_back(part->extruder_id()); + REQUIRE(painted_filaments.size() == 1); + REQUIRE(painted_filaments.front() == 1); + } +} + +TEST_CASE("A dovetail cut keeps parts with different materials apart", "[Cut]") +{ + Model model; + const TwoPartBox box = add_two_part_box(model); + box.part_a->set_material_id("mat_a"); + box.part_b->set_material_id("mat_b"); + + Cut cut(box.object, 0, Transform3d::Identity(), + ModelObjectCutAttribute::KeepUpper | ModelObjectCutAttribute::KeepLower); + const ModelObjectPtrs& objects = run_dovetail(cut); + + REQUIRE(objects.size() == 2); + for (const ModelObject* object : objects) { + std::vector materials; + for (const ModelVolume* part : model_parts(*object)) { + REQUIRE(part->extruder_id() == 1); + materials.push_back(part->material_id()); + } + std::sort(materials.begin(), materials.end()); + REQUIRE(materials == std::vector{ "mat_a", "mat_b" }); + } +} + +TEST_CASE("A dovetail cut inherits the object's filament", "[Cut]") +{ + Model model; + const TwoPartBox box = add_two_part_box(model); + box.object->config.set("extruder", 3); + + Cut cut(box.object, 0, Transform3d::Identity(), + ModelObjectCutAttribute::KeepUpper | ModelObjectCutAttribute::KeepLower); + const ModelObjectPtrs& objects = run_dovetail(cut); + + REQUIRE(objects.size() == 2); + for (const ModelObject* object : objects) { + const std::vector parts = model_parts(*object); + REQUIRE(parts.size() == 1); + REQUIRE(parts.front()->extruder_id() == 3); + } +} + +TEST_CASE("Cut by contour keeps each part's filament", "[Cut]") +{ + Model model; + ModelObject* object = model.add_object(); + add_half(object, -12.5f); + ModelVolume* right = add_half(object, 0.f); + right->config.set("extruder", 2); + object->add_instance(); + + Cut cut(object, 0, Transform3d::Identity(), + ModelObjectCutAttribute::KeepUpper | ModelObjectCutAttribute::KeepLower); + const ModelObjectPtrs& objects = + cut.perform_by_contour(object, { { true, false }, { true, false } }, 0); + + REQUIRE(objects.size() == 1); + std::vector filaments; + for (const ModelVolume* part : model_parts(*objects.front())) + filaments.push_back(part->extruder_id()); + std::sort(filaments.begin(), filaments.end()); + REQUIRE(filaments == std::vector{ 1, 2 }); +} diff --git a/tests/libslic3r/test_model.cpp b/tests/libslic3r/test_model.cpp index 88a96ee3b8..0c79bd83ed 100644 --- a/tests/libslic3r/test_model.cpp +++ b/tests/libslic3r/test_model.cpp @@ -507,3 +507,42 @@ TEST_CASE("Unplaced objects scaled to millimetres still merge on a common base", bases.push_back(volume->mesh().transformed_bounding_box(volume->get_matrix()).min.z()); CHECK_THAT(bases.front(), Catch::Matchers::WithinAbs(bases.back(), 1e-3)); } + +TEST_CASE("Converting a part's units keeps its material", "[Model]") +{ + Model model; + ModelObject *object = model.add_object(); + ModelVolume *volume = object->add_volume(make_cube(10, 10, 10), ModelVolumeType::MODEL_PART, false); + volume->set_material_id("mat_a"); + + ModelObjectPtrs converted; + object->convert_units(converted, ConversionType::CONV_FROM_INCH, {}); + + REQUIRE(converted.size() == 1); + REQUIRE(converted.front()->volumes.size() == 1); + CHECK(converted.front()->volumes.front()->material_id() == "mat_a"); + + // convert_units() hands its objects to the caller unowned; give them to a model so they are freed. + Model owner; + owner.objects = std::move(converted); +} + +TEST_CASE("Converting a part's units keeps an id whose material is missing", "[Model]") +{ + Model model; + ModelObject *object = model.add_object(); + ModelVolume *volume = object->add_volume(make_cube(10, 10, 10), ModelVolumeType::MODEL_PART, false); + volume->set_material_id("mat_a"); + model.delete_material("mat_a"); + + ModelObjectPtrs converted; + object->convert_units(converted, ConversionType::CONV_FROM_INCH, {}); + + REQUIRE(converted.size() == 1); + REQUIRE(converted.front()->volumes.size() == 1); + CHECK(converted.front()->volumes.front()->material_id() == "mat_a"); + + // convert_units() hands its objects to the caller unowned; give them to a model so they are freed. + Model owner; + owner.objects = std::move(converted); +} diff --git a/tests/libslic3r/test_preset_collection.cpp b/tests/libslic3r/test_preset_collection.cpp new file mode 100644 index 0000000000..b7b697b297 --- /dev/null +++ b/tests/libslic3r/test_preset_collection.cpp @@ -0,0 +1,72 @@ +#include + +#include +#include +#include +#include + +#include "libslic3r/Config.hpp" +#include "libslic3r/Preset.hpp" +#include "libslic3r/PrintConfig.hpp" + +using namespace Slic3r; + +namespace { + +struct FilamentSpec +{ + const char* name; + const char* filament_id; + const char* filament_type; +}; + +// A standalone filament collection of visible, compatible system base presets. +struct FilamentCollection : public PresetCollection +{ + explicit FilamentCollection(const std::vector& specs) + : PresetCollection(Preset::TYPE_FILAMENT, Preset::filament_options(), static_cast(FullPrintConfig::defaults())) + { + for (const FilamentSpec& spec : specs) { + DynamicPrintConfig config(default_preset().config); + config.option("filament_type", true)->values = {spec.filament_type}; + load_preset(std::string(), spec.name, config, /*select=*/false); + } + // A second pass: load_preset() keeps the presets sorted, so earlier references can move. + for (auto it = begin(); it != end(); ++it) { + const auto spec = std::find_if(specs.begin(), specs.end(), [&](const FilamentSpec& s) { return it->name == s.name; }); + if (spec == specs.end()) + continue; + it->filament_id = spec->filament_id; + it->is_system = true; + it->is_default = false; + it->is_visible = true; + it->is_compatible = true; + } + } +}; + +} // namespace + +TEST_CASE("A filament type resolves to the visible preset of that type", "[PresetCollection]") +{ + const FilamentCollection filaments({{"Generic PLA", "PLA-GENERIC", "PLA"}, {"Generic ABS", "ABS-GENERIC", "ABS"}}); + CHECK(filaments.filament_id_by_type("ABS") == "ABS-GENERIC"); +} + +TEST_CASE("A filament type with a modifier resolves to its base type", "[PresetCollection]") +{ + const FilamentCollection filaments({{"Generic PLA", "PLA-GENERIC", "PLA"}}); + CHECK(filaments.filament_id_by_type("PLA High Speed") == "PLA-GENERIC"); +} + +TEST_CASE("A filament type with no visible preset resolves to no preset, not another material", "[PresetCollection]") +{ + const FilamentCollection filaments({{"Generic PLA", "PLA-GENERIC", "PLA"}}); + CHECK(filaments.filament_id_by_type("ABS").empty()); +} + +TEST_CASE("A filament type with no visible preset has no preset index", "[PresetCollection]") +{ + const FilamentCollection filaments({{"Generic PLA", "PLA-GENERIC", "PLA"}}); + CHECK(filaments.first_visible_idx_by_type("ABS") == size_t(-1)); +} diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index d9d01e74ed..1eea1c4e35 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -2,6 +2,7 @@ get_filename_component(_TEST_NAME ${CMAKE_CURRENT_LIST_DIR} NAME) add_executable(${_TEST_NAME}_tests ${_TEST_NAME}_tests_main.cpp test_bambu_filament_ids.cpp + test_bbl_cert_dir.cpp test_bed_exclusion_fields.cpp test_cloud_delete_queue.cpp test_config_value_formatter.cpp @@ -10,6 +11,7 @@ add_executable(${_TEST_NAME}_tests test_dev_mapping.cpp test_device_access.cpp test_moonraker_printer_agent.cpp + test_snapmaker_filament_match.cpp test_network_discovery.cpp test_filament_bitmap_utils.cpp test_colour_picker_field.cpp diff --git a/tests/slic3rutils/test_bbl_cert_dir.cpp b/tests/slic3rutils/test_bbl_cert_dir.cpp new file mode 100644 index 0000000000..671153b6a7 --- /dev/null +++ b/tests/slic3rutils/test_bbl_cert_dir.cpp @@ -0,0 +1,128 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include "libslic3r/Utils.hpp" +#include "slic3r/Utils/BBLPrinterAgent.hpp" +#include "test_utils.hpp" + +using namespace Slic3r; +namespace fs = boost::filesystem; + +namespace { + +// Stand-in for the bundled CA list. It is copied as it is, never parsed. +const std::string bundled_pem = "-----BEGIN CERTIFICATE-----\nBUNDLED\n-----END CERTIFICATE-----\n"; + +// Self-signed, basicConstraints CA:TRUE, valid until 2126. +const std::string ca_pem = "-----BEGIN CERTIFICATE-----\n" + "MIIBdDCCARqgAwIBAgIUHgU8NZU4wLWpjhUvuDFYyLC462YwCgYIKoZIzj0EAwIw\n" + "FzEVMBMGA1UEAwwMT3JjYSBUZXN0IENBMCAXDTI2MTAzMDE3NTcyNFoYDzIxMjYx\n" + "MDA2MTc1NzI0WjAXMRUwEwYDVQQDDAxPcmNhIFRlc3QgQ0EwWTATBgcqhkjOPQIB\n" + "BggqhkjOPQMBBwNCAASgb/DwDMUKTWsm+8Mqc9o646Co6OZsgZZUMkj/uZf8ZmcM\n" + "hJLS+iciD44/h37HHxw/r9f2l1kqv3mk3RalWJdWo0IwQDAdBgNVHQ4EFgQUYqhd\n" + "KI+8k/orAS81GcJ1D14QteIwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n" + "AgQwCgYIKoZIzj0EAwIDSAAwRQIgXgYJ+qQTNM0Cg0j7QilqsowswWaFX8eM8gLv\n" + "Jqa8nWcCIQCnLysLNA0PlKGWcfIqZ093RJg/y4lDq9vn9lp5Ss5NrQ==\n" + "-----END CERTIFICATE-----\n"; + +// Signed by the CA above, basicConstraints CA:FALSE: a server certificate, not a CA. +const std::string leaf_pem = "-----BEGIN CERTIFICATE-----\n" + "MIIBRjCB7aADAgECAhQETSnonAw6sZXxIjMMJZJr58MS8TAKBggqhkjOPQQDAjAX\n" + "MRUwEwYDVQQDDAxPcmNhIFRlc3QgQ0EwIBcNMjYxMDMwMTc1NzI0WhgPMjEyNjEw\n" + "MDYxNzU3MjRaMBwxGjAYBgNVBAMMEW9yY2EtdGVzdC1wcmludGVyMFkwEwYHKoZI\n" + "zj0CAQYIKoZIzj0DAQcDQgAEuLIhVucena1P1KJzYyW1i6kWmgqbG0/KrfosMeA+\n" + "+9Lt0zxSKwEntR5Gl9B1SuQsdsrBUv61toCyKctXp/lfXqMQMA4wDAYDVR0TAQH/\n" + "BAIwADAKBggqhkjOPQQDAgNIADBFAiEA7Qp7rXzT1UfVKSkVqmUICjFzxkTbSrxQ\n" + "5JHSKxTn6eICIES+RhZNXmt1D6MX04UYGeIF+LXKcSImuhaDWVDYoAPS\n" + "-----END CERTIFICATE-----\n"; + +std::string read_file(const fs::path& path) +{ + std::string content; + load_string_file(path, content); + return content; +} + +// A stand-in for resources/cert: the plug-in's CA bundle and the cloud certificate next to it. +struct BundledCertDir +{ + ScopedTemporaryDir dir{"orca-bbl-cert-bundled"}; + BundledCertDir() + { + save_string_file(dir.path() / "printer.cer", bundled_pem); + save_string_file(dir.path() / "slicer_base64.cer", "cloud"); + } +}; + +} // namespace + +TEST_CASE("A custom CA is appended to a copy of the bundled printer.cer", "[BBLCertDir]") +{ + BundledCertDir bundled; + ScopedTemporaryDir scratch{"orca-bbl-cert-out"}; + const fs::path out = scratch.path() / "cert"; + const fs::path ca = scratch.path() / "proxy-ca.crt"; + save_string_file(ca, ca_pem + "text after the certificate\n"); + + const std::string used = BBLPrinterAgent::cert_dir_with_cas(bundled.dir.path().string(), out.string(), {ca.string()}); + + CHECK(used == out.string()); + CHECK(read_file(out / "printer.cer") == bundled_pem + ca_pem); // only the parsed certificate, not the trailing text + CHECK(read_file(out / "slicer_base64.cer") == "cloud"); + CHECK(read_file(bundled.dir.path() / "printer.cer") == bundled_pem); +} + +TEST_CASE("The bundled cert folder is kept when no custom CA is usable", "[BBLCertDir]") +{ + const std::string unusable = GENERATE("none", "missing", "not-pem", "broken-pem", "encrypted", "leaf-only", "ca-and-leaf"); + + BundledCertDir bundled; + ScopedTemporaryDir scratch{"orca-bbl-cert-out"}; + const fs::path out = scratch.path() / "cert"; + const fs::path file = scratch.path() / "ca.crt"; + + std::set extra_cas; + if (unusable != "none") + extra_cas.insert(file.string()); + if (unusable == "not-pem") + save_string_file(file, "hello"); + else if (unusable == "broken-pem") + save_string_file(file, "-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n"); + else if (unusable == "encrypted") // must not prompt for a passphrase + save_string_file(file, "-----BEGIN CERTIFICATE-----\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-128-CBC,000102030405060708090A0B0C0D0E0F\n\n" + + ca_pem.substr(ca_pem.find('\n') + 1)); + else if (unusable == "leaf-only") + save_string_file(file, leaf_pem); + else if (unusable == "ca-and-leaf") + save_string_file(file, ca_pem + leaf_pem); + + INFO("unusable CA: " << unusable); + CHECK(BBLPrinterAgent::cert_dir_with_cas(bundled.dir.path().string(), out.string(), extra_cas) == bundled.dir.path().string()); + CHECK_FALSE(fs::exists(out)); +} + +TEST_CASE("An unchanged cert folder is not rewritten", "[BBLCertDir]") +{ + BundledCertDir bundled; + ScopedTemporaryDir scratch{"orca-bbl-cert-out"}; + const fs::path out = scratch.path() / "cert"; + const fs::path ca = scratch.path() / "proxy-ca.crt"; + save_string_file(ca, ca_pem); + + BBLPrinterAgent::cert_dir_with_cas(bundled.dir.path().string(), out.string(), {ca.string()}); + const std::time_t long_ago = 1000000000; + fs::last_write_time(out / "printer.cer", long_ago); + fs::last_write_time(out / "slicer_base64.cer", long_ago); + + BBLPrinterAgent::cert_dir_with_cas(bundled.dir.path().string(), out.string(), {ca.string()}); + + CHECK(fs::last_write_time(out / "printer.cer") == long_ago); + CHECK(fs::last_write_time(out / "slicer_base64.cer") == long_ago); + CHECK_FALSE(fs::exists(out / "printer.cer.tmp")); +} diff --git a/tests/slic3rutils/test_device_manager_integration.cpp b/tests/slic3rutils/test_device_manager_integration.cpp index 85b9170ba0..2994ca6793 100644 --- a/tests/slic3rutils/test_device_manager_integration.cpp +++ b/tests/slic3rutils/test_device_manager_integration.cpp @@ -64,8 +64,15 @@ public: return send_message(std::move(dev_id), std::move(json_str), qos, flag); } + int connect_printer(const PrinterConnectionParams& params) override + { + connected_ca_file = params.ca_file; + return 0; + } + std::string published_device; json published_message; + std::string connected_ca_file; private: AgentInfo m_info; @@ -270,6 +277,53 @@ TEST_CASE("Logging out cancels a pending last-machine restore", "[DeviceManager] CHECK_FALSE(manager.has_pending_last_machine_restore()); } +TEST_CASE("A CA file stays with the agent that saved it when a device is rebound", "[DeviceManager][integration]") +{ + ScopedAppConfig app_config; + auto agent_a = std::make_shared("integration-agent-a"); + auto agent_b = std::make_shared("integration-agent-b"); + NetworkAgent network(nullptr, agent_a); + DeviceManager manager(&network, false, &app_config.config); + + BBLocalMachine machine; + machine.dev_id = "integration-lan-device"; + machine.dev_name = "Integration LAN device"; + machine.dev_ip = "192.0.2.10"; + machine.printer_type = "C11"; + + MachineObject* object = manager.insert_local_device(machine, "lan", "free", "", "access-code"); + REQUIRE(object != nullptr); + object->set_ca_file("agent-a-ca.crt"); + CHECK(app_config.config.get_local_machines().at(machine.dev_id).ca_file == "agent-a-ca.crt"); + + // Rebinding under the same agent keeps the CA file. + manager.insert_local_device(machine, "lan", "free", "", "access-code"); + CHECK(object->get_ca_file() == "agent-a-ca.crt"); + + network.set_printer_agent(agent_b); + manager.insert_local_device(machine, "lan", "free", "", "access-code"); + CHECK(object->printer_agent_id == "integration-agent-b"); + CHECK(object->get_ca_file().empty()); + CHECK(app_config.config.get_local_machines().at(machine.dev_id).ca_file.empty()); +} + +TEST_CASE("A device saved without an agent id connects with the CA file of the agent that connects it", "[DeviceManager][integration]") +{ + ScopedAppConfig app_config; + const std::string agent_id = GENERATE(std::string(BBL_PRINTER_AGENT_ID), std::string("integration-agent")); + auto agent = std::make_shared(agent_id); + NetworkAgent network(nullptr, agent); + DeviceManager manager(&network, false, &app_config.config); + MachineObject object(&manager, &network, "Test printer", "integration-device", "192.0.2.10"); + object.set_access_code("access-code", false); + object.set_ca_file("device-ca.crt", false); + REQUIRE(object.printer_agent_id.empty()); + + REQUIRE(object.connect() == 0); + // Other agents take the CA from the printer preset, which this test has none of. + CHECK(agent->connected_ca_file == (agent_id == BBL_PRINTER_AGENT_ID ? "device-ca.crt" : "")); +} + TEST_CASE("AMS filament settings keep legacy single-color commands compatible", "[DeviceManager][AMSMaterialsSetting][integration]") { ScopedAppConfig app_config; diff --git a/tests/slic3rutils/test_filament_bitmap_utils.cpp b/tests/slic3rutils/test_filament_bitmap_utils.cpp index b4f691901d..b094b71b74 100644 --- a/tests/slic3rutils/test_filament_bitmap_utils.cpp +++ b/tests/slic3rutils/test_filament_bitmap_utils.cpp @@ -18,7 +18,11 @@ #include #include +#include +#include +#include +#include #include #include @@ -38,7 +42,6 @@ #include #include #include -#include #endif #include @@ -279,6 +282,25 @@ TEST_CASE("sample_gradient_ramp returns nothing without a usable curve or step c REQUIRE(Slic3r::GUI::sample_gradient_ramp(wxColour(255, 0, 0), wxColour(0, 0, 255), curve, 0).empty()); } +TEST_CASE("tri_clamp snaps a point outside the triangle to the nearest point on its outline", "[FilamentBitmapUtils]") +{ + using Slic3r::GUI::TriPoint; + // Same winding as the ratio picker: top, bottom-left, bottom-right, with y growing downwards. + const TriPoint v0{50, 0}, v1{0, 100}, v2{100, 100}; + struct Case { TriPoint p; std::array weights; }; + const Case c = GENERATE(Case{{95, 40}, {0.5, 0.0, 0.5}}, // right of the right edge, nearest its midpoint + Case{{90, 150}, {0.0, 0.1, 0.9}}, // straight below (90, 100) on the bottom edge + Case{{50, -50}, {1.0, 0.0, 0.0}}, // above the top vertex + Case{{150, 150}, {0.0, 0.0, 1.0}}, // past the bottom-right vertex + Case{{50, 50}, {0.5, 0.25, 0.25}}); // inside, left as is + + double w0, w1, w2; + Slic3r::GUI::tri_barycentric(Slic3r::GUI::tri_clamp(c.p, v0, v1, v2), v0, v1, v2, w0, w1, w2); + CHECK_THAT(w0, Catch::Matchers::WithinAbs(c.weights[0], 1e-9)); + CHECK_THAT(w1, Catch::Matchers::WithinAbs(c.weights[1], 1e-9)); + CHECK_THAT(w2, Catch::Matchers::WithinAbs(c.weights[2], 1e-9)); +} + // The headless GTK/macOS suite does not initialize GUI display/font stock objects. // Exercise native bitmap pixels on Windows without adding that dependency elsewhere. #ifdef __WXMSW__ diff --git a/tests/slic3rutils/test_slicing_pipeline_config.cpp b/tests/slic3rutils/test_slicing_pipeline_config.cpp index 73a3840577..ef8614fb9b 100644 --- a/tests/slic3rutils/test_slicing_pipeline_config.cpp +++ b/tests/slic3rutils/test_slicing_pipeline_config.cpp @@ -107,6 +107,19 @@ fs::path write_plugin(const std::string& stem, const std::string& source) return plugin_dir; } +void load_config_probe(PluginManager& manager) +{ + write_plugin("ConfigProbe", CONFIG_PROBE_SOURCE); + manager.get_config().load(); // reset the singleton's store against the empty temp data dir + manager.discover_plugins(/*async=*/false, /*clear=*/true); + + std::string error; + manager.load_plugin("ConfigProbe", /*skip_deps=*/true, {}); + REQUIRE(manager.wait_for_plugin_load("ConfigProbe", std::chrono::seconds(120), error)); + INFO("load error: " << error); + REQUIRE(manager.is_plugin_loaded("ConfigProbe")); +} + } // namespace TEST_CASE("slicing-pipeline dispatch delivers the stored config to self.get_config()", "[slicing_pipeline][PluginConfig][Python]") @@ -116,17 +129,8 @@ TEST_CASE("slicing-pipeline dispatch delivers the stored config to self.get_conf SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); ScopedDataDir data_dir_guard("pipeline-config"); - write_plugin("ConfigProbe", CONFIG_PROBE_SOURCE); - PluginManager& manager = PluginManager::instance(); - manager.get_config().load(); // reset the singleton's store against the empty temp data dir - manager.discover_plugins(/*async=*/false, /*clear=*/true); - - std::string error; - manager.load_plugin("ConfigProbe", /*skip_deps=*/true, {}); - REQUIRE(manager.wait_for_plugin_load("ConfigProbe", std::chrono::seconds(120), error)); - INFO("load error: " << error); - REQUIRE(manager.is_plugin_loaded("ConfigProbe")); + load_config_probe(manager); const PluginCapabilityId id{PluginCapabilityType::SlicingPipeline, "ConfigEcho", "ConfigProbe"}; @@ -164,3 +168,39 @@ TEST_CASE("slicing-pipeline dispatch delivers the stored config to self.get_conf manager.unload_plugin("ConfigProbe"); } + +TEST_CASE("slicing-pipeline dispatch runs a selected capability missing from the plugins manifest", "[slicing_pipeline][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedDataDir data_dir_guard("pipeline-no-manifest"); + PluginManager& manager = PluginManager::instance(); + load_config_probe(manager); + + // The interpreter outlives each test case, so clear what an earlier run of the probe left behind. + { + PythonGILState gil; + REQUIRE(static_cast(gil)); + pybind11::module_ orca = pybind11::module_::import("orca"); + if (pybind11::hasattr(orca, "_probe_config")) + pybind11::delattr(orca, "_probe_config"); + } + + Print print; + Model model; + auto config = DynamicPrintConfig::full_print_config(); + config.set_key_value("slicing_pipeline_plugin", new ConfigOptionStrings({"ConfigEcho"})); + config.set_key_value("plugins", new ConfigOptionStrings()); + init_print({cube(20)}, print, model, config); + print.process(); + + { + PythonGILState gil; + REQUIRE(static_cast(gil)); + CHECK(pybind11::hasattr(pybind11::module_::import("orca"), "_probe_config")); + } + + manager.unload_plugin("ConfigProbe"); +} diff --git a/tests/slic3rutils/test_snapmaker_filament_match.cpp b/tests/slic3rutils/test_snapmaker_filament_match.cpp new file mode 100644 index 0000000000..caa5f94c28 --- /dev/null +++ b/tests/slic3rutils/test_snapmaker_filament_match.cpp @@ -0,0 +1,320 @@ +#include +#include +#include +#include + +#include "libslic3r/Preset.hpp" +#include "libslic3r/PresetBundle.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "slic3r/Utils/SnapmakerPrinterAgent.hpp" + +using namespace Slic3r; + +namespace { + +// A standalone filament collection, built the same way PresetBundle builds its own, so the +// matcher can be exercised without loading the shipped profiles or touching a printer. +struct FilamentTestCollection : public PresetCollection +{ + FilamentTestCollection() + : PresetCollection(Preset::TYPE_FILAMENT, Preset::filament_options(), + static_cast(FullPrintConfig::defaults())) + {} +}; + +struct FilamentSpec +{ + const char *name; + const char *filament_id; + const char *filament_type; + const char *vendor; + const char *colour; // "#RRGGBB", as a profile stores it + const char *inherits = ""; // non-empty makes this a derived user preset +}; + +// Load the specs into the collection, then stamp the fields the matcher reads. Done in a second +// pass because load_preset() keeps m_presets sorted, so a reference taken during the first pass +// can be left dangling by a later load. +void populate(PresetCollection &filaments, const std::vector &specs) +{ + for (const FilamentSpec &spec : specs) { + DynamicPrintConfig config(filaments.default_preset().config); + config.option("filament_type", true)->values = {spec.filament_type}; + config.option("filament_vendor", true)->values = {spec.vendor}; + config.option("default_filament_colour", true)->values = {spec.colour}; + config.option("inherits", true)->value = spec.inherits; + filaments.load_preset(std::string(), spec.name, config, /*select=*/false); + } + for (auto it = filaments.begin(); it != filaments.end(); ++it) { + const auto spec = std::find_if(specs.begin(), specs.end(), + [&](const FilamentSpec &s) { return it->name == s.name; }); + if (spec == specs.end()) + continue; + it->filament_id = spec->filament_id; + it->is_system = std::string(spec->inherits).empty(); + it->is_default = false; + it->is_visible = true; + it->is_compatible = true; + } +} + +std::string match(const std::vector &specs, const std::string &vendor, + const std::string &type, const std::string &sub_type, const std::string &colour) +{ + FilamentTestCollection filaments; + populate(filaments, specs); + return SnapmakerPrinterAgent::find_closest_color_preset_by_vendor_and_type(filaments, vendor, type, sub_type, + colour); +} + +// Two variants of the same vendor and type, as the U1 profiles ship them: the variant lives in the +// preset name, not in filament_type, and only their colours differ. +const std::vector pla_variants{ + {"Snapmaker PLA Basic", "PLA-BASIC", "PLA", "Snapmaker", "#102030"}, + {"Snapmaker PLA Matte", "PLA-MATTE", "PLA", "Snapmaker", "#F0A0B0"}, + {"Snapmaker PLA Silk", "PLA-SILK", "PLA", "Snapmaker", "#30F060"}, +}; + +} // namespace + +// Orca: a spool reports its variant as a sub type, so a Matte spool must not resolve to whichever +// variant happens to sit nearest in colour - here Basic, which the spool colour matches exactly. +TEST_CASE("A spool's sub type beats a closer colour", "[Snapmaker]") +{ + CHECK(match(pla_variants, "Snapmaker", "PLA", "Matte", "102030FF") == "PLA-MATTE"); + // With no sub type to go on, colour decides as before. + CHECK(match(pla_variants, "Snapmaker", "PLA", "", "102030FF") == "PLA-BASIC"); +} + +// Orca: the printer sends an empty colour for a spool with no tag, and std::stoul threw on it. +TEST_CASE("An unusable spool colour returns no match instead of throwing", "[Snapmaker]") +{ + CHECK(match(pla_variants, "Snapmaker", "PLA", "Matte", "").empty()); + CHECK(match(pla_variants, "Snapmaker", "PLA", "Matte", "not-a-colour").empty()); + CHECK(match(pla_variants, "Snapmaker", "PLA", "Matte", "#").empty()); +} + +// Orca: a tag's vendor field and a profile's filament_vendor rarely agree exactly. The match is +// case-insensitive and accepts a whole-word containment either way, so a tag that carries the +// whole product name still reaches the vendor's presets. +TEST_CASE("Vendor matching ignores case and accepts a product name in the vendor field", "[Snapmaker]") +{ + const std::vector sunlu{ + {"SUNLU PLA", "SUNLU-PLA", "PLA", "SUNLU", "#102030"}, + }; + CHECK(match(sunlu, "Sunlu", "PLA", "", "102030FF") == "SUNLU-PLA"); + + const std::vector anycubic{ + {"Anycubic PLA Basic", "ANY-BASIC", "PLA", "Anycubic", "#102030"}, + {"Anycubic PLA Matte", "ANY-MATTE", "PLA", "Anycubic", "#F0A0B0"}, + }; + // A legacy tag names the whole product in the vendor field and leaves the sub type empty; + // "Anycubic PLA Basic" still matches the profiles whose vendor is just "Anycubic". + CHECK(match(anycubic, "Anycubic PLA Basic", "PLA", "", "102030FF") == "ANY-BASIC"); + // With no sub type to go on, the variant named in the vendor field decides, so Basic wins + // even when Matte is the exact colour match. + CHECK(match(anycubic, "Anycubic PLA Basic", "PLA", "", "F0A0B0FF") == "ANY-BASIC"); +} + +// Orca: a finish lives in the preset name - only a handful of profiles put it in filament_type, +// and first_visible_idx_by_type() strips anything after the first space - so the name match is +// what finds it. A silk spool takes the silk preset however far its colour is, and when the +// vendor ships none it falls back to that vendor's nearest preset rather than to no match: +// sync_ams_list() reads an empty filament_id as an empty slot, which drops the spool entirely. +TEST_CASE("A finish sub type is preferred, and falls back within the vendor", "[Snapmaker]") +{ + // Basic is an exact colour match and still loses to the Silk preset the spool asks for. + CHECK(match(pla_variants, "Snapmaker", "PLA", "Silk", "102030FF") == "PLA-SILK"); + + const std::vector no_silk{ + {"Snapmaker PLA Basic", "PLA-BASIC", "PLA", "Snapmaker", "#102030"}, + {"Snapmaker PLA Matte", "PLA-MATTE", "PLA", "Snapmaker", "#F0A0B0"}, + }; + CHECK(match(no_silk, "Snapmaker", "PLA", "Silk", "102030FF") == "PLA-BASIC"); + CHECK(match(no_silk, "Snapmaker", "PLA", "Silk", "F0A0B0FF") == "PLA-MATTE"); +} + +// Orca: a grade or brand word names the same material, so it stays a preference. A Polar Filament +// "Pure" spool has no "Pure" preset to find - Snapmaker ships Generic PLA, High Speed, Silk and +// Matte for the U1 - and must still resolve by colour rather than coming back empty. +TEST_CASE("A brand sub type stays a preference", "[Snapmaker]") +{ + CHECK(match(pla_variants, "Snapmaker", "PLA", "Pure", "102030FF") == "PLA-BASIC"); + CHECK(match(pla_variants, "Snapmaker", "PLA", "Basic", "30F060FF") == "PLA-BASIC"); +} + +// Orca: CF10, CF15 and friends are fibre loadings of the same material, so a CF sub type has to +// match them all and colour decides between them. A trailing letter is a different product. +TEST_CASE("A CF sub type matches every CF fibre loading", "[Snapmaker]") +{ + const std::vector cf_presets{ + {"Snapmaker PA12-CF", "PA12-CF", "PA12-CF", "Snapmaker", "#F0A0B0"}, + {"Snapmaker PA12-CF10", "PA12-CF10", "PA12-CF", "Snapmaker", "#102030"}, + }; + // Both match the sub type, so the closer colour wins - either way round. + CHECK(match(cf_presets, "Snapmaker", "PA12-CF", "CF", "102030FF") == "PA12-CF10"); + CHECK(match(cf_presets, "Snapmaker", "PA12-CF", "CF", "F0A0B0FF") == "PA12-CF"); + // And a tag that reports the loading itself still matches the plain -CF preset. + CHECK(match(cf_presets, "Snapmaker", "PA12-CF", "CF10", "F0A0B0FF") == "PA12-CF"); + CHECK(match(cf_presets, "Snapmaker", "PA12-CF", "CF15", "102030FF") == "PA12-CF10"); +} + +// Orca: the same for glass fibre. QIDI ships "QIDI PPS-GF" (filament_type PPS-GF), and a GF20 +// spool has to reach it as readily as a preset that spells the loading out. +TEST_CASE("A GF sub type matches every GF fibre loading", "[Snapmaker]") +{ + const std::vector gf_presets{ + {"QIDI PPS-GF", "PPS-GF", "PPS-GF", "QIDI", "#F0A0B0"}, + {"QIDI PPS-GF20", "PPS-GF20", "PPS-GF", "QIDI", "#102030"}, + }; + CHECK(match(gf_presets, "QIDI", "PPS-GF", "GF", "102030FF") == "PPS-GF20"); + CHECK(match(gf_presets, "QIDI", "PPS-GF", "GF", "F0A0B0FF") == "PPS-GF"); + // A tag reporting the loading reaches the plain -GF preset too. + CHECK(match(gf_presets, "QIDI", "PPS-GF", "GF20", "F0A0B0FF") == "PPS-GF"); + CHECK(match(gf_presets, "QIDI", "PPS-GF", "GF20", "102030FF") == "PPS-GF20"); +} + +// Orca: the fibre word still has to end at a digit or a boundary. "CFX" is its own product, so a +// CF spool must not prefer it - here it is an exact colour match and still has to lose. +TEST_CASE("A CF sub type does not match a CFX preset", "[Snapmaker]") +{ + const std::vector cfx_presets{ + {"Snapmaker PA12-CF", "PA12-CF", "PA12-CF", "Snapmaker", "#F0A0B0"}, + {"Snapmaker PA12-CFX", "PA12-CFX", "PA12-CF", "Snapmaker", "#102030"}, + }; + CHECK(match(cfx_presets, "Snapmaker", "PA12-CF", "CF", "102030FF") == "PA12-CF"); +} + +// Orca: combine_filament_type() has already folded CF into filament_type, so a CF spool may still +// take a correctly typed preset whose name does not repeat the fibre - unlike a finish sub type. +TEST_CASE("A CF sub type stays a preference once the type carries the fibre", "[Snapmaker]") +{ + const std::vector unnamed_fibre{ + {"Snapmaker PA12 Structural", "PA12-STRUCT", "PA12-CF", "Snapmaker", "#102030"}, + }; + CHECK(match(unnamed_fibre, "Snapmaker", "PA12-CF", "CF", "102030FF") == "PA12-STRUCT"); +} + +// Orca: a profile with no declared colour used to score as black, which let it win every dark +// spool and beat profiles that do declare a colour. It is now unranked - a last resort only. +TEST_CASE("A preset with no colour is unranked, not black", "[Snapmaker]") +{ + const std::vector mixed{ + {"Snapmaker PETG Clear", "PETG-CLEAR", "PETG", "Snapmaker", "#FFFFFF"}, + {"Snapmaker PETG", "PETG-PLAIN", "PETG", "Snapmaker", ""}, + }; + // A dark spool: black would be the closer match, but the colourless preset cannot be ranked. + CHECK(match(mixed, "Snapmaker", "PETG", "", "292929FF") == "PETG-CLEAR"); + CHECK(match(mixed, "Snapmaker", "PETG", "", "FEFEFEFF") == "PETG-CLEAR"); + + // With nothing else to go on it is still returned, rather than reporting no match at all. + const std::vector colourless{ + {"Snapmaker PETG", "PETG-PLAIN", "PETG", "Snapmaker", ""}, + }; + CHECK(match(colourless, "Snapmaker", "PETG", "", "292929FF") == "PETG-PLAIN"); +} + +// Orca: Orca ships U1-compatible presets for a handful of vendors, so a spool from any other +// brand finds nothing in the vendor pass. Orca's own Generic presets cover the sub types the U1 +// sees and carry no other brand's temperatures or flow, so they are the fallback - ahead of the +// caller's filament_id_by_type(), which ignores the sub type entirely. +TEST_CASE("A spool from an unknown vendor falls back to a Generic preset", "[Snapmaker]") +{ + const std::vector library{ + {"Generic PLA", "PLA-GENERIC", "PLA", "Generic", "#102030"}, + {"Generic PLA Silk", "PLA-SILK", "PLA", "Generic", "#F0A0B0"}, + }; + // Nothing carries the spool's vendor, and the plain preset is the exact colour match, so only + // the sub type can decide it. + CHECK(match(library, "Polar Filament", "PLA", "Silk", "102030FF") == "PLA-SILK"); + // With no sub type the Generic preset of the type is taken, rather than whichever preset + // filament_id_by_type() happens to find first. + CHECK(match(library, "Polar Filament", "PLA", "", "102030FF") == "PLA-GENERIC"); + // Within the sub type, colour still ranks. + const std::vector two_silks{ + {"Generic PLA", "PLA-GENERIC", "PLA", "Generic", "#102030"}, + {"Generic PLA Silk", "PLA-SILK", "PLA", "Generic", "#F0A0B0"}, + {"Generic PLA Silk HF", "PLA-SILK-HF", "PLA", "Generic", "#102030"}, + }; + CHECK(match(two_silks, "Polar Filament", "PLA", "Silk", "102030FF") == "PLA-SILK-HF"); +} + +// Orca: the fallback pass looks at Generic presets only. An unknown brand's Matte spool taking +// "Snapmaker PLA Matte", or a user's Matte preset from a third brand, would print with that +// brand's temperatures and flow, which is worse than a plain profile that carries nobody's. +TEST_CASE("The Generic pass ignores other brands' presets", "[Snapmaker]") +{ + const std::vector other_brand{ + {"Generic PLA", "PLA-GENERIC", "PLA", "Generic", "#102030"}, + {"Snapmaker PLA Matte", "SM-MATTE", "PLA", "Snapmaker", "#F0A0B0"}, + }; + // The Snapmaker preset names the sub type and matches the colour exactly, and still loses. + CHECK(match(other_brand, "Anycubic", "PLA", "Matte", "F0A0B0FF") == "PLA-GENERIC"); + + // A Generic preset that does name the finish is taken, however far its colour. + const std::vector generic_matte{ + {"Generic PLA", "PLA-GENERIC", "PLA", "Generic", "#102030"}, + {"Generic PLA Matte", "PLA-MATTE", "PLA", "Generic", "#F0A0B0"}, + }; + CHECK(match(generic_matte, "Anycubic", "PLA", "Matte", "102030FF") == "PLA-MATTE"); +} + +// Orca: a tag that reports no vendor matches no profile's filament_vendor, so the vendor pass +// finds nothing for it - a vendorless spool must not take the closest-coloured preset of any +// brand. The Generic pass then handles it, with or without a sub type. +TEST_CASE("A tag with no vendor does not match every vendor", "[Snapmaker]") +{ + const std::vector library{ + {"Generic PLA", "PLA-GENERIC", "PLA", "Generic", "#102030"}, + {"Snapmaker PLA", "SM-PLA", "PLA", "Snapmaker", "#102030"}, + {"Generic PLA Silk", "PLA-SILK", "PLA", "Generic", "#F0A0B0"}, + }; + // The Snapmaker preset is an equally exact colour match and is never considered. + CHECK(match(library, "", "PLA", "", "102030FF") == "PLA-GENERIC"); + // A vendorless tag that does name a sub type still reaches it through the Generic pass. + CHECK(match(library, "", "PLA", "Silk", "102030FF") == "PLA-SILK"); +} + +// Orca: the Generic pass only helps for a type Orca ships a Generic preset of. For any other +// type the slot falls through to the caller's type-only lookup, as it did before - an unrelated +// vendor's filament is never dragged in. +TEST_CASE("A type with no Generic preset falls through", "[Snapmaker]") +{ + const std::vector library{ + {"Generic PLA", "PLA-GENERIC", "PLA", "Generic", "#102030"}, + {"QIDI PPS-GF", "PPS-GF", "PPS-GF", "QIDI", "#102030"}, + }; + CHECK(match(library, "Polar Filament", "PPS-GF", "GF", "102030FF").empty()); + // A sub type no preset carries is still only a preference, so the plain Generic preset of the + // type is taken. + CHECK(match(library, "Polar Filament", "PLA", "Pure", "102030FF") == "PLA-GENERIC"); +} + +// Orca: sync_ams_list() resolves a filament_id to the first base preset carrying it, so a derived +// user copy can never be loaded and must not win the match - even with an exact colour. +TEST_CASE("A derived user preset never wins the match", "[Snapmaker]") +{ + const std::vector with_copy{ + {"Snapmaker PLA Basic", "PLA-BASIC", "PLA", "Snapmaker", "#F0A0B0"}, + {"Snapmaker PLA Basic copy", "PLA-COPY", "PLA", "Snapmaker", "#102030", "Snapmaker PLA Basic"}, + }; + CHECK(match(with_copy, "Snapmaker", "PLA", "", "102030FF") == "PLA-BASIC"); +} + +// Orca: only CF and GF are material types; every other sub type is a finish or a brand name, and a +// base that already carries the suffix must not gain a second one. +TEST_CASE("Only CF and GF change the material type", "[Snapmaker]") +{ + CHECK(SnapmakerPrinterAgent::combine_filament_type("PLA", "CF") == "PLA-CF"); + CHECK(SnapmakerPrinterAgent::combine_filament_type("PETG", "GF") == "PETG-GF"); + CHECK(SnapmakerPrinterAgent::combine_filament_type("PA12-CF", "CF") == "PA12-CF"); + // A fibre loading is not a material type: MaterialType::all() has PA12-CF, never PA12-CF10. + CHECK(SnapmakerPrinterAgent::combine_filament_type("PA12", "CF10") == "PA12-CF"); + CHECK(SnapmakerPrinterAgent::combine_filament_type("PA12-CF", "CF10") == "PA12-CF"); + CHECK(SnapmakerPrinterAgent::combine_filament_type("ABS", "GF30") == "ABS-GF"); + CHECK(SnapmakerPrinterAgent::combine_filament_type("PPS", "GF20") == "PPS-GF"); + CHECK(SnapmakerPrinterAgent::combine_filament_type("PPS-GF", "GF20") == "PPS-GF"); + CHECK(SnapmakerPrinterAgent::combine_filament_type("PLA", "Silk") == "PLA"); + CHECK(SnapmakerPrinterAgent::combine_filament_type("PLA", "NONE") == "PLA"); + CHECK(SnapmakerPrinterAgent::combine_filament_type("", "CF") == "PLA"); +}