diff --git a/localization/i18n/list.txt b/localization/i18n/list.txt index 8f9dda0673..b4b7b4e260 100644 --- a/localization/i18n/list.txt +++ b/localization/i18n/list.txt @@ -294,6 +294,7 @@ src/slic3r/GUI/FilamentPickerDialog.cpp src/slic3r/GUI/NetworkPluginDialog.cpp src/slic3r/GUI/RammingChart.cpp src/slic3r/GUI/StepMeshDialog.cpp +src/slic3r/GUI/GeometryImportDialog.cpp src/slic3r/GUI/FilamentPickerDialog.hpp src/slic3r/GUI/PresetBundleDialog.cpp src/slic3r/GUI/ExportPresetBundleDialog.cpp diff --git a/src/libslic3r/AppConfig.cpp b/src/libslic3r/AppConfig.cpp index 5614385e05..e4b577e633 100644 --- a/src/libslic3r/AppConfig.cpp +++ b/src/libslic3r/AppConfig.cpp @@ -18,6 +18,7 @@ #include "nlohmann/json.hpp" #include +#include #include #include #include @@ -703,8 +704,29 @@ void AppConfig::set_defaults() set("angle_deflection", "0.5"); } if (get("is_split_compound").empty()) { - set_bool("is_split_compound", false); + // Splitting keeps the bodies of a multi-body part, and with them their original names. + set_bool("is_split_compound", true); } + // Geometry-import choices are editor preferences, never project print settings. + for (const std::string format : {"step", "amf", "3mf"}) { + const std::string prefix = "import_names_" + format + "_"; + if (get(prefix + "keep").empty()) + set_bool(prefix + "keep", true); + if (get(prefix + "sort").empty()) + set_bool(prefix + "sort", false); + if (format != "3mf" && get(prefix + "assembly").empty()) + set_bool(prefix + "assembly", true); + if (format == "amf" && get(prefix + "separate").empty()) + set_bool(prefix + "separate", true); + if (format != "step" && get(prefix + "show_dialog").empty()) + set_bool(prefix + "show_dialog", true); + } + if (get("import_names_cleanup_show_dialog").empty()) + set_bool("import_names_cleanup_show_dialog", true); + if (get("import_names_cleanup_remove").empty()) + set_bool("import_names_cleanup_remove", false); + if (get("import_names_cleanup_replacement").empty()) + set("import_names_cleanup_replacement", "_"); if (get("enable_primitive_size_dialog").empty()) { set_bool("enable_primitive_size_dialog", true); } diff --git a/src/libslic3r/CMakeLists.txt b/src/libslic3r/CMakeLists.txt index 034f8b577a..116a154319 100644 --- a/src/libslic3r/CMakeLists.txt +++ b/src/libslic3r/CMakeLists.txt @@ -217,6 +217,8 @@ set(lisbslic3r_sources Format/3mf.hpp Format/AMF.cpp Format/AMF.hpp + Format/ImportNames.cpp + Format/ImportNames.hpp Format/AssembleList.cpp Format/AssembleList.hpp Format/DRC.cpp diff --git a/src/libslic3r/Format/AMF.cpp b/src/libslic3r/Format/AMF.cpp index 42583419b4..08495f2359 100644 --- a/src/libslic3r/Format/AMF.cpp +++ b/src/libslic3r/Format/AMF.cpp @@ -2,11 +2,13 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include @@ -20,6 +22,7 @@ #include "libslic3r/TriangleMesh.hpp" #include "AMF.hpp" +#include "ProjectStrategy.hpp" #include #include @@ -67,11 +70,15 @@ namespace Slic3r struct AMFParserContext { - AMFParserContext(XML_Parser parser, DynamicPrintConfig* config, ConfigSubstitutionContext* config_substitutions, Model* model) : + AMFParserContext(XML_Parser parser, DynamicPrintConfig* config, ConfigSubstitutionContext* config_substitutions, Model* model, LoadStrategy options, + const char* source_path) : m_parser(parser), m_model(*model), m_config(config), - m_config_substitutions(config_substitutions) + m_config_substitutions(config_substitutions), + m_assemble_parts((options & LoadStrategy::AssembleParts) && !(options & LoadStrategy::LoadConfig)), + m_keep_original_names(options & LoadStrategy::KeepOriginalNames), + m_fallback_name(boost::filesystem::path(source_path).filename().string()) { m_path.reserve(12); } @@ -96,7 +103,8 @@ struct AMFParserContext void startElement(const char *name, const char **atts); void endElement(const char *name); - void endDocument(); + bool endDocument(); + bool assemble_constellations(); void characters(const XML_Char *s, int len); static void XMLCALL startElement(void *userData, const char *name, const char **atts) @@ -246,6 +254,10 @@ struct AMFParserContext ModelObject *m_object { nullptr }; // Map from obect name to object idx & instances. std::map m_object_instances_map; + // Preserve XML membership and occurrence order only for explicit assembly import. + std::vector>> m_constellations; + // XML ids of m_constellations, so a group can be referenced from another group. + std::vector m_constellation_ids; // Vertices parsed for the current m_object. std::vector m_object_vertices; // Current volume allocated for an amf/object/mesh/volume subtree. @@ -266,6 +278,9 @@ struct AMFParserContext ConfigSubstitutionContext *m_config_substitutions { nullptr }; //BBS: add units logic bool m_use_inches { false }; + bool m_assemble_parts { false }; + bool m_keep_original_names { false }; + std::string m_fallback_name; private: AMFParserContext& operator=(AMFParserContext&); @@ -306,6 +321,11 @@ void AMFParserContext::startElement(const char *name, const char **atts) node_type_new = NODE_TYPE_OBJECT; } } else if (strcmp(name, "constellation") == 0) { + if (m_assemble_parts) { + m_constellations.emplace_back(); + const char *constellation_id = get_attribute(atts, "id"); + m_constellation_ids.emplace_back(constellation_id == nullptr ? "" : constellation_id); + } node_type_new = NODE_TYPE_CONSTELLATION; }/*else if (strcmp(name, "custom_gcodes_per_height") == 0) { node_type_new = NODE_TYPE_CUSTOM_GCODE; @@ -333,8 +353,14 @@ void AMFParserContext::startElement(const char *name, const char **atts) if (object_id == nullptr) this->stop(); else { - m_object_instances_map[object_id].instances.push_back(AMFParserContext::Instance()); - m_instance = &m_object_instances_map[object_id].instances.back(); + if (m_assemble_parts) { + auto &occurrences = m_constellations.back(); + occurrences.emplace_back(object_id, Instance()); + m_instance = &occurrences.back().second; + } else { + m_object_instances_map[object_id].instances.push_back(Instance()); + m_instance = &m_object_instances_map[object_id].instances.back(); + } node_type_new = NODE_TYPE_INSTANCE; } } @@ -858,8 +884,178 @@ void AMFParserContext::endElement(const char * /* name */) m_path.pop_back(); } -void AMFParserContext::endDocument() +bool AMFParserContext::assemble_constellations() { + auto object_index = [this](const std::string &target) { + auto definition = m_object_instances_map.find(target); + return definition == m_object_instances_map.end() ? -1 : definition->second.idx; + }; + // Malformed ids are skipped as Orca always did: an objectid names an object first, then the first group with that id. + std::map constellation_index; + for (size_t index = 0; index < m_constellation_ids.size(); ++index) { + const std::string &id = m_constellation_ids[index]; + if (id.empty()) + continue; + if (object_index(id) >= 0) + BOOST_LOG_TRIVIAL(warning) << "AMF constellation id " << id << " equals an object id; references resolve to the object"; + else if (!constellation_index.emplace(id, index).second) + BOOST_LOG_TRIVIAL(error) << "Duplicate AMF constellation id " << id << "; only the first group can be referenced"; + } + auto group_index = [&constellation_index](const std::string &target) { + auto group = constellation_index.find(target); + return group == constellation_index.end() ? -1 : int(group->second); + }; + + // A group referenced from another group is flattened into it and is not an assembly of its own. + std::set nested; + for (const auto &constellation : m_constellations) + for (const auto &occurrence : constellation) { + if (object_index(occurrence.first) >= 0) + continue; + if (const int group = group_index(occurrence.first); group >= 0) + nested.insert(size_t(group)); + else + BOOST_LOG_TRIVIAL(error) << "Undefined object " << occurrence.first << " referenced in constellation"; + } + + auto instance_matrix = [](const Instance &source) { + Geometry::Transformation transformation; + transformation.set_offset(Vec3d(source.deltax_set ? source.deltax : 0., source.deltay_set ? source.deltay : 0., + source.deltaz_set ? source.deltaz : 0.)); + transformation.set_rotation(Vec3d(source.rx_set ? source.rx : 0., source.ry_set ? source.ry : 0., + source.rz_set ? source.rz : 0.)); + transformation.set_scaling_factor(Vec3d(source.scalex_set ? source.scalex : 1., source.scaley_set ? source.scaley : 1., + source.scalez_set ? source.scalez : 1.)); + transformation.set_mirror(Vec3d(source.mirrorx_set ? source.mirrorx : 1., source.mirrory_set ? source.mirrory : 1., + source.mirrorz_set ? source.mirrorz : 1.)); + return transformation.get_matrix(); + }; + // Nesting and expansion limits keep a small malformed file from exhausting the stack or the time. + constexpr size_t max_depth = 256; + constexpr size_t max_expanded = 100000; + // One depth-first pass rejects cycles, so the expansion below always terminates. + std::vector state(m_constellations.size(), 0); // 0 new, 1 on the current path, 2 done + std::function acyclic = [&](size_t group, size_t depth) { + if (depth > max_depth) + return false; + state[group] = 1; + for (const auto &occurrence : m_constellations[group]) { + const int child = object_index(occurrence.first) >= 0 ? -1 : group_index(occurrence.first); + if (child < 0) + continue; + if (state[child] == 1 || (state[child] == 0 && !acyclic(size_t(child), depth + 1))) + return false; + } + state[group] = 2; + return true; + }; + for (size_t group = 0; group < m_constellations.size(); ++group) + if (state[group] == 0 && !acyclic(group, 0)) { + BOOST_LOG_TRIVIAL(error) << "Cyclic or too deeply nested AMF constellation references"; + return false; + } + + struct Placement + { + int index; + Transform3d matrix; + bool printable; + // Some occurrence on the path sets a transform; the legacy loader creates instances only then. + bool placed; + }; + // Every expanded occurrence counts, so groups that reach no body cannot multiply the work unnoticed. + size_t expanded = 0; + // Nested placements multiply down to the object definitions of the top-level group. + // The cycle check skips groups it already visited, so the expansion bounds its own depth too. + std::function &)> flatten = + [&](size_t group, const Transform3d &parent, bool parent_printable, bool parent_placed, size_t depth, + std::vector &out) { + if (depth > max_depth) + return false; + for (const auto &occurrence : m_constellations[group]) { + if (++expanded > max_expanded) + return false; + const Transform3d matrix = parent * instance_matrix(occurrence.second); + const bool printable = parent_printable && occurrence.second.printable; + const bool placed = parent_placed || occurrence.second.anything_set(); + if (const int index = object_index(occurrence.first); index >= 0) + out.push_back({index, matrix, printable, placed}); + else if (const int group = group_index(occurrence.first); + group >= 0 && !flatten(size_t(group), matrix, printable, placed, depth + 1, out)) + return false; + } + return true; + }; + + std::set referenced; + std::vector> groups; + for (size_t group = 0; group < m_constellations.size(); ++group) { + if (nested.count(group) != 0) + continue; + std::vector placements; + if (!flatten(group, Transform3d::Identity(), true, false, 0, placements)) { + BOOST_LOG_TRIVIAL(error) << "Too many AMF constellation placements"; + return false; + } + for (const Placement &placement : placements) + referenced.insert(placement.index); + groups.emplace_back(std::move(placements)); + } + + Model prepared; + int assemblies = 0; + for (const std::vector &placements : groups) { + if (placements.empty()) + continue; + Model group; + const bool printable = placements.front().printable; + bool mixed_printable = false; + bool placed = false; + for (const Placement &placement : placements) { + ModelObject *object = group.add_object(*m_model.objects[placement.index]); + // Match the GUI's filename fallback before merging discards the source objects. + if (object->name.empty()) + object->name = m_fallback_name; + for (ModelVolume* volume : object->volumes) + if (volume->name.empty()) + volume->name = object->name; + object->clear_instances(); + ModelInstance *instance = object->add_instance(); + // An identity occurrence is still an explicit instance, including its printability. + instance->set_transformation(Geometry::Transformation(placement.matrix)); + instance->printable = placement.printable; + mixed_printable = mixed_printable || placement.printable != printable; + placed = placed || placement.placed; + } + if (!mixed_printable && group.objects.size() > 1) { + group.convert_multipart_object(0, m_keep_original_names); + // An assembly is named after its file like other single-file imports; later groups get a suffix. + ++assemblies; + group.objects.front()->name = m_fallback_name + (assemblies > 1 ? "_" + std::to_string(assemblies) : std::string()); + group.objects.front()->add_instance()->printable = printable; + } + // Without any placement in the file the GUI centres the object on the bed, as for legacy AMF objects. + // An excluded group keeps its identity instance: dropping it would make the part printable. + if (!placed && printable && group.objects.size() == 1) + group.objects.front()->clear_instances(); + // Mixed printability cannot be expressed by one instance; preserve separate occurrences. + for (const ModelObject *object : group.objects) + prepared.add_object(*object); + } + // Unreferenced definitions remain independent, in their original XML order. + for (size_t index = 0; index < m_model.objects.size(); ++index) + if (referenced.count(static_cast(index)) == 0) + prepared.add_object(*m_model.objects[index]); + m_model.clear_objects(); + for (const ModelObject *object : prepared.objects) + m_model.add_object(*object); + return true; +} + +bool AMFParserContext::endDocument() +{ + if (m_assemble_parts) + return assemble_constellations(); for (const auto &object : m_object_instances_map) { if (object.second.idx == -1) { BOOST_LOG_TRIVIAL(error) << "Undefined object " << object.first.c_str() << " referenced in constellation"; @@ -888,11 +1084,12 @@ void AMFParserContext::endDocument() } } } + return true; } // Load an AMF file into a provided model. //BBS: add inches check logic -bool load_amf_file(const char *path, DynamicPrintConfig *config, ConfigSubstitutionContext *config_substitutions, Model *model, bool *use_inches) +bool load_amf_file(const char *path, DynamicPrintConfig *config, ConfigSubstitutionContext *config_substitutions, Model *model, bool *use_inches, LoadStrategy options) { if ((path == nullptr) || (model == nullptr)) return false; @@ -909,7 +1106,7 @@ bool load_amf_file(const char *path, DynamicPrintConfig *config, ConfigSubstitut return false; } - AMFParserContext ctx(parser, config, config_substitutions, model); + AMFParserContext ctx(parser, config, config_substitutions, model, options, path); XML_SetUserData(parser, (void*)&ctx); XML_SetElementHandler(parser, AMFParserContext::startElement, AMFParserContext::endElement); XML_SetCharacterDataHandler(parser, AMFParserContext::characters); @@ -937,7 +1134,7 @@ bool load_amf_file(const char *path, DynamicPrintConfig *config, ConfigSubstitut ::fclose(pFile); if (result) - ctx.endDocument(); + result = ctx.endDocument(); if (use_inches) { *use_inches = ctx.m_use_inches; } @@ -955,7 +1152,7 @@ bool load_amf_file(const char *path, DynamicPrintConfig *config, ConfigSubstitut } //BBS: add inches logic -bool extract_model_from_archive(mz_zip_archive& archive, const mz_zip_archive_file_stat& stat, DynamicPrintConfig* config, ConfigSubstitutionContext* config_substitutions, Model* model, bool* use_inches) +bool extract_model_from_archive(mz_zip_archive& archive, const mz_zip_archive_file_stat& stat, DynamicPrintConfig* config, ConfigSubstitutionContext* config_substitutions, Model* model, bool* use_inches, LoadStrategy options, const char* source_path) { if (stat.m_uncomp_size == 0) { @@ -971,7 +1168,7 @@ bool extract_model_from_archive(mz_zip_archive& archive, const mz_zip_archive_fi return false; } - AMFParserContext ctx(parser, config, config_substitutions, model); + AMFParserContext ctx(parser, config, config_substitutions, model, options, source_path); XML_SetUserData(parser, (void*)&ctx); XML_SetElementHandler(parser, AMFParserContext::startElement, AMFParserContext::endElement); XML_SetCharacterDataHandler(parser, AMFParserContext::characters); @@ -1017,7 +1214,8 @@ bool extract_model_from_archive(mz_zip_archive& archive, const mz_zip_archive_fi return false; } - ctx.endDocument(); + if (!ctx.endDocument()) + return false; if (use_inches) { *use_inches = ctx.m_use_inches; } @@ -1033,7 +1231,7 @@ bool extract_model_from_archive(mz_zip_archive& archive, const mz_zip_archive_fi } // Load an AMF archive into a provided model. -bool load_amf_archive(const char* path, DynamicPrintConfig* config, ConfigSubstitutionContext* config_substitutions, Model* model, bool* use_inches) +bool load_amf_archive(const char* path, DynamicPrintConfig* config, ConfigSubstitutionContext* config_substitutions, Model* model, bool* use_inches, LoadStrategy options) { if ((path == nullptr) || (model == nullptr)) return false; @@ -1059,7 +1257,7 @@ bool load_amf_archive(const char* path, DynamicPrintConfig* config, ConfigSubsti { try { - if (!extract_model_from_archive(archive, stat, config, config_substitutions, model, use_inches)) + if (!extract_model_from_archive(archive, stat, config, config_substitutions, model, use_inches, options, path)) { close_zip_reader(&archive); BOOST_LOG_TRIVIAL(error) << "Archive does not contain a valid model"; @@ -1102,7 +1300,7 @@ bool load_amf_archive(const char* path, DynamicPrintConfig* config, ConfigSubsti // Load an AMF file into a provided model. // If config is not a null pointer, updates it if the amf file/archive contains config data //BBS: refine the amf logic -bool load_amf(const char *path, DynamicPrintConfig *config, ConfigSubstitutionContext *config_substitutions, Model *model, bool* use_inches) +bool load_amf(const char *path, DynamicPrintConfig *config, ConfigSubstitutionContext *config_substitutions, Model *model, bool* use_inches, LoadStrategy options) { CNumericLocalesSetter locales_setter; // use "C" locales and point as a decimal separator @@ -1116,7 +1314,8 @@ bool load_amf(const char *path, DynamicPrintConfig *config, ConfigSubstitutionCo file.read(zip_mask.data(), 2); file.close(); - return (zip_mask == "PK") ? load_amf_archive(path, config, config_substitutions, model, use_inches) : load_amf_file(path, config, config_substitutions, model, use_inches); + return (zip_mask == "PK") ? load_amf_archive(path, config, config_substitutions, model, use_inches, options) : + load_amf_file(path, config, config_substitutions, model, use_inches, options); } else return false; diff --git a/src/libslic3r/Format/AMF.hpp b/src/libslic3r/Format/AMF.hpp index 335d47d6fb..1133660c7b 100644 --- a/src/libslic3r/Format/AMF.hpp +++ b/src/libslic3r/Format/AMF.hpp @@ -1,6 +1,8 @@ #ifndef slic3r_Format_AMF_hpp_ #define slic3r_Format_AMF_hpp_ +#include "ProjectStrategy.hpp" + namespace Slic3r { class Model; @@ -8,7 +10,8 @@ class DynamicPrintConfig; struct ConfigSubstitutionContext; // Load the content of an amf file into the given model and configuration. -extern bool load_amf(const char* path, DynamicPrintConfig* config, ConfigSubstitutionContext* config_substitutions, Model* model, bool* use_inches); +extern bool load_amf(const char* path, DynamicPrintConfig* config, ConfigSubstitutionContext* config_substitutions, Model* model, bool* use_inches, + LoadStrategy options = LoadStrategy::Default); //BBS: remove amf export // Save the given model and the config data into an amf file. diff --git a/src/libslic3r/Format/ImportNames.cpp b/src/libslic3r/Format/ImportNames.cpp new file mode 100644 index 0000000000..7c95ecd403 --- /dev/null +++ b/src/libslic3r/Format/ImportNames.cpp @@ -0,0 +1,115 @@ +#include "ImportNames.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { +namespace { + +std::u32string decode_name(const std::string& name) +{ + try { + return boost::locale::conv::utf_to_utf(name, boost::locale::conv::stop); + } catch (const boost::locale::conv::conversion_error&) { + throw std::invalid_argument("An imported name contains invalid UTF-8."); + } +} + +bool unsupported_character(char32_t c) +{ + // XML permits tab/newline/CR, but excludes other C0 controls and noncharacters FFFE/FFFF. + const bool valid_xml = c == 9 || c == 10 || c == 13 || + (c >= 0x20 && c <= 0xd7ff) || + (c >= 0xe000 && c <= 0xfffd) || + (c >= 0x10000 && c <= 0x10ffff); + constexpr std::u32string_view forbidden = U"<>:/\\|?*\""; + return !valid_xml || forbidden.find(c) != std::u32string_view::npos; +} + +std::string replace_characters(const std::string& name, const std::string& replacement) +{ + std::u32string output; + const std::u32string substitute = decode_name(replacement); + for (char32_t c : decode_name(name)) { + if (unsupported_character(c)) + output += substitute; + else + output += c; + } + return boost::locale::conv::utf_to_utf(output); +} + +} // namespace + +bool has_unsupported_name_characters(const std::string& name) +{ + for (char32_t c : decode_name(name)) + if (unsupported_character(c)) + return true; + return false; +} + +bool valid_import_name_replacement(const std::string& replacement) +{ + if (replacement.empty()) + return false; + try { + return !has_unsupported_name_characters(replacement); + } catch (const std::invalid_argument&) { + return false; + } +} + +std::vector sanitize_import_names(const std::vector& names, + const std::string& replacement, + const std::string& fallback) +{ + if (!replacement.empty() && !valid_import_name_replacement(replacement)) + throw std::invalid_argument("The name replacement contains unsupported characters."); + + // Reserve all existing valid names before processing, including those appearing later. + std::set reserved; + for (const auto& name : names) + if (!has_unsupported_name_characters(name)) + reserved.insert(name); + + std::string safe_fallback = replace_characters(fallback, replacement); + if (safe_fallback.empty()) + safe_fallback = "Part"; + + std::map cleaned; + std::vector result; + result.reserve(names.size()); + for (const auto& name : names) { + if (!has_unsupported_name_characters(name)) { + result.push_back(name); + continue; + } + // Equal original names stay equal even when both require the same cleaning. + const auto previous = cleaned.find(name); + if (previous != cleaned.end()) { + result.push_back(previous->second); + continue; + } + std::string base = replace_characters(name, replacement); + if (base.empty()) + base = safe_fallback; + std::string candidate = base; + for (size_t suffix = 2; reserved.count(candidate) != 0; ++suffix) + candidate = base + " (" + std::to_string(suffix) + ")"; + reserved.insert(candidate); + cleaned.emplace(name, candidate); + result.push_back(candidate); + } + return result; +} + +} // namespace Slic3r diff --git a/src/libslic3r/Format/ImportNames.hpp b/src/libslic3r/Format/ImportNames.hpp new file mode 100644 index 0000000000..dc6ba84e34 --- /dev/null +++ b/src/libslic3r/Format/ImportNames.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include +#include + +namespace Slic3r { + +// Names follow Orca's rename restrictions as well as XML 1.0 and UTF-8 requirements. +bool has_unsupported_name_characters(const std::string& name); +bool valid_import_name_replacement(const std::string& replacement); + +// Empty replacement means removal; only collisions introduced by cleaning receive suffixes. +std::vector sanitize_import_names(const std::vector& names, + const std::string& replacement, + const std::string& fallback = "Part"); + +} // namespace Slic3r diff --git a/src/libslic3r/Format/ProjectStrategy.hpp b/src/libslic3r/Format/ProjectStrategy.hpp index a274dd52b9..7ff3d8a23c 100644 --- a/src/libslic3r/Format/ProjectStrategy.hpp +++ b/src/libslic3r/Format/ProjectStrategy.hpp @@ -18,6 +18,9 @@ enum class LoadStrategy LoadAuxiliary = 16, Silence = 32, ImperialUnits = 64, + // Geometry-import policies are opt-in; opening existing projects retains its defaults. + KeepOriginalNames = 128, + AssembleParts = 256, Restore = 0x10000 | LoadModel | LoadConfig | LoadAuxiliary | Silence, }; diff --git a/src/libslic3r/Format/STEP.cpp b/src/libslic3r/Format/STEP.cpp index 28dbe6aaa5..b26b6a7259 100644 --- a/src/libslic3r/Format/STEP.cpp +++ b/src/libslic3r/Format/STEP.cpp @@ -14,7 +14,10 @@ #include #include #include +#include #include +#include +#include #include #include #include @@ -48,6 +51,7 @@ #include "XCAFDoc_ShapeTool.hxx" #include "XCAFApp_Application.hxx" #include "NCollection_Sequence.hxx" +#include #include "TDF_Label.hxx" #include "TopoDS_Solid.hxx" #include "TopoDS_Compound.hxx" @@ -59,6 +63,16 @@ #include "BRep_Tool.hxx" #include "BRepTools.hxx" #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include namespace fs = boost::filesystem; @@ -201,13 +215,41 @@ int StepPreProcessor::preNum(const unsigned char byte) { return num; } +using StepBodyNames = NCollection_DataMap; + +// Resolve the original topology before BRepBuilderAPI_Transform copies its TShape. +static void add_named_solid(std::vector& namedSolids, const TopoDS_Shape& mesh_shape, const TopoDS_Shape& source, + const StepBodyNames* body_names, const std::string& fallback) +{ + if (body_names != nullptr && body_names->IsBound(source)) + namedSolids.emplace_back(mesh_shape, body_names->Find(source), true); + else + namedSolids.emplace_back(mesh_shape, fallback); +} + +// The single body of a compound, or a null shape when Split compound would produce several parts. +static TopoDS_Shape single_body(const TopoDS_Shape& compound) +{ + TopoDS_Shape body; + int bodies = 0; + TopExp_Explorer explorer; + for (explorer.Init(compound, TopAbs_SOLID); explorer.More(); explorer.Next(), ++bodies) + body = explorer.Current(); + for (explorer.Init(compound, TopAbs_SHELL, TopAbs_SOLID); explorer.More(); explorer.Next(), ++bodies) + body = explorer.Current(); + explorer.Init(compound, TopAbs_FACE, TopAbs_SHELL); + // Loose faces form one more part, so the compound is then not a single body. + return bodies == 1 && !explorer.More() ? body : TopoDS_Shape(); +} + static void getNamedSolids(const TopLoc_Location& location, const std::string& prefix, unsigned int& id, const Handle(XCAFDoc_ShapeTool) shapeTool, const TDF_Label label, std::vector& namedSolids, - bool isSplitCompound = false) { + bool isSplitCompound = false, + const StepBodyNames* body_names = nullptr) { TDF_Label referredLabel{label}; if (shapeTool->IsReference(label)) shapeTool->GetReferredShape(label, referredLabel); @@ -226,7 +268,7 @@ static void getNamedSolids(const TopLoc_Location& location, NCollection_Sequence components; if (shapeTool->GetComponents(referredLabel, components)) { for (int compIndex = 1; compIndex <= components.Length(); ++compIndex) { - getNamedSolids(localLocation, fullName, id, shapeTool, components.Value(compIndex), namedSolids, isSplitCompound); + getNamedSolids(localLocation, fullName, id, shapeTool, components.Value(compIndex), namedSolids, isSplitCompound, body_names); } } else { TopoDS_Shape shape; @@ -239,23 +281,30 @@ static void getNamedSolids(const TopLoc_Location& location, case TopAbs_COMPOUND: case TopAbs_COMPSOLID: if (!isSplitCompound) { - namedSolids.emplace_back(transform.Shape(), fullName); + // One body keeps its label without splitting; the mesh is the unchanged compound. + const TopoDS_Shape body = single_body(shape); + if (body.IsNull()) + namedSolids.emplace_back(transform.Shape(), fullName); + else + add_named_solid(namedSolids, transform.Shape(), body, body_names, fullName); } else { - for (explorer.Init(transform.Shape(), TopAbs_SOLID); explorer.More(); explorer.Next()) { + for (explorer.Init(shape, TopAbs_SOLID); explorer.More(); explorer.Next()) { i++; const TopoDS_Shape& currentShape = explorer.Current(); - namedSolids.emplace_back(TopoDS::Solid(currentShape), fullName + "-SOLID-" + std::to_string(i)); + add_named_solid(namedSolids, transform.ModifiedShape(currentShape), currentShape, body_names, + fullName + "-SOLID-" + std::to_string(i)); } // Surface models have no solids: each shell outside a solid is a part, and loose faces stay together. i = 0; - for (explorer.Init(transform.Shape(), TopAbs_SHELL, TopAbs_SOLID); explorer.More(); explorer.Next()) - namedSolids.emplace_back(explorer.Current(), fullName + "-SHELL-" + std::to_string(++i)); + for (explorer.Init(shape, TopAbs_SHELL, TopAbs_SOLID); explorer.More(); explorer.Next()) + add_named_solid(namedSolids, transform.ModifiedShape(explorer.Current()), explorer.Current(), body_names, + fullName + "-SHELL-" + std::to_string(++i)); TopoDS_Compound loose_faces; TopoDS_Builder builder; builder.MakeCompound(loose_faces); bool has_loose_faces = false; - for (explorer.Init(transform.Shape(), TopAbs_FACE, TopAbs_SHELL); explorer.More(); explorer.Next()) { - builder.Add(loose_faces, explorer.Current()); + for (explorer.Init(shape, TopAbs_FACE, TopAbs_SHELL); explorer.More(); explorer.Next()) { + builder.Add(loose_faces, transform.ModifiedShape(explorer.Current())); has_loose_faces = true; } if (has_loose_faces) @@ -263,10 +312,10 @@ static void getNamedSolids(const TopLoc_Location& location, } break; case TopAbs_SOLID: - namedSolids.emplace_back(TopoDS::Solid(transform.Shape()), fullName); + add_named_solid(namedSolids, TopoDS::Solid(transform.Shape()), shape, body_names, fullName); break; case TopAbs_SHELL: - namedSolids.emplace_back(TopoDS::Shell(transform.Shape()), fullName); + add_named_solid(namedSolids, TopoDS::Shell(transform.Shape()), shape, body_names, fullName); break; default: break; @@ -486,8 +535,9 @@ void Step::update_process(int load_stage, int current, int total, bool& cancel) } } -Step::Step_Status Step::load() +Step::Step_Status Step::load(bool collect_original_names) { + m_body_names.Clear(); if (!StepPreProcessor::isUtf8File(m_path.c_str()) && m_utf8Fn) { m_utf8Fn(false); return Step_Status::LOAD_ERROR; @@ -512,6 +562,27 @@ Step::Step_Status Step::load() } if (cb_cancel) return; progress = 6; + if (collect_original_names) { + // The transfer process records which BREP produced each shape, independently of traversal order. + const auto step_model = reader.Reader().StepModel(); + const auto transfer = reader.Reader().WS()->TransferReader()->TransientProcess(); + for (int entity_index = 1; entity_index <= step_model->NbEntities(); ++entity_index) { + const auto entity = step_model->Value(entity_index); + if (!entity->IsKind(STANDARD_TYPE(StepShape_ManifoldSolidBrep)) && + !entity->IsKind(STANDARD_TYPE(StepShape_ConnectedFaceSet)) && + !entity->IsKind(STANDARD_TYPE(StepShape_ShellBasedSurfaceModel))) + continue; + const auto item = Handle(StepRepr_RepresentationItem)::DownCast(entity); + if (item.IsNull() || item->Name().IsNull() || item->Name()->IsEmpty()) + continue; + const std::string body_name = item->Name()->ToCString(); + if (!StepPreProcessor::isUtf8(body_name)) + continue; + const TopoDS_Shape original_shape = TransferBRep::ShapeResult(transfer, entity); + if (!original_shape.IsNull() && !m_body_names.IsBound(original_shape)) + m_body_names.Bind(original_shape, body_name); + } + } m_shape_tool = XCAFDoc_DocumentTool::ShapeTool(m_doc->Main()); NCollection_Sequence topLevelShapes; m_shape_tool->GetFreeShapes(topLevelShapes); @@ -521,6 +592,11 @@ Step::Step_Status Step::load() if (cb_cancel) return; getNamedSolids(TopLoc_Location{}, "", id, m_shape_tool, topLevelShapes.Value(iLabel), m_name_solids); } + // Without Split compound these leaves stay whole; a multi-body one would lose its body names. + m_multi_body_compound = std::any_of(m_name_solids.begin(), m_name_solids.end(), [](const NamedSolid& leaf) { + const TopAbs_ShapeEnum type = leaf.solid.ShapeType(); + return (type == TopAbs_COMPOUND || type == TopAbs_COMPSOLID) && single_body(leaf.solid).IsNull(); + }); progress = 10; load_result = true; task_result = true; @@ -557,7 +633,8 @@ Step::Step_Status Step::mesh(Model* model, bool& is_cancel, bool isSplitCompound, double linear_deflection/*=0.003*/, - double angle_deflection/*= 0.5*/) + double angle_deflection/*= 0.5*/, + bool keep_original_names/*= false*/) { bool task_result = false; @@ -582,8 +659,12 @@ Step::Step_Status Step::mesh(Model* model, if (cb_cancel) { return; } - getNamedSolids(TopLoc_Location{}, "", id, m_shape_tool, topLevelShapes.Value(iLabel), namedSolids, isSplitCompound); + getNamedSolids(TopLoc_Location{}, "", id, m_shape_tool, topLevelShapes.Value(iLabel), namedSolids, + isSplitCompound, keep_original_names ? &m_body_names : nullptr); } + // A single part is not listed under its object, so the object shows the body label instead. + if (namedSolids.size() == 1 && namedSolids.front().original_name) + new_object->name = namedSolids.front().name; std::vector stl; stl.resize(namedSolids.size()); diff --git a/src/libslic3r/Format/STEP.hpp b/src/libslic3r/Format/STEP.hpp index 5d18f9e88f..422c0ea0cb 100644 --- a/src/libslic3r/Format/STEP.hpp +++ b/src/libslic3r/Format/STEP.hpp @@ -5,6 +5,9 @@ #include "XCAFDoc_ShapeTool.hxx" #include #include +#include +#include +#include #include #include #include @@ -37,10 +40,13 @@ typedef std::function StepIsUtf8Fn; struct NamedSolid { NamedSolid(const TopoDS_Shape& s, - const std::string& n) : solid{ s }, name{ n } { + const std::string& n, + bool original = false) : solid{ s }, name{ n }, original_name{ original } { } const TopoDS_Shape solid; const std::string name; + // The name is the CAD body label rather than a generated or product name. + const bool original_name; int tri_face_cout = 0; }; @@ -106,7 +112,14 @@ public: Step(boost::filesystem::path path, ImportStepProgressFn stepFn = nullptr, StepIsUtf8Fn isUtf8Fn = nullptr); Step(std::string path, ImportStepProgressFn stepFn = nullptr, StepIsUtf8Fn isUtf8Fn = nullptr); ~Step(); - Step_Status load(); + Step_Status load(bool collect_original_names = false); + // The import dialog may change this preference after the CAD document is read. + void set_keep_original_names(bool keep) { m_keep_original_names = keep; } + bool keep_original_names() const { return m_keep_original_names; } + // Valid after load(true): the file stores body labels that Keep original names can apply. + bool has_original_names() const { return !m_body_names.IsEmpty(); } + // Valid after load(): some compound holds several bodies, so their names need Split compound. + bool has_multi_body_compound() const { return m_multi_body_compound; } unsigned int get_triangle_num(double linear_deflection, double angle_deflection); unsigned int get_triangle_num_tbb(double linear_deflection, double angle_deflection); void clean_mesh_data(); @@ -114,7 +127,8 @@ public: bool& is_cancel, bool isSplitCompound, double linear_deflection = 0.003, - double angle_deflection = 0.5); + double angle_deflection = 0.5, + bool keep_original_names = false); std::atomic m_stop_mesh{false}; void update_process(int load_stage, int current, int total, bool& cancel); @@ -126,6 +140,10 @@ private: Handle(TDocStd_Document) m_doc; Handle(XCAFDoc_ShapeTool) m_shape_tool; std::vector m_name_solids; + // Keys retain the exact transferred topology and location, before copied transforms. + NCollection_DataMap m_body_names; + bool m_keep_original_names = false; + bool m_multi_body_compound = false; }; }; // namespace Slic3r diff --git a/src/libslic3r/Format/bbs_3mf.cpp b/src/libslic3r/Format/bbs_3mf.cpp index d00349fb66..4d07e2606e 100644 --- a/src/libslic3r/Format/bbs_3mf.cpp +++ b/src/libslic3r/Format/bbs_3mf.cpp @@ -351,6 +351,7 @@ static constexpr const char* TRANSFORM_ATTR = "transform"; static constexpr const char* OFFSET_ATTR = "offset"; static constexpr const char* PRINTABLE_ATTR = "printable"; static constexpr const char* AUTO_DROP_ATTR = "auto_drop"; +static constexpr const char* IMPORTED_PARTS_HIDDEN_KEY = "orca:imported_parts_hidden"; static constexpr const char* INSTANCESCOUNT_ATTR = "instances_count"; static constexpr const char* CUSTOM_SUPPORTS_ATTR = "paint_supports"; static constexpr const char* CUSTOM_FUZZY_SKIN_ATTR = "paint_fuzzy_skin"; @@ -1167,6 +1168,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) bool m_load_model = false; bool m_load_aux = false; bool m_load_config = false; + bool m_keep_original_names = false; // backup & restore bool m_load_restore = false; std::string m_backup_path; @@ -1492,6 +1494,8 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) m_load_aux = strategy & LoadStrategy::LoadAuxiliary; m_load_restore = strategy & LoadStrategy::Restore; m_load_config = strategy & LoadStrategy::LoadConfig; + // Project part metadata remains authoritative; the opt-in only fills missing CAD labels. + m_keep_original_names = (strategy & LoadStrategy::KeepOriginalNames) && !m_load_config; m_model = &model; m_unit_factor = 1.0f; m_curr_object = nullptr; @@ -2259,6 +2263,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) ObjectMetadata::VolumeMetadataList volumes; ObjectMetadata::VolumeMetadataList* volumes_ptr = nullptr; + bool imported_parts_hidden = false; // 2.4.x stored auto_drop on build items, shared by all instances of an object; any "off" wins const bool legacy_auto_drop = !m_items_auto_drop_off.count(object.first.second); @@ -2273,6 +2278,9 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) for (const Metadata& metadata : obj_metadata->second.metadata) { if (metadata.key == "name") model_object->name = metadata.value; + // This is model presentation state, never a print configuration option. + else if (metadata.key == IMPORTED_PARTS_HIDDEN_KEY) + imported_parts_hidden = metadata.value == "1"; //BBS: add module name else if (metadata.key == "module") model_object->module_name = metadata.value; @@ -2316,6 +2324,8 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) if (!_generate_volumes_new(*model_object, object_id_list, *volumes_ptr, config_substitutions)) return false; + // add_volume reveals edited objects, so restore persisted presentation after creation. + model_object->imported_parts_hidden = imported_parts_hidden; // Apply cut information for object if any was loaded // m_cut_object_ids are indexed by a 1 based model object index. @@ -5476,6 +5486,8 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) } // this may happen for 3mf saved by 3rd part softwares + if (volume->name.empty() && m_keep_original_names) + volume->name = sub_object->name; if (volume->name.empty()) { volume->name = object.name; if (renamed_volumes_count > 0) @@ -8321,6 +8333,9 @@ bool _BBS_3MF_Exporter::_add_model_config_file_to_archive(mz_zip_archive& archiv stream << " <" << METADATA_TAG << " " << KEY_ATTR << "=\"module\" " << VALUE_ATTR << "=\"" << xml_escape(obj->module_name) << "\"/>\n"; // stores object's config data + if (obj->imported_parts_hidden) + stream << " <" << METADATA_TAG << " " << KEY_ATTR << "=\"" << IMPORTED_PARTS_HIDDEN_KEY + << "\" " << VALUE_ATTR << "=\"1\"/>\n"; for (const std::string& key : obj->config.keys()) { stream << " <" << METADATA_TAG << " " << KEY_ATTR << "=\"" << key << "\" " << VALUE_ATTR << "=\"" << obj->config.opt_serialize(key) << "\"/>\n"; } diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index c4cff42a64..6074107d76 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -251,7 +251,9 @@ Model Model::read_from_step(const std::string& bool is_cb_cancel = false; Step::Step_Status status; Step step_file(input_file, stepFn); - status = step_file.load(); + step_file.set_keep_original_names(options & LoadStrategy::KeepOriginalNames); + // A geometry-import dialog can enable names after load, so collect them for that path too. + status = step_file.load(step_file.keep_original_names() || (options & LoadStrategy::AssembleParts)); if(status != Step::Step_Status::LOAD_SUCCESS) { goto _finished; } @@ -262,7 +264,9 @@ Model Model::read_from_step(const std::string& } } - status = step_file.mesh(&model, is_cb_cancel, is_split_compound, linear_deflection, angle_deflection); + // The callback may have changed the name preference after inspecting the CAD document. + status = step_file.mesh(&model, is_cb_cancel, is_split_compound, linear_deflection, angle_deflection, + step_file.keep_original_names()); _finished: @@ -463,7 +467,7 @@ Model Model::read_from_file(const std::string& result = load_drc(input_file.c_str(), &model); else if (boost::algorithm::iends_with(input_file, ".amf")) //BBS: is_xxx is used for is_inches when load amf - result = load_amf(input_file.c_str(), config, config_substitutions, &model, is_xxx); + result = load_amf(input_file.c_str(), config, config_substitutions, &model, is_xxx, options); else if (boost::algorithm::iends_with(input_file, ".3mf")) //BBS: add part plate related logic // BBS: backup & restore @@ -543,7 +547,7 @@ Model Model::read_from_archive(const std::string& input_file, DynamicPrintConfig } } else if (boost::algorithm::iends_with(input_file, ".zip.amf")) - result = load_amf(input_file.c_str(), config, config_substitutions, &model, &is_bbl_3mf); + result = load_amf(input_file.c_str(), config, config_substitutions, &model, &is_bbl_3mf, options); else throw Slic3r::RuntimeError(_L("Unknown file format: input file must have .3mf or .zip.amf extension.")); @@ -904,7 +908,8 @@ bool Model::looks_like_multipart_object() const if (obj->volumes.size() > 1 || obj->config.keys().size() > 1) return false; - double zmin_this = obj->min_z(); + // Objects the file does not place have no instance yet; they read zero, as min_z() did in Release builds. + double zmin_this = obj->instances.empty() ? 0. : obj->min_z(); if (zmin == std::numeric_limits::max()) zmin = zmin_this; else if (std::abs(zmin - zmin_this) > EPSILON) @@ -923,7 +928,7 @@ static inline int auto_extruder_id(unsigned int max_extruders, unsigned int &cnt return out; } -void Model::convert_multipart_object(unsigned int max_extruders) +void Model::convert_multipart_object(unsigned int max_extruders, bool preserve_volume_names) { assert(this->objects.size() >= 2); if (this->objects.size() < 2) @@ -945,9 +950,13 @@ void Model::convert_multipart_object(unsigned int max_extruders) // Revert the centering operation. trafo_volume.set_offset(trafo_volume.get_offset() - o->origin_translation); int counter = 1; - auto copy_volume = [o, v, &counter](ModelVolume *new_v) { + auto copy_volume = [o, v, &counter, preserve_volume_names](ModelVolume *new_v) { assert(new_v != nullptr); - new_v->name = (counter > 1) ? o->name + "_" + std::to_string(counter++) : o->name; + // Existing callers keep their naming; CAD import retains a concrete part name. + if (preserve_volume_names) + new_v->name = v->name.empty() ? o->name : v->name; + else + new_v->name = (counter > 1) ? o->name + "_" + std::to_string(counter++) : o->name; //BBS: Use extruder priority: volumn > object > default if (v->config.option("extruder")) new_v->config.set("extruder", v->config.extruder()); @@ -1285,6 +1294,7 @@ ModelObject& ModelObject::assign_copy(const ModelObject &rhs) this->layer_height_profile = rhs.layer_height_profile; this->printable = rhs.printable; this->auto_drop = rhs.auto_drop; + this->imported_parts_hidden = rhs.imported_parts_hidden; this->origin_translation = rhs.origin_translation; this->cut_id.copy(rhs.cut_id); this->copy_transformation_caches(rhs); @@ -1326,6 +1336,7 @@ ModelObject& ModelObject::assign_copy(ModelObject &&rhs) this->layer_height_profile = std::move(rhs.layer_height_profile); this->printable = std::move(rhs.printable); this->auto_drop = rhs.auto_drop; + this->imported_parts_hidden = rhs.imported_parts_hidden; this->origin_translation = std::move(rhs.origin_translation); this->copy_transformation_caches(rhs); @@ -1388,6 +1399,8 @@ bool ModelObject::make_boolean(ModelObject *cut_object, const std::string &boole ModelVolume *ModelObject::add_volume(const TriangleMesh &mesh, bool modify_to_center_geometry) { + // Newly added parts must remain visible even on a single-object import. + imported_parts_hidden = false; ModelVolume* v = new ModelVolume(this, mesh); this->volumes.push_back(v); if (modify_to_center_geometry) { @@ -1401,6 +1414,7 @@ ModelVolume *ModelObject::add_volume(const TriangleMesh &mesh, bool modify_to_ce ModelVolume *ModelObject::add_volume(TriangleMesh &&mesh, ModelVolumeType type /*= ModelVolumeType::MODEL_PART*/, bool modify_to_center_geometry) { + imported_parts_hidden = false; ModelVolume* v = new ModelVolume(this, std::move(mesh), type); this->volumes.push_back(v); if (modify_to_center_geometry) { @@ -1414,6 +1428,7 @@ ModelVolume *ModelObject::add_volume(TriangleMesh &&mesh, ModelVolumeType type / ModelVolume* ModelObject::add_volume(const ModelVolume &other, ModelVolumeType type /*= ModelVolumeType::INVALID*/) { + imported_parts_hidden = false; ModelVolume* v = new ModelVolume(this, other); if (type != ModelVolumeType::INVALID && v->type() != type) v->set_type(type); @@ -1431,6 +1446,7 @@ ModelVolume* ModelObject::add_volume(const ModelVolume &other, ModelVolumeType t ModelVolume* ModelObject::add_volume(const ModelVolume &other, TriangleMesh &&mesh) { + imported_parts_hidden = false; ModelVolume* v = new ModelVolume(this, other, std::move(mesh)); this->volumes.push_back(v); v->center_geometry_after_creation(); @@ -1442,6 +1458,7 @@ ModelVolume* ModelObject::add_volume(const ModelVolume &other, TriangleMesh &&me ModelVolume* ModelObject::add_volume_with_shared_mesh(const ModelVolume &other, ModelVolumeType type /*= ModelVolumeType::INVALID*/) { + imported_parts_hidden = false; ModelVolume* v = new ModelVolume(this, other.m_mesh); if (type != ModelVolumeType::INVALID && v->type() != type) v->set_type(type); @@ -1511,6 +1528,27 @@ bool ModelObject::is_fuzzy_skin_painted() const return std::any_of(this->volumes.cbegin(), this->volumes.cend(), [](const ModelVolume *mv) { return mv->is_fuzzy_skin_painted(); }); } +bool ModelObject::has_individual_part_settings() const +{ + // Copying objects gives them filament 1, and merging copies it to their parts. + const int object_extruder = this->config.has("extruder") && this->config.extruder() > 0 ? this->config.extruder() : 1; + const bool part_settings = std::any_of(this->volumes.cbegin(), this->volumes.cend(), [object_extruder](const ModelVolume *mv) { + if (!mv->is_model_part() || !mv->texture_displacement_layers.empty()) + return true; + const size_t keys = mv->config.size(); + const bool same_filament = keys == 1 && mv->config.has("extruder") && + (mv->config.extruder() == 0 || mv->config.extruder() == object_extruder); + return keys > 0 && !same_filament; + }); + return part_settings || this->is_fdm_support_painted() || this->is_seam_painted() || this->is_mm_painted() || + this->is_fuzzy_skin_painted(); +} + +bool ModelObject::hides_imported_parts() const +{ + return this->imported_parts_hidden && this->volumes.size() > 1 && !this->has_individual_part_settings(); +} + void ModelObject::sort_volumes(bool full_sort) { // sort volumes inside the object to order "Model Part, Negative Volume, Modifier, Support Blocker and Support Enforcer. " diff --git a/src/libslic3r/Model.hpp b/src/libslic3r/Model.hpp index 6d9797ff67..5f56f981a9 100644 --- a/src/libslic3r/Model.hpp +++ b/src/libslic3r/Model.hpp @@ -403,6 +403,9 @@ public: // Whether this object is snapped to the build plate after transformations. // Instance Z offsets are shared by all instances of an object. bool auto_drop { true }; + // Single-object import keeps named bodies internally until the user reveals its parts. + // A stored choice: part settings or painting still show the parts, see hides_imported_parts(). + bool imported_parts_hidden { false }; // This vector holds position of selected support points for SLA. The data are // saved in mesh coordinates to allow using them for several instances. @@ -458,6 +461,11 @@ public: bool is_mm_painted() const; // Checks if any of object volume is painted using the fuzzy skin painting gizmo. bool is_fuzzy_skin_painted() const; + // Whether a part has settings or painting of its own; a part that only repeats the object's filament has none. + bool has_individual_part_settings() const; + // Whether the object list shows a single-object import without its parts. Never true while + // a part has its own settings or painting, so effective per-part controls stay visible. + bool hides_imported_parts() const; // This object may have a varying layer height by painting or by a table. // Even if true is returned, the layer height profile may be "flat" with no difference to default layering. bool has_custom_layering() const @@ -709,7 +717,7 @@ private: Internal::StaticSerializationWrapper config_wrapper(config); Internal::StaticSerializationWrapper layer_heigth_profile_wrapper(layer_height_profile); ar(name, module_name, input_file, instances, volumes, config_wrapper, layer_config_ranges, layer_heigth_profile_wrapper, - sla_support_points, sla_points_status, sla_drain_holes, printable, auto_drop, origin_translation, brim_points, + sla_support_points, sla_points_status, sla_drain_holes, printable, auto_drop, imported_parts_hidden, origin_translation, brim_points, m_bounding_box_approx, m_bounding_box_approx_valid, m_bounding_box_exact, m_bounding_box_exact_valid, m_min_max_z_valid, m_raw_bounding_box, m_raw_bounding_box_valid, m_raw_mesh_bounding_box, m_raw_mesh_bounding_box_valid, @@ -722,7 +730,7 @@ private: // BBS: add backup, check modify SaveObjectGaurd gaurd(*this); ar(name, module_name, input_file, instances, volumes, config_wrapper, layer_config_ranges, layer_heigth_profile_wrapper, - sla_support_points, sla_points_status, sla_drain_holes, printable, auto_drop, origin_translation, brim_points, + sla_support_points, sla_points_status, sla_drain_holes, printable, auto_drop, imported_parts_hidden, origin_translation, brim_points, m_bounding_box_approx, m_bounding_box_approx_valid, m_bounding_box_exact, m_bounding_box_exact_valid, m_min_max_z_valid, m_raw_bounding_box, m_raw_bounding_box_valid, m_raw_mesh_bounding_box, m_raw_mesh_bounding_box_valid, @@ -832,6 +840,8 @@ class ModelVolume final : public ObjectBase { public: std::string name; + // Session-only tree position; snapshots preserve it without changing project file order. + int import_display_order { -1 }; // struct used by reload from disk command to recover data from disk struct Source { @@ -1253,7 +1263,7 @@ private: // Copying an existing volume, therefore this volume will get a copy of the ID assigned. ModelVolume(ModelObject *object, const ModelVolume &other) : ObjectBase(other), - name(other.name), source(other.source), m_mesh(other.m_mesh), m_convex_hull(other.m_convex_hull), + name(other.name), import_display_order(other.import_display_order), source(other.source), m_mesh(other.m_mesh), m_convex_hull(other.m_convex_hull), config(other.config), m_type(other.m_type), object(object), m_transformation(other.m_transformation), supported_facets(other.supported_facets), seam_facets(other.seam_facets), mmu_segmentation_facets(other.mmu_segmentation_facets), fuzzy_skin_facets(other.fuzzy_skin_facets), @@ -1286,7 +1296,7 @@ private: } // Providing a new mesh, therefore this volume will get a new unique ID assigned. ModelVolume(ModelObject *object, const ModelVolume &other, TriangleMesh &&mesh) : - name(other.name), source(other.source), config(other.config), object(object), m_mesh(new TriangleMesh(std::move(mesh))), m_type(other.m_type), m_transformation(other.m_transformation), + name(other.name), import_display_order(other.import_display_order), source(other.source), config(other.config), object(object), m_mesh(new TriangleMesh(std::move(mesh))), m_type(other.m_type), m_transformation(other.m_transformation), cut_info(other.cut_info), text_configuration(other.text_configuration), emboss_shape(other.emboss_shape) { assert(this->id().valid()); @@ -1343,7 +1353,7 @@ private: // BBS: add backup, check modify bool mesh_changed = false; auto tr = m_transformation; - ar(name, source, m_mesh, m_type, m_material_id, m_transformation, m_is_splittable, has_convex_hull, cut_info); + ar(name, import_display_order, source, m_mesh, m_type, m_material_id, m_transformation, m_is_splittable, has_convex_hull, cut_info); mesh_changed |= !(tr == m_transformation); auto t = supported_facets.timestamp(); cereal::load_by_value(ar, supported_facets); @@ -1379,7 +1389,7 @@ private: } template void save(Archive &ar) const { bool has_convex_hull = m_convex_hull.get() != nullptr; - ar(name, source, m_mesh, m_type, m_material_id, m_transformation, m_is_splittable, has_convex_hull, cut_info); + ar(name, import_display_order, source, m_mesh, m_type, m_material_id, m_transformation, m_is_splittable, has_convex_hull, cut_info); cereal::save_by_value(ar, supported_facets); cereal::save_by_value(ar, seam_facets); cereal::save_by_value(ar, mmu_segmentation_facets); @@ -1845,7 +1855,7 @@ public: void duplicate_objects_grid(size_t x, size_t y, coordf_t dist); bool looks_like_multipart_object() const; - void convert_multipart_object(unsigned int max_extruders); + void convert_multipart_object(unsigned int max_extruders, bool preserve_volume_names = false); bool looks_like_imperial_units() const; void convert_from_imperial_units(bool only_small_volumes); bool looks_like_saved_in_meters() const; diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 41cb56646a..3b4962eec5 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -547,6 +547,8 @@ set(SLIC3R_GUI_SOURCES GUI/StatusPanel.hpp GUI/StepMeshDialog.cpp GUI/StepMeshDialog.hpp + GUI/GeometryImportDialog.cpp + GUI/GeometryImportDialog.hpp GUI/SurfaceDrag.cpp GUI/SurfaceDrag.hpp GUI/Tabbook.cpp diff --git a/src/slic3r/GUI/GUI_ObjectList.cpp b/src/slic3r/GUI/GUI_ObjectList.cpp index 20b0047689..58718073c4 100644 --- a/src/slic3r/GUI/GUI_ObjectList.cpp +++ b/src/slic3r/GUI/GUI_ObjectList.cpp @@ -2126,6 +2126,34 @@ void ObjectList::OnDrop(wxDataViewEvent &event) return; } + // Move in the displayed order too, keeping presentation independent of slicing precedence. + const bool imported_order = std::any_of(volumes.begin(), volumes.end(), [](const ModelVolume* volume) { + return volume->import_display_order >= 0; + }); + ModelVolume* dragged_volume = volumes[visible_volume_indices[size_t(from_volume_id)]]; + if (imported_order) { + // The rebuild below deletes the rows, so a name editor still open on one of them must not write back. + if (wxDataViewRenderer* renderer = GetColumn(colName)->GetRenderer(); renderer->GetEditorCtrl()) + renderer->CancelEditing(); + wxDataViewItemArray children; + m_objects_model->GetChildren(m_objects_model->GetParent(item), children); + std::vector displayed; + for (const auto& child : children) { + const int index = m_objects_model->GetVolumeIdByItem(child); + if (index >= 0 && size_t(index) < visible_volume_indices.size()) + displayed.push_back(volumes[visible_volume_indices[size_t(index)]]); + } + ModelVolume* target_volume = volumes[visible_volume_indices[size_t(to_volume_id)]]; + const auto from = std::find(displayed.begin(), displayed.end(), dragged_volume); + const auto to = std::find(displayed.begin(), displayed.end(), target_volume); + if (from != displayed.end() && to != displayed.end()) { + const auto target_position = to - displayed.begin(); + displayed.erase(from); + displayed.insert(displayed.begin() + target_position, dragged_volume); + for (size_t i = 0; i < displayed.size(); ++i) + displayed[i]->import_display_order = static_cast(i); + } + } // Move through visible slots only, keeping hidden cut connectors at their original indices. // The local mapping stays valid because no hidden volume changes slots during the move. for (int id = from_volume_id; id != to_volume_id; id += delta) { @@ -2140,7 +2168,15 @@ void ObjectList::OnDrop(wxDataViewEvent &event) for (size_t idx = 0; idx < visible_volume_indices.size(); ++idx) ui_to_model[int(idx)] = int(visible_volume_indices[idx]); - select_item(m_objects_model->ReorganizeChildren(from_volume_id, to_volume_id, m_objects_model->GetParent(item))); + if (imported_order) { + // Rebuild re-reads presentation ranks; native ReorganizeChildren assumes model order. + const auto selected = add_volumes_to_object_in_list(size_t(obj_idx), [dragged_volume](const ModelVolume* volume) { + return volume == dragged_volume; + }); + if (!selected.empty()) + select_item(selected.front()); + } else + select_item(m_objects_model->ReorganizeChildren(from_volume_id, to_volume_id, m_objects_model->GetParent(item))); changed_object(m_dragged_data.obj_idx()); } @@ -3083,6 +3119,16 @@ void ObjectList::split() if (!item || obj_idx < 0) return; + ModelObject* imported = (*m_objects)[obj_idx]; + if (imported->hides_imported_parts()) { + // Reveal the original CAD bodies, including their names and exact transforms. + take_snapshot(_u8L("Split to parts")); + imported->imported_parts_hidden = false; + add_volumes_to_object_in_list(size_t(obj_idx)); + changed_object(obj_idx); + return; + } + ModelVolume* volume; if (!get_volume_by_item(item, volume)) return; DynamicPrintConfig& config = printer_config(); @@ -3619,6 +3665,13 @@ bool ObjectList::is_splittable(bool to_objects) const wxDataViewItem item = GetSelection(); if (!item) return false; + const int selected_object = get_selected_obj_idx(); + if (!to_objects && selected_object >= 0) { + const ModelObject* object = (*m_objects)[size_t(selected_object)]; + if (object->hides_imported_parts()) + return true; + } + if (to_objects) { ItemType type = m_objects_model->GetItemType(item); @@ -4123,6 +4176,8 @@ void ObjectList::update_variable_layer_obj_num(ObjectDataViewModelNode* obj_node } } +static bool can_add_volumes_to_object(const ModelObject *object); + void ObjectList::update_info_items(size_t obj_idx, wxDataViewItemArray *selections /* = nullptr*/, bool added_object /* = false*/, bool color_mode_changed /* = false*/) { // BBS @@ -4133,6 +4188,35 @@ void ObjectList::update_info_items(size_t obj_idx, wxDataViewItemArray *selectio wxDataViewItem item_obj = m_objects_model->GetItemById(obj_idx); assert(item_obj.IsOk()); + // Painting decides whether a single-object import shows its parts; the painting gizmos call this after each change. + if (model_object->imported_parts_hidden) { + wxDataViewItemArray children; + m_objects_model->GetChildren(item_obj, children); + bool shows_parts = false; + for (const wxDataViewItem& child : children) + shows_parts = shows_parts || m_objects_model->GetItemType(child) == itVolume; + if (shows_parts != can_add_volumes_to_object(model_object)) { + // A tracked selection must not keep rows of the parts that are about to go. + if (selections != nullptr && shows_parts) { + auto in_removed_parts = [this, &item_obj](const wxDataViewItem& item) { + const wxDataViewItem parent = m_objects_model->GetParent(item); + if (m_objects_model->GetItemType(item) == itVolume) + return parent == item_obj; + return parent.IsOk() && m_objects_model->GetItemType(parent) == itVolume && m_objects_model->GetParent(parent) == item_obj; + }; + bool removed = false; + for (int index = int(selections->GetCount()) - 1; index >= 0; --index) + if (in_removed_parts((*selections)[index])) { + selections->RemoveAt(index); + removed = true; + } + if (removed && selections->Index(item_obj) == wxNOT_FOUND) + selections->Add(item_obj); + } + add_volumes_to_object_in_list(obj_idx); + } + } + // Cut connectors { wxDataViewItem item = m_objects_model->GetInfoItemByType(item_obj, InfoItemType::CutConnectors); @@ -4365,6 +4449,9 @@ void ObjectList::add_object_to_list(size_t obj_idx, bool call_selection_changed, static bool can_add_volumes_to_object(const ModelObject *object) { + // Single-object imports retain their bodies internally until the user chooses Split to parts. + if (object->hides_imported_parts()) + return false; bool can = object->volumes.size() > 1; if (can && object->is_cut()) { @@ -4391,7 +4478,7 @@ wxDataViewItemArray ObjectList::add_volumes_to_object_in_list(size_t obj_idx, st wxDataViewItemArray items; - const ModelObject *object = (*m_objects)[obj_idx]; + ModelObject *object = (*m_objects)[obj_idx]; // add volumes to the object if (can_add_volumes_to_object(object)) { if (object->volumes.size() > 1) { @@ -7076,6 +7163,19 @@ void sort_objects(std::vector& objects, ObjectOrder order, bool de objects[i] = entries[i].object; } +void set_import_volume_order(ModelObject& object, bool sort_names) +{ + // Capture after the final clone and before the model's required type grouping. + auto parts = object.volumes; + if (sort_names) + std::stable_sort(parts.begin(), parts.end(), [](const ModelVolume* a, const ModelVolume* b) { + return wxCmpNatural(from_u8(a->name).Lower(), from_u8(b->name).Lower()) < 0; + }); + // The rank travels with the volume through cloning and Undo/Redo, without changing slicing order. + for (size_t i = 0; i < parts.size(); ++i) + parts[i]->import_display_order = static_cast(i); +} + void ObjectList::order_objects(ObjectOrder order, bool all_plates) { Plater* plater = wxGetApp().plater(); diff --git a/src/slic3r/GUI/GUI_ObjectList.hpp b/src/slic3r/GUI/GUI_ObjectList.hpp index 36446b4af1..32657721b9 100644 --- a/src/slic3r/GUI/GUI_ObjectList.hpp +++ b/src/slic3r/GUI/GUI_ObjectList.hpp @@ -63,6 +63,9 @@ enum class ObjectOrder { Name, Filament, Height, Size }; // Stable sort by natural name order, filament, top Z, or bounding box volume of the first instance. void sort_objects(std::vector& objects, ObjectOrder order, bool descending = false); +// Set import-only presentation ranks without changing part order used by slicing. +void set_import_volume_order(ModelObject& object, bool sort_names); + class PartPlate; wxDECLARE_EVENT(EVT_OBJ_LIST_OBJECT_SELECT, SimpleEvent); diff --git a/src/slic3r/GUI/GeometryImportDialog.cpp b/src/slic3r/GUI/GeometryImportDialog.cpp new file mode 100644 index 0000000000..0f276e7028 --- /dev/null +++ b/src/slic3r/GUI/GeometryImportDialog.cpp @@ -0,0 +1,461 @@ +#include "GeometryImportDialog.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "GUI.hpp" +#include "GUI_App.hpp" +#include "GUI_Utils.hpp" +#include "I18N.hpp" +#include "MsgDialog.hpp" +#include "slic3r/GUI/format.hpp" +#include "Widgets/Button.hpp" +#include "Widgets/CheckBox.hpp" +#include "Widgets/DialogButtons.hpp" +#include "Widgets/Label.hpp" +#include "Widgets/RadioGroup.hpp" +#include "Widgets/RoundedRectangle.hpp" +#include "Widgets/StateColor.hpp" +#include "Widgets/TextInput.hpp" +#include "libslic3r/AppConfig.hpp" +#include "libslic3r/Format/ImportNames.hpp" +#include "libslic3r/LocalesUtils.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/miniz_extension.hpp" +#include "libslic3r/Utils.hpp" + +namespace Slic3r::GUI { +namespace { + +class ImportDialog final : public DPIDialog { +public: + using DPIDialog::DPIDialog; + +protected: + void on_dpi_changed(const wxRect&) override { + // Respect the controls' new minimum size when moved between DPI settings. + if (GetSizer() != nullptr) + GetSizer()->SetSizeHints(this); + Layout(); + } +}; + +std::string option_key(const std::string& format, const char* suffix) +{ + return "import_names_" + format + "_" + suffix; +} + +bool config_bool(const AppConfig& config, const std::string& key, bool fallback) +{ + // Existing user configurations predate these keys. + return config.has(key) ? config.get_bool(key) : fallback; +} + +// Same font and label color as the check boxes of the STEP import dialog. +void apply_label_style(wxWindow* control) +{ + control->SetFont(::Label::Body_14); + control->SetForegroundColour(StateColor::darkModeColorFor(wxColour("#363636"))); +} + +// White dialog with the explanation in a grey rounded box, as in the STEP import dialog. +void add_tip(DPIDialog& dialog, wxBoxSizer& sizer, const wxString& text, int wrap_width) +{ + dialog.SetBackgroundColour(*wxWHITE); + const wxColour tip_colour = StateColor::darkModeColorFor(wxColour("#F1F1F1")); + auto* frame = new RoundedRectangle(&dialog, tip_colour, wxDefaultPosition, wxSize(-1, -1), 6, 0); + auto* tip_sizer = new wxBoxSizer(wxHORIZONTAL); + auto* info = new wxStaticText(frame, wxID_ANY, text); + apply_label_style(info); + info->SetBackgroundColour(tip_colour); + info->Wrap(dialog.FromDIP(wrap_width)); + tip_sizer->Add(info, 0, wxEXPAND | wxALL, dialog.FromDIP(10)); + frame->SetSizer(tip_sizer); + frame->Layout(); + sizer.Add(frame, 0, wxEXPAND | wxLEFT | wxRIGHT | wxTOP, dialog.FromDIP(12)); +} + +ImportCheckBox add_checkbox(DPIDialog& dialog, wxBoxSizer& sizer, const wxString& label, bool value) +{ + return add_import_checkbox(&dialog, sizer, label, value, wxLEFT | wxRIGHT | wxTOP, dialog.FromDIP(12)); +} + +// The radio group takes the dialog background at creation, so add it after add_tip. +RadioGroup* add_radio_group(DPIDialog& dialog, const std::vector& labels, int selection, long direction) +{ + auto* group = new RadioGroup(&dialog, labels, direction); + group->SetSelection(selection); + return group; +} + +using NameGroup = std::vector; + +// Each group has its own collision scope: object siblings or parts of one object. +std::vector name_groups(const std::vector& models) +{ + std::vector groups; + for (Model* model : models) { + NameGroup objects; + for (ModelObject* object : model->objects) { + objects.push_back(&object->name); + NameGroup parts; + for (ModelVolume* volume : object->volumes) + parts.push_back(&volume->name); + groups.push_back(std::move(parts)); + } + groups.push_back(std::move(objects)); + } + return groups; +} + +std::vector> cleaned_groups(const std::vector& groups, const std::string& replacement) +{ + std::vector> results; + results.reserve(groups.size()); + for (const NameGroup& group : groups) { + std::vector names; + names.reserve(group.size()); + for (const std::string* name : group) + names.push_back(*name); + results.push_back(sanitize_import_names(names, replacement)); + } + return results; +} + +} // namespace + +std::string geometry_import_format(const std::string& path) +{ + if (boost::algorithm::iends_with(path, ".step") || boost::algorithm::iends_with(path, ".stp")) + return "step"; + if (boost::algorithm::iends_with(path, ".amf")) + return "amf"; + if (boost::algorithm::iends_with(path, ".3mf")) + return "3mf"; + return {}; +} + +GeometryImportOptions geometry_import_options(const AppConfig& config, const std::string& format) +{ + GeometryImportOptions options; + options.keep_names = config_bool(config, option_key(format, "keep"), true); + options.sort_names = config_bool(config, option_key(format, "sort"), false); + // A 3MF keeps the structure written in it, so it has no presentation choice. + options.load_as_assembly = format == "3mf" || config_bool(config, option_key(format, "assembly"), true); + // Files from other slicers keep a whole plate in one AMF group, so assembling it is opt-in. + options.separate_objects = format == "amf" && config_bool(config, option_key(format, "separate"), true); + // The same key drives Preferences, Replace and Reload, so all STEP paths split alike. + options.split_compound = format == "step" && config_bool(config, "is_split_compound", true); + options.show_dialog = config_bool(config, format == "step" ? "enable_step_mesh_setting" : option_key(format, "show_dialog"), true); + // Read the same quality defaults as the existing STEP import dialog. + options.linear_deflection = string_to_double_decimal_point(config.get("linear_deflection")); + options.angle_deflection = string_to_double_decimal_point(config.get("angle_deflection")); + if (!std::isfinite(options.linear_deflection) || options.linear_deflection < 0.001 || options.linear_deflection > 0.1) + options.linear_deflection = 0.003; + if (!std::isfinite(options.angle_deflection) || options.angle_deflection < 0.01 || options.angle_deflection > 1.0) + options.angle_deflection = 0.5; + return options; +} + +bool is_geometry_only_3mf(const std::string& path) +{ + if (!boost::algorithm::iends_with(path, ".3mf")) + return false; + mz_zip_archive archive; + mz_zip_zero_struct(&archive); + if (!open_zip_reader(&archive, path)) + return false; // Let the normal reader report unreadable or malformed archives. + ScopeGuard close_archive([&archive]() { close_zip_reader(&archive); }); + + // Minimal published Orca projects also retain model_settings.config. + const char* project_markers[] = { + "Metadata/model_settings.config", "Metadata/project_settings.config", "Metadata/print_profile.config", + "Metadata/slice_info.config", "Metadata/Slic3r_PE.config", "Metadata/Slic3r_PE_model.config", + "Metadata/Prusa_Slicer_layer_config_ranges.xml", "Metadata/Slic3r_PE_layer_heights_profile.txt", + "Metadata/Slic3r_PE_sla_support_points.txt", "Metadata/Slic3r_PE_sla_drain_holes.txt" + }; + bool has_model = false; + for (mz_uint index = 0; index < mz_zip_reader_get_num_files(&archive); ++index) { + mz_zip_archive_file_stat stat; + if (!mz_zip_reader_file_stat(&archive, index, &stat)) + return false; + std::string name = stat.m_filename; + std::replace(name.begin(), name.end(), '\\', '/'); + while (boost::algorithm::starts_with(name, "./")) + name.erase(0, 2); + for (const char* marker : project_markers) + if (boost::algorithm::iequals(name, marker)) + return false; + has_model = has_model || (boost::algorithm::istarts_with(name, "3D/") && boost::algorithm::iends_with(name, ".model")); + } + return has_model; +} + +GeometryImportNamePolicy geometry_import_name_policy(const AppConfig& config) +{ + GeometryImportNamePolicy policy; + policy.show_dialog = config_bool(config, "import_names_cleanup_show_dialog", true); + policy.remove = config_bool(config, "import_names_cleanup_remove", false); + if (config.has("import_names_cleanup_replacement")) + policy.replacement = config.get("import_names_cleanup_replacement"); + return policy; +} + +bool ImportCheckBox::GetValue() const { return box->GetValue(); } + +void ImportCheckBox::SetValue(bool value) const { box->SetValue(value); } + +void ImportCheckBox::Enable(bool enable) const +{ + box->Enable(enable); + label->Enable(enable); + // Same disabled text color as RadioGroup. + label->SetForegroundColour(enable ? StateColor::darkModeColorFor(wxColour("#363636")) : wxColour("#6B6A6A")); + label->Refresh(); +} + +void ImportCheckBox::SetToolTip(const wxString& tip) const +{ + box->SetToolTip(tip); + label->SetToolTip(tip); +} + +ImportCheckBox add_import_checkbox(wxWindow* parent, wxSizer& sizer, const wxString& text, bool value, int flags, int border) +{ + ImportCheckBox checkbox{new ::CheckBox(parent), new wxStaticText(parent, wxID_ANY, text)}; + apply_label_style(checkbox.label); + checkbox.box->SetValue(value); + ::CheckBox* box = checkbox.box; + auto toggle = [box]() { + if (!box->IsEnabled()) + return; + box->SetValue(!box->GetValue()); + wxCommandEvent event(wxEVT_TOGGLEBUTTON, box->GetId()); + event.SetEventObject(box); + box->GetEventHandler()->ProcessEvent(event); + }; + // A double click arrives as one down and one double-click event, so each toggles once. + checkbox.label->Bind(wxEVT_LEFT_DOWN, [toggle](wxMouseEvent&) { toggle(); }); + checkbox.label->Bind(wxEVT_LEFT_DCLICK, [toggle](wxMouseEvent&) { toggle(); }); + auto* row = new wxBoxSizer(wxHORIZONTAL); + row->Add(checkbox.box, 0, wxALIGN_CENTER_VERTICAL); + row->Add(checkbox.label, 0, wxALIGN_CENTER_VERTICAL | wxLEFT, parent->FromDIP(5)); + sizer.Add(row, 0, flags, border); + return checkbox; +} + +// Sorting only makes sense for original names; while Keep is off it is disabled but keeps its remembered value. +void link_sort_to_keep(const ImportCheckBox& keep, const ImportCheckBox& sort) +{ + sort.Enable(keep.GetValue()); + keep.box->Bind(wxEVT_TOGGLEBUTTON, [keep, sort](wxCommandEvent& event) { + sort.Enable(keep.GetValue()); + event.Skip(); + }); +} + +bool show_geometry_import_options(wxWindow* parent, const std::string& format, GeometryImportOptions& options) +{ + if (options.chosen) + return true; + options.chosen = true; + if (!options.show_dialog) + return true; + + // One choice per format applies to all of its files in this import operation. + ImportDialog dialog(parent, wxID_ANY, format == "3mf" ? _L("3MF geometry import options") : _L("AMF geometry import options"), wxDefaultPosition, wxDefaultSize, + wxDEFAULT_DIALOG_STYLE); + auto* sizer = new wxBoxSizer(wxVERTICAL); + // A 3MF keeps its own structure, so only the naming choices remain for it. + add_tip(dialog, *sizer, format == "3mf" ? _L("Choose how to name and order the parts of this file.") : + _L("Choose how to load the bodies in this file."), 430); + + // Item 0 loads separate objects, item 1 an assembly, item 2 a single object. + RadioGroup* load_mode = nullptr; + if (format != "3mf") { + load_mode = add_radio_group(dialog, {_L("Load as separate objects"), _L("Load as an assembly"), _L("Load as a single object (can be split later)")}, + options.separate_objects ? 0 : options.load_as_assembly ? 1 : 2, wxVERTICAL); + load_mode->SetRadioTooltip(0, _L("Each object in the file is loaded on its own, as OrcaSlicer always loaded AMF files.")); + load_mode->SetRadioTooltip(1, _L("The bodies of each group in the file become parts of one object, in their relative positions.")); + load_mode->SetRadioTooltip(2, _L("The original bodies and names are kept inside the object. Use Split to parts to show them as separate parts.")); + sizer->Add(load_mode, 0, wxLEFT | wxRIGHT | wxTOP, dialog.FromDIP(12)); + } + const auto keep = add_checkbox(dialog, *sizer, _L("Keep original names"), options.keep_names); + keep.SetToolTip(_L("Use the body names stored in the file, when there are any. When disabled, the usual OrcaSlicer names are used; existing project names are kept.")); + const auto sort = add_checkbox(dialog, *sizer, _L("Sort parts by name"), options.sort_names); + sort.SetToolTip(_L("Sort the parts inside each imported assembly in the object list. This does not change the order used for slicing. Available when Keep original names is on.")); + link_sort_to_keep(keep, sort); + const auto remember = add_checkbox(dialog, *sizer, _L("Remember my choice"), false); + remember.SetToolTip(_L("Use these choices as defaults next time. The dialog still opens.")); + const auto dont_ask = add_checkbox(dialog, *sizer, _L("Don't ask again"), false); + dont_ask.SetToolTip(_L("Save these choices and apply them without asking next time. You can show this dialog again in Preferences.")); + + auto* buttons = new DialogButtons(&dialog, {"OK", "Cancel"}); + buttons->GetOK()->Bind(wxEVT_BUTTON, [&](wxCommandEvent&) { dialog.EndModal(wxID_OK); }); + buttons->GetCANCEL()->Bind(wxEVT_BUTTON, [&](wxCommandEvent&) { dialog.EndModal(wxID_CANCEL); }); + sizer->Add(buttons, 0, wxEXPAND | wxALL, dialog.FromDIP(12)); + dialog.SetSizerAndFit(sizer); + // DPIDialog centres itself before the sizer sets the final size. + dialog.CenterOnParent(); + wxGetApp().UpdateDlgDarkUI(&dialog); + if (dialog.ShowModal() != wxID_OK) + return false; + + options.keep_names = keep.GetValue(); + options.sort_names = sort.GetValue(); + if (load_mode != nullptr) { + options.separate_objects = load_mode->GetSelection() == 0; + // Separate objects leave the remembered assembly choice as it was. + if (!options.separate_objects) + options.load_as_assembly = load_mode->GetSelection() == 1; + } + options.remember = remember.GetValue(); + options.dont_ask = dont_ask.GetValue(); + return true; +} + +bool prepare_geometry_import_names(wxWindow* parent, const std::vector& models, GeometryImportNamePolicy& policy) +{ + const std::vector groups = name_groups(models); + bool needs_cleanup = false; + try { + for (const NameGroup& group : groups) + for (const std::string* name : group) + needs_cleanup = has_unsupported_name_characters(*name) || needs_cleanup; + } catch (const std::invalid_argument&) { + MessageDialog(parent, _L("A name in the file is not valid Unicode. The geometry was not imported."), + _L("Invalid name"), wxOK | wxICON_ERROR).ShowModal(); + return false; + } + if (!needs_cleanup) + return true; + policy.used = true; + + // A damaged saved replacement must not silently create more invalid names. + if (!policy.remove && !valid_import_name_replacement(policy.replacement)) { + policy.replacement = "_"; + policy.show_dialog = true; + } + + if (policy.show_dialog) { + ImportDialog dialog(parent, wxID_ANY, _L("Unsupported characters in names"), wxDefaultPosition, wxDefaultSize, + wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER); + auto* sizer = new wxBoxSizer(wxVERTICAL); + add_tip(dialog, *sizer, _L("Some original names contain characters that OrcaSlicer cannot use. Choose how to change them before importing."), 520); + // Item 0 removes the characters, item 1 replaces them with the text right after it. + auto* rule = add_radio_group(dialog, {_L("Remove unsupported characters"), _L("Replace with:")}, policy.remove ? 0 : 1, wxHORIZONTAL); + rule->SetRadioTooltip(1, _L("Each unsupported character is replaced with this text. It may be longer than one character.")); + auto* replacement_row = new wxBoxSizer(wxHORIZONTAL); + replacement_row->Add(rule, 0, wxALIGN_CENTER_VERTICAL); + auto* replacement = new ::TextInput(&dialog, from_u8(policy.replacement)); + replacement->GetTextCtrl()->SetFont(::Label::Body_14); + replacement_row->Add(replacement, 1, wxALIGN_CENTER_VERTICAL); + sizer->Add(replacement_row, 0, wxEXPAND | wxLEFT | wxRIGHT | wxTOP, dialog.FromDIP(12)); + auto* preview = new wxTextCtrl(&dialog, wxID_ANY, wxEmptyString, wxDefaultPosition, dialog.FromDIP(wxSize(540, 180)), + wxTE_MULTILINE | wxTE_READONLY | wxTE_DONTWRAP); + apply_label_style(preview); + sizer->Add(preview, 1, wxEXPAND | wxALL, dialog.FromDIP(12)); + const auto remember = add_checkbox(dialog, *sizer, _L("Remember my choice"), false); + remember.SetToolTip(_L("Use this rule as the default next time. The dialog still opens.")); + const auto dont_ask = add_checkbox(dialog, *sizer, _L("Don't ask again"), false); + dont_ask.SetToolTip(_L("Save this rule and apply it without asking next time. You can show this dialog again in Preferences.")); + auto* buttons = new DialogButtons(&dialog, {"OK", "Cancel"}); + + auto update_preview = [&]() { + const bool remove = rule->GetSelection() == 0; + replacement->Enable(!remove); + const std::string text = into_u8(replacement->GetTextCtrl()->GetValue()); + const bool valid = remove || valid_import_name_replacement(text); + buttons->GetOK()->Enable(valid); + if (!valid) { + preview->ChangeValue(_L("Enter a non-empty replacement containing only supported characters, or choose removal.")); + return; + } + const auto results = cleaned_groups(groups, remove ? std::string() : text); + wxString lines; + for (size_t group = 0; group < groups.size(); ++group) + for (size_t index = 0; index < groups[group].size(); ++index) + if (*groups[group][index] != results[group][index]) { + // TRN The placeholders are the original name and its imported replacement. + lines += format_wxstr(_L("%1% → %2%"), from_u8(*groups[group][index]), from_u8(results[group][index])) + "\n"; + } + preview->ChangeValue(lines); + }; + rule->Bind(wxEVT_COMMAND_RADIOBOX_SELECTED, [&](wxCommandEvent&) { update_preview(); }); + replacement->Bind(wxEVT_TEXT, [&](wxCommandEvent&) { update_preview(); }); + buttons->GetOK()->Bind(wxEVT_BUTTON, [&](wxCommandEvent&) { dialog.EndModal(wxID_OK); }); + buttons->GetCANCEL()->Bind(wxEVT_BUTTON, [&](wxCommandEvent&) { dialog.EndModal(wxID_CANCEL); }); + sizer->Add(buttons, 0, wxEXPAND | wxALL, dialog.FromDIP(12)); + dialog.SetSizerAndFit(sizer); + // DPIDialog centres itself before the sizer sets the final size. + dialog.CenterOnParent(); + wxGetApp().UpdateDlgDarkUI(&dialog); + update_preview(); + if (dialog.ShowModal() != wxID_OK) + return false; + policy.remove = rule->GetSelection() == 0; + policy.replacement = into_u8(replacement->GetTextCtrl()->GetValue()); + policy.remember = remember.GetValue(); + policy.dont_ask = dont_ask.GetValue(); + } + + const auto results = cleaned_groups(groups, policy.remove ? std::string() : policy.replacement); + for (size_t group = 0; group < groups.size(); ++group) + for (size_t index = 0; index < groups[group].size(); ++index) + *groups[group][index] = results[group][index]; + return true; +} + +void save_geometry_import_options(AppConfig& config, const std::string& format, const GeometryImportOptions& options) +{ + if (!options.chosen || (!options.remember && !options.dont_ask)) + return; + config.set_bool(option_key(format, "keep"), options.keep_names); + // A disabled sorting choice (Keep off) leaves the remembered one untouched. + if (options.keep_names) + config.set_bool(option_key(format, "sort"), options.sort_names); + if (format != "3mf") + config.set_bool(option_key(format, "assembly"), options.load_as_assembly); + if (format == "amf") + config.set_bool(option_key(format, "separate"), options.separate_objects); + if (format == "step") + config.set_bool("is_split_compound", options.split_compound); + if (options.dont_ask) + config.set_bool(format == "step" ? "enable_step_mesh_setting" : option_key(format, "show_dialog"), false); + if (format == "step") { + config.set("linear_deflection", float_to_string_decimal_point(options.linear_deflection, 3)); + config.set("angle_deflection", float_to_string_decimal_point(options.angle_deflection, 2)); + } +} + +void save_geometry_import_name_policy(AppConfig& config, const GeometryImportNamePolicy& policy) +{ + if (!policy.used || (!policy.remember && !policy.dont_ask)) + return; + config.set_bool("import_names_cleanup_remove", policy.remove); + config.set("import_names_cleanup_replacement", policy.replacement); + if (policy.dont_ask) + config.set_bool("import_names_cleanup_show_dialog", false); +} + +} // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/GeometryImportDialog.hpp b/src/slic3r/GUI/GeometryImportDialog.hpp new file mode 100644 index 0000000000..7623e7e981 --- /dev/null +++ b/src/slic3r/GUI/GeometryImportDialog.hpp @@ -0,0 +1,71 @@ +#pragma once + +#include +#include + +class CheckBox; +class wxSizer; +class wxStaticText; +class wxString; +class wxWindow; + +namespace Slic3r { +class AppConfig; +class Model; + +namespace GUI { + +// Values remain local to an import until all of its new dialogs have succeeded. +struct GeometryImportOptions { + bool keep_names = true; + bool sort_names = false; + bool load_as_assembly = true; + // AMF only: load the objects as separate objects, as OrcaSlicer did before; the assembly choice is then unused. + bool separate_objects = false; + // STEP only: Orca's Split compound choice; without it a multi-body compound loses its body names. + bool split_compound = true; + bool show_dialog = true; + bool remember = false; + bool dont_ask = false; + bool chosen = false; + double linear_deflection = 0.003; + double angle_deflection = 0.5; + bool single_object() const { return !separate_objects && !load_as_assembly; } +}; + +struct GeometryImportNamePolicy { + bool show_dialog = true; + bool remove = false; + bool remember = false; + bool dont_ask = false; + bool used = false; + std::string replacement = "_"; +}; + +// STEP and STP share one preference set; an empty result means an unrelated format. +std::string geometry_import_format(const std::string& path); +// Inspect the ZIP directory only, so CAD files do not enter the project-opening path. +bool is_geometry_only_3mf(const std::string& path); +GeometryImportOptions geometry_import_options(const AppConfig& config, const std::string& format); +GeometryImportNamePolicy geometry_import_name_policy(const AppConfig& config); +bool show_geometry_import_options(wxWindow* parent, const std::string& format, GeometryImportOptions& options); +// App-styled check box with its label, shared by the import dialogs. +struct ImportCheckBox { + ::CheckBox* box = nullptr; + wxStaticText* label = nullptr; + bool GetValue() const; + void SetValue(bool value) const; + // Greys the label too and stops it toggling the box. + void Enable(bool enable) const; + void SetToolTip(const wxString& tip) const; +}; +// A click on the label toggles the box and sends its wxEVT_TOGGLEBUTTON, as a click on the box does. +ImportCheckBox add_import_checkbox(wxWindow* parent, wxSizer& sizer, const wxString& text, bool value, int flags, int border); +// Sorting is offered only together with Keep original names; shared by the STEP dialog. +void link_sort_to_keep(const ImportCheckBox& keep, const ImportCheckBox& sort); +bool prepare_geometry_import_names(wxWindow* parent, const std::vector& models, GeometryImportNamePolicy& policy); +void save_geometry_import_options(AppConfig& config, const std::string& format, const GeometryImportOptions& options); +void save_geometry_import_name_policy(AppConfig& config, const GeometryImportNamePolicy& policy); + +} // namespace GUI +} // namespace Slic3r diff --git a/src/slic3r/GUI/ObjectDataViewModel.cpp b/src/slic3r/GUI/ObjectDataViewModel.cpp index 6694c27448..7eaa8ee6bb 100644 --- a/src/slic3r/GUI/ObjectDataViewModel.cpp +++ b/src/slic3r/GUI/ObjectDataViewModel.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include "slic3r/GUI/GUI_ObjectSettings.hpp" #include #include @@ -1298,7 +1299,9 @@ void ObjectDataViewModel::DeleteVolumeChildren(wxDataViewItem& parent) // set m_containet to FALSE if parent has no child #ifndef __WXGTK__ - root->m_container = false; + // Instances, settings and other rows may remain after the volumes are gone. + if (root->GetChildCount() == 0) + root->m_container = false; #endif //__WXGTK__ } @@ -2105,12 +2108,44 @@ unsigned int ObjectDataViewModel::GetChildren(const wxDataViewItem &parent, wxDa return 0; } - unsigned int count = node->GetChildren().GetCount(); - for (unsigned int pos = 0; pos < count; pos++) - { - ObjectDataViewModelNode* child = node->GetChildren().Item(pos); - array.Add(wxDataViewItem((void*)child)); + std::vector children; + for (auto* child : node->GetChildren()) + children.push_back(child); + if (node->m_type == itObject && node->m_model_object != nullptr) { + const ModelObject& object = *node->m_model_object; + if (std::any_of(object.volumes.begin(), object.volumes.end(), [](const ModelVolume* volume) { + return volume->import_display_order >= 0; + })) { + // Node indices count visible volumes; cut connectors do not create tree nodes. + std::vector visible_parts; + for (const ModelVolume* part : object.volumes) + if (!(object.is_cut() && part->is_cut_connector())) + visible_parts.push_back(part); + std::vector slots; + std::vector parts; + for (size_t i = 0; i < children.size(); ++i) + if (children[i]->GetType() == itVolume) { + slots.push_back(i); + parts.push_back(children[i]); + } + auto rank = [&](const ObjectDataViewModelNode* part) { + const int index = part->GetIdx(); + if (index >= 0 && size_t(index) < visible_parts.size() && + visible_parts[size_t(index)]->import_display_order >= 0) + return size_t(visible_parts[size_t(index)]->import_display_order); + return std::numeric_limits::max(); + }; + std::stable_sort(parts.begin(), parts.end(), [&](const auto* a, const auto* b) { + return rank(a) < rank(b); + }); + // Keep settings/layers/instances in their existing slots and never alter m_idx. + for (size_t i = 0; i < slots.size(); ++i) + children[slots[i]] = parts[i]; + } } + const auto count = static_cast(children.size()); + for (auto* child : children) + array.Add(wxDataViewItem((void*)child)); return count; } diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 80f77ed1f8..93e39ae892 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -300,6 +300,10 @@ #include "../Utils/Http.hpp" #include "../Utils/OrcaCloudServiceAgent.hpp" #include "StepMeshDialog.hpp" +#include "GeometryImportDialog.hpp" +#include "libslic3r/Format/ImportNames.hpp" +#include "libslic3r/Utils.hpp" +#include #include "FilamentMapDialog.hpp" #include "CloneDialog.hpp" #include "PurgeModeDialog.hpp" @@ -429,12 +433,12 @@ bool Plater::has_illegal_filename_characters(const wxString& wxs_name) bool Plater::has_illegal_filename_characters(const std::string& name) { - const char* illegal_characters = "<>:/\\|?*\""; - for (size_t i = 0; i < std::strlen(illegal_characters); i++) - if (name.find_first_of(illegal_characters[i]) != std::string::npos) - return true; - - return false; + try { + return has_unsupported_name_characters(name); + } catch (const std::invalid_argument&) { + // Invalid Unicode is not a valid editable project name either. + return true; + } } void Plater::show_illegal_characters_warning(wxWindow* parent) @@ -7472,8 +7476,11 @@ struct Plater::priv LoadStrategy strategy, bool ask_multi = false, bool* published_out = nullptr, - bool* config_loaded_out = nullptr); - std::vector load_model_objects(const ModelObjectPtrs& model_objects, bool allow_negative_z = false, bool split_object = false, bool auto_drop = true); + bool* config_loaded_out = nullptr, + // Runs once the import dialogs were answered and the files read, before the model changes. + const std::function& before_publish = nullptr); + std::vector load_model_objects(const ModelObjectPtrs& model_objects, bool allow_negative_z = false, bool split_object = false, + bool auto_drop = true, const std::map* import_display_options = nullptr); // Texture-to-color import: a mesh loaded with UVs + a texture map gets its faces clustered // into printable colours, which are then matched against (or added to) the filament list. @@ -8961,7 +8968,8 @@ std::vector Plater::priv::load_files(const std::vector& input_ LoadStrategy strategy, bool ask_multi, bool* published_out, - bool* config_loaded_out) + bool* config_loaded_out, + const std::function& before_publish) { if (config_loaded_out != nullptr) *config_loaded_out = false; @@ -8976,11 +8984,30 @@ std::vector Plater::priv::load_files(const std::vector& input_ if (input_files.empty()) return std::vector(); - if (!input_files.empty()) - q->m_3mf_path = input_files[0].string(); - - // SoftFever: ugly fix so we can exist pa calib mode - background_process.fff_print()->calib_mode() = CalibMode::Calib_None; + const bool previous_thumbnail_state = q->skip_thumbnail_invalid; + ScopeGuard restore_thumbnail_state([this, previous_thumbnail_state]() { + // In particular, parser errors and cancelled preparation must restore this flag. + q->skip_thumbnail_invalid = previous_thumbnail_state; + }); + + if ((strategy & LoadStrategy::LoadModel) && (strategy & LoadStrategy::LoadConfig) && !(strategy & LoadStrategy::Restore)) { + const bool has_3mf = std::any_of(input_files.begin(), input_files.end(), [](const fs::path& file) { + return boost::algorithm::iends_with(file.string(), ".3mf"); + }); + const bool geometry_only = has_3mf && std::all_of(input_files.begin(), input_files.end(), [](const fs::path& file) { + return !boost::algorithm::iends_with(file.string(), ".3mf") || is_geometry_only_3mf(file.string()); + }); + if (geometry_only) { + // A plain CAD 3MF has no project to restore, even if its caller used default load flags. + const int project_flags = static_cast(LoadStrategy::LoadConfig) | static_cast(LoadStrategy::LoadAuxiliary); + strategy = static_cast(static_cast(strategy) & ~project_flags); + } + } + // New import dialogs run before any project path, calibration or material changes. + const bool stage_geometry = (strategy & LoadStrategy::LoadModel) && !(strategy & LoadStrategy::LoadConfig) && + std::any_of(input_files.begin(), input_files.end(), [](const fs::path& file) { + return !geometry_import_format(file.string()).empty(); + }); // BBS @@ -9006,7 +9033,9 @@ std::vector Plater::priv::load_files(const std::vector& input_ ProgressDialog dlg(loading, "", 100, find_toplevel_parent(q), wxPD_AUTO_HIDE | wxPD_CAN_ABORT | wxPD_APP_MODAL); wxBusyCursor busy; - auto *new_model = (!load_model || one_by_one) ? nullptr : new Slic3r::Model(); + // Owned here so that early returns of the import preparation do not leak it. + std::unique_ptr new_model_owner((!load_model || one_by_one) ? nullptr : new Slic3r::Model()); + auto *new_model = new_model_owner.get(); std::vector obj_idxs; std::string designer_model_id; @@ -9050,6 +9079,189 @@ std::vector Plater::priv::load_files(const std::vector& input_ const float LOAD_MODEL_RATIO = 0.9; + struct StagedGeometryFile { + // Reader outputs have one owner even when parsing throws or the user cancels. + Model model; + DynamicPrintConfig config; + ConfigSubstitutionContext substitutions{ForwardCompatibilitySubstitutionRule::Enable}; + PlateDataPtrs plates; + std::vector presets; + Semver version; + En3mfType file_type = En3mfType::From_BBS; + bool is_inches = false; + std::string format; + // Keep original names actually applied to this file, not only the remembered preference. + bool names_kept = false; + // A 3MF without project data; only its CAD part labels are offered as original names. + bool cad_3mf = false; + std::string designer_id; + std::string country_code; + ~StagedGeometryFile() { + release_PlateData_list(plates); + for (Preset* preset : presets) + delete preset; + } + }; + std::vector> staged_files; + std::map import_options; + GeometryImportNamePolicy name_policy = geometry_import_name_policy(*wxGetApp().app_config); + std::map import_display_options; + // Applies the presentation choices; returns true when part settings keep a single object shown as an assembly. + auto apply_import_presentation = [&import_display_options](ModelObject& object, bool single_object, bool sort) { + const bool has_part_settings = object.has_individual_part_settings(); + // Never hide effective part-specific print controls in the single-object mode. + object.imported_parts_hidden = single_object && object.volumes.size() > 1 && !has_part_settings; + import_display_options[object.id()] = sort; + return single_object && object.volumes.size() > 1 && has_part_settings; + }; + // Staged files are read before the load loop: the reading takes this share of the bar and the loop the rest. + const int staged_read_share = stage_geometry ? static_cast(INPUT_FILES_RATIO * 100) : 0; + auto loop_progress = [staged_read_share](int percent) { return staged_read_share + percent * (100 - staged_read_share) / 100; }; + if (stage_geometry) { + staged_files.reserve(input_files.size()); + bool visible_part_settings = false; + try { + auto file_options = [&](const StagedGeometryFile& file) -> GeometryImportOptions* { + return file.format.empty() ? nullptr : &import_options.at(file.format); + }; + // Keep original names is applied by the readers, so every choice is made before a file is read. + auto read_staged = [&](size_t index, StagedGeometryFile& target) { + const fs::path& file_path = input_files[index]; + // Readers restart their count at each stage, so the bar keeps the furthest point of this file. + int file_percent = 0; + auto progress = [&](int percent) { + file_percent = std::max(file_percent, std::clamp(percent, 0, 100)); + const int overall = static_cast(staged_read_share * (static_cast(index) + file_percent / 100.0) / input_files.size()); + return dlg.Update(overall, format_wxstr(_L("Loading file: %s"), from_path(file_path.filename()))); + }; + if (!progress(0)) + return false; + GeometryImportOptions* options = file_options(target); + LoadStrategy read_strategy = strategy; + if (options != nullptr) { + // Assembly modes keep each group's bodies together as one object; the presentation is chosen separately. + if (!options->separate_objects) + read_strategy = read_strategy | LoadStrategy::AssembleParts; + // Project part names already win in a 3MF project, so only a CAD 3MF takes its labels. + if (options->keep_names && (target.format != "3mf" || target.cad_3mf)) + read_strategy = read_strategy | LoadStrategy::KeepOriginalNames; + } + if (target.format == "step") { + target.model = Model::read_from_step(file_path.string(), read_strategy, + [&](int, int current, int total, bool& cancel) { + cancel = !progress(total > 0 ? current * 100 / total : 0); + is_user_cancel = is_user_cancel || cancel; + }, nullptr, + [&](Step& file, double& linear, double& angle, bool& split) { + if (!options->chosen) { + if (options->show_dialog) { + StepMeshDialog mesh_dialog(q, file, options->linear_deflection, options->angle_deflection, options); + if (mesh_dialog.ShowModal() != wxID_OK) { + is_user_cancel = true; + return -1; + } + } + options->chosen = true; + } + linear = options->linear_deflection; + angle = options->angle_deflection; + split = options->split_compound; + // Names of bodies merged by an unsplit compound cannot be kept, so that file gets Orca's names. + file.set_keep_original_names(options->keep_names && file.has_original_names() && + (split || !file.has_multi_body_compound())); + target.names_kept = file.keep_original_names(); + return 1; + }, options->linear_deflection, options->angle_deflection, options->split_compound); + } else if (target.format == "3mf") { + target.model = Model::read_from_archive(file_path.string(), &target.config, &target.substitutions, + target.file_type, read_strategy, &target.plates, &target.presets, &target.version, + [&](int, int current, int total, bool& cancel) { + cancel = !progress(total > 0 ? current * 100 / total : 0); + is_user_cancel = is_user_cancel || cancel; + }); + } else { + target.model = Model::read_from_file(file_path.string(), nullptr, nullptr, read_strategy, + &target.plates, &target.presets, &target.is_inches, &target.version, nullptr, + [&](int current, int total, bool& cancel, std::string& designer, std::string& country) { + target.designer_id = designer; + target.country_code = country; + cancel = !progress(total > 0 ? current * 100 / total : 0); + is_user_cancel = is_user_cancel || cancel; + }); + } + return !is_user_cancel && !dlg.WasCancelled(); + }; + + for (size_t index = 0; index < input_files.size(); ++index) { + auto staged = std::make_unique(); + staged->format = geometry_import_format(input_files[index].string()); + if (!staged->format.empty()) { + auto inserted = import_options.emplace(staged->format, geometry_import_options(*wxGetApp().app_config, staged->format)); + if (silence) + inserted.first->second.show_dialog = false; + } + staged->cad_3mf = staged->format == "3mf" && is_geometry_only_3mf(input_files[index].string()); + // One AMF/3MF dialog per format, at its first file; a 3MF project has nothing to choose. + // The STEP dialog runs inside the reader, which needs the document for its triangle count. + if ((staged->format == "amf" || staged->cad_3mf) && + !show_geometry_import_options(q, staged->format, import_options.at(staged->format))) + return empty_result; + if (!read_staged(index, *staged)) + return empty_result; + staged_files.push_back(std::move(staged)); + } + + for (const auto& staged : staged_files) { + const GeometryImportOptions* options = file_options(*staged); + if (options == nullptr) + continue; + if (staged->format != "step") + // A 3MF project keeps its own part names; only a CAD 3MF takes the labels from the file. + staged->names_kept = options->keep_names && (staged->format != "3mf" || staged->cad_3mf); + // Orca's own names carry no order worth sorting by. + for (ModelObject* object : staged->model.objects) + visible_part_settings = apply_import_presentation(*object, options->single_object(), + options->keep_names && options->sort_names) || visible_part_settings; + } + std::vector named_models; + for (const auto& staged : staged_files) + if (staged->names_kept) + named_models.push_back(&staged->model); + if (silence) + name_policy.show_dialog = false; + if (!prepare_geometry_import_names(q, named_models, name_policy)) + return empty_result; + if (visible_part_settings && !silence) + MessageDialog(q, _L("Some imported objects contain modifiers or parts with individual settings. They are shown as assemblies so that these settings remain visible."), + _L("Geometry import"), wxOK | wxICON_INFORMATION).ShowModal(); + } catch (const std::exception& error) { + if (!is_user_cancel && !dlg.WasCancelled()) + GUI::show_error(q, error.what()); + return empty_result; + } + } + + // The new import dialogs and the staged reading are done: a deferred project replacement starts here. + if (before_publish) { + // Only a CAD 3MF defers the replacement, and it always takes the staged path. + assert(stage_geometry); + // Replacing the project needs something to load; objects below this volume are dropped while loading, + // as in Model::removed_objects_with_zero_volume(). + const bool has_geometry = std::any_of(staged_files.begin(), staged_files.end(), [](const auto& staged) { + return std::any_of(staged->model.objects.begin(), staged->model.objects.end(), [](const ModelObject* object) { + return object->get_object_stl_stats().volume >= 0.0000000001; + }); + }); + if (!has_geometry) { + GUI::show_error(q, _L("The file does not contain any geometry data.")); + return empty_result; + } + before_publish(); + } + q->m_3mf_path = input_files.front().string(); + // Leave the previous calibration mode intact when preparation was cancelled. + background_process.fff_print()->calib_mode() = CalibMode::Calib_None; + for (size_t i = 0; i < input_files.size(); ++i) { int project_filament_count = 1; @@ -9066,7 +9278,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ const auto real_filename = (strategy & LoadStrategy::Restore) ? input_files[++i].filename() : filename; const auto dlg_info = _L("Loading file") + ": " + from_path(real_filename); BOOST_LOG_TRIVIAL(trace) << __FUNCTION__ << boost::format(": load file %1%") % filename; - dlg_cont = dlg.Update(progress_percent, dlg_info); + dlg_cont = dlg.Update(loop_progress(progress_percent), dlg_info); if (!dlg_cont) return empty_result; const bool type_3mf = std::regex_match(path.string(), pattern_3mf); @@ -9075,6 +9287,8 @@ std::vector Plater::priv::load_files(const std::vector& input_ // const bool type_prusa = std::regex_match(path.string(), pattern_prusa); Slic3r::Model model; + StagedGeometryFile legacy_read; + StagedGeometryFile& parsed_file = stage_geometry ? *staged_files[i] : legacy_read; // BBS: add auxiliary files related logic bool load_aux = strategy & LoadStrategy::LoadAuxiliary, load_old_project = false; if (load_model && load_config && type_3mf) { @@ -9087,23 +9301,26 @@ std::vector Plater::priv::load_files(const std::vector& input_ try { if (type_3mf) { DynamicPrintConfig config; - Semver file_version; - En3mfType en_3mf_file_type = En3mfType::From_BBS; + Semver& file_version = parsed_file.version; + En3mfType& en_3mf_file_type = parsed_file.file_type; // BBS: a "published" 3MF carries a flag plus the author-selected setting keys; // on load keep the user's current presets and overlay only those keys. Declared // here (outside the config block below) so it stays alive for the embedded-preset // gate, the metadata strip and the preset overlay after the block closes. PublishedConfig published_config; { - DynamicPrintConfig config_loaded; + DynamicPrintConfig& config_loaded = parsed_file.config; - // BBS: add part plate related logic - PlateDataPtrs plate_data; - ConfigSubstitutionContext config_substitutions{ForwardCompatibilitySubstitutionRule::Enable}; - std::vector project_presets; + // Reader outputs remain owned through every downstream early return. + PlateDataPtrs& plate_data = parsed_file.plates; + ConfigSubstitutionContext& config_substitutions = parsed_file.substitutions; + std::vector& project_presets = parsed_file.presets; // BBS: backup & restore q->skip_thumbnail_invalid = true; - model = Slic3r::Model::read_from_archive(path.string(), &config_loaded, &config_substitutions, en_3mf_file_type, strategy, &plate_data, &project_presets, + if (stage_geometry) { + model = std::move(parsed_file.model); + } else { + model = Slic3r::Model::read_from_archive(path.string(), &config_loaded, &config_substitutions, en_3mf_file_type, strategy, &plate_data, &project_presets, &file_version, [&dlg, real_filename, &progress_percent, stage_percent, INPUT_FILES_RATIO, total_files, i, &is_user_cancel](int import_stage, int current, int total, bool &cancel) { @@ -9117,6 +9334,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ if (cancel) is_user_cancel = cancel; }); + } BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ":" << __LINE__ << boost::format(", plate_data.size %1%, project_preset.size %2%, is_bbs_or_orca_3mf %3%, file_version %4% \n") % plate_data.size() % project_presets.size() % (en_3mf_file_type == En3mfType::From_BBS || en_3mf_file_type == En3mfType::From_Orca) % file_version.to_string(); @@ -9396,7 +9614,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ if (plate_data.size() > 0) { BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ":" << __LINE__ << boost::format(", import 3mf UPDATE_GCODE_RESULT \n"); wxString msg = wxString::Format(_L("Loading file: %s"), from_path(real_filename)); - dlg_cont = dlg.Update(progress_percent, msg); + dlg_cont = dlg.Update(loop_progress(progress_percent), msg); if (!dlg_cont) { q->skip_thumbnail_invalid = false; return empty_result; @@ -9449,7 +9667,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ if (load_config && !config_loaded.empty()) { BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ":" << __LINE__ << boost::format(", import 3mf IMPORT_LOAD_CONFIG \n"); wxString msg = wxString::Format(_L("Loading file: %s"), from_path(real_filename)); - dlg_cont = dlg.Update(progress_percent, msg); + dlg_cont = dlg.Update(loop_progress(progress_percent), msg); if (!dlg_cont) { q->skip_thumbnail_invalid = false; return empty_result; @@ -9773,13 +9991,17 @@ std::vector Plater::priv::load_files(const std::vector& input_ } } else { // BBS: add plate data related logic - PlateDataPtrs plate_data; - // BBS: project embedded settings - std::vector project_presets; - bool is_xxx; - Semver file_version; + PlateDataPtrs& plate_data = parsed_file.plates; + // Reader outputs stay alive through the existing import branches. + std::vector& project_presets = parsed_file.presets; + bool& is_xxx = parsed_file.is_inches; + Semver& file_version = parsed_file.version; - if (boost::iends_with(path.string(), ".stp") || + if (stage_geometry) { + model = std::move(parsed_file.model); + designer_model_id = parsed_file.designer_id; + designer_country_code = parsed_file.country_code; + } else if (boost::iends_with(path.string(), ".stp") || boost::iends_with(path.string(), ".step")) { double linear = string_to_double_decimal_point(wxGetApp().app_config->get("linear_deflection")); if (linear <= 0) linear = 0.003; @@ -9892,7 +10114,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ } progress_percent = 100.0f * (float)i / (float)total_files + INIT_MODEL_RATIO * 100.0f / (float)total_files; - dlg_cont = dlg.Update(progress_percent); + dlg_cont = dlg.Update(loop_progress(progress_percent)); if (!dlg_cont) { q->skip_thumbnail_invalid = false; return empty_result; @@ -9952,11 +10174,25 @@ std::vector Plater::priv::load_files(const std::vector& input_ // convert_model_if(model, answer_convert_from_imperial_units == wxID_YES); } - if (!is_project_file && model.looks_like_multipart_object()) { + // An AMF group with non-printable bodies was kept apart on purpose; merging it would make them printable. + // Only the assembly modes keep such groups apart; Separate objects asks as before. + const auto amf_options = import_options.find("amf"); + const bool amf_assembly = stage_geometry && parsed_file.format == "amf" && amf_options != import_options.end() && + !amf_options->second.separate_objects; + const bool has_excluded_bodies = amf_assembly && std::any_of(model.objects.begin(), model.objects.end(), [](const ModelObject* object) { + return std::any_of(object->instances.begin(), object->instances.end(), [](const ModelInstance* instance) { return !instance->printable; }); + }); + if (!is_project_file && !has_excluded_bodies && model.looks_like_multipart_object()) { MessageDialog msg_dlg(q, _L("This file contains several objects positioned at multiple heights.\nInstead of considering them as multiple objects, should the file be loaded as a single object with multiple parts\?") + "\n", _L("Multi-part object detected"), wxICON_WARNING | wxYES | wxNO); if (msg_dlg.ShowModal() == wxID_YES) { - model.convert_multipart_object(filaments_cnt); + // Kept original part names survive Orca's own merge; other files keep its naming. + model.convert_multipart_object(filaments_cnt, parsed_file.names_kept); + // The merged object is new, so the choices of this file's import dialog apply to it again. + if (auto options = import_options.find(parsed_file.format); stage_geometry && options != import_options.end()) + for (ModelObject* object : model.objects) + apply_import_presentation(*object, options->second.single_object(), + options->second.keep_names && options->second.sort_names); } } } @@ -9972,7 +10208,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ //} progress_percent = 100.0f * (float)i / (float)total_files + CENTER_AROUND_ORIGIN_RATIO * 100.0f / (float)total_files; - dlg_cont = dlg.Update(progress_percent); + dlg_cont = dlg.Update(loop_progress(progress_percent)); if (!dlg_cont) { q->skip_thumbnail_invalid = false; return empty_result; @@ -9987,7 +10223,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ":" << __LINE__ << " " << boost::format("import 3mf IMPORT_LOAD_MODEL_OBJECTS \n"); wxString msg = wxString::Format(_L("Loading file: %s"), from_path(real_filename)); model_idx++; - dlg_cont = dlg.Update(progress_percent, msg); + dlg_cont = dlg.Update(loop_progress(progress_percent), msg); if (!dlg_cont) { q->skip_thumbnail_invalid = false; return empty_result; @@ -10000,7 +10236,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ tolal_model_count += model_idx; progress_percent = 100.0f * (float)i / (float)total_files + LOAD_MODEL_RATIO * 100.0f / (float)total_files; - dlg_cont = dlg.Update(progress_percent); + dlg_cont = dlg.Update(loop_progress(progress_percent)); if (!dlg_cont) { q->skip_thumbnail_invalid = false; return empty_result; @@ -10023,9 +10259,9 @@ std::vector Plater::priv::load_files(const std::vector& input_ if (model.texture_mesh && has_importable_texture(*model.texture_mesh)) { TextureImportResult texture_import_result; auto cancel_cb = [&dlg, &dlg_cont]() { return !dlg_cont || dlg.WasCancelled(); }; - auto progress_cb = [&dlg, &dlg_cont, &progress_percent](int percent) { + auto progress_cb = [&dlg, &dlg_cont, &progress_percent, &loop_progress](int percent) { progress_percent = std::clamp(percent, 0, 100); - dlg_cont = dlg.Update(progress_percent, _L("Matching textures to filaments")); + dlg_cont = dlg.Update(loop_progress(progress_percent), _L("Matching textures to filaments")); return dlg_cont; }; if (!run_textured_mesh_import_dialog(model, texture_import_result, cancel_cb, progress_cb)) { @@ -10040,8 +10276,8 @@ std::vector Plater::priv::load_files(const std::vector& input_ if (!texture_import_result.painted.face_colors.empty()) { std::vector texture_object_idxs(model.objects.size()); std::iota(texture_object_idxs.begin(), texture_object_idxs.end(), 0); - auto apply_progress_cb = [&dlg](int percent, const wxString& msg) { - dlg.Update(std::clamp(percent, 0, 100), msg); + auto apply_progress_cb = [&dlg, &loop_progress](int percent, const wxString& msg) { + dlg.Update(loop_progress(std::clamp(percent, 0, 100)), msg); return true; }; apply_textured_mesh_import_result(model, texture_object_idxs, texture_import_result, @@ -10050,7 +10286,8 @@ std::vector Plater::priv::load_files(const std::vector& input_ } BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ":" << __LINE__ << boost::format(", before load_model_objects, count %1%")%model.objects.size(); - auto loaded_idxs = load_model_objects(model.objects, is_project_file); + auto loaded_idxs = load_model_objects(model.objects, is_project_file, false, true, + stage_geometry ? &import_display_options : nullptr); obj_idxs.insert(obj_idxs.end(), loaded_idxs.begin(), loaded_idxs.end()); // load_model_objects only transfers ModelObjects; carry the Model-level CAD recipe @@ -10065,7 +10302,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ":" << __LINE__ << boost::format(", finished load_model_objects"); wxString msg = wxString::Format(_L("Loading file: %s"), from_path(real_filename)); - dlg_cont = dlg.Update(progress_percent, msg); + dlg_cont = dlg.Update(loop_progress(progress_percent), msg); if (!dlg_cont) { q->skip_thumbnail_invalid = false; return empty_result; @@ -10073,11 +10310,14 @@ std::vector Plater::priv::load_files(const std::vector& input_ } else { // This must be an .stl or .obj file, which may contain a maximum of one volume. for (const ModelObject *model_object : model.objects) { - new_model->add_object(*model_object); + ModelObject* copied_object = new_model->add_object(*model_object); + const auto display = import_display_options.find(model_object->id()); + if (display != import_display_options.end()) + import_display_options.emplace(copied_object->id(), display->second); BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ":" << __LINE__ << boost::format(", added object %1%")%model_object->name; wxString msg = wxString::Format(_L("Loading file: %s"), from_path(real_filename)); - dlg_cont = dlg.Update(progress_percent, msg); + dlg_cont = dlg.Update(loop_progress(progress_percent), msg); if (!dlg_cont) { q->skip_thumbnail_invalid = false; return empty_result; @@ -10103,8 +10343,24 @@ std::vector Plater::priv::load_files(const std::vector& input_ // convert to multipart and split after load_model_objects // to keep relative positioning if auto_drop == false - if (single_object_answer == wxID_YES || new_model_auto_drop == false) - new_model->convert_multipart_object(filaments_cnt); + if (single_object_answer == wxID_YES || new_model_auto_drop == false) { + // Parts keep their imported names when any geometry import asked to keep them. + new_model->convert_multipart_object(filaments_cnt, std::any_of(staged_files.begin(), staged_files.end(), + [](const auto& staged) { return staged->names_kept; })); + // Files of several kinds share the merged object; it takes a choice only when every file made it. + const bool all_staged = stage_geometry && std::all_of(staged_files.begin(), staged_files.end(), + [](const auto& staged) { return !staged->format.empty(); }); + bool single_object = all_staged; + bool sort = all_staged; + for (const auto& staged : staged_files) + if (const auto options = import_options.find(staged->format); options != import_options.end()) { + single_object = single_object && options->second.single_object(); + sort = sort && options->second.keep_names && options->second.sort_names; + } + if (stage_geometry) + for (ModelObject* object : new_model->objects) + apply_import_presentation(*object, single_object, sort); + } } // TODO @@ -10114,7 +10370,8 @@ std::vector Plater::priv::load_files(const std::vector& input_ // DONE when manually split to object ask users if looks_like_multipart and none have auto_drob disabled if they want to disable auto_drop for all resulting objects. // - add icon in object list, similar to fuzzy painting, etc. - auto loaded_idxs = load_model_objects(new_model->objects, false, false, new_model_auto_drop); + auto loaded_idxs = load_model_objects(new_model->objects, false, false, new_model_auto_drop, + stage_geometry ? &import_display_options : nullptr); obj_idxs.insert(obj_idxs.end(), loaded_idxs.begin(), loaded_idxs.end()); if (single_object_answer == wxID_NO && new_model_auto_drop == false) { @@ -10166,7 +10423,6 @@ std::vector Plater::priv::load_files(const std::vector& input_ } } - if (new_model) delete new_model; //BBS: translate old 3mf to correct positions if (translate_old) { @@ -10304,6 +10560,12 @@ std::vector Plater::priv::load_files(const std::vector& input_ msg.ShowModal(); } } + if (stage_geometry && !obj_idxs.empty()) { + // Save only after all new questions succeeded and the prepared models were published. + for (const auto& entry : import_options) + save_geometry_import_options(*wxGetApp().app_config, entry.first, entry.second); + save_geometry_import_name_policy(*wxGetApp().app_config, name_policy); + } q->schedule_background_process(true); q->mark_plate_toolbar_image_dirty(); return obj_idxs; @@ -10311,7 +10573,8 @@ std::vector Plater::priv::load_files(const std::vector& input_ #define AUTOPLACEMENT_ON_LOAD -std::vector Plater::priv::load_model_objects(const ModelObjectPtrs& model_objects, bool allow_negative_z, bool split_object, bool auto_drop) +std::vector Plater::priv::load_model_objects(const ModelObjectPtrs& model_objects, bool allow_negative_z, bool split_object, + bool auto_drop, const std::map* import_display_options) { const Vec3d bed_size = Slic3r::to_3d(this->bed.build_volume().bounding_volume2d().size(), 1.0) - 2.0 * Vec3d::Ones(); @@ -10327,6 +10590,12 @@ std::vector Plater::priv::load_model_objects(const ModelObjectPtrs& mode #endif /* AUTOPLACEMENT_ON_LOAD */ for (ModelObject *model_object : model_objects) { auto *object = model.add_object(*model_object); + if (import_display_options != nullptr) { + const auto display = import_display_options->find(model_object->id()); + if (display != import_display_options->end()) + // The final clone has fresh IDs but still has the source volume order here. + set_import_volume_order(*object, display->second); + } object->sort_volumes(true); std::string object_name = object->name.empty() ? fs::path(object->input_file).filename().string() : object->name; obj_idxs.push_back(obj_count++); @@ -16191,9 +16460,6 @@ LoadType determine_load_type(std::string filename, std::string override_setting void Plater::load_project(wxString const& filename2, wxString const& originfile) { - model().calib_pa_pattern.reset(nullptr); - model().plates_custom_gcodes.clear(); - BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "filename is: " << filename2 << "and originfile is: " << originfile; BOOST_LOG_TRIVIAL(info) << __FUNCTION__; auto filename = filename2; @@ -16210,7 +16476,9 @@ void Plater::load_project(wxString const& filename2, // BSS: save project, force close int result; - if ((result = close_with_confirm(check)) == wxID_CANCEL) { + // Run by replace_project(), so a load that stops before it leaves the current project unchanged. + std::function close_project; + if ((result = close_with_confirm(check, &close_project)) == wxID_CANCEL) { return; } @@ -16225,17 +16493,6 @@ void Plater::load_project(wxString const& filename2, m_loading_project = true; ScopeGuard loading_project_sc([this]() { m_loading_project = false; }); // Make sure state restored on any early return - m_only_gcode = false; - m_exported_file = false; - get_notification_manager()->bbl_close_plateinfo_notification(); - get_notification_manager()->bbl_close_preview_only_notification(); - get_notification_manager()->bbl_close_3mf_warn_notification(); - get_notification_manager()->close_notification_of_type(NotificationType::PlaterError); - get_notification_manager()->close_notification_of_type(NotificationType::PlaterWarning); - get_notification_manager()->close_notification_of_type(NotificationType::SlicingError); - get_notification_manager()->close_notification_of_type(NotificationType::SlicingSeriousWarning); - get_notification_manager()->close_notification_of_type(NotificationType::SlicingWarning); - auto path = into_path(filename); auto strategy = LoadStrategy::LoadModel | LoadStrategy::LoadConfig; @@ -16254,10 +16511,32 @@ void Plater::load_project(wxString const& filename2, } bool load_restore = strategy & LoadStrategy::Restore; - // Take the Undo / Redo snapshot. - reset(); - - Plater::TakeSnapshot snapshot(this, "Load Project", UndoRedo::SnapshotType::ProjectSeparator); + std::optional snapshot; + auto replace_project = [&]() { + // close_with_confirm() sets it on every path that does not cancel. + assert(close_project); + close_project(); + get_notification_manager()->bbl_close_plateinfo_notification(); + get_notification_manager()->bbl_close_preview_only_notification(); + get_notification_manager()->bbl_close_3mf_warn_notification(); + get_notification_manager()->close_notification_of_type(NotificationType::PlaterError); + get_notification_manager()->close_notification_of_type(NotificationType::PlaterWarning); + get_notification_manager()->close_notification_of_type(NotificationType::SlicingError); + get_notification_manager()->close_notification_of_type(NotificationType::SlicingSeriousWarning); + get_notification_manager()->close_notification_of_type(NotificationType::SlicingWarning); + model().calib_pa_pattern.reset(nullptr); + model().plates_custom_gcodes.clear(); + m_only_gcode = false; + m_exported_file = false; + reset(); + // Take the Undo / Redo snapshot. + snapshot.emplace(this, "Load Project", UndoRedo::SnapshotType::ProjectSeparator); + }; + // A CAD 3MF passes its import dialogs first: the project is replaced only once the file is ready, + // so a Cancel there keeps the current project. + const bool replace_when_ready = !load_restore && is_geometry_only_3mf(path.string()); + if (!replace_when_ready) + replace_project(); std::vector input_paths; input_paths.push_back(path); @@ -16265,7 +16544,11 @@ void Plater::load_project(wxString const& filename2, input_paths.push_back(into_u8(originfile)); bool loaded_published = false; - std::vector res = load_files(input_paths, strategy, false, &loaded_published); + std::vector res = load_files(input_paths, strategy, false, &loaded_published, + replace_when_ready ? replace_project : std::function()); + // The import was cancelled or failed before the project was replaced. + if (!snapshot) + return; reset_project_dirty_initial_presets(); update_project_dirty_from_presets(); @@ -18458,13 +18741,25 @@ void Plater::force_update_all_plate_thumbnails() } // BBS: backup -std::vector Plater::load_files(const std::vector& input_files, LoadStrategy strategy, bool ask_multi, bool* published_out) { - //BBS: wish to reset state when load a new file - p->m_slice_all_only_has_gcode = false; - //BBS: wish to reset all plates stats item selected state when load a new file - p->preview->get_canvas3d()->reset_select_plate_toolbar_selection(); +std::vector Plater::load_files(const std::vector& input_files, LoadStrategy strategy, bool ask_multi, bool* published_out, + const std::function& before_publish) { + auto reset_load_state = [this]() { + //BBS: wish to reset state when load a new file + p->m_slice_all_only_has_gcode = false; + //BBS: wish to reset all plates stats item selected state when load a new file + p->preview->get_canvas3d()->reset_select_plate_toolbar_selection(); + }; + // A deferred project replacement also defers this reset, so a cancelled import keeps the preview state. + std::function publish; + if (before_publish) + publish = [&]() { + reset_load_state(); + before_publish(); + }; + else + reset_load_state(); bool config_loaded = false; - std::vector result = p->load_files(input_files, strategy, ask_multi, published_out, &config_loaded); + std::vector result = p->load_files(input_files, strategy, ask_multi, published_out, &config_loaded, publish); if (config_loaded && !is_loading_project()) normalize_bed_types(false); return result; @@ -18802,6 +19097,17 @@ void ProjectDropDialog::on_dpi_changed(const wxRect& suggested_rect) Refresh(); } +LoadType determine_load_type(std::string filename, std::string override_setting); + +static LoadType choose_3mf_load_type(Plater& plater, const fs::path& file) +{ + if (is_geometry_only_3mf(file.string())) + return LoadType::LoadGeometry; + const std::string filename = encode_path(file.filename().string().c_str()); + const bool ask_when_relevant = wxGetApp().app_config->get(SETTING_PROJECT_LOAD_BEHAVIOUR) == OPTION_PROJECT_LOAD_BEHAVIOUR_ASK_WHEN_RELEVANT; + return determine_load_type(filename, !plater.model().objects.empty() && ask_when_relevant ? OPTION_PROJECT_LOAD_BEHAVIOUR_ALWAYS_ASK : ""); +} + //BBS: remove GCodeViewer as seperate APP logic bool Plater::load_files(const wxArrayString& filenames) { @@ -18910,9 +19216,27 @@ bool Plater::load_files(const wxArrayString& filenames) return res; }; + const auto first_3mf = std::find_if(normal_paths.begin(), normal_paths.end(), [](const fs::path& path) { + return boost::algorithm::iends_with(path.string(), ".3mf"); + }); + LoadType first_3mf_action = LoadType::Unknown; + if (first_3mf != normal_paths.end()) { + first_3mf_action = choose_3mf_load_type(*this, *first_3mf); + if (first_3mf_action == LoadType::Unknown) + return false; + const bool contains_zip = std::any_of(normal_paths.begin(), normal_paths.end(), [](const fs::path& path) { + return boost::algorithm::iends_with(path.string(), ".zip"); + }); + if (first_3mf_action == LoadType::LoadGeometry && !contains_zip) { + // Do not split a geometry operation into several imports: Cancel applies to the entire set. + Plater::TakeSnapshot snapshot(this, snapshot_label); + return !load_files(normal_paths, LoadStrategy::LoadModel, false).empty(); + } + } + switch (loadfiles_type) { case LoadFilesType::Single3MF: - open_3mf_file(normal_paths[0]); + res = open_3mf_file(normal_paths[0], first_3mf_action); break; case LoadFilesType::SingleOther: { @@ -18927,7 +19251,7 @@ bool Plater::load_files(const wxArrayString& filenames) if (i > 0) { other_file.push_back(normal_paths[i]); } }; - open_3mf_file(first_file[0]); + if (!open_3mf_file(first_file[0], first_3mf_action)) return false; if (load_files(other_file, LoadStrategy::LoadModel).empty()) { res = false; } break; @@ -18952,7 +19276,7 @@ bool Plater::load_files(const wxArrayString& filenames) } } - open_3mf_file(first_file[0]); + if (!open_3mf_file(first_file[0], first_3mf_action)) return false; if (load_files(tmf_file, LoadStrategy::LoadModel).empty()) { res = false; } if (res && handle_zips(other_file)) { if (normal_paths.empty()) return true; @@ -18997,39 +19321,30 @@ LoadType determine_load_type(std::string filename, std::string override_setting) bool Plater::open_3mf_file(const fs::path &file_path) { - std::string filename = encode_path(file_path.filename().string().c_str()); - if (!boost::algorithm::iends_with(filename, ".3mf")) { + if (!boost::algorithm::iends_with(file_path.string(), ".3mf")) return false; - } - - bool not_empty_plate = !model().objects.empty(); - bool load_setting_ask_when_relevant = wxGetApp().app_config->get(SETTING_PROJECT_LOAD_BEHAVIOUR) == OPTION_PROJECT_LOAD_BEHAVIOUR_ASK_WHEN_RELEVANT; - LoadType load_type = determine_load_type(filename, (not_empty_plate && load_setting_ask_when_relevant) ? OPTION_PROJECT_LOAD_BEHAVIOUR_ALWAYS_ASK : ""); - - if (load_type == LoadType::Unknown) return false; + return open_3mf_file(file_path, choose_3mf_load_type(*this, file_path)); +} +bool Plater::open_3mf_file(const fs::path &file_path, LoadType load_type) +{ switch (load_type) { - case LoadType::OpenProject: { - if (wxGetApp().can_load_project()) - load_project(from_path(file_path), ""); - break; - } + case LoadType::OpenProject: + if (!wxGetApp().can_load_project()) + return false; + load_project(from_path(file_path), ""); + return true; case LoadType::LoadGeometry: { Plater::TakeSnapshot snapshot(this, "Import Object"); - load_files({file_path}, LoadStrategy::LoadModel); - break; + return !load_files({file_path}, LoadStrategy::LoadModel).empty(); } - case LoadType::LoadConfig: { + case LoadType::LoadConfig: load_files({file_path}, LoadStrategy::LoadConfig); - break; - } - case LoadType::Unknown: { - assert(false); - break; - } + return true; + case LoadType::Unknown: + return false; } - - return true; + return false; } int Plater::get_3mf_file_count(std::vector paths) @@ -19064,6 +19379,28 @@ void Plater::add_file() snapshot_label += encode_path(paths[i].filename().string().c_str()); } + const auto first_3mf = std::find_if(paths.begin(), paths.end(), [](const fs::path& path) { + return boost::algorithm::iends_with(path.string(), ".3mf"); + }); + LoadType first_3mf_action = LoadType::Unknown; + if (first_3mf != paths.end()) { + first_3mf_action = choose_3mf_load_type(*this, *first_3mf); + if (first_3mf_action == LoadType::Unknown) + return; + if (first_3mf_action == LoadType::LoadGeometry) { + Plater::TakeSnapshot snapshot(this, snapshot_label); + if (!load_files(paths, LoadStrategy::LoadModel, false).empty()) { + if (get_project_name() == _L("Untitled")) + p->set_project_name(from_u8(paths.front().stem().string())); + wxGetApp().mainframe->update_title(); + if (wxGetApp().app_config->get("recent_models") == "true") + for (const fs::path& file : paths) + wxGetApp().mainframe->add_to_recent_projects(file.wstring()); + } + return; + } + } + // BBS: check file types auto loadfiles_type = LoadFilesType::NoFile; auto amf_files_count = get_3mf_file_count(paths); @@ -19081,7 +19418,7 @@ void Plater::add_file() switch (loadfiles_type) { case LoadFilesType::Single3MF: - open_3mf_file(paths[0]); + open_3mf_file(paths[0], first_3mf_action); break; case LoadFilesType::SingleOther: { @@ -19103,7 +19440,7 @@ void Plater::add_file() if (i > 0) { other_file.push_back(paths[i]); } }; - open_3mf_file(first_file[0]); + if (!open_3mf_file(first_file[0], first_3mf_action)) return; if (!load_files(other_file, LoadStrategy::LoadModel).empty()) { wxGetApp().mainframe->update_title(); } break; @@ -19133,7 +19470,7 @@ void Plater::add_file() } } - open_3mf_file(first_file[0]); + if (!open_3mf_file(first_file[0], first_3mf_action)) return; load_files(tmf_file, LoadStrategy::LoadModel); if (!load_files(other_file, LoadStrategy::LoadModel, false).empty()) { wxGetApp().mainframe->update_title(); @@ -19253,11 +19590,18 @@ void Plater::reset_with_confirm() } // BBS: save logic -int GUI::Plater::close_with_confirm(std::function second_check) +int GUI::Plater::close_with_confirm(std::function second_check, std::function* deferred_close) { + // A caller that may still keep the current project runs these steps itself once it is replaced. + auto close = [deferred_close](std::function steps) { + if (deferred_close != nullptr) + *deferred_close = std::move(steps); + else + steps(); + }; if (up_to_date(false, false)) { if (second_check && !second_check(false)) return wxID_CANCEL; - model().set_backup_path(""); + close([this]() { model().set_backup_path(""); }); return wxID_NO; } @@ -19282,9 +19626,11 @@ int GUI::Plater::close_with_confirm(std::function second_check) if (second_check && !second_check(result == wxID_YES)) return wxID_CANCEL; - model().set_backup_path(""); - up_to_date(true, false); - up_to_date(true, true); + close([this]() { + model().set_backup_path(""); + up_to_date(true, false); + up_to_date(true, true); + }); return result; } diff --git a/src/slic3r/GUI/Plater.hpp b/src/slic3r/GUI/Plater.hpp index e3a59b2993..623f836c1d 100644 --- a/src/slic3r/GUI/Plater.hpp +++ b/src/slic3r/GUI/Plater.hpp @@ -95,6 +95,7 @@ namespace UndoRedo { } namespace GUI { +enum class LoadType : unsigned char; class SyncAmsInfoDialog; class MainFrame; class ConfigOptionsGroup; @@ -389,6 +390,8 @@ public: bool up_to_date(bool saved, bool backup); bool open_3mf_file(const boost::filesystem::path &file_path); + // Batch import resolves the project/geometry question once before staging the whole set. + bool open_3mf_file(const boost::filesystem::path &file_path, LoadType resolved_type); int get_3mf_file_count(std::vector paths); void add_file(); // Returns false when no object was added (e.g. the user cancelled the load dialog). @@ -454,7 +457,8 @@ public: bool preview_zip_archive(const boost::filesystem::path& archive_path); // BBS: restore - std::vector load_files(const std::vector& input_files, LoadStrategy strategy = LoadStrategy::LoadModel | LoadStrategy::LoadConfig, bool ask_multi = false, bool* published_out = nullptr); + std::vector load_files(const std::vector& input_files, LoadStrategy strategy = LoadStrategy::LoadModel | LoadStrategy::LoadConfig, bool ask_multi = false, bool* published_out = nullptr, + const std::function& before_publish = nullptr); // to be called on drag and drop bool load_files(const wxArrayString& filenames); @@ -550,7 +554,8 @@ public: void reset(bool apply_presets_change = false, bool reload_presets = true); void reset_with_confirm(); //BBS: return int for various result - int close_with_confirm(std::function second_check = nullptr); // BBS close project + // With deferred_close, the steps that mark the current project closed are returned instead of run. + int close_with_confirm(std::function second_check = nullptr, std::function* deferred_close = nullptr); // BBS close project //BBS: trigger a restore project event void trigger_restore_project(int skip_confirm = 0); bool delete_object_from_model(size_t obj_idx, bool refresh_immediately = true); // BBS support refresh immediately diff --git a/src/slic3r/GUI/Preferences.cpp b/src/slic3r/GUI/Preferences.cpp index bc475f9b0f..e55884f4f0 100644 --- a/src/slic3r/GUI/Preferences.cpp +++ b/src/slic3r/GUI/Preferences.cpp @@ -1827,16 +1827,27 @@ void PreferencesDialog::create_items() g_sizer->Add(create_item_title(_L("Folder paths")), 1, wxEXPAND); auto item_downloads = create_item_downloads(_L("Downloads folder"), _L("Target folder for downloaded items")); g_sizer->Add(item_downloads); + + //// FILES > File import + g_sizer->Add(create_item_title(_L("File import")), 1, wxEXPAND); + g_sizer->Add(create_item_checkbox(_L("Ask how to handle unsupported characters in imported names"), + _L("Show the removal or replacement choices when original names contain unsupported characters."), + "import_names_cleanup_show_dialog")); //// FILES > 3MF import g_sizer->Add(create_item_title(_L("3MF import")), 1, wxEXPAND); + g_sizer->Add(create_item_checkbox(_L("Show options when importing"), + _L("Show original-name and sorting options when importing a 3MF without project settings into the current project."), + "import_names_3mf_show_dialog")); + g_sizer->Add(create_item_checkbox(_L("Keep original names"), + _L("Use the body names stored in the imported file when it contains them."), "import_names_3mf_keep")); auto item_gcodes_warning = create_item_checkbox(_L("Don't warn when loading 3MF with modified G-code"), "", "no_warn_when_modified_gcodes"); g_sizer->Add(item_gcodes_warning); //// FILES > STEP import g_sizer->Add(create_item_title(_L("STEP import")), 1, wxEXPAND); auto item_step_dialog = create_item_checkbox( - _L("Show options when importing STEP file"), _L("If enabled, a parameter settings dialog will appear during STEP file import."), + _L("Show options when importing"), _L("If enabled, a parameter settings dialog will appear during STEP file import."), "enable_step_mesh_setting", wxEmptyString, "import_export#dont-show-again" ); g_sizer->Add(item_step_dialog); @@ -1847,8 +1858,19 @@ void PreferencesDialog::create_items() auto item_step_angle = create_item_decimal_input(_L("Angle deflection"), "", _L("Angle deflection used when meshing imported STEP files.\nSmaller values produce higher-quality meshes but increase processing time.\nUsed as the default in the import dialog, or directly when the import dialog is disabled.\nDefault: 0.5."), "angle_deflection", 0.01, 1.0, 2); g_sizer->Add(item_step_angle); - auto item_step_split = create_item_checkbox(_L("Split compound and compsolid into multiple objects"), _L("If enabled, compound and compsolid shapes in imported STEP files are split into multiple objects.\nUsed as the default in the import dialog, or directly when the import dialog is disabled.\nDefault: disabled."), "is_split_compound"); + auto item_step_split = create_item_checkbox(_L("Split into multiple objects"), _L("If enabled, compound and compsolid shapes in imported STEP files are split into multiple objects.\nUsed as the default in the import dialog, or directly when the import dialog is disabled.\nDefault: enabled."), "is_split_compound"); g_sizer->Add(item_step_split); + + g_sizer->Add(create_item_checkbox(_L("Keep original names"), + _L("Use the body names stored in the imported file when it contains them."), "import_names_step_keep")); + + //// FILES > AMF import + g_sizer->Add(create_item_title(_L("AMF import")), 1, wxEXPAND); + g_sizer->Add(create_item_checkbox(_L("Show options when importing"), + _L("Show body grouping, original-name and sorting options when importing geometry into the current project."), + "import_names_amf_show_dialog")); + g_sizer->Add(create_item_checkbox(_L("Keep original names"), + _L("Use the body names stored in the imported file when it contains them."), "import_names_amf_keep")); //// FILES > DRC export g_sizer->Add(create_item_title(_L("DRC export")), 1, wxEXPAND); diff --git a/src/slic3r/GUI/StepMeshDialog.cpp b/src/slic3r/GUI/StepMeshDialog.cpp index ec7917a3d1..0841777a43 100644 --- a/src/slic3r/GUI/StepMeshDialog.cpp +++ b/src/slic3r/GUI/StepMeshDialog.cpp @@ -1,6 +1,7 @@ #include "StepMeshDialog.hpp" #include "libslic3r/Format/STEP.hpp" +#include "slic3r/GUI/GeometryImportDialog.hpp" #include "slic3r/GUI/GUI_Utils.hpp" #include "slic3r/GUI/Widgets/StateColor.hpp" #include "slic3r/GUI/Widgets/Label.hpp" @@ -14,6 +15,7 @@ #include #include #include +#include #include #include "GUI_App.hpp" #include "I18N.hpp" @@ -21,6 +23,7 @@ #include "Widgets/Button.hpp" #include "Widgets/TextInput.hpp" #include "Widgets/DialogButtons.hpp" +#include "Widgets/RadioGroup.hpp" #include "Widgets/RoundedRectangle.hpp" #include #include @@ -84,13 +87,14 @@ bool StepMeshDialog:: validate_number_range(const wxString& value, double min, d return (num >= min && num <= max); } -StepMeshDialog::StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double linear_init, double angle_init) +StepMeshDialog::StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double linear_init, double angle_init, + Slic3r::GUI::GeometryImportOptions* import_options) : DPIDialog(parent ? parent : static_cast(wxGetApp().mainframe), wxID_ANY, _(L("STEP file import parameters")), wxDefaultPosition, wxDefaultSize, - wxDEFAULT_DIALOG_STYLE /* | wxRESIZE_BORDER*/), m_file(file) + wxDEFAULT_DIALOG_STYLE /* | wxRESIZE_BORDER*/), m_import_options(import_options), m_file(file) { m_linear_last = wxString::Format("%.3f", linear_init); m_angle_last = wxString::Format("%.2f", angle_init); @@ -255,13 +259,38 @@ StepMeshDialog::StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double line bSizer->Add(angle_sizer, 0, wxEXPAND | wxLEFT | wxRIGHT, LEFT_RIGHT_PADING); - wxBoxSizer* check_sizer = new wxBoxSizer(wxHORIZONTAL); - m_split_compound_checkbox = new wxCheckBox(this, wxID_ANY, _L("Split compound and compsolid into multiple objects"), wxDefaultPosition, wxDefaultSize, 0); - m_split_compound_checkbox->SetFont(::Label::Body_14); - m_split_compound_checkbox->SetForegroundColour(StateColor::darkModeColorFor(FONT_COLOR)); - m_split_compound_checkbox->SetValue(wxGetApp().app_config->get_bool("is_split_compound")); - check_sizer->Add(m_split_compound_checkbox, 0, wxALIGN_LEFT); - bSizer->Add(check_sizer, 0, wxEXPAND | wxLEFT | wxRIGHT | wxTOP, LEFT_RIGHT_PADING); + // App-styled check boxes, the same as in the AMF and 3MF import dialogs. + m_split_compound_checkbox = add_import_checkbox(this, *bSizer, _L("Split compound and compsolid into multiple objects"), + wxGetApp().app_config->get_bool("is_split_compound"), wxLEFT | wxRIGHT | wxTOP, LEFT_RIGHT_PADING); + if (m_import_options != nullptr) { + m_split_compound_checkbox.SetToolTip(_L("Loads each body of a multi-body part separately. Needed to keep the bodies' original names.")); + m_split_compound_checkbox.SetValue(m_import_options->split_compound); + m_load_mode = new RadioGroup(this, {_L("Load as an assembly"), _L("Load as a single object (can be split later)")}, wxVERTICAL); + m_load_mode->SetSelection(m_import_options->load_as_assembly ? 0 : 1); + m_load_mode->SetRadioTooltip(1, _L("The original bodies and names are kept inside the object. Use Split to parts to show them as separate parts.")); + bSizer->Add(m_load_mode, 0, wxLEFT | wxRIGHT | wxTOP, LEFT_RIGHT_PADING); + m_keep_names_checkbox = add_import_checkbox(this, *bSizer, _L("Keep original names"), m_import_options->keep_names, + wxLEFT | wxRIGHT | wxTOP, LEFT_RIGHT_PADING); + m_keep_names_checkbox.SetToolTip(_L("Use the body names stored in the file, when there are any. Needs Split compound for parts with several bodies.")); + m_sort_names_checkbox = add_import_checkbox(this, *bSizer, _L("Sort parts by name"), m_import_options->sort_names, + wxLEFT | wxRIGHT | wxTOP, LEFT_RIGHT_PADING); + m_sort_names_checkbox.SetToolTip(_L("Sort the parts inside each imported assembly in the object list. This does not change the order used for slicing. Available when Keep original names is on.")); + // The dialog opens with the remembered values; only the user's clicks move the linked option. + m_keep_names_checkbox.box->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent& e) { + // Body names of a multi-body part exist only after splitting it. + if (m_keep_names_checkbox.GetValue()) + m_split_compound_checkbox.SetValue(true); + e.Skip(); + }); + m_split_compound_checkbox.box->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent& e) { + if (!m_split_compound_checkbox.GetValue() && m_keep_names_checkbox.GetValue()) { + m_keep_names_checkbox.SetValue(false); + m_sort_names_checkbox.Enable(false); + } + e.Skip(); + }); + Slic3r::GUI::link_sort_to_keep(m_keep_names_checkbox, m_sort_names_checkbox); + } wxBoxSizer* mesh_face_number_sizer = new wxBoxSizer(wxHORIZONTAL); wxStaticText *mesh_face_number_title = new wxStaticText(this, wxID_ANY, _L("Number of triangular facets") + ": "); @@ -276,20 +305,16 @@ StepMeshDialog::StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double line bSizer->AddSpacer(FromDIP(10)); - wxBoxSizer* save_default_sizer = new wxBoxSizer(wxHORIZONTAL); - m_save_default_checkbox = new wxCheckBox(this, wxID_ANY, _L("Save these settings as default"), wxDefaultPosition, wxDefaultSize, 0); - m_save_default_checkbox->SetFont(::Label::Body_14); - m_save_default_checkbox->SetForegroundColour(StateColor::darkModeColorFor(FONT_COLOR)); - m_save_default_checkbox->SetToolTip(_L("If enabled, the values above are stored as the defaults used for future STEP imports (and shown in Preferences).")); - save_default_sizer->Add(m_save_default_checkbox, 0, wxALIGN_LEFT); - bSizer->Add(save_default_sizer, 0, wxEXPAND | wxLEFT | wxRIGHT, LEFT_RIGHT_PADING); + m_save_default_checkbox = add_import_checkbox(this, *bSizer, + m_import_options ? _L("Remember my choice") : _L("Save these settings as default"), false, wxLEFT | wxRIGHT, LEFT_RIGHT_PADING); + m_save_default_checkbox.SetToolTip(_L("If enabled, the values above are stored as the defaults used for future STEP imports (and shown in Preferences).")); bSizer->AddSpacer(FromDIP(10)); - m_checkbox = new wxCheckBox(this, wxID_ANY, _L("Don't show again"), wxDefaultPosition, wxDefaultSize, 0); - m_checkbox->SetFont(::Label::Body_14); - m_checkbox->SetForegroundColour(StateColor::darkModeColorFor(FONT_COLOR)); - bSizer->Add(m_checkbox, 0, wxLEFT, LEFT_RIGHT_PADING); + m_checkbox = add_import_checkbox(this, *bSizer, + m_import_options ? _L("Don't ask again") : _L("Don't show again"), false, wxLEFT, LEFT_RIGHT_PADING); + if (m_import_options != nullptr) + m_checkbox.SetToolTip(_L("Save these choices and apply them without asking next time. You can show this dialog again in Preferences.")); wxBoxSizer* bSizer_button = new wxBoxSizer(wxHORIZONTAL); @@ -312,13 +337,26 @@ StepMeshDialog::StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double line stop_task(); if (validate_number_range(angle_input->GetTextCtrl()->GetValue(), 0.01, 1) && validate_number_range(linear_input->GetTextCtrl()->GetValue(), 0.001, 0.1)) { - if (m_checkbox->IsChecked()) { - wxGetApp().app_config->set_bool("enable_step_mesh_setting", false); - } - if (m_save_default_checkbox->IsChecked()) { - wxGetApp().app_config->set_bool("is_split_compound", m_split_compound_checkbox->GetValue()); - wxGetApp().app_config->set("linear_deflection", float_to_string_decimal_point(get_linear_deflection(), 3)); - wxGetApp().app_config->set("angle_deflection", float_to_string_decimal_point(get_angle_deflection(), 2)); + if (m_import_options != nullptr) { + // The callback uses these values now; AppConfig is updated only after batch success. + m_import_options->keep_names = m_keep_names_checkbox.GetValue(); + m_import_options->split_compound = m_split_compound_checkbox.GetValue(); + m_import_options->sort_names = m_sort_names_checkbox.GetValue(); + m_import_options->load_as_assembly = m_load_mode->GetSelection() == 0; + m_import_options->remember = m_save_default_checkbox.GetValue(); + m_import_options->dont_ask = m_checkbox.GetValue(); + m_import_options->linear_deflection = get_linear_deflection(); + m_import_options->angle_deflection = get_angle_deflection(); + m_import_options->chosen = true; + } else { + if (m_checkbox.GetValue()) { + wxGetApp().app_config->set_bool("enable_step_mesh_setting", false); + } + if (m_save_default_checkbox.GetValue()) { + wxGetApp().app_config->set_bool("is_split_compound", m_split_compound_checkbox.GetValue()); + wxGetApp().app_config->set("linear_deflection", float_to_string_decimal_point(get_linear_deflection(), 3)); + wxGetApp().app_config->set("angle_deflection", float_to_string_decimal_point(get_angle_deflection(), 2)); + } } EndModal(wxID_OK); @@ -336,6 +374,8 @@ StepMeshDialog::StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double line this->SetSizerAndFit(bSizer); update_mesh_number_text(); this->Layout(); + // DPIDialog centres itself before the sizer sets the final size. + CenterOnParent(); this->Bind(wxEVT_LEFT_DOWN, [this](auto& e) { SetFocusIgnoringChildren(); @@ -404,4 +444,4 @@ void StepMeshDialog::update_mesh_number_text() } })); } -} \ No newline at end of file +} diff --git a/src/slic3r/GUI/StepMeshDialog.hpp b/src/slic3r/GUI/StepMeshDialog.hpp index 34673d1561..ce5b95f022 100644 --- a/src/slic3r/GUI/StepMeshDialog.hpp +++ b/src/slic3r/GUI/StepMeshDialog.hpp @@ -7,12 +7,15 @@ #include "GUI_Utils.hpp" #include "libslic3r/Format/STEP.hpp" #include "Widgets/Button.hpp" +#include "GeometryImportDialog.hpp" class Button; +class RadioGroup; class StepMeshDialog : public Slic3r::GUI::DPIDialog { public: - StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double linear_init, double angle_init); + StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double linear_init, double angle_init, + Slic3r::GUI::GeometryImportOptions* import_options = nullptr); ~StepMeshDialog() override; void on_dpi_changed(const wxRect& suggested_rect) override; inline double get_linear_deflection() { @@ -32,13 +35,19 @@ public: } } inline bool get_split_compound_value() { - return m_split_compound_checkbox->GetValue(); + return m_split_compound_checkbox.GetValue(); } private: + // A non-null context defers all preference writes until the whole import is ready. + Slic3r::GUI::GeometryImportOptions* m_import_options = nullptr; + Slic3r::GUI::ImportCheckBox m_keep_names_checkbox; + Slic3r::GUI::ImportCheckBox m_sort_names_checkbox; + // Item 0 loads as an assembly, item 1 as a single object. + RadioGroup* m_load_mode = nullptr; Slic3r::Step& m_file; - wxCheckBox* m_checkbox = nullptr; - wxCheckBox* m_split_compound_checkbox = nullptr; - wxCheckBox* m_save_default_checkbox = nullptr; + Slic3r::GUI::ImportCheckBox m_checkbox; + Slic3r::GUI::ImportCheckBox m_split_compound_checkbox; + Slic3r::GUI::ImportCheckBox m_save_default_checkbox; wxString m_linear_last; wxString m_angle_last; wxStaticText* mesh_face_number_text; @@ -52,4 +61,4 @@ private: void stop_task(); }; -#endif // _STEP_MESH_DIALOG_H_ \ No newline at end of file +#endif // _STEP_MESH_DIALOG_H_ diff --git a/tests/data/named_compound_bodies.step b/tests/data/named_compound_bodies.step new file mode 100644 index 0000000000..6a05345b33 --- /dev/null +++ b/tests/data/named_compound_bodies.step @@ -0,0 +1,124 @@ +ISO-10303-21; +HEADER; +FILE_DESCRIPTION(('Named tetrahedra for body identity regression'),'2;1'); +FILE_NAME('named_compound_bodies','2026-10-27T00:00:00',(''),(''),'','',''); +FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }')); +ENDSEC; +DATA; +#1=APPLICATION_CONTEXT('automotive design'); +#2=APPLICATION_PROTOCOL_DEFINITION('international standard','automotive_design',2000,#1); +#3=PRODUCT_CONTEXT('',#1,'mechanical'); +#4=PRODUCT('Body collection','Body collection','',(#3)); +#5=PRODUCT_DEFINITION_FORMATION('','',#4); +#6=PRODUCT_DEFINITION_CONTEXT('part definition',#1,'design'); +#7=PRODUCT_DEFINITION('design','',#5,#6); +#8=PRODUCT_DEFINITION_SHAPE('','',#7); +#9=SHAPE_DEFINITION_REPRESENTATION(#8,#20); +#13=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.)); +#14=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.)); +#15=(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT()); +#16=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(0.001),#13,'distance_accuracy_value',''); +#17=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#16))GLOBAL_UNIT_ASSIGNED_CONTEXT((#13,#14,#15))REPRESENTATION_CONTEXT('','')); +#21=AXIS2_PLACEMENT_3D('',#30,#40,#41); +#20=FACETED_BREP_SHAPE_REPRESENTATION('',(#21,#22,#1022,#2022),#17); +#22=FACETED_BREP('Part10',#23); +#23=CLOSED_SHELL('',(#50,#51,#52,#53)); +#30=CARTESIAN_POINT('',(0.0,0.,0.)); +#31=CARTESIAN_POINT('',(10.0,0.,0.)); +#32=CARTESIAN_POINT('',(0.0,10.,0.)); +#33=CARTESIAN_POINT('',(0.0,0.,10.)); +#40=DIRECTION('',(0.,0.,1.)); +#41=DIRECTION('',(1.,0.,0.)); +#42=DIRECTION('',(0.,0.,-1.)); +#43=DIRECTION('',(0.,-1.,0.)); +#44=DIRECTION('',(-1.,0.,0.)); +#45=DIRECTION('',(0.577350269189626,0.577350269189626,0.577350269189626)); +#46=DIRECTION('',(0.,0.,1.)); +#50=FACE_SURFACE('',(#60),#70,.T.); +#51=FACE_SURFACE('',(#61),#71,.T.); +#52=FACE_SURFACE('',(#62),#72,.T.); +#53=FACE_SURFACE('',(#63),#73,.T.); +#60=FACE_OUTER_BOUND('',#80,.T.); +#61=FACE_OUTER_BOUND('',#81,.T.); +#62=FACE_OUTER_BOUND('',#82,.T.); +#63=FACE_OUTER_BOUND('',#83,.T.); +#70=PLANE('',#90); +#71=PLANE('',#91); +#72=PLANE('',#92); +#73=PLANE('',#93); +#80=POLY_LOOP('',(#30,#32,#31)); +#81=POLY_LOOP('',(#30,#31,#33)); +#82=POLY_LOOP('',(#30,#33,#32)); +#83=POLY_LOOP('',(#31,#32,#33)); +#90=AXIS2_PLACEMENT_3D('',#30,#42,#41); +#91=AXIS2_PLACEMENT_3D('',#30,#43,#41); +#92=AXIS2_PLACEMENT_3D('',#30,#44,#46); +#93=AXIS2_PLACEMENT_3D('',#31,#45,$); +#1022=FACETED_BREP('Part2',#1023); +#1023=CLOSED_SHELL('',(#1050,#1051,#1052,#1053)); +#1030=CARTESIAN_POINT('',(25.0,0.,0.)); +#1031=CARTESIAN_POINT('',(35.0,0.,0.)); +#1032=CARTESIAN_POINT('',(25.0,10.,0.)); +#1033=CARTESIAN_POINT('',(25.0,0.,10.)); +#1040=DIRECTION('',(0.,0.,1.)); +#1041=DIRECTION('',(1.,0.,0.)); +#1042=DIRECTION('',(0.,0.,-1.)); +#1043=DIRECTION('',(0.,-1.,0.)); +#1044=DIRECTION('',(-1.,0.,0.)); +#1045=DIRECTION('',(0.577350269189626,0.577350269189626,0.577350269189626)); +#1046=DIRECTION('',(0.,0.,1.)); +#1050=FACE_SURFACE('',(#1060),#1070,.T.); +#1051=FACE_SURFACE('',(#1061),#1071,.T.); +#1052=FACE_SURFACE('',(#1062),#1072,.T.); +#1053=FACE_SURFACE('',(#1063),#1073,.T.); +#1060=FACE_OUTER_BOUND('',#1080,.T.); +#1061=FACE_OUTER_BOUND('',#1081,.T.); +#1062=FACE_OUTER_BOUND('',#1082,.T.); +#1063=FACE_OUTER_BOUND('',#1083,.T.); +#1070=PLANE('',#1090); +#1071=PLANE('',#1091); +#1072=PLANE('',#1092); +#1073=PLANE('',#1093); +#1080=POLY_LOOP('',(#1030,#1032,#1031)); +#1081=POLY_LOOP('',(#1030,#1031,#1033)); +#1082=POLY_LOOP('',(#1030,#1033,#1032)); +#1083=POLY_LOOP('',(#1031,#1032,#1033)); +#1090=AXIS2_PLACEMENT_3D('',#1030,#1042,#1041); +#1091=AXIS2_PLACEMENT_3D('',#1030,#1043,#1041); +#1092=AXIS2_PLACEMENT_3D('',#1030,#1044,#1046); +#1093=AXIS2_PLACEMENT_3D('',#1031,#1045,$); +#2022=FACETED_BREP('\X2\04220435043B043E\X0\ & shell',#2023); +#2023=CLOSED_SHELL('',(#2050,#2051,#2052,#2053)); +#2030=CARTESIAN_POINT('',(50.0,0.,0.)); +#2031=CARTESIAN_POINT('',(60.0,0.,0.)); +#2032=CARTESIAN_POINT('',(50.0,10.,0.)); +#2033=CARTESIAN_POINT('',(50.0,0.,10.)); +#2040=DIRECTION('',(0.,0.,1.)); +#2041=DIRECTION('',(1.,0.,0.)); +#2042=DIRECTION('',(0.,0.,-1.)); +#2043=DIRECTION('',(0.,-1.,0.)); +#2044=DIRECTION('',(-1.,0.,0.)); +#2045=DIRECTION('',(0.577350269189626,0.577350269189626,0.577350269189626)); +#2046=DIRECTION('',(0.,0.,1.)); +#2050=FACE_SURFACE('',(#2060),#2070,.T.); +#2051=FACE_SURFACE('',(#2061),#2071,.T.); +#2052=FACE_SURFACE('',(#2062),#2072,.T.); +#2053=FACE_SURFACE('',(#2063),#2073,.T.); +#2060=FACE_OUTER_BOUND('',#2080,.T.); +#2061=FACE_OUTER_BOUND('',#2081,.T.); +#2062=FACE_OUTER_BOUND('',#2082,.T.); +#2063=FACE_OUTER_BOUND('',#2083,.T.); +#2070=PLANE('',#2090); +#2071=PLANE('',#2091); +#2072=PLANE('',#2092); +#2073=PLANE('',#2093); +#2080=POLY_LOOP('',(#2030,#2032,#2031)); +#2081=POLY_LOOP('',(#2030,#2031,#2033)); +#2082=POLY_LOOP('',(#2030,#2033,#2032)); +#2083=POLY_LOOP('',(#2031,#2032,#2033)); +#2090=AXIS2_PLACEMENT_3D('',#2030,#2042,#2041); +#2091=AXIS2_PLACEMENT_3D('',#2030,#2043,#2041); +#2092=AXIS2_PLACEMENT_3D('',#2030,#2044,#2046); +#2093=AXIS2_PLACEMENT_3D('',#2031,#2045,$); +ENDSEC; +END-ISO-10303-21; diff --git a/tests/data/named_single_body.step b/tests/data/named_single_body.step new file mode 100644 index 0000000000..f1a0ff78bb --- /dev/null +++ b/tests/data/named_single_body.step @@ -0,0 +1,58 @@ +ISO-10303-21; +HEADER; +FILE_DESCRIPTION(('Named tetrahedra for body identity regression'),'2;1'); +FILE_NAME('named_single_body','2026-10-27T00:00:00',(''),(''),'','',''); +FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }')); +ENDSEC; +DATA; +#1=APPLICATION_CONTEXT('automotive design'); +#2=APPLICATION_PROTOCOL_DEFINITION('international standard','automotive_design',2000,#1); +#3=PRODUCT_CONTEXT('',#1,'mechanical'); +#4=PRODUCT('Body collection','Body collection','',(#3)); +#5=PRODUCT_DEFINITION_FORMATION('','',#4); +#6=PRODUCT_DEFINITION_CONTEXT('part definition',#1,'design'); +#7=PRODUCT_DEFINITION('design','',#5,#6); +#8=PRODUCT_DEFINITION_SHAPE('','',#7); +#9=SHAPE_DEFINITION_REPRESENTATION(#8,#20); +#13=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.)); +#14=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.)); +#15=(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT()); +#16=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(0.001),#13,'distance_accuracy_value',''); +#17=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#16))GLOBAL_UNIT_ASSIGNED_CONTEXT((#13,#14,#15))REPRESENTATION_CONTEXT('','')); +#21=AXIS2_PLACEMENT_3D('',#30,#40,#41); +#20=FACETED_BREP_SHAPE_REPRESENTATION('',(#21,#22),#17); +#22=FACETED_BREP('Body name',#23); +#23=CLOSED_SHELL('',(#50,#51,#52,#53)); +#30=CARTESIAN_POINT('',(0.0,0.,0.)); +#31=CARTESIAN_POINT('',(10.0,0.,0.)); +#32=CARTESIAN_POINT('',(0.0,10.,0.)); +#33=CARTESIAN_POINT('',(0.0,0.,10.)); +#40=DIRECTION('',(0.,0.,1.)); +#41=DIRECTION('',(1.,0.,0.)); +#42=DIRECTION('',(0.,0.,-1.)); +#43=DIRECTION('',(0.,-1.,0.)); +#44=DIRECTION('',(-1.,0.,0.)); +#45=DIRECTION('',(0.577350269189626,0.577350269189626,0.577350269189626)); +#46=DIRECTION('',(0.,0.,1.)); +#50=FACE_SURFACE('',(#60),#70,.T.); +#51=FACE_SURFACE('',(#61),#71,.T.); +#52=FACE_SURFACE('',(#62),#72,.T.); +#53=FACE_SURFACE('',(#63),#73,.T.); +#60=FACE_OUTER_BOUND('',#80,.T.); +#61=FACE_OUTER_BOUND('',#81,.T.); +#62=FACE_OUTER_BOUND('',#82,.T.); +#63=FACE_OUTER_BOUND('',#83,.T.); +#70=PLANE('',#90); +#71=PLANE('',#91); +#72=PLANE('',#92); +#73=PLANE('',#93); +#80=POLY_LOOP('',(#30,#32,#31)); +#81=POLY_LOOP('',(#30,#31,#33)); +#82=POLY_LOOP('',(#30,#33,#32)); +#83=POLY_LOOP('',(#31,#32,#33)); +#90=AXIS2_PLACEMENT_3D('',#30,#42,#41); +#91=AXIS2_PLACEMENT_3D('',#30,#43,#41); +#92=AXIS2_PLACEMENT_3D('',#30,#44,#46); +#93=AXIS2_PLACEMENT_3D('',#31,#45,$); +ENDSEC; +END-ISO-10303-21; diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index 2925c0dbef..a95b476341 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -8,6 +8,8 @@ add_executable(${_TEST_NAME}_tests ${_TEST_NAME}_tests.cpp test_3mf.cpp test_amf.cpp + # Import naming policy is independent of the GUI and slicing pipeline. + test_import_names.cpp # Round-trip seam metadata and active/dormant volume settings in both formats. test_precise_seam_3mf.cpp # Pure perimeter extraction is independent of Print/Layer fixtures. diff --git a/tests/libslic3r/test_3mf.cpp b/tests/libslic3r/test_3mf.cpp index c37e5e1d36..fedda45f64 100644 --- a/tests/libslic3r/test_3mf.cpp +++ b/tests/libslic3r/test_3mf.cpp @@ -9,6 +9,7 @@ #include "libslic3r/Model.hpp" #include "libslic3r/Format/3mf.hpp" #include "libslic3r/Format/bbs_3mf.hpp" +#include "libslic3r/Format/ProjectStrategy.hpp" #include "libslic3r/GCode/ThumbnailData.hpp" #include "libslic3r/Format/STL.hpp" #include "libslic3r/Utils.hpp" @@ -111,6 +112,128 @@ namespace Catch { using namespace Slic3r; +namespace { + +// A plain CAD archive exercises core object names without exporter-generated part metadata. +void write_named_cad_3mf(const std::string &path, bool project_part_names, bool leaf_names = true) +{ + std::string model = R"xml( + + + + + + + + + + + + + + + +)xml"; + if (!leaf_names) + for (const std::string label : {" name=\"Leaf2\"", " name=\"Leaf10\""}) + model.erase(model.find(label), label.size()); + Zipper archive(path); + archive.add_entry("[Content_Types].xml"); + archive << R"xml()xml"; + archive.add_entry("_rels/.rels"); + archive << R"xml()xml"; + archive.add_entry("3D/3dmodel.model", model.data(), model.size()); + if (project_part_names) { + // Conflicting names prove that project metadata takes priority over core mesh labels. + archive.add_entry("Metadata/model_settings.config"); + archive << R"xml( + + + +)xml"; + } + archive.finalize(); +} + +bool load_named_cad_3mf(const std::string &path, Model &model, LoadStrategy options) +{ + DynamicPrintConfig config; + ConfigSubstitutionContext substitutions(ForwardCompatibilitySubstitutionRule::Enable); + PlateDataPtrs plates; + std::vector presets; + bool is_bambu = false; + bool is_orca = false; + Semver version; + const bool loaded = load_bbs_3mf(path.c_str(), &config, &substitutions, &model, &plates, + &presets, &is_bambu, &is_orca, &version, nullptr, options); + release_PlateData_list(plates); + for (Preset *preset : presets) + delete preset; + return loaded; +} + +} // namespace + +TEST_CASE("CAD 3MF imports leaf names only when original names are enabled", "[3mf][OriginalNames]") +{ + const bool keep_names = GENERATE(false, true); + ScopedSlic3rTemporaryDir temporary_dir("orca_cad_names"); + ScopedTemporaryFile file(".3mf"); + write_named_cad_3mf(file.string(), false); + LoadStrategy options = LoadStrategy::LoadModel | LoadStrategy::AssembleParts; + if (keep_names) + options = options | LoadStrategy::KeepOriginalNames; + Model model; + REQUIRE(load_named_cad_3mf(file.string(), model, options)); + REQUIRE(model.objects.size() == 1); + CHECK(model.objects.front()->name == "Assembly"); + const auto &parts = model.objects.front()->volumes; + REQUIRE(parts.size() == 2); + CHECK(parts[0]->name == (keep_names ? "Leaf2" : "Assembly")); + CHECK(parts[1]->name == (keep_names ? "Leaf10" : "Assembly_2")); + // Different shapes and offsets prove name-to-geometry correspondence, not just a name set. + TriangleMesh first(parts[0]->mesh()); + TriangleMesh second(parts[1]->mesh()); + first.transform(parts[0]->get_matrix()); + second.transform(parts[1]->get_matrix()); + CHECK_THAT(first.bounding_box().size().x(), Catch::Matchers::WithinAbs(1.0, 1e-6)); + CHECK_THAT(second.bounding_box().size().x(), Catch::Matchers::WithinAbs(2.0, 1e-6)); + CHECK_THAT(second.bounding_box().min.x() - first.bounding_box().min.x(), Catch::Matchers::WithinAbs(10.0, 1e-6)); + CHECK_THAT(second.bounding_box().min.z() - first.bounding_box().min.z(), Catch::Matchers::WithinAbs(5.0, 1e-6)); +} + +TEST_CASE("A CAD 3MF without part labels keeps Orca's part names", "[3mf][OriginalNames]") +{ + ScopedSlic3rTemporaryDir temporary_dir("orca_cad_unnamed"); + ScopedTemporaryFile file(".3mf"); + write_named_cad_3mf(file.string(), false, false); + Model model; + REQUIRE(load_named_cad_3mf(file.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 2); + CHECK(model.objects.front()->volumes[0]->name == "Assembly"); + CHECK(model.objects.front()->volumes[1]->name == "Assembly_2"); +} + +TEST_CASE("3MF project part names take priority over CAD mesh names", "[3mf][OriginalNames]") +{ + const bool keep_names = GENERATE(false, true); + ScopedSlic3rTemporaryDir temporary_dir("orca_project_names"); + ScopedTemporaryFile file(".3mf"); + write_named_cad_3mf(file.string(), true); + LoadStrategy options = LoadStrategy::LoadModel; + if (keep_names) + options = options | LoadStrategy::KeepOriginalNames; + Model model; + REQUIRE(load_named_cad_3mf(file.string(), model, options)); + REQUIRE(model.objects.size() == 1); + CHECK(model.objects.front()->name == "ProjectAssembly"); + REQUIRE(model.objects.front()->volumes.size() == 2); + CHECK(model.objects.front()->volumes[0]->name == "UserPartA"); + CHECK(model.objects.front()->volumes[1]->name == "UserPartB"); +} + SCENARIO("Reading 3mf file", "[3mf]") { GIVEN("umlauts in the path of the file") { @@ -485,6 +608,46 @@ static bool load_project(const std::string& path, Model& model, const ScopedTemp return loaded; } +TEST_CASE("A single imported object retains hidden named bodies through cloning and project reload", "[3mf][OriginalNames]") +{ + const bool hidden = GENERATE(false, true); + ScopedSlic3rTemporaryDir temporary_dir("orca_hidden_parts"); + ScopedTemporaryDir backup_dir("orca_hidden_parts_reload"); + ScopedTemporaryFile file(".3mf"); + Model source; + ModelObject *object = source.add_object(); + object->name = "Assembly"; + object->add_volume(make_cube(1., 1., 1.))->name = "FirstBody"; + object->add_volume(make_cube(2., 2., 2.))->name = "SecondBody"; + object->add_instance(); + object->imported_parts_hidden = hidden; + + // Cloning must preserve the wrapper without collapsing its underlying independent bodies. + Model cloned(source); + REQUIRE(cloned.objects.size() == 1); + CHECK(cloned.objects.front()->imported_parts_hidden == hidden); + REQUIRE(cloned.objects.front()->volumes.size() == 2); + CHECK(cloned.objects.front()->volumes[0]->name == "FirstBody"); + CHECK(cloned.objects.front()->volumes[1]->name == "SecondBody"); + store_project(cloned, file.string(), SaveStrategy::Zip64 | SaveStrategy::Silence); + bool metadata_present = false; + rewrite_3mf_entries(file.string(), [&](std::string &name, std::string &data) { + if (boost::algorithm::ends_with(name, "model_settings.config")) + metadata_present = data.find("orca:imported_parts_hidden") != std::string::npos; + return false; + }); + CHECK(metadata_present == hidden); + + Model restored; + REQUIRE(load_project(file.string(), restored, backup_dir)); + REQUIRE(restored.objects.size() == 1); + CHECK(restored.objects.front()->imported_parts_hidden == hidden); + CHECK_FALSE(restored.objects.front()->config.has("orca:imported_parts_hidden")); + REQUIRE(restored.objects.front()->volumes.size() == 2); + CHECK(restored.objects.front()->volumes[0]->name == "FirstBody"); + CHECK(restored.objects.front()->volumes[1]->name == "SecondBody"); +} + TEST_CASE("A plate's G-code statistics are stored next to its G-code", "[3mf]") { const bool with_statistics = GENERATE(false, true); diff --git a/tests/libslic3r/test_amf.cpp b/tests/libslic3r/test_amf.cpp index eea678fc4a..f8b416894f 100644 --- a/tests/libslic3r/test_amf.cpp +++ b/tests/libslic3r/test_amf.cpp @@ -1,16 +1,28 @@ #include +#include +#include +#include +#include #include "libslic3r/Config.hpp" +#include "libslic3r/BoundingBox.hpp" #include "libslic3r/Format/AMF.hpp" +#include "libslic3r/Format/ProjectStrategy.hpp" #include "libslic3r/Model.hpp" #include "libslic3r/PrintConfig.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/libslic3r.h" #include "test_utils.hpp" #include +#include +#include +#include #include #include +#include using namespace Slic3r; @@ -78,3 +90,554 @@ TEST_CASE("An AMF object metadata element with no type attribute is rejected", " CHECK_FALSE(load(tmp.string(), model)); } } + +namespace { + +// Reuse the tetrahedron fixture, giving object and volume deliberately different names. +std::string named_amf_object(int id, const std::string &object_name, const std::string &volume_name) +{ + std::string xml = amf_with_object_metadata("" + object_name + ""); + const size_t begin = xml.find(" ", begin) + std::string(" ").size() - begin); + const std::string id_attribute = "id=\"0\""; + xml.replace(xml.find(id_attribute), id_attribute.size(), "id=\"" + std::to_string(id) + "\""); + xml.insert(xml.find("") + std::string("").size(), + "" + volume_name + ""); + return xml; +} + +bool load_amf_with_options(const std::string &path, Model &model, LoadStrategy options) +{ + DynamicPrintConfig config; + ConfigSubstitutionContext substitutions(ForwardCompatibilitySubstitutionRule::Disable); + return load_amf(path.c_str(), &config, &substitutions, &model, nullptr, options); +} + +// Read the part's actual geometry in assembly coordinates, including importer centering. +BoundingBoxf3 amf_part_bounds(const ModelVolume &volume) +{ + TriangleMesh mesh(volume.mesh()); + mesh.transform(volume.get_matrix()); + return mesh.bounding_box(); +} + +} // namespace + +TEST_CASE("AMF assembly parts retain their volume names and instance transforms", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + "" + "" + "1052" + ""); + + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + const auto &parts = model.objects.front()->volumes; + REQUIRE(parts.size() == 2); + CHECK(parts[0]->name == "LeafA"); + CHECK(parts[1]->name == "LeafB"); + const BoundingBoxf3 first = amf_part_bounds(*parts[0]); + const BoundingBoxf3 second = amf_part_bounds(*parts[1]); + CHECK_THAT(first.min.x(), Catch::Matchers::WithinAbs(0.0, 1e-6)); + CHECK_THAT(first.min.z(), Catch::Matchers::WithinAbs(0.0, 1e-6)); + CHECK_THAT(second.min.x(), Catch::Matchers::WithinAbs(10.0, 1e-6)); + CHECK_THAT(second.min.z(), Catch::Matchers::WithinAbs(5.0, 1e-6)); + CHECK_THAT(second.size().x(), Catch::Matchers::WithinAbs(2.0, 1e-6)); + CHECK_THAT(second.size().z(), Catch::Matchers::WithinAbs(2.0, 1e-6)); +} + +TEST_CASE("AMF constellations preserve separate groups and repeated object occurrences", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + // The same definition is referenced twice in one group and again in another. + write_file(tmp.string(), "" + + named_amf_object(1, "SharedParent", "SharedLeaf") + named_amf_object(2, "Standalone", "Alone") + + "" + "10" + "30" + ""); + + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 3); + size_t repeated_groups = 0; + size_t distant_groups = 0; + size_t standalone_objects = 0; + for (const ModelObject *object : model.objects) { + if (object->name == "Standalone") { + ++standalone_objects; + REQUIRE(object->volumes.size() == 1); + CHECK(object->volumes.front()->name == "Alone"); + } else if (object->volumes.size() == 2) { + ++repeated_groups; + CHECK(object->volumes[0]->name == "SharedLeaf"); + CHECK(object->volumes[1]->name == "SharedLeaf"); + CHECK_THAT(amf_part_bounds(*object->volumes[1]).min.x() - + amf_part_bounds(*object->volumes[0]).min.x(), Catch::Matchers::WithinAbs(10.0, 1e-6)); + } else { + ++distant_groups; + REQUIRE(object->volumes.size() == 1); + CHECK(object->volumes.front()->name == "SharedLeaf"); + REQUIRE(object->instances.size() == 1); + CHECK_THAT(object->instance_bounding_box(0).min.x(), Catch::Matchers::WithinAbs(30.0, 1e-6)); + } + } + CHECK(repeated_groups == 1); + CHECK(distant_groups == 1); + CHECK(standalone_objects == 1); +} + +TEST_CASE("AMF assembly structure is independent of original name selection", "[AMF][OriginalNames]") +{ + const bool keep_names = GENERATE(false, true); + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + ""); + LoadStrategy options = LoadStrategy::LoadModel | LoadStrategy::AssembleParts; + if (keep_names) + options = options | LoadStrategy::KeepOriginalNames; + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, options)); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 2); + CHECK(model.objects.front()->volumes[0]->name == (keep_names ? "LeafA" : "ParentA")); + CHECK(model.objects.front()->volumes[1]->name == (keep_names ? "LeafB" : "ParentB")); +} + +TEST_CASE("AMF assemblies without placements are left for the GUI to centre on the bed", "[AMF][OriginalNames]") +{ + // CAD exporters list occurrences without deltas; the legacy loader then creates no instance either. + const bool merged = GENERATE(false, true); + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + "" + + std::string(merged ? "" : "") + ""); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + // Unreferenced object 2 of the single-occurrence case stays a separate object, as before. + REQUIRE(model.objects.size() == (merged ? 1 : 2)); + CHECK(model.objects.front()->volumes.size() == (merged ? 2 : 1)); + CHECK(model.objects.front()->instances.empty()); +} + +TEST_CASE("Unplaced excluded AMF assemblies keep their excluded instance", "[AMF][OriginalNames]") +{ + // Without an instance the GUI would add a printable one and print the excluded part. + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + "0" + "0"); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->instances.size() == 1); + CHECK_FALSE(model.objects.front()->instances.front()->printable); +} + +TEST_CASE("Multi-part detection compares unplaced AMF groups at zero height", "[AMF][OriginalNames]") +{ + // The GUI checks before it adds instances to unplaced objects, so they have no height on the bed yet; + // as before, they compare at zero and their mesh heights are ignored. + const bool placed = GENERATE(false, true); + const bool raised = GENERATE(false, true); + const std::string placement = placed ? "10" : ""; + // A placed object is raised by its placement; the GUI's centering moves the volumes, not the instance, so the rise stays. + const std::string raised_placement = placement + (placed && raised ? "10" : ""); + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + "" + placement + "" + "" + raised_placement + ""); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 2); + // An unplaced object can only be raised in its mesh. + if (raised && !placed) { + model.objects[1]->volumes.front()->translate(Vec3d(0., 0., 10.)); + model.objects[1]->invalidate_bounding_box(); + } + CHECK(model.looks_like_multipart_object() == (placed && raised)); + // The check must not place the objects; the GUI still centers unplaced ones later. + CHECK(model.objects[0]->instances.empty() == !placed); + CHECK(model.objects[1]->instances.empty() == !placed); +} + +TEST_CASE("Multi-part detection of mixed and centered unplaced AMF objects", "[AMF][OriginalNames]") +{ + // Either object comes first, so the result does not depend on which one sets the reference height. + const bool swapped = GENERATE(false, true); + const size_t first = swapped ? 1 : 0; + const size_t second = swapped ? 0 : 1; + // A placed object stands at its placement, and an unplaced one compares at zero, so they differ. + SECTION("mixed placement asks") { + const std::string unplaced = ""; + const std::string placed = "1010"; + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + "" + (swapped ? placed : unplaced) + "" + "" + (swapped ? unplaced : placed) + ""); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 2); + CHECK(model.looks_like_multipart_object()); + // The unplaced object comes from the first group unless swapped. + CHECK(model.objects[first]->instances.empty()); + CHECK(model.objects[second]->instances.size() == 1); + } + // The reviewer's case: unplaced objects of different heights after the GUI's rotation, which centers them. + SECTION("unplaced objects of different heights do not ask") { + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + ""); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, LoadStrategy::LoadModel | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 2); + model.objects[first]->volumes.front()->scale(Vec3d(1., 1., 4.)); + for (ModelObject *object : model.objects) { + object->invalidate_bounding_box(); + object->rotate(0., Axis::Z); + } + CHECK_FALSE(model.looks_like_multipart_object()); + CHECK(model.objects[0]->instances.empty()); + CHECK(model.objects[1]->instances.empty()); + } +} + +TEST_CASE("AMF assemblies with any placement keep their position from the file", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + "" + "10"); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->instances.size() == 1); + CHECK_THAT(model.objects.front()->instance_bounding_box(0).min.x(), Catch::Matchers::WithinAbs(0.0, 1e-6)); +} + +TEST_CASE("Legacy AMF loading keeps independent object definitions", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + ""); + Model model; + REQUIRE(load(tmp.string(), model)); + REQUIRE(model.objects.size() == 2); + CHECK(model.objects[0]->name == "ParentA"); + CHECK(model.objects[0]->volumes.front()->name == "LeafA"); + CHECK(model.objects[1]->name == "ParentB"); + CHECK(model.objects[1]->volumes.front()->name == "LeafB"); +} + +TEST_CASE("AMF mixed printable occurrences retain their individual printability", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + // Combining these occurrences into one printable instance would print an excluded part. + write_file(tmp.string(), "" + named_amf_object(1, "Parent", "Leaf") + + "" + "1" + "100" + ""); + + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 2); + size_t printable = 0; + size_t excluded = 0; + for (const ModelObject *object : model.objects) { + REQUIRE(object->volumes.size() == 1); + REQUIRE(object->instances.size() == 1); + CHECK(object->volumes.front()->name == "Leaf"); + const BoundingBoxf3 bounds = object->instance_bounding_box(0); + if (object->instances.front()->printable) { + ++printable; + CHECK_THAT(bounds.min.x(), Catch::Matchers::WithinAbs(0.0, 1e-6)); + } else { + ++excluded; + CHECK_THAT(bounds.min.x(), Catch::Matchers::WithinAbs(10.0, 1e-6)); + } + } + CHECK(printable == 1); + CHECK(excluded == 1); +} + +TEST_CASE("AMF constellations containing only excluded occurrences stay excluded", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + "" + "0" + "100" + ""); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 2); + REQUIRE(model.objects.front()->instances.size() == 1); + CHECK_FALSE(model.objects.front()->instances.front()->printable); +} + +TEST_CASE("AMF assembly import skips unresolved constellation references like the legacy loader", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + named_amf_object(1, "Parent", "Leaf") + + named_amf_object(2, "Other", "OtherLeaf") + + "" + "10"); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + CHECK(model.objects.front()->volumes.size() == 2); +} + +TEST_CASE("AMF assembly import rejects cyclic constellation references", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + named_amf_object(1, "Parent", "Leaf") + + "" + ""); + Model model; + CHECK_FALSE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); +} + +TEST_CASE("AMF nested constellations flatten into one assembly with composed placements", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + // Group 20 is placed twice inside group 10; its own occurrence offset adds to each placement. + write_file(tmp.string(), "" + + named_amf_object(1, "Base", "BaseBody") + named_amf_object(2, "Pin", "PinBody") + + "" + "10" + "20" + "5"); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + // The nested group is not an assembly of its own. + REQUIRE(model.objects.size() == 1); + const auto &parts = model.objects.front()->volumes; + REQUIRE(parts.size() == 3); + CHECK(parts[0]->name == "BaseBody"); + CHECK(parts[1]->name == "PinBody"); + CHECK(parts[2]->name == "PinBody"); + CHECK_THAT(amf_part_bounds(*parts[1]).min.x() - amf_part_bounds(*parts[0]).min.x(), Catch::Matchers::WithinAbs(10.0, 1e-6)); + CHECK_THAT(amf_part_bounds(*parts[2]).min.x() - amf_part_bounds(*parts[0]).min.x(), Catch::Matchers::WithinAbs(20.0, 1e-6)); + CHECK_THAT(amf_part_bounds(*parts[1]).min.z() - amf_part_bounds(*parts[0]).min.z(), Catch::Matchers::WithinAbs(5.0, 1e-6)); +} + +TEST_CASE("AMF nested placements apply the parent transform to the child placement", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + // The nested group is mirrored in X; the child's own +5 shift must be mirrored with it. + write_file(tmp.string(), "" + + named_amf_object(1, "Base", "BaseBody") + named_amf_object(2, "Pin", "PinBody") + + "" + "-1" + "5"); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 2); + // parent * child puts the pin at x in [-6, -5]; child * parent would give [4, 5]. + CHECK_THAT(amf_part_bounds(*model.objects.front()->volumes[1]).max.x() - + amf_part_bounds(*model.objects.front()->volumes[0]).min.x(), Catch::Matchers::WithinAbs(-5.0, 1e-6)); +} + +TEST_CASE("AMF nested printability multiplies into the top-level group", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "Base", "BaseBody") + named_amf_object(2, "Pin", "PinBody") + + "" + "0" + ""); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + // A non-printable nested occurrence makes the group mixed, so its bodies stay separate objects. + REQUIRE(model.objects.size() == 2); + CHECK(model.objects[0]->instances.front()->printable); + CHECK_FALSE(model.objects[1]->instances.front()->printable); +} + +TEST_CASE("AMF assembly import loads files with duplicate or object-like constellation ids", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + // Group 1 shares its id with object 1, and two groups share id 10: references still resolve to the object. + write_file(tmp.string(), "" + named_amf_object(1, "Parent", "Leaf") + + "" + "10" + "20"); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + // Each single-occurrence group stays one object with its own placement. + CHECK(model.objects.size() == 3); +} + +TEST_CASE("AMF nesting that only multiplies work or depth is rejected", "[AMF][OriginalNames]") +{ + const bool deep = GENERATE(false, true); + // The order of declaration must not let a deep chain slip past the cycle check. + const bool leaf_first = GENERATE(false, true); + CAPTURE(deep, leaf_first); + ScopedTemporaryFile tmp(".amf"); + // Doubling chain: every group references the next twice and the last one reaches no body. + // Deep chain: one reference per level, deeper than any real assembly. + const int levels = deep ? 400 : 30; + std::vector chain; + for (int level = 0; level < levels; ++level) { + const std::string next = level + 1 < levels ? std::to_string(1000 + level + 1) : std::string("999"); + chain.push_back("" + + (deep ? std::string() : "") + ""); + } + if (leaf_first) + std::reverse(chain.begin(), chain.end()); + std::string groups; + for (const std::string &group : chain) + groups += group; + write_file(tmp.string(), "" + named_amf_object(1, "Parent", "Leaf") + groups + ""); + Model model; + CHECK_FALSE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); +} + +TEST_CASE("AMF assemblies are named after the file, with suffixes for later groups", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "First", "FirstBody") + named_amf_object(2, "Second", "SecondBody") + + "10" + "10" + ""); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 2); + const std::string file_name = boost::filesystem::path(tmp.string()).filename().string(); + CHECK(model.objects[0]->name == file_name); + CHECK(model.objects[1]->name == file_name + "_2"); + // The first body name is a part name, never the assembly name. + CHECK(model.objects[0]->volumes.front()->name == "FirstBody"); +} + +TEST_CASE("AMF preserves equal valid names belonging to different bodies", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "Same") + named_amf_object(2, "ParentB", "Same") + + "" + "7"); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 2); + CHECK(model.objects.front()->volumes[0]->name == "Same"); + CHECK(model.objects.front()->volumes[1]->name == "Same"); + CHECK_THAT(amf_part_bounds(*model.objects.front()->volumes[1]).min.z() - + amf_part_bounds(*model.objects.front()->volumes[0]).min.z(), Catch::Matchers::WithinAbs(7.0, 1e-6)); +} + +TEST_CASE("AMF standalone multipart objects keep their volume metadata and definition order", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + std::string multipart = named_amf_object(9, "FirstDefinition", "FirstPart"); + const size_t volume_begin = multipart.find(""); + std::string second_volume = multipart.substr(volume_begin, + multipart.find("", volume_begin) + std::string("").size() - volume_begin); + second_volume.replace(second_volume.find("FirstPart"), std::string("FirstPart").size(), "SecondPart"); + multipart.insert(multipart.find(""), second_volume); + // Numeric IDs deliberately disagree with file order; neither object belongs to a constellation. + write_file(tmp.string(), "" + multipart + + named_amf_object(1, "SecondDefinition", "LastPart") + ""); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 2); + CHECK(model.objects[0]->name == "FirstDefinition"); + REQUIRE(model.objects[0]->volumes.size() == 2); + CHECK(model.objects[0]->volumes[0]->name == "FirstPart"); + CHECK(model.objects[0]->volumes[1]->name == "SecondPart"); + CHECK(model.objects[1]->name == "SecondDefinition"); + REQUIRE(model.objects[1]->volumes.size() == 1); + CHECK(model.objects[1]->volumes.front()->name == "LastPart"); +} + +TEST_CASE("Unnamed AMF assembly parts use the existing filename fallback", "[AMF][OriginalNames]") +{ + const bool keep_names = GENERATE(false, true); + ScopedTemporaryFile tmp(".amf"); + std::string objects = named_amf_object(1, "", "") + named_amf_object(2, "", ""); + const std::string empty_metadata = ""; + // No name metadata at either level: this matches the user's unmodified CAD AMF export. + for (size_t pos = objects.find(empty_metadata); pos != std::string::npos; pos = objects.find(empty_metadata)) + objects.erase(pos, empty_metadata.size()); + write_file(tmp.string(), "" + objects + + "" + "10"); + LoadStrategy options = LoadStrategy::LoadModel | LoadStrategy::AssembleParts; + if (keep_names) + options = options | LoadStrategy::KeepOriginalNames; + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, options)); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 2); + const std::string fallback = boost::filesystem::path(tmp.string()).filename().string(); + CHECK(model.objects.front()->name == fallback); + CHECK(model.objects.front()->volumes[0]->name == fallback); + CHECK(model.objects.front()->volumes[1]->name == fallback); + // Later splitting existing bodies into objects must retain these same ordinary names. + ModelObjectPtrs separated; + model.objects.front()->split(&separated, false); + REQUIRE(separated.size() == 2); + CHECK(separated[0]->name == fallback); + CHECK(separated[1]->name == fallback); +} + +TEST_CASE("AMF assemblies have no part settings of their own", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(0, "ParentA", "LeafA") + named_amf_object(1, "ParentB", "LeafB") + + "10" + "20"); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + ModelObject& object = *model.objects.front(); + REQUIRE(object.volumes.size() == 3); + // Merging copies the object's filament to every part; repeating it is not a setting of the part. + CHECK_FALSE(object.has_individual_part_settings()); + object.imported_parts_hidden = true; + CHECK(object.hides_imported_parts()); + + object.volumes[1]->config.set("extruder", 2); + CHECK(object.has_individual_part_settings()); + CHECK_FALSE(object.hides_imported_parts()); +} diff --git a/tests/libslic3r/test_import_names.cpp b/tests/libslic3r/test_import_names.cpp new file mode 100644 index 0000000000..fb8eb2ee84 --- /dev/null +++ b/tests/libslic3r/test_import_names.cpp @@ -0,0 +1,63 @@ +#include + +#include "libslic3r/Format/ImportNames.hpp" + +#include +#include +#include + +using namespace Slic3r; + +TEST_CASE("Imported names preserve Unicode and XML escaping characters", "[ImportNames]") +{ + // Ampersands need XML escaping at serialization, not destructive renaming. + const std::vector names{u8"Шов & тело", u8"部品2", "Same", "Same", ""}; + CHECK(sanitize_import_names(names, "_") == names); + for (const auto& name : names) + CHECK_FALSE(has_unsupported_name_characters(name)); +} + +TEST_CASE("Each unsupported character accepts a complete replacement string", "[ImportNames]") +{ + // Multi-character replacement applies to each character, including adjacent ones. + CHECK(sanitize_import_names({"Part/A:B"}, "_slash_") == + std::vector{"Part_slash_A_slash_B"}); + CHECK(sanitize_import_names({"A//B"}, "xyz") == std::vector{"AxyzxyzB"}); + CHECK(sanitize_import_names({"A<>:/\\|?*\"B"}, "") == std::vector{"AB"}); +} + +TEST_CASE("Cleaning names resolves only newly introduced sibling collisions", "[ImportNames]") +{ + // Existing duplicates remain equal; a cleaned name cannot take an existing valid name. + const auto names = sanitize_import_names({"A/B", "AB", "AB", "A:B", "A/B", "AB (2)"}, ""); + REQUIRE(names.size() == 6); + CHECK(names[0] == "AB (3)"); + CHECK(names[1] == "AB"); + CHECK(names[2] == "AB"); + CHECK(names[3] == "AB (4)"); + CHECK(names[4] == names[0]); + CHECK(names[5] == "AB (2)"); +} + +TEST_CASE("Names emptied by cleaning receive a usable fallback", "[ImportNames]") +{ + // An unnamed input stays under the importer's existing fallback policy. + CHECK(sanitize_import_names({"///", "Part", ""}, "") == + std::vector{"Part (2)", "Part", ""}); + CHECK(sanitize_import_names({"///"}, "", "Assembly/part") == + std::vector{"Assemblypart"}); +} + +TEST_CASE("Name validation rejects unsupported replacement and malformed Unicode", "[ImportNames]") +{ + CHECK(valid_import_name_replacement("_slash_")); + CHECK(valid_import_name_replacement(u8"替换")); + CHECK_FALSE(valid_import_name_replacement("")); + CHECK_FALSE(valid_import_name_replacement("x/y")); + CHECK_FALSE(valid_import_name_replacement(std::string("x\x01", 2))); + CHECK_THROWS_AS(sanitize_import_names({"A/B"}, "/"), std::invalid_argument); + CHECK_THROWS_AS(sanitize_import_names({std::string("\xc3\x28", 2)}, "_"), std::invalid_argument); + CHECK(has_unsupported_name_characters(std::string("x\x01", 2))); + CHECK(has_unsupported_name_characters(u8"x\ufffe")); + CHECK_FALSE(has_unsupported_name_characters("\t\n\r")); +} diff --git a/tests/libslic3r/test_step.cpp b/tests/libslic3r/test_step.cpp index ff8ce1dcba..45714e8cd5 100644 --- a/tests/libslic3r/test_step.cpp +++ b/tests/libslic3r/test_step.cpp @@ -3,12 +3,42 @@ #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 #include #include #include +#include +#include +#include "libslic3r/BoundingBox.hpp" #include "libslic3r/Model.hpp" #include "libslic3r/Format/STEP.hpp" +#include "libslic3r/Format/ProjectStrategy.hpp" #include "libslic3r/TriangleMesh.hpp" #include "test_utils.hpp" @@ -112,6 +142,243 @@ TEST_CASE("A surface model imports whether or not compounds are split", "[Step]" CHECK(model.objects.front()->volumes.front()->mesh().facets_count() > 0); } +// Three tetrahedra share one product, while each BREP carries its own independent name. +TEST_CASE("Original STEP body names stay attached to their own compound geometry", "[Step][OriginalNames]") +{ + const bool keep_names = GENERATE(false, true); + const std::string path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR "named_compound_bodies.step"; + LoadStrategy strategy = LoadStrategy::LoadModel | LoadStrategy::AddDefaultInstances; + if (keep_names) + strategy = strategy | LoadStrategy::KeepOriginalNames; + + Model model = Model::read_from_step(path, strategy, nullptr, nullptr, nullptr, 0.003, 0.5, true); + REQUIRE(model.objects.size() == 1); + const ModelObject *object = model.objects.front(); + REQUIRE(object->volumes.size() == 3); + REQUIRE(object->instances.size() == 1); + + const std::array names = {"Part10", "Part2", "\xD0\xA2\xD0\xB5\xD0\xBB\xD0\xBE & shell"}; + for (size_t i = 0; i < names.size(); ++i) { + CAPTURE(i, keep_names); + const ModelVolume *volume = object->volumes[i]; + CHECK(volume->name == (keep_names ? names[i] : "Body collection-SOLID-" + std::to_string(i + 1))); + const BoundingBoxf3 bounds = volume->mesh().transformed_bounding_box(volume->get_matrix()); + // Distinct X positions verify identity, rather than only comparing the list of names. + CHECK_THAT(bounds.min.x(), Catch::Matchers::WithinAbs(25.0 * i, 1e-5)); + CHECK_THAT(bounds.max.x(), Catch::Matchers::WithinAbs(25.0 * i + 10.0, 1e-5)); + CHECK_THAT(bounds.size().y(), Catch::Matchers::WithinAbs(10.0, 1e-5)); + CHECK_THAT(bounds.size().z(), Catch::Matchers::WithinAbs(10.0, 1e-5)); + CHECK(volume->mesh().facets_count() == 4); + } +} + +TEST_CASE("A STEP body name takes precedence over its enclosing product name only when requested", "[Step][OriginalNames]") +{ + const bool keep_names = GENERATE(false, true); + const bool split = GENERATE(false, true); + CAPTURE(keep_names, split); + LoadStrategy strategy = LoadStrategy::LoadModel; + if (keep_names) + strategy = strategy | LoadStrategy::KeepOriginalNames; + + const std::string path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR "named_single_body.step"; + Model model = Model::read_from_step(path, strategy, nullptr, nullptr, nullptr, 0.003, 0.5, split); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 1); + CHECK(model.objects.front()->volumes.front()->name == (keep_names ? "Body name" : "Body collection")); + CHECK(model.objects.front()->volumes.front()->mesh().facets_count() == 4); + // A single part is not listed, so the object carries the body name; otherwise the file name stays. + CHECK(model.objects.front()->name == (keep_names ? std::string("Body name") : std::string("named_single_body.step"))); +} + +TEST_CASE("The STEP import dialog can change original names after loading the CAD document", "[Step][OriginalNames]") +{ + const bool initial_keep = GENERATE(false, true); + LoadStrategy strategy = LoadStrategy::LoadModel | LoadStrategy::AssembleParts; + if (initial_keep) + strategy = strategy | LoadStrategy::KeepOriginalNames; + const std::string path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR "named_single_body.step"; + auto callback = [initial_keep](Step& step, double&, double&, bool&) { + CHECK(step.keep_original_names() == initial_keep); + step.set_keep_original_names(!initial_keep); + return 1; + }; + Model model = Model::read_from_step(path, strategy, nullptr, nullptr, callback, 0.003, 0.5, true); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 1); + CHECK(model.objects.front()->volumes.front()->name == (initial_keep ? "Body collection" : "Body name")); +} + +TEST_CASE("STEP geometry import honours Split compound like the legacy import", "[Step][OriginalNames]") +{ + const bool split = GENERATE(false, true); + CAPTURE(split); + const std::string path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR "named_compound_bodies.step"; + Model model = Model::read_from_step(path, LoadStrategy::LoadModel | LoadStrategy::AssembleParts, + nullptr, nullptr, nullptr, 0.003, 0.5, split); + REQUIRE(model.objects.size() == 1); + if (split) { + REQUIRE(model.objects.front()->volumes.size() == 3); + CHECK(model.objects.front()->volumes[0]->name == "Body collection-SOLID-1"); + CHECK(model.objects.front()->volumes[1]->name == "Body collection-SOLID-2"); + } else { + // An unsplit compound stays one part, as before this feature. + REQUIRE(model.objects.front()->volumes.size() == 1); + CHECK(model.objects.front()->volumes.front()->name == "Body collection"); + } +} + +TEST_CASE("One body beside helper geometry keeps its name without Split compound", "[Step][OriginalNames]") +{ + const std::string source_path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR "named_single_body.step"; + boost::nowide::ifstream input(source_path, std::ios::binary); + REQUIRE(input.good()); + std::string data{std::istreambuf_iterator(input), std::istreambuf_iterator()}; + // A curve set next to the body makes OCCT return a compound that holds a single solid. + const std::string representation = "#20=FACETED_BREP_SHAPE_REPRESENTATION('',(#21,#22),#17);"; + const size_t representation_pos = data.find(representation); + REQUIRE(representation_pos != std::string::npos); + data.replace(representation_pos, representation.size(), + "#20=SHAPE_REPRESENTATION('',(#21,#22,#24),#17);\n#24=GEOMETRIC_CURVE_SET('',(#25));\n#25=POLYLINE('',(#30,#31));"); + ScopedTemporaryFile file(".step"); + { + boost::nowide::ofstream output(file.string(), std::ios::binary); + REQUIRE(output.good()); + output << data; + } + // Prove the fixture reaches the compound branch rather than the plain solid one. + STEPControl_Reader reader; + REQUIRE(reader.ReadFile(file.string().c_str()) == IFSelect_RetDone); + REQUIRE(reader.TransferRoots() > 0); + REQUIRE(reader.OneShape().ShapeType() == TopAbs_COMPOUND); + + Step step(file.string()); + REQUIRE(step.load(true) == Step::Step_Status::LOAD_SUCCESS); + CHECK_FALSE(step.has_multi_body_compound()); + + Model model = Model::read_from_step(file.string(), LoadStrategy::LoadModel | LoadStrategy::KeepOriginalNames, + nullptr, nullptr, nullptr, 0.003, 0.5, false); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 1); + CHECK(model.objects.front()->volumes.front()->name == "Body name"); + CHECK(model.objects.front()->name == "Body name"); + CHECK(model.objects.front()->volumes.front()->mesh().facets_count() == 4); +} + +TEST_CASE("A loaded STEP document reports its body labels and multi-body compounds", "[Step][OriginalNames]") +{ + const bool compound = GENERATE(false, true); + CAPTURE(compound); + const std::string path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR + + (compound ? "named_compound_bodies.step" : "named_single_body.step"); + Step step(path); + REQUIRE(step.load(true) == Step::Step_Status::LOAD_SUCCESS); + CHECK(step.has_original_names()); + // Only a compound of several bodies needs Split compound for its names. + CHECK(step.has_multi_body_compound() == compound); +} + +TEST_CASE("Empty STEP body names retain the product fallback and raw Unicode names survive", "[Step][OriginalNames]") +{ + const std::string body_name = GENERATE(std::string(), std::string("\xD0\xA2\xD0\xB5\xD0\xBB\xD0\xBE")); + const std::string source_path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR "named_single_body.step"; + boost::nowide::ifstream input(source_path, std::ios::binary); + REQUIRE(input.good()); + std::string data{std::istreambuf_iterator(input), std::istreambuf_iterator()}; + const size_t name_pos = data.find("'Body name'"); + REQUIRE(name_pos != std::string::npos); + // Change only the body metadata; the product label and geometry remain independent controls. + data.replace(name_pos, std::string("'Body name'").size(), "'" + body_name + "'"); + ScopedTemporaryFile file(".STEP"); + { + boost::nowide::ofstream output(file.string(), std::ios::binary); + REQUIRE(output.good()); + output << data; + } + Model model = Model::read_from_step(file.string(), LoadStrategy::LoadModel | LoadStrategy::KeepOriginalNames, + nullptr, nullptr, nullptr, 0.003, 0.5, true); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 1); + CHECK(model.objects.front()->volumes.front()->name == (body_name.empty() ? "Body collection" : body_name)); +} + +TEST_CASE("Equal STEP body names remain equal without losing their individual geometry", "[Step][OriginalNames]") +{ + const std::string source_path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR "named_compound_bodies.step"; + boost::nowide::ifstream input(source_path, std::ios::binary); + REQUIRE(input.good()); + std::string data{std::istreambuf_iterator(input), std::istreambuf_iterator()}; + const size_t name_pos = data.find("'Part2'"); + REQUIRE(name_pos != std::string::npos); + // Duplicate only the label, so matching by name would assign the wrong geometry to a sibling. + data.replace(name_pos, std::string("'Part2'").size(), "'Part10'"); + ScopedTemporaryFile file(".stp"); + { + boost::nowide::ofstream output(file.string(), std::ios::binary); + REQUIRE(output.good()); + output << data; + } + Model model = Model::read_from_step(file.string(), LoadStrategy::LoadModel | LoadStrategy::KeepOriginalNames, + nullptr, nullptr, nullptr, 0.003, 0.5, true); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 3); + for (size_t i = 0; i < 2; ++i) { + const ModelVolume *volume = model.objects.front()->volumes[i]; + CHECK(volume->name == "Part10"); + CHECK_THAT(volume->mesh().transformed_bounding_box(volume->get_matrix()).min.x(), + Catch::Matchers::WithinAbs(25.0 * i, 1e-5)); + } +} + +TEST_CASE("Repeated STEP assembly prototypes keep each instance placement", "[Step][OriginalNames]") +{ + ScopedTemporaryFile file(".step"); + Handle(TDocStd_Document) document; + const auto application = XCAFApp_Application::GetApplication(); + application->NewDocument(TCollection_ExtendedString("BinXCAF"), document); + const auto shape_tool = XCAFDoc_DocumentTool::ShapeTool(document->Main()); + const TDF_Label prototype = shape_tool->AddShape(BRepPrimAPI_MakeBox(10.0, 20.0, 30.0).Shape(), false); + TDataStd_Name::Set(prototype, "Repeated prototype"); + + TopoDS_Compound compound; + BRep_Builder builder; + builder.MakeCompound(compound); + const TDF_Label assembly = shape_tool->AddShape(compound, true); + TDataStd_Name::Set(assembly, "Assembly"); + gp_Trsf first_location; + first_location.SetTranslation(gp_Vec(25.0, 0.0, 5.0)); + shape_tool->AddComponent(assembly, prototype, TopLoc_Location(first_location)); + gp_Trsf second_location; + second_location.SetRotation(gp_Ax1(gp_Pnt(0.0, 0.0, 0.0), gp_Dir(0.0, 0.0, 1.0)), 0.5 * std::acos(-1.0)); + second_location.SetTranslationPart(gp_Vec(100.0, 40.0, 0.0)); + shape_tool->AddComponent(assembly, prototype, TopLoc_Location(second_location)); + shape_tool->UpdateAssemblies(); + + STEPCAFControl_Writer writer; + REQUIRE(writer.Transfer(document)); + REQUIRE(writer.Write(file.string().c_str()) == IFSelect_RetDone); + application->Close(document); + + Model model = Model::read_from_step(file.string(), LoadStrategy::LoadModel | LoadStrategy::KeepOriginalNames, + nullptr, nullptr, nullptr, 0.003, 0.5, true); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 2); + // Both volumes use the shared prototype name; their independent transforms must not be merged. + for (const ModelVolume *volume : model.objects.front()->volumes) + CHECK(volume->name == "Repeated prototype"); + const auto first = model.objects.front()->volumes[0]; + const auto second = model.objects.front()->volumes[1]; + const auto first_bounds = first->mesh().transformed_bounding_box(first->get_matrix()); + const auto second_bounds = second->mesh().transformed_bounding_box(second->get_matrix()); + CHECK_THAT(first_bounds.min.x(), Catch::Matchers::WithinAbs(25.0, 1e-5)); + CHECK_THAT(first_bounds.min.z(), Catch::Matchers::WithinAbs(5.0, 1e-5)); + CHECK_THAT(first_bounds.size().x(), Catch::Matchers::WithinAbs(10.0, 1e-5)); + CHECK_THAT(second_bounds.min.x(), Catch::Matchers::WithinAbs(80.0, 1e-5)); + CHECK_THAT(second_bounds.min.y(), Catch::Matchers::WithinAbs(40.0, 1e-5)); + CHECK_THAT(second_bounds.size().x(), Catch::Matchers::WithinAbs(20.0, 1e-5)); + CHECK_THAT(second_bounds.size().y(), Catch::Matchers::WithinAbs(10.0, 1e-5)); +} + TEST_CASE("isUtf8 recognises two, three and four byte sequences", "[Step]") { CHECK(StepPreProcessor::isUtf8("\xC3\xA9")); // U+00E9 diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index 0ff09b2b04..b52e60c404 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -58,6 +58,7 @@ add_executable(${_TEST_NAME}_tests test_user_manager.cpp test_sequential_clearance.cpp test_object_list.cpp + test_geometry_import.cpp ../fff_print/test_helpers.cpp ) diff --git a/tests/slic3rutils/test_geometry_import.cpp b/tests/slic3rutils/test_geometry_import.cpp new file mode 100644 index 0000000000..70c32f1bae --- /dev/null +++ b/tests/slic3rutils/test_geometry_import.cpp @@ -0,0 +1,141 @@ +#include +#include +#include + +#include "slic3r/GUI/GeometryImportDialog.hpp" +#include "libslic3r/AppConfig.hpp" +#include "libslic3r/Zipper.hpp" +#include "test_utils.hpp" + +#include + +using namespace Slic3r; +using namespace Slic3r::GUI; + +TEST_CASE("CAD 3MF routing recognizes project markers without reading geometry", "[GeometryImport]") +{ + const std::string marker = GENERATE(std::string(), std::string("Metadata/model_settings.config"), + std::string("Metadata/project_settings.config"), std::string("Metadata/Slic3r_PE.config"), + std::string("Metadata/Slic3r_PE_model.config")); + CAPTURE(marker); + ScopedTemporaryFile file(".3mf"); + Zipper archive(file.string()); + // Directory-only classification must not triangulate or parse this placeholder mesh. + archive.add_entry("3D/3dmodel.model"); + archive << ""; + if (!marker.empty()) { + archive.add_entry(marker); + archive << "{}"; + } + archive.finalize(); + CHECK(is_geometry_only_3mf(file.string()) == marker.empty()); +} + +TEST_CASE("Geometry import choices distinguish remembering from suppressing questions", "[GeometryImport]") +{ + const std::string format = GENERATE(std::string("step"), std::string("amf"), std::string("3mf")); + const bool remember = GENERATE(false, true); + const bool dont_ask = GENERATE(false, true); + CAPTURE(format, remember, dont_ask); + AppConfig config; + const std::string prefix = "import_names_" + format + "_"; + const std::string show = format == "step" ? "enable_step_mesh_setting" : prefix + "show_dialog"; + config.set_bool(prefix + "keep", false); + config.set_bool(prefix + "sort", false); + config.set_bool(prefix + "assembly", false); + config.set_bool("is_split_compound", false); + config.set_bool(show, true); + GeometryImportOptions options; + options.keep_names = true; + options.sort_names = true; + options.load_as_assembly = true; + options.split_compound = true; + options.chosen = true; + options.remember = remember; + options.dont_ask = dont_ask; + save_geometry_import_options(config, format, options); + // Suppression must persist the action even with Remember my choice unchecked. + const bool persisted = remember || dont_ask; + CHECK(config.get_bool(prefix + "keep") == persisted); + CHECK(config.get_bool(prefix + "sort") == persisted); + // A 3MF keeps its own structure, so it has no presentation choice to remember. + CHECK(config.get_bool(prefix + "assembly") == (persisted && format != "3mf")); + // Reading side: a 3MF keeps the structure written in it whatever the stored key says. + CHECK(geometry_import_options(config, format).load_as_assembly == (format == "3mf" || persisted)); + CHECK(config.get_bool("is_split_compound") == (persisted && format == "step")); + CHECK(config.get_bool(show) == !dont_ask); +} + +TEST_CASE("Sorting disabled by Keep original names keeps its remembered value", "[GeometryImport]") +{ + const std::string format = GENERATE(std::string("step"), std::string("amf"), std::string("3mf")); + CAPTURE(format); + AppConfig config; + const std::string prefix = "import_names_" + format + "_"; + config.set_bool(prefix + "sort", true); + GeometryImportOptions options; + options.keep_names = false; + options.sort_names = false; + options.chosen = true; + options.remember = true; + save_geometry_import_options(config, format, options); + CHECK_FALSE(config.get_bool(prefix + "keep")); + CHECK(config.get_bool(prefix + "sort")); +} + +TEST_CASE("Name cleanup remembers the complete replacement string", "[GeometryImport]") +{ + const bool remember = GENERATE(false, true); + const bool dont_ask = GENERATE(false, true); + AppConfig config; + config.set("import_names_cleanup_replacement", "_"); + config.set_bool("import_names_cleanup_remove", true); + config.set_bool("import_names_cleanup_show_dialog", true); + GeometryImportNamePolicy policy; + policy.used = true; + policy.remove = false; + policy.replacement = "_slash_"; + policy.remember = remember; + policy.dont_ask = dont_ask; + save_geometry_import_name_policy(config, policy); + const bool persisted = remember || dont_ask; + CHECK(config.get("import_names_cleanup_replacement") == (persisted ? "_slash_" : "_")); + CHECK(config.get_bool("import_names_cleanup_remove") == !persisted); + CHECK(config.get_bool("import_names_cleanup_show_dialog") == !dont_ask); +} + +TEST_CASE("Geometry import treats STEP and STP extensions as the same format", "[GeometryImport]") +{ + CHECK(geometry_import_format("model.STEP") == "step"); + CHECK(geometry_import_format("model.sTp") == "step"); + CHECK(geometry_import_format("model.AMF") == "amf"); + CHECK(geometry_import_format("model.3MF") == "3mf"); + CHECK(geometry_import_format("model.stl").empty()); +} + +TEST_CASE("AMF loads separate objects unless an assembly mode was chosen", "[GeometryImport]") +{ + AppConfig config; + // Files from other slicers hold a whole plate in one group, so the default keeps them apart. + CHECK(geometry_import_options(config, "amf").separate_objects); + CHECK_FALSE(geometry_import_options(config, "amf").single_object()); + CHECK_FALSE(geometry_import_options(config, "step").separate_objects); + CHECK_FALSE(geometry_import_options(config, "3mf").separate_objects); + + const bool separate = GENERATE(false, true); + const bool assembly = GENERATE(false, true); + CAPTURE(separate, assembly); + config.set_bool("import_names_amf_assembly", !assembly); + GeometryImportOptions options; + options.separate_objects = separate; + options.load_as_assembly = assembly; + options.chosen = true; + options.remember = true; + save_geometry_import_options(config, "amf", options); + const GeometryImportOptions restored = geometry_import_options(config, "amf"); + CHECK(restored.separate_objects == separate); + CHECK(restored.load_as_assembly == assembly); + CHECK(restored.single_object() == (!separate && !assembly)); + // The STEP dialog has no separate mode and keeps its own key. + CHECK_FALSE(config.has("import_names_step_separate")); +} diff --git a/tests/slic3rutils/test_object_list.cpp b/tests/slic3rutils/test_object_list.cpp index 0552d0eabb..16e41cfabe 100644 --- a/tests/slic3rutils/test_object_list.cpp +++ b/tests/slic3rutils/test_object_list.cpp @@ -1,12 +1,16 @@ #include +#include +#include #include "slic3r/GUI/GUI_ObjectList.hpp" #include #include #include +#include #include +#include #include using namespace Slic3r; @@ -88,3 +92,110 @@ TEST_CASE("Objects sort by bounding box volume", "[ObjectList]") CHECK(sorted_names(model, ObjectOrder::Size) == std::vector{"cube", "tall", "flat"}); } + +TEST_CASE("Imported part names sort only their presentation and survive cloning", "[ObjectList][OriginalNames]") +{ + Model model; + ModelObject* object = model.add_object(); + // Include a modifier to ensure display sorting never changes its slicing precedence. + auto* ten = object->add_volume(make_cube(10., 10., 10.)); + ten->name = "Part10"; + auto* two = object->add_volume(make_cube(2., 2., 2.)); + two->name = "part2"; + auto* duplicate = object->add_volume(make_cube(3., 3., 3.)); + duplicate->name = "part2"; + duplicate->set_type(ModelVolumeType::PARAMETER_MODIFIER); + const auto slicing_order = object->volumes; + set_import_volume_order(*object, true); + CHECK(object->volumes == slicing_order); + CHECK(two->import_display_order < duplicate->import_display_order); + CHECK(duplicate->import_display_order < ten->import_display_order); + + Model clone; + const ModelObject* copied = clone.add_object(*object); + REQUIRE(copied->volumes.size() == object->volumes.size()); + for (size_t i = 0; i < copied->volumes.size(); ++i) { + CHECK(copied->volumes[i]->id() != object->volumes[i]->id()); + CHECK(copied->volumes[i]->import_display_order == object->volumes[i]->import_display_order); + } +} + +TEST_CASE("Unsorted imports preserve source presentation through type grouping", "[ObjectList][OriginalNames]") +{ + Model model; + ModelObject* object = model.add_object(); + auto* modifier = object->add_volume(make_cube(2., 2., 2.)); + modifier->name = "Z modifier"; + modifier->set_type(ModelVolumeType::PARAMETER_MODIFIER); + auto* part = object->add_volume(make_cube(10., 10., 10.)); + part->name = "A part"; + set_import_volume_order(*object, false); + object->sort_volumes(true); + CHECK(object->volumes.front() == part); + CHECK(modifier->import_display_order < part->import_display_order); +} + +TEST_CASE("Adding a part or modifier reveals a single-object import", "[ObjectList][OriginalNames]") +{ + const auto type = GENERATE(ModelVolumeType::MODEL_PART, ModelVolumeType::PARAMETER_MODIFIER); + Model model; + ModelObject* object = model.add_object(); + object->add_volume(make_cube(10., 10., 10.)); + object->add_volume(make_cube(2., 2., 2.)); + object->imported_parts_hidden = true; + // An editing operation must not leave the newly added, effective geometry invisible. + object->add_volume(make_cube(3., 3., 3.), type); + CHECK_FALSE(object->imported_parts_hidden); + REQUIRE(object->volumes.size() == 3); + CHECK(object->volumes.back()->type() == type); +} + +TEST_CASE("Part settings show a single-object import without changing it", "[ObjectList][OriginalNames]") +{ + Model model; + ModelObject* object = model.add_object(); + object->add_volume(make_cube(10., 10., 10.)); + ModelVolume* body = object->add_volume(make_cube(2., 2., 2.)); + object->imported_parts_hidden = true; + REQUIRE(object->hides_imported_parts()); + + // The check only reads the object: the stored choice survives while part settings show the parts. + body->config.set("wall_loops", 3); + CHECK_FALSE(object->hides_imported_parts()); + CHECK(object->imported_parts_hidden); + CHECK(body->config.has("wall_loops")); + + body->config.erase("wall_loops"); + CHECK(object->hides_imported_parts()); + + TriangleSelector selector(body->mesh()); + selector.set_facet(0, EnforcerBlockerType::ENFORCER); + REQUIRE(body->seam_facets.set(selector)); + CHECK_FALSE(object->hides_imported_parts()); + CHECK(object->imported_parts_hidden); + + body->seam_facets.reset(); + CHECK(object->hides_imported_parts()); +} + +TEST_CASE("A part that repeats the object's filament has no settings of its own", "[ObjectList][OriginalNames]") +{ + struct Case { int object_filament; int part_filament; bool extra_setting; bool individual; }; + // object_filament 0 means no object filament, which prints with filament 1. + const Case c = GENERATE(Case{0, 1, false, false}, Case{2, 2, false, false}, Case{2, 0, false, false}, + Case{2, 1, false, true}, Case{0, 2, false, true}, Case{2, 2, true, true}); + CAPTURE(c.object_filament, c.part_filament, c.extra_setting); + Model model; + ModelObject* object = model.add_object(); + object->config.erase("extruder"); + if (c.object_filament > 0) + object->config.set("extruder", c.object_filament); + object->add_volume(make_cube(10., 10., 10.)); + ModelVolume* body = object->add_volume(make_cube(2., 2., 2.)); + body->config.set("extruder", c.part_filament); + if (c.extra_setting) + body->config.set("wall_loops", 3); + object->imported_parts_hidden = true; + CHECK(object->has_individual_part_settings() == c.individual); + CHECK(object->hides_imported_parts() == !c.individual); +}