Merge branch 'main' into cad-mainline

This commit is contained in:
SoftFever
2026-09-18 14:01:23 +08:00
committed by GitHub
2596 changed files with 133083 additions and 118866 deletions
+6
View File
@@ -19,6 +19,7 @@ add_executable(${_TEST_NAME}_tests
test_preset_setting_id.cpp
test_preset_diff.cpp
test_vendor_cache.cpp
test_preset_options.cpp
test_elephant_foot_compensation.cpp
test_fill_corner_smoothing.cpp
test_filament_mixer.cpp
@@ -29,16 +30,21 @@ add_executable(${_TEST_NAME}_tests
test_polygon.cpp
test_mutable_polygon.cpp
test_mutable_priority_queue.cpp
test_minimum_spanning_tree.cpp
test_nozzle_volume_type.cpp
test_step.cpp
test_stl.cpp
test_triangle_selector.cpp
test_meshboolean.cpp
test_marchingsquares.cpp
test_lay_on_face.cpp
test_model.cpp
test_utils.cpp
test_timeutils.cpp
test_voronoi.cpp
test_wipe_tower_estimate.cpp
test_wipe_tower.cpp
test_wipe_path.cpp
test_optimizers.cpp
test_ordering_strategies.cpp
# test_png_io.cpp
+639 -2
View File
@@ -1,6 +1,5 @@
#include "libslic3r/Model.hpp"
#include "libslic3r/TriangleSelector.hpp"
#include "libslic3r/Format/3mf.hpp"
#include "libslic3r/Format/bbs_3mf.hpp"
#include "libslic3r/Format/STL.hpp"
@@ -11,9 +10,12 @@
#include "libslic3r/Preset.hpp"
#include "libslic3r/MultiNozzleUtils.hpp"
#include "libslic3r/ProjectTask.hpp"
#include "libslic3r/PublishSettings.hpp"
#include "test_utils.hpp"
#include <nlohmann/json.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <algorithm>
@@ -733,7 +735,6 @@ SCENARIO("Nozzle-group metadata .3mf round-trip", "[3mf][MultiNozzle]") {
}
}
// A mixed-color filament occupies an ordinary filament slot, and painting with it stores an
// ordinary extruder state: a project saved by BambuStudio encodes filament 5 of a 5-slot setup
// as paint state 5, with the mix described by the parallel filament_mixed_* project arrays.
@@ -824,3 +825,639 @@ SCENARIO("Mixed-color filament setup and painting round-trip through a .3mf", "[
}
}
}
// Locks the serialization contract of the "Publish" metadata: the orca_published flag and the
// orca_published_keys JSON array in model.model_info->metadata_items must survive a store_bbs_3mf ->
// load_bbs_3mf round-trip unchanged. (The full preset-preservation behavior is exercised
// headlessly in test_preset_bundle_loading.cpp.)
SCENARIO("Published 3MF round-trips the published flag and published_keys metadata", "[3mf]") {
GIVEN("a model carrying published metadata") {
Model model;
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
REQUIRE(load_stl(src_file.c_str(), &model));
model.add_default_instances();
model.model_info = std::make_shared<ModelInfo>();
model.model_info->metadata_items[ORCA_PUBLISHED_TAG] = "1";
model.model_info->metadata_items[ORCA_PUBLISHED_KEYS_TAG] = R"(["layer_height","wall_thickness"])";
// store_bbs_3mf stages project_settings.config through the model's backup path; point
// it at a writable temp dir (the default lives under a read-only root in CI).
ScopedTemporaryDir backup_dir("orca_pub");
model.set_backup_path(backup_dir.string());
WHEN("stored to and reloaded from a .3mf") {
ScopedTemporaryFile temp(".3mf");
const std::string test_file = temp.string();
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
StoreParams store_params;
store_params.path = test_file.c_str();
store_params.model = &model;
store_params.config = &config;
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
REQUIRE(store_bbs_3mf(store_params));
Model dst_model;
DynamicPrintConfig dst_config;
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
PlateDataPtrs dst_plates;
std::vector<Preset*> project_presets;
bool is_bbl_3mf = false, is_orca_3mf = false;
Semver file_version;
bool loaded = load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
LoadStrategy::LoadModel | LoadStrategy::LoadConfig);
THEN("the published metadata round-trips unchanged") {
REQUIRE(loaded);
REQUIRE(dst_model.model_info != nullptr);
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_TAG] == "1");
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_KEYS_TAG] == R"(["layer_height","wall_thickness"])");
// The orca_published_keys value is a JSON array of setting keys; it must parse back to
// the same keys that were selected.
nlohmann::json keys = nlohmann::json::parse(dst_model.model_info->metadata_items[ORCA_PUBLISHED_KEYS_TAG]);
REQUIRE(keys.is_array());
REQUIRE(keys.size() == 2);
REQUIRE(keys[0] == "layer_height");
REQUIRE(keys[1] == "wall_thickness");
}
release_PlateData_list(dst_plates);
}
}
}
// A normal 3MF (no Publish metadata) must load identically: the loader must not fabricate a
// "orca_published" flag or orca_published_keys for files that never carried them.
SCENARIO("Legacy 3MF without published metadata loads unchanged", "[3mf]") {
GIVEN("a model without any published metadata") {
Model model;
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
REQUIRE(load_stl(src_file.c_str(), &model));
model.add_default_instances();
ScopedTemporaryDir backup_dir("orca_legacy");
model.set_backup_path(backup_dir.string());
WHEN("stored to and reloaded from a .3mf") {
ScopedTemporaryFile temp(".3mf");
const std::string test_file = temp.string();
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
StoreParams store_params;
store_params.path = test_file.c_str();
store_params.model = &model;
store_params.config = &config;
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
REQUIRE(store_bbs_3mf(store_params));
Model dst_model;
DynamicPrintConfig dst_config;
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
PlateDataPtrs dst_plates;
std::vector<Preset*> project_presets;
bool is_bbl_3mf = false, is_orca_3mf = false;
Semver file_version;
bool loaded = load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
LoadStrategy::LoadModel | LoadStrategy::LoadConfig);
THEN("no published key is fabricated") {
REQUIRE(loaded);
REQUIRE(dst_model.model_info != nullptr);
REQUIRE(dst_model.model_info->metadata_items.count(ORCA_PUBLISHED_TAG) == 0);
REQUIRE(dst_model.model_info->metadata_items.count(ORCA_PUBLISHED_KEYS_TAG) == 0);
}
release_PlateData_list(dst_plates);
}
}
}
// Locks the serialization contract of the orca_published_material_keys metadata: the per-entry JSON
// must survive a store_bbs_3mf -> load_bbs_3mf round-trip verbatim, exactly like orca_published_keys.
SCENARIO("Published 3MF round-trips the published_material_keys metadata", "[3mf]") {
GIVEN("a model carrying published material keys metadata") {
Model model;
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
REQUIRE(load_stl(src_file.c_str(), &model));
model.add_default_instances();
const std::string material_keys_json =
R"([{"material":{"filament_type":"PLA","filament_vendor":"Generic","filament_id":"GFL99"},"slot":0,"keys":["filament_retraction_length","filament_z_hop"]}])";
model.model_info = std::make_shared<ModelInfo>();
model.model_info->metadata_items[ORCA_PUBLISHED_MATERIAL_TAG] = material_keys_json;
ScopedTemporaryDir backup_dir("orca_pub_mat");
model.set_backup_path(backup_dir.string());
WHEN("stored to and reloaded from a .3mf") {
ScopedTemporaryFile temp(".3mf");
const std::string test_file = temp.string();
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
StoreParams store_params;
store_params.path = test_file.c_str();
store_params.model = &model;
store_params.config = &config;
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
REQUIRE(store_bbs_3mf(store_params));
Model dst_model;
DynamicPrintConfig dst_config;
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
PlateDataPtrs dst_plates;
std::vector<Preset*> project_presets;
bool is_bbl_3mf = false, is_orca_3mf = false;
Semver file_version;
bool loaded = load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
LoadStrategy::LoadModel | LoadStrategy::LoadConfig);
THEN("the published material keys metadata round-trips unchanged") {
REQUIRE(loaded);
REQUIRE(dst_model.model_info != nullptr);
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_MATERIAL_TAG] == material_keys_json);
// The value must parse back to one material entry carrying the nested identity
// object, the author slot ordinal and the key list.
nlohmann::json entries = nlohmann::json::parse(material_keys_json);
REQUIRE(entries.is_array());
REQUIRE(entries.size() == 1);
REQUIRE(entries[0]["material"]["filament_type"] == "PLA");
REQUIRE(entries[0]["material"]["filament_vendor"] == "Generic");
REQUIRE(entries[0]["material"]["filament_id"] == "GFL99");
REQUIRE(entries[0]["slot"] == 0);
REQUIRE(entries[0]["keys"].is_array());
REQUIRE(entries[0]["keys"].size() == 2);
REQUIRE(entries[0]["keys"][0] == "filament_retraction_length");
}
release_PlateData_list(dst_plates);
}
}
}
SCENARIO("Minimal published 3MF omits project config, preset dumps and slicer tags", "[3mf]") {
GIVEN("a multi-instance model carrying published metadata and a published_config payload") {
Model model;
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
REQUIRE(load_stl(src_file.c_str(), &model));
model.add_default_instances();
// A second instance: tag-less third-party files get their multi-instance objects split,
// published files must not (the loader recognizes them by their metadata).
model.objects.front()->add_instance();
DynamicPrintConfig full_cfg = DynamicPrintConfig::full_print_config();
full_cfg.set_key_value("layer_height", new ConfigOptionFloat(0.24));
full_cfg.set_key_value("retraction_length", new ConfigOptionFloats({ 1.2 }));
const std::vector<std::string> published_keys = { "layer_height", "retraction_length" };
const std::vector<PublishedMaterialEntry> material_keys = {
{ "PLA", "Generic", "GFL99", "", "Generic PLA", 0, { "filament_retraction_length" } }
};
// The payload builder keeps the published and identity keys and drops everything else.
DynamicPrintConfig filtered_cfg = filter_published_config(full_cfg, published_keys, material_keys);
REQUIRE(filtered_cfg.option("layer_height") != nullptr);
REQUIRE(filtered_cfg.option("retraction_length") != nullptr);
REQUIRE(filtered_cfg.option("filament_colour") != nullptr);
REQUIRE(filtered_cfg.option("filament_type") != nullptr);
REQUIRE(filtered_cfg.option("wipe_tower_x") != nullptr);
REQUIRE(filtered_cfg.option("sparse_infill_density") == nullptr);
REQUIRE(filtered_cfg.option("machine_start_gcode") == nullptr);
// Serialize the payload exactly like export_published_3mf does.
std::string payload;
for (const std::string &key : filtered_cfg.keys())
payload += key + " = " + filtered_cfg.opt_serialize(key) + "\n";
model.model_info = std::make_shared<ModelInfo>();
model.model_info->metadata_items[ORCA_PUBLISHED_TAG] = "1";
model.model_info->metadata_items[ORCA_PUBLISHED_KEYS_TAG] = R"(["layer_height","retraction_length"])";
model.model_info->metadata_items[ORCA_PUBLISHED_CONFIG_TAG] = payload;
ScopedTemporaryDir backup_dir("orca_min_pub");
model.set_backup_path(backup_dir.string());
WHEN("stored using SaveStrategy::MinimalPublished and reloaded") {
ScopedTemporaryFile temp(".3mf");
const std::string test_file = temp.string();
// Create a fake project preset to verify MinimalPublished omits it.
Preset preset(Preset::TYPE_PRINT, "TestPrintPreset");
preset.config = full_cfg;
std::vector<Preset*> project_presets = { &preset };
StoreParams store_params;
store_params.path = test_file.c_str();
store_params.model = &model;
store_params.config = &filtered_cfg;
store_params.project_presets = project_presets;
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence | SaveStrategy::MinimalPublished;
REQUIRE(store_bbs_3mf(store_params));
Model dst_model;
ScopedTemporaryDir loaded_backup_dir("orca_min_pub_loaded");
dst_model.set_backup_path(loaded_backup_dir.string());
DynamicPrintConfig dst_config;
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
PlateDataPtrs dst_plates;
std::vector<Preset*> loaded_presets;
bool is_bbl_3mf = false, is_orca_3mf = false;
Semver file_version;
bool loaded = load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
&loaded_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
LoadStrategy::LoadModel | LoadStrategy::LoadConfig);
THEN("the 3MF loads without project config or embedded presets") {
REQUIRE(loaded);
REQUIRE(dst_config.empty());
REQUIRE(loaded_presets.empty());
}
THEN("the file carries no slicer tags and classifies as a generic 3MF") {
REQUIRE_FALSE(is_bbl_3mf);
REQUIRE_FALSE(is_orca_3mf);
// No Application / OrcaSlicer tag: old receivers import the geometry silently
// instead of showing a baked-in, wrong "old version" popup.
REQUIRE_FALSE(file_version.valid());
}
THEN("the geometry keeps BBS-grade handling: instances are not split") {
REQUIRE(dst_model.objects.size() == 1);
REQUIRE(dst_model.objects.front()->instances.size() == 2);
}
THEN("the published metadata and payload round-trip unchanged") {
REQUIRE(dst_model.model_info != nullptr);
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_TAG] == "1");
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_KEYS_TAG] == R"(["layer_height","retraction_length"])");
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_CONFIG_TAG] == payload);
}
THEN("the payload parses back to the published values") {
DynamicPrintConfig parsed_payload;
parsed_payload.load_from_ini_string(dst_model.model_info->metadata_items[ORCA_PUBLISHED_CONFIG_TAG], ForwardCompatibilitySubstitutionRule::Enable);
REQUIRE(parsed_payload.option("layer_height") != nullptr);
REQUIRE_THAT(parsed_payload.opt_float("layer_height"), Catch::Matchers::WithinAbs(0.24, 1e-6));
REQUIRE(parsed_payload.option("retraction_length") != nullptr);
REQUIRE_THAT(parsed_payload.opt<ConfigOptionFloats>("retraction_length")->get_at(0), Catch::Matchers::WithinAbs(1.2, 1e-6));
}
release_PlateData_list(dst_plates);
}
}
}
// A minimal published 3MF must not leak the slicer tags of the source project. The exporter seeds
// metadata_item_map from the input file's metadata_items, so re-publishing a project opened from a
// regular Orca/BBS 3MF (the typical remix flow) must strip the Application / OrcaSlicer tags it
// came with, otherwise old receivers route onto the baked-in "old version" popup.
SCENARIO("MinimalPublished strips slicer tags carried by the source project", "[3mf]") {
GIVEN("a model loaded from a regular Orca/BBS 3MF whose metadata carries the slicer tags") {
Model model;
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
REQUIRE(load_stl(src_file.c_str(), &model));
model.add_default_instances();
model.model_info = std::make_shared<ModelInfo>();
model.model_info->metadata_items[ORCA_PUBLISHED_TAG] = "1";
model.model_info->metadata_items["Application"] = "BambuStudio-2.0.0";
model.model_info->metadata_items["OrcaSlicer"] = "2.1.0";
ScopedTemporaryDir backup_dir("orca_strip_tags");
model.set_backup_path(backup_dir.string());
WHEN("stored using SaveStrategy::MinimalPublished and reloaded") {
ScopedTemporaryFile temp(".3mf");
const std::string test_file = temp.string();
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
StoreParams store_params;
store_params.path = test_file.c_str();
store_params.model = &model;
store_params.config = &config;
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence | SaveStrategy::MinimalPublished;
REQUIRE(store_bbs_3mf(store_params));
Model dst_model;
DynamicPrintConfig dst_config;
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
PlateDataPtrs dst_plates;
std::vector<Preset*> loaded_presets;
bool is_bbl_3mf = false, is_orca_3mf = false;
Semver file_version;
bool loaded = load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
&loaded_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
LoadStrategy::LoadModel | LoadStrategy::LoadConfig);
THEN("the source slicer tags are stripped, not carried through") {
REQUIRE(loaded);
REQUIRE(dst_model.model_info != nullptr);
REQUIRE(dst_model.model_info->metadata_items.count("Application") == 0);
REQUIRE(dst_model.model_info->metadata_items.count("OrcaSlicer") == 0);
// The published marker itself must survive.
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_TAG] == "1");
}
THEN("the file classifies as a generic 3MF without a version popup") {
REQUIRE_FALSE(is_bbl_3mf);
REQUIRE_FALSE(is_orca_3mf);
REQUIRE_FALSE(file_version.valid());
}
release_PlateData_list(dst_plates);
}
}
}
// An entry masks the non-published slots to their defaults so publishing slot 1 never leaks slot
// 0's value into the file. Both a full entry (the whole-slot key list) and a partial entry (a
// per-slot key) go through the same masking path in filter_published_config (keys and full_keys
// are filtered identically), so the two forms are exercised together.
SCENARIO("Published entries mask the other slots to their defaults", "[3mf]") {
const bool full = GENERATE(true, false);
GIVEN("a full print configuration with two filament slots") {
DynamicPrintConfig full_cfg = DynamicPrintConfig::full_print_config();
full_cfg.opt<ConfigOptionFloats>("filament_diameter")->values = { 1.75, 1.75 };
full_cfg.opt<ConfigOptionStrings>("filament_colour")->values = { "#111111", "#222222" };
// filament_flow_ratio carries a non-empty option default (1.0) of the same type, so the
// mask can restore it on the non-published slot.
full_cfg.opt<ConfigOptionFloatsNullable>("filament_flow_ratio", true)->values = { 1.02, 0.98 };
WHEN("filtering with a published entry for slot 1") {
PublishedMaterialEntry entry;
entry.slot = 1;
if (full) {
entry.full = true;
entry.full_keys = { "filament_flow_ratio" };
} else {
entry.keys = { "filament_flow_ratio" };
}
DynamicPrintConfig filtered_cfg = filter_published_config(full_cfg, {}, { entry });
THEN("the selected key is present with the author's slot value") {
REQUIRE(filtered_cfg.option("filament_flow_ratio") != nullptr);
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloatsNullable>("filament_flow_ratio")->values[1], Catch::Matchers::WithinAbs(0.98, 1e-6));
}
THEN("the non-published slot is masked to its default") {
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloatsNullable>("filament_flow_ratio")->values[0], Catch::Matchers::WithinAbs(1.0, 1e-6));
}
THEN("the identity keys stay present") {
REQUIRE(filtered_cfg.option("filament_colour") != nullptr);
}
}
}
}
// A key needing slot masking that cannot be masked (no registered option default of the same
// type) is dropped from the payload entirely instead of shipping the author's whole vector.
SCENARIO("Unmaskable keys are dropped from the published payload instead of leaking", "[3mf]") {
GIVEN("a config carrying a synthetic def-less vector key and a maskable one") {
DynamicPrintConfig full_cfg = DynamicPrintConfig::full_print_config();
full_cfg.opt<ConfigOptionFloats>("filament_diameter")->values = { 1.75, 1.75 };
full_cfg.opt<ConfigOptionStrings>("filament_colour")->values = { "#111111", "#222222" };
// Not a PrintConfig key: print_config_def has no default to mask with.
full_cfg.set_key_value("orca_synthetic_setting", new ConfigOptionFloats({ 9.9, 8.8 }));
full_cfg.opt<ConfigOptionFloatsNullable>("filament_flow_ratio", true)->values = { 1.02, 0.98 };
PublishedMaterialEntry partial_entry;
partial_entry.slot = 1;
partial_entry.keys = { "orca_synthetic_setting", "filament_flow_ratio" };
WHEN("filtering with a partial entry for slot 1") {
DynamicPrintConfig filtered_cfg = filter_published_config(full_cfg, {}, { partial_entry });
THEN("the unmaskable synthetic key is not published") {
REQUIRE(filtered_cfg.option("orca_synthetic_setting") == nullptr);
}
THEN("the maskable key is present, author slot kept, other slot masked") {
REQUIRE(filtered_cfg.opt<ConfigOptionFloatsNullable>("filament_flow_ratio") != nullptr);
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloatsNullable>("filament_flow_ratio")->values[1], Catch::Matchers::WithinAbs(0.98, 1e-6));
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloatsNullable>("filament_flow_ratio")->values[0], Catch::Matchers::WithinAbs(1.0, 1e-6));
}
THEN("the identity keys stay present") {
REQUIRE(filtered_cfg.option("filament_colour") != nullptr);
}
}
}
}
// A per-extruder printer key carrying a "#N" variant (e.g. retraction_length#1) must not serialize
// every extruder's value: the base is masked to the author's extruder and the other slots are
// restored to their option default, matching the material-side slot-masking invariant. A bare
// printer base key (no variant) keeps whole-vector serialization.
SCENARIO("Published per-extruder printer keys mask the other extruders to their defaults", "[3mf]") {
GIVEN("a full print configuration with three extruders carrying per-extruder retraction values") {
DynamicPrintConfig full_cfg = DynamicPrintConfig::full_print_config();
// Non-default values on the un-selected slots, so a leak is distinguishable from the mask
// restoring the option default (retraction_length defaults to {0.8}).
full_cfg.opt<ConfigOptionFloats>("retraction_length")->values = { 3.0, 1.2, 4.0 };
WHEN("filtering with only extruder 1's retraction_length checked") {
DynamicPrintConfig filtered_cfg = filter_published_config(full_cfg, { "retraction_length#1" }, {});
THEN("the author's extruder value survives") {
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloats>("retraction_length")->values[1], Catch::Matchers::WithinAbs(1.2, 1e-6));
}
THEN("the other extruders are masked to their default") {
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloats>("retraction_length")->values[0], Catch::Matchers::WithinAbs(0.8, 1e-6));
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloats>("retraction_length")->values[2], Catch::Matchers::WithinAbs(0.8, 1e-6));
}
}
WHEN("filtering the bare base key without a '#N' variant") {
DynamicPrintConfig filtered_cfg = filter_published_config(full_cfg, { "retraction_length" }, {});
THEN("the whole vector is serialized unmasked") {
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloats>("retraction_length")->values[0], Catch::Matchers::WithinAbs(3.0, 1e-6));
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloats>("retraction_length")->values[1], Catch::Matchers::WithinAbs(1.2, 1e-6));
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloats>("retraction_length")->values[2], Catch::Matchers::WithinAbs(4.0, 1e-6));
}
}
}
}
// The extended per-entry fields (full dump list, published type and colour) travel inside the
// published_material_keys metadata and round-trip unchanged.
SCENARIO("Published 3MF round-trips the extended material metadata", "[3mf]") {
GIVEN("a model carrying extended published material keys metadata") {
Model model;
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
REQUIRE(load_stl(src_file.c_str(), &model));
model.add_default_instances();
const std::string material_keys_json =
R"([{"material":{"filament_type":"PLA","filament_vendor":"Generic","filament_id":"GFL99","setting_id":"RFs9eCKYOMUSmvZf","name":"Generic PLA Matte @System"},"slot":1,"keys":[],"full":true,"full_keys":["filament_retraction_length","filament_colour"],"publish_type":true,"type":"PLA","publish_color":false,"color":""}])";
model.model_info = std::make_shared<ModelInfo>();
model.model_info->metadata_items[ORCA_PUBLISHED_MATERIAL_TAG] = material_keys_json;
ScopedTemporaryDir backup_dir("orca_pub_mat2");
model.set_backup_path(backup_dir.string());
WHEN("stored to and reloaded from a .3mf") {
ScopedTemporaryFile temp(".3mf");
const std::string test_file = temp.string();
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
StoreParams store_params;
store_params.path = test_file.c_str();
store_params.model = &model;
store_params.config = &config;
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
REQUIRE(store_bbs_3mf(store_params));
Model dst_model;
DynamicPrintConfig dst_config;
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
PlateDataPtrs dst_plates;
std::vector<Preset*> project_presets;
bool is_bbl_3mf = false, is_orca_3mf = false;
Semver file_version;
bool loaded = load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
LoadStrategy::LoadModel | LoadStrategy::LoadConfig);
THEN("the extended material metadata round-trips unchanged") {
REQUIRE(loaded);
REQUIRE(dst_model.model_info != nullptr);
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_MATERIAL_TAG] == material_keys_json);
// The value must parse back with every extended field intact.
nlohmann::json entries = nlohmann::json::parse(material_keys_json);
REQUIRE(entries.is_array());
REQUIRE(entries.size() == 1);
REQUIRE(entries[0]["full"].get<bool>() == true);
REQUIRE(entries[0]["full_keys"].is_array());
REQUIRE(entries[0]["full_keys"].size() == 2);
REQUIRE(entries[0]["publish_type"].get<bool>() == true);
REQUIRE(entries[0]["type"] == "PLA");
REQUIRE(entries[0]["publish_color"].get<bool>() == false);
}
release_PlateData_list(dst_plates);
}
}
}
// A published mixed filament serializes its whole definition (components, ratios, gradient)
// masked to the author's slot: the mix slot's values survive, the non-published slots reset to
// their defaults, so a partial publish never leaks another slot's mix data.
SCENARIO("Published mixed-filament keys are masked to the author's slot", "[3mf]") {
GIVEN("a full print configuration with three slots, one of them mixed") {
DynamicPrintConfig full_cfg = DynamicPrintConfig::full_print_config();
full_cfg.opt<ConfigOptionFloats>("filament_diameter")->values = { 1.75, 1.75, 1.75 };
full_cfg.opt<ConfigOptionStrings>("filament_colour")->values = { "#111111", "#222222", "#333333" };
full_cfg.opt<ConfigOptionBools>("filament_is_mixed")->values = { 0, 0, 1 };
full_cfg.opt<ConfigOptionStrings>("filament_mixed_components")->values = { "", "", "1,2" };
full_cfg.opt<ConfigOptionStrings>("filament_mixed_sublayer_ratios")->values = { "", "", "0.6,0.4" };
full_cfg.opt<ConfigOptionBools>("filament_mixed_gradient")->values = { 0, 0, 1 };
full_cfg.opt<ConfigOptionStrings>("filament_mixed_gradient_range")->values = { "", "", "0.9,0.1" };
full_cfg.opt<ConfigOptionStrings>("filament_mixed_gradient_curve")->values = { "", "", "0,0.1|1,0.9" };
full_cfg.opt<ConfigOptionBools>("filament_mixed_gradient_per_part")->values = { 0, 0, 1 };
PublishedMaterialEntry mix_entry;
mix_entry.slot = 2;
mix_entry.keys = {
"filament_is_mixed", "filament_mixed_components", "filament_mixed_sublayer_ratios",
"filament_mixed_gradient", "filament_mixed_gradient_range", "filament_mixed_gradient_curve",
"filament_mixed_gradient_per_part"
};
WHEN("filtering with a mixed entry for slot 2") {
DynamicPrintConfig filtered_cfg = filter_published_config(full_cfg, {}, { mix_entry });
THEN("the author's mixed slot keeps its definition") {
REQUIRE(filtered_cfg.option("filament_is_mixed") != nullptr);
REQUIRE(filtered_cfg.opt<ConfigOptionBools>("filament_is_mixed")->values == std::vector<unsigned char>{ 0, 0, 1 });
const auto& components = filtered_cfg.opt<ConfigOptionStrings>("filament_mixed_components")->values;
REQUIRE(components.size() == 3);
CHECK(components[2] == "1,2");
CHECK(filtered_cfg.opt<ConfigOptionStrings>("filament_mixed_sublayer_ratios")->values[2] == "0.6,0.4");
CHECK(filtered_cfg.opt<ConfigOptionStrings>("filament_mixed_gradient_curve")->values[2] == "0,0.1|1,0.9");
CHECK(filtered_cfg.opt<ConfigOptionBools>("filament_mixed_gradient")->values[2]);
CHECK(filtered_cfg.opt<ConfigOptionBools>("filament_mixed_gradient_per_part")->values[2]);
}
THEN("the non-published slots are masked to their defaults") {
CHECK(filtered_cfg.opt<ConfigOptionStrings>("filament_mixed_components")->values[0] == "");
CHECK(filtered_cfg.opt<ConfigOptionStrings>("filament_mixed_components")->values[1] == "");
CHECK(filtered_cfg.opt<ConfigOptionBools>("filament_is_mixed")->values[0] == 0);
CHECK(filtered_cfg.opt<ConfigOptionBools>("filament_is_mixed")->values[1] == 0);
}
THEN("the identity keys stay present") {
REQUIRE(filtered_cfg.option("filament_colour") != nullptr);
}
}
}
}
// The published flag is gated on the exact string "1": any other serialized value means "not
// published", so a receiver never treats a file as published on a loose truthiness check.
TEST_CASE("is_published_3mf_flag accepts only the literal \"1\"", "[3mf]") {
CHECK(is_published_3mf_flag("1"));
CHECK_FALSE(is_published_3mf_flag("0"));
CHECK_FALSE(is_published_3mf_flag("false"));
CHECK_FALSE(is_published_3mf_flag("true"));
CHECK_FALSE(is_published_3mf_flag(""));
CHECK_FALSE(is_published_3mf_flag("YES"));
}
// bbs_3mf_is_published is the lightweight metadata probe used to decide whether a file was
// produced by the publish feature (GUI "recently published" tracking). It must return true only
// for a file whose metadata carries the flag set to "1", and false for legacy files and for a
// file whose flag is present but not "1" (which loads as a normal, non-published 3MF).
SCENARIO("bbs_3mf_is_published detects only genuinely published 3MFs", "[3mf]") {
auto store_model = [](const std::string &path, const std::string &flag_value, const std::string &keys_value) {
Model model;
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
REQUIRE(load_stl(src_file.c_str(), &model));
model.add_default_instances();
model.model_info = std::make_shared<ModelInfo>();
// An empty flag_value means "don't write the flag at all" (a legacy file).
if (!flag_value.empty())
model.model_info->metadata_items[ORCA_PUBLISHED_TAG] = flag_value;
model.model_info->metadata_items[ORCA_PUBLISHED_KEYS_TAG] = keys_value;
ScopedTemporaryDir backup_dir("orca_is_pub");
model.set_backup_path(backup_dir.string());
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
StoreParams store_params;
store_params.path = path.c_str();
store_params.model = &model;
store_params.config = &config;
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
REQUIRE(store_bbs_3mf(store_params));
};
GIVEN("a minimal published 3MF whose flag is \"1\"") {
ScopedTemporaryFile temp(".3mf");
store_model(temp.string(), "1", R"(["layer_height"])");
WHEN("probed by bbs_3mf_is_published") {
THEN("it is recognized as published") {
CHECK(bbs_3mf_is_published(temp.string()));
}
}
}
GIVEN("a legacy 3MF without any published flag") {
ScopedTemporaryFile temp(".3mf");
store_model(temp.string(), "", R"(["layer_height"])");
WHEN("probed by bbs_3mf_is_published") {
THEN("it is not recognized as published") {
CHECK_FALSE(bbs_3mf_is_published(temp.string()));
}
}
}
GIVEN("a 3MF carrying the flag set to \"0\"") {
ScopedTemporaryFile temp(".3mf");
store_model(temp.string(), "0", R"(["layer_height"])");
WHEN("probed and loaded") {
THEN("it is not recognized as published") {
CHECK_FALSE(bbs_3mf_is_published(temp.string()));
}
THEN("it loads as a normal, non-published 3MF") {
Model dst_model;
DynamicPrintConfig dst_config;
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
PlateDataPtrs dst_plates;
std::vector<Preset*> project_presets;
bool is_bbl_3mf = false, is_orca_3mf = false;
Semver file_version;
REQUIRE(load_bbs_3mf(temp.string().c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
LoadStrategy::LoadModel | LoadStrategy::LoadConfig));
REQUIRE(dst_model.model_info != nullptr);
// The key is present but not "1", so nothing treats the file as published; the
// stored keys still round-trip verbatim.
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_TAG] == "0");
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_KEYS_TAG] == R"(["layer_height"])");
release_PlateData_list(dst_plates);
}
}
}
}
+96 -2
View File
@@ -4,6 +4,8 @@
#include "libslic3r/BoundingBox.hpp"
#include "libslic3r/ClipperUtils.hpp"
#include "libslic3r/ExPolygon.hpp"
#include "libslic3r/Print.hpp"
#include "libslic3r/PrintConfig.hpp"
using namespace Slic3r;
using namespace Slic3r::arrangement;
@@ -24,11 +26,13 @@ ArrangePolygon make_square(coord_t side)
return ap;
}
ArrangePolygons squares(int n, double side_mm)
ArrangePolygons squares(int n, double side_mm, double height_mm = 0.)
{
ArrangePolygons items;
for (int i = 0; i < n; ++i)
for (int i = 0; i < n; ++i) {
items.emplace_back(make_square(scaled(side_mm)));
items.back().height = height_mm;
}
return items;
}
@@ -82,6 +86,38 @@ void require_no_overlap(const ArrangePolygons &items)
REQUIRE(disjoint(placed_shapes(items)));
}
// The sequential-print floor is chosen by comparing object height against the nozzle,
// so the two are defined together and every expectation is derived from them.
constexpr double NOZZLE_HEIGHT_MM = 2.5;
constexpr double CLEARANCE_MM = 30.;
constexpr double NOZZLE_FLOOR_MM = MAX_OUTER_NOZZLE_DIAMETER / 2.;
ArrangeParams seq_print_params(coord_t min_dist)
{
ArrangeParams p = quiet_params(min_dist);
p.is_seq_print = true;
p.clearance_radius = float(CLEARANCE_MM);
p.nozzle_height = float(NOZZLE_HEIGHT_MM);
p.object_skirt_offset = 0.f;
return p;
}
// update_selected_items_inflation reads the bed out of the config to cap inflation.
DynamicPrintConfig bed_config()
{
DynamicPrintConfig c;
c.set_key_value("printable_area", new ConfigOptionPoints{{0, 0}, {200, 0}, {200, 200}, {0, 200}});
return c;
}
ArrangePolygons squares_of_heights(const std::vector<double> &heights_mm)
{
ArrangePolygons items;
for (double height_mm : heights_mm)
items.push_back(squares(1, 20., height_mm).front());
return items;
}
} // namespace
// Prove the overlap check the other tests rely on actually detects overlap.
@@ -222,3 +258,61 @@ TEST_CASE("Arrange aligns the pile to a custom center", "[Arrange]")
REQUIRE(ap.bed_idx == 0);
require_no_overlap(items);
}
TEST_CASE("Sequential print floors the object distance by object height", "[Arrange]")
{
// The only place sequential-print clearance is enforced. The arrange menu offers
// no floor of its own, so a stored 0 has to be raised here or not at all.
struct Case
{
std::string description;
std::vector<double> heights;
double skirt_offset_mm;
double expected_floor_mm;
};
auto c = GENERATE(values<Case>({
{"objects taller than the nozzle need the full clearance", {NOZZLE_HEIGHT_MM * 2, NOZZLE_HEIGHT_MM * 2}, 0., CLEARANCE_MM},
{"an object exactly at the nozzle height counts as tall", {NOZZLE_HEIGHT_MM, NOZZLE_HEIGHT_MM}, 0., CLEARANCE_MM},
{"one tall object among short ones is enough", {NOZZLE_HEIGHT_MM / 2, NOZZLE_HEIGHT_MM * 2}, 0., CLEARANCE_MM},
{"objects the nozzle clears keep only the nozzle-width floor", {NOZZLE_HEIGHT_MM / 2, NOZZLE_HEIGHT_MM / 2}, 0., NOZZLE_FLOOR_MM},
{"a wide skirt raises the floor for short objects", {NOZZLE_HEIGHT_MM / 2, NOZZLE_HEIGHT_MM / 2}, 3., 6.},
}));
DYNAMIC_SECTION(c.description)
{
ArrangePolygons items = squares_of_heights(c.heights);
DynamicPrintConfig cfg = bed_config();
ArrangeParams p = seq_print_params(0);
p.object_skirt_offset = float(c.skirt_offset_mm);
update_selected_items_inflation(items, &cfg, p);
CHECK(p.min_obj_distance >= scaled(c.expected_floor_mm));
CHECK(p.min_obj_distance <= scaled(c.expected_floor_mm + 0.01));
// Half each, so a pair ends up a full min_obj_distance apart.
CHECK(items.front().inflation == p.min_obj_distance / 2);
}
}
TEST_CASE("Sequential print keeps an object distance already above the floor", "[Arrange]")
{
const coord_t stored = scaled(CLEARANCE_MM * 2);
ArrangePolygons items = squares_of_heights({NOZZLE_HEIGHT_MM * 2, NOZZLE_HEIGHT_MM * 2});
DynamicPrintConfig cfg = bed_config();
ArrangeParams p = seq_print_params(stored);
update_selected_items_inflation(items, &cfg, p);
CHECK(p.min_obj_distance == stored);
}
TEST_CASE("Layered printing does not floor the object distance", "[Arrange]")
{
ArrangePolygons items = squares_of_heights({NOZZLE_HEIGHT_MM * 2, NOZZLE_HEIGHT_MM * 2});
DynamicPrintConfig cfg = bed_config();
ArrangeParams p = seq_print_params(0);
p.is_seq_print = false;
update_selected_items_inflation(items, &cfg, p);
CHECK(p.min_obj_distance == 0);
}
+180
View File
@@ -15,6 +15,8 @@
#include <boost/nowide/fstream.hpp>
#include <nlohmann/json.hpp>
#include <sstream>
using namespace Slic3r;
SCENARIO("Generic config validation performs as expected.", "[Config]") {
@@ -488,6 +490,59 @@ TEST_CASE("save_to_json round-trips plugin capability references as strings", "[
CHECK(reloaded.option<ConfigOptionStrings>("slicing_pipeline_plugin")->values == refs);
}
TEST_CASE("save_to_json writes the same document to a stream as to a file", "[Config]") {
DynamicPrintConfig config;
config.set_key_value("layer_height", new ConfigOptionFloat(0.2));
config.set_key_value("wall_loops", new ConfigOptionInt(3));
config.set_key_value("filament_type", new ConfigOptionStrings({ "PLA", "PETG" }));
config.set_key_value("machine_start_gcode", new ConfigOptionString("G28\nG1 Z5"));
ScopedTemporaryFile tmp(".json");
config.save_to_json(tmp.string(), "test_preset", "User", "1.0.0.0");
std::string file_contents;
{
boost::nowide::ifstream ifs(tmp.string());
file_contents.assign(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
}
// The file format: one tab per nesting level and a trailing newline.
REQUIRE_FALSE(file_contents.empty());
CHECK(file_contents.rfind("{\n\t\"", 0) == 0);
CHECK(file_contents.back() == '\n');
std::ostringstream strict, replaced;
config.save_to_json(strict, "test_preset", "User", "1.0.0.0");
config.save_to_json(replaced, "test_preset", "User", "1.0.0.0", true);
CHECK(strict.str() == file_contents);
CHECK(replaced.str() == file_contents);
CHECK(nlohmann::json::parse(strict.str())["machine_start_gcode"] == "G28\nG1 Z5");
}
TEST_CASE("save_to_json replaces invalid UTF-8 in a stream only when asked", "[Config]") {
DynamicPrintConfig config;
config.set_key_value("machine_start_gcode", new ConfigOptionString("G28 ; \xff"));
std::ostringstream strict, replaced;
CHECK_THROWS_AS(config.save_to_json(strict, "test_preset", "User", "1.0.0.0"), nlohmann::json::type_error);
REQUIRE_NOTHROW(config.save_to_json(replaced, "test_preset", "User", "1.0.0.0", true));
CHECK(nlohmann::json::parse(replaced.str())["machine_start_gcode"] == "G28 ; \xEF\xBF\xBD");
}
TEST_CASE("save_to_json leaves an existing file untouched when the config cannot be serialized", "[Config]") {
DynamicPrintConfig config;
config.set_key_value("machine_start_gcode", new ConfigOptionString("G28 ; \xff"));
ScopedTemporaryFile tmp(".json");
{
boost::nowide::ofstream ofs(tmp.string());
ofs << "previous";
}
CHECK_THROWS_AS(config.save_to_json(tmp.string(), "test_preset", "User", "1.0.0.0"), nlohmann::json::type_error);
boost::nowide::ifstream ifs(tmp.string());
const std::string contents((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
CHECK(contents == "previous");
}
TEST_CASE("plugin capability references survive string-map serialization", "[Config][plugins]") {
const std::vector<std::string> refs = {
"master_plugin;;header-stamp",
@@ -1091,3 +1146,128 @@ TEST_CASE("get_filament_type treats empty vector options as absent", "[Config][F
REQUIRE(displayed == "Sup.PLA");
}
}
namespace {
// min_object_distance reads exactly these three options.
DynamicPrintConfig spacing_config(PrinterTechnology tech, PrintSequence seq, double clearance_radius)
{
DynamicPrintConfig c;
c.set_key_value("printer_technology", new ConfigOptionEnum<PrinterTechnology>(tech));
c.set_key_value("print_sequence", new ConfigOptionEnum<PrintSequence>(seq));
c.set_key_value("extruder_clearance_radius", new ConfigOptionFloat(clearance_radius));
return c;
}
} // namespace
TEST_CASE("min_object_distance floors object spacing per print sequence", "[Config]")
{
struct Case
{
std::string description;
PrinterTechnology tech;
PrintSequence sequence;
double clearance_radius;
double expected;
};
auto c = GENERATE(values<Case>({
{"sequential FFF takes a clearance radius above the floor", ptFFF, PrintSequence::ByObject, 12., 12.},
{"sequential FFF holds the floor at the radius", ptFFF, PrintSequence::ByObject, 6., 6.},
{"sequential FFF holds the floor below the radius", ptFFF, PrintSequence::ByObject, 4., 6.},
{"layered FFF ignores the clearance radius", ptFFF, PrintSequence::ByLayer, 12., 6.},
{"SLA is a flat 6mm", ptSLA, PrintSequence::ByObject, 12., 6.},
{"SLA ignores the print sequence too", ptSLA, PrintSequence::ByLayer, 12., 6.},
}));
DYNAMIC_SECTION(c.description)
{
CHECK_THAT(min_object_distance(spacing_config(c.tech, c.sequence, c.clearance_radius)),
Catch::Matchers::WithinAbs(c.expected, 1e-9));
}
}
TEST_CASE("min_object_distance yields no floor when an FFF config lacks the options", "[Config]")
{
// Missing options yield 0 rather than an error, so a caller gets no floor at all.
SECTION("no clearance radius") {
DynamicPrintConfig c;
c.set_key_value("printer_technology", new ConfigOptionEnum<PrinterTechnology>(ptFFF));
c.set_key_value("print_sequence", new ConfigOptionEnum<PrintSequence>(PrintSequence::ByObject));
CHECK_THAT(min_object_distance(c), Catch::Matchers::WithinAbs(0., 1e-9));
}
SECTION("no print sequence") {
DynamicPrintConfig c;
c.set_key_value("printer_technology", new ConfigOptionEnum<PrinterTechnology>(ptFFF));
c.set_key_value("extruder_clearance_radius", new ConfigOptionFloat(12.));
CHECK_THAT(min_object_distance(c), Catch::Matchers::WithinAbs(0., 1e-9));
}
SECTION("nothing at all") {
CHECK_THAT(min_object_distance(DynamicPrintConfig{}), Catch::Matchers::WithinAbs(0., 1e-9));
}
SECTION("an unset printer technology is treated as FFF") {
DynamicPrintConfig c;
c.set_key_value("print_sequence", new ConfigOptionEnum<PrintSequence>(PrintSequence::ByObject));
c.set_key_value("extruder_clearance_radius", new ConfigOptionFloat(12.));
CHECK_THAT(min_object_distance(c), Catch::Matchers::WithinAbs(12., 1e-9));
}
}
TEST_CASE("Static print configs compare, order and hash by their option values", "[Config]")
{
// PrintObjectConfig comes from PRINT_CONFIG_CLASS_DEFINE; PrintConfig combines MachineEnvelopeConfig
// and GCodeConfig through PRINT_CONFIG_CLASS_DERIVED_DEFINE. Both generate hash(), operator==,
// operator< and the option registration from the same option list. The hash inequalities use fixed
// inputs, so they are deterministic; they check that hash() covers the changed option.
SECTION("default-constructed configs are equal and find their options by key")
{
PrintObjectConfig a, b;
REQUIRE(a == b);
REQUIRE(a.hash() == b.hash());
REQUIRE_FALSE(a < b);
REQUIRE_FALSE(b < a);
REQUIRE(a.optptr("layer_height") == &a.layer_height);
REQUIRE(a.optptr("brim_object_gap") == &a.brim_object_gap);
}
SECTION("one differing option makes the configs unequal and orders them")
{
PrintObjectConfig a, b;
b.layer_height.value = a.layer_height.value + 0.05;
REQUIRE(a != b);
REQUIRE(a.hash() != b.hash());
REQUIRE(a < b);
REQUIRE_FALSE(b < a);
}
SECTION("ordering is decided by the first option in declaration order that differs")
{
PrintObjectConfig a, b;
a.brim_object_gap.value = b.brim_object_gap.value + 1.0; // declared first
a.layer_height.value = b.layer_height.value - 0.05; // declared later, points the other way
REQUIRE(b < a);
REQUIRE_FALSE(a < b);
}
SECTION("a derived config sees differences in its parents and in its own options")
{
PrintConfig a, b;
REQUIRE(a == b);
REQUIRE(a.hash() == b.hash());
b.gcode_flavor.value = b.gcode_flavor.value == gcfMarlinLegacy ? gcfKlipper : gcfMarlinLegacy; // GCodeConfig parent
REQUIRE(a != b);
REQUIRE(a.hash() != b.hash());
PrintConfig c, d;
d.skirt_distance.value = c.skirt_distance.value + 1.0; // PrintConfig's own list
REQUIRE(c != d);
REQUIRE(c.hash() != d.hash());
REQUIRE(c.optptr("skirt_distance") == &c.skirt_distance);
REQUIRE(c.optptr("gcode_flavor") == &c.gcode_flavor);
}
}
@@ -484,6 +484,34 @@ TEST_CASE("update_values_to_printer_extruders_for_multiple_filaments resolves pe
REQUIRE(config.option<ConfigOptionFloats>("filament_max_volumetric_speed")->values == std::vector<double>({12., 21.}));
REQUIRE(config.option<ConfigOptionInts>("filament_self_index")->values == std::vector<int>({1, 2}));
}
SECTION("a variant option shorter than the filament slots keeps its first value instead of zero") {
DynamicPrintConfig config;
config.option<ConfigOptionEnumsGeneric>("extruder_type", true)->values = {etDirectDrive, etDirectDrive};
config.option<ConfigOptionEnumsGeneric>("nozzle_volume_type", true)->values = {nvtStandard, nvtHighFlow};
config.option<ConfigOptionStrings>("extruder_variant_list", true)->values = {"Direct Drive Standard,Direct Drive High Flow",
"Direct Drive Standard,Direct Drive High Flow"};
make_filament_arrays(config);
config.option<ConfigOptionInts>("filament_map", true)->values = {1, 2};
// no loaded preset carries the key, so only its single registered default is present
config.option<ConfigOptionFloatsNullable>("filament_cooling_before_tower", true)->values = {10.};
// only the first filament's two variant columns were loaded
config.option<ConfigOptionFloatsNullable>("filament_ramming_volumetric_speed", true)->values = {-1., -2.};
std::vector<std::vector<NozzleVolumeType>> nozzle_volume_types;
int extruder_count = 2;
int count = config.get_extruder_nozzle_volume_count(extruder_count, nozzle_volume_types);
config.update_values_to_printer_extruders_for_multiple_filaments(config, extruder_count, count, filament_keys,
"filament_self_index", "filament_extruder_variant");
// filament 2 resolves to column 3 (its extruder's High Flow column), past the end of both vectors
REQUIRE_THAT(config.option<ConfigOptionFloatsNullable>("filament_cooling_before_tower")->values,
Catch::Matchers::Approx(std::vector<double>({10., 10.})));
REQUIRE_THAT(config.option<ConfigOptionFloatsNullable>("filament_ramming_volumetric_speed")->values,
Catch::Matchers::Approx(std::vector<double>({-1., -1.})));
REQUIRE(config.option<ConfigOptionFloats>("filament_max_volumetric_speed")->values == std::vector<double>({12., 21.}));
}
}
// update_values_from_multi_to_multi_2 walks the DESTINATION PRINTER's variant list while writing
+205
View File
@@ -0,0 +1,205 @@
#include <catch2/catch_all.hpp>
#include "libslic3r/LayOnFace.hpp"
#include "libslic3r/Model.hpp"
using namespace Slic3r;
using Catch::Matchers::WithinAbs;
namespace {
// Adds a box part spanning `origin` to `origin + size`, in object coordinates.
void add_box(ModelObject &object, const Vec3d &size, const Vec3d &origin = Vec3d::Zero())
{
TriangleMesh mesh = make_cube(size.x(), size.y(), size.z());
mesh.translate(origin.cast<float>());
object.add_volume(std::move(mesh), ModelVolumeType::MODEL_PART, false);
}
ModelObject &add_box_object(Model &model, const Vec3d &size)
{
ModelObject *object = model.add_object();
add_box(*object, size);
object->add_instance();
return *object;
}
// A 30 x 30 x 2 plate with three 1 mm thick, 20 mm tall ribs along Y. The rib sides facing -X add up
// to more area than the plate's bottom, but only the bottom is a face of the convex hull.
ModelObject &add_ribbed_plate(Model &model)
{
ModelObject *object = model.add_object();
add_box(*object, { 30, 30, 2 });
for (double x : { 5., 14.5, 24. })
add_box(*object, { 1, 30, 20 }, { x, 0, 2 });
object->add_instance();
return *object;
}
std::vector<LayOnFacePlane> instance_planes(const ModelObject &object)
{
return lay_on_face_planes(object, object.instances.front()->get_matrix_no_offset());
}
void lay_on_largest_face(ModelObject &object)
{
const std::vector<LayOnFacePlane> planes = instance_planes(object);
const int idx = find_largest_plane(planes);
REQUIRE(idx >= 0);
lay_on_face(object, 0, planes[idx].normal);
}
void check_size(const ModelObject &object, const Vec3d &expected)
{
const Vec3d size = object.instance_bounding_box(0).size();
CHECK_THAT(size.x(), WithinAbs(expected.x(), 1e-3));
CHECK_THAT(size.y(), WithinAbs(expected.y(), 1e-3));
CHECK_THAT(size.z(), WithinAbs(expected.z(), 1e-3));
}
void check_on_bed(const ModelObject &object) { CHECK_THAT(object.instance_bounding_box(0).min.z(), WithinAbs(0., 1e-3)); }
} // namespace
TEST_CASE("A tilted box is laid on its largest face and dropped onto the bed", "[LayOnFace]")
{
Model model;
ModelObject &box = add_box_object(model, { 40, 20, 10 }); // the 40 x 20 faces are the largest
box.instances.front()->set_rotation({ 0.3, 0.5, 0.2 });
box.instances.front()->set_offset({ 0, 0, 50 });
REQUIRE(box.instance_bounding_box(0).size().z() > 11.);
const std::vector<LayOnFacePlane> planes = instance_planes(box);
REQUIRE(planes.size() == 6);
CHECK_THAT(planes.front().area, WithinAbs(40. * 20., 1e-2));
lay_on_largest_face(box);
CHECK_THAT(box.instance_bounding_box(0).size().z(), WithinAbs(10., 1e-3));
check_on_bed(box);
}
TEST_CASE("A box lying on one of its equally large faces is not flipped", "[LayOnFace]")
{
// A half turn about X puts the other large face down, so the two cases expect different faces
// and neither can pass on the order in which the hull lists them.
const double rotation_x = GENERATE(0., PI);
Model model;
ModelObject &box = add_box_object(model, { 40, 20, 10 }); // the bottom and top are both 40 x 20
box.instances.front()->set_rotation({ rotation_x, 0, 0 });
const Transform3d before = box.instances.front()->get_matrix_no_offset();
const std::vector<LayOnFacePlane> planes = instance_planes(box);
const int idx = find_largest_plane(planes);
REQUIRE(idx >= 0);
// The face down on the plate is the object's -Z face, or its +Z face after the half turn.
CHECK_THAT(planes[idx].normal.z(), WithinAbs(rotation_x == 0. ? -1. : 1., 1e-6));
lay_on_face(box, 0, planes[idx].normal);
CHECK(box.instances.front()->get_matrix_no_offset().isApprox(before, 1e-9));
}
TEST_CASE("Faces are chosen from the orientation left by an earlier part rotation", "[LayOnFace]")
{
Model model;
ModelObject &box = add_box_object(model, { 40, 20, 10 });
box.rotate(PI / 2., X); // what --rotate-x 90 does: rotates the parts, not the instance
check_size(box, { 40, 10, 20 });
SECTION("the largest face") {
lay_on_largest_face(box);
check_size(box, { 40, 20, 10 });
check_on_bed(box);
}
SECTION("the face pointing along +X") {
const std::vector<LayOnFacePlane> planes = instance_planes(box);
const int idx = find_plane_by_normal(planes, { 1, 0, 0 });
REQUIRE(idx >= 0);
CHECK_THAT(planes[idx].normal.x(), WithinAbs(1., 1e-6));
lay_on_face(box, 0, planes[idx].normal);
check_size(box, { 20, 10, 40 });
check_on_bed(box);
}
}
TEST_CASE("Objects are laid on their own faces independently", "[LayOnFace]")
{
Model model;
// Standing on end through its instance rotation.
ModelObject &standing = add_box_object(model, { 40, 20, 10 });
standing.instances.front()->set_rotation({ 0, PI / 2., 0 });
// Standing on edge through a part rotation, lifted above the bed.
ModelObject &on_edge = add_box_object(model, { 30, 20, 5 });
on_edge.rotate(PI / 2., X);
on_edge.instances.front()->set_offset({ 100, 0, 30 });
check_size(standing, { 10, 20, 40 });
check_size(on_edge, { 30, 5, 20 });
for (ModelObject *object : model.objects)
lay_on_largest_face(*object);
check_size(standing, { 40, 20, 10 });
check_on_bed(standing);
check_size(on_edge, { 30, 20, 5 });
check_on_bed(on_edge);
}
TEST_CASE("A part rests on its largest hull face even when parallel inner faces add up to more area", "[LayOnFace]")
{
Model model;
ModelObject &plate = add_ribbed_plate(model);
double area_facing_minus_x = 0.;
for (const ModelVolume *volume : plate.volumes) {
const indexed_triangle_set &its = volume->mesh().its;
for (const Vec3i32 &face : its.indices) {
const Vec3d cross = (its.vertices[face[1]] - its.vertices[face[0]]).cast<double>().cross(
(its.vertices[face[2]] - its.vertices[face[0]]).cast<double>());
if (cross.normalized().x() < -0.999)
area_facing_minus_x += 0.5 * cross.norm();
}
}
// Summing triangle area per normal would pick a rib side over the 900 mm² bottom.
REQUIRE(area_facing_minus_x > 30. * 30.);
plate.instances.front()->set_rotation({ 0, PI / 2., 0 }); // stand the plate on its side
check_size(plate, { 22, 30, 30 });
const std::vector<LayOnFacePlane> planes = instance_planes(plate);
const int idx = find_largest_plane(planes);
REQUIRE(idx >= 0);
CHECK_THAT(planes[idx].area, WithinAbs(30. * 30., 1e-2));
CHECK_THAT(planes[idx].normal.z(), WithinAbs(-1., 1e-6));
lay_on_face(plate, 0, planes[idx].normal);
check_size(plate, { 30, 30, 22 });
check_on_bed(plate);
}
TEST_CASE("Faces are selected in object coordinates whatever the instance rotation", "[LayOnFace]")
{
Model model;
ModelObject &plate = add_ribbed_plate(model);
plate.instances.front()->set_rotation({ 0, 0, PI / 2. });
const Transform3d instance_matrix = plate.instances.front()->get_matrix_no_offset();
const std::vector<LayOnFacePlane> planes = lay_on_face_planes(plate, instance_matrix);
REQUIRE_FALSE(planes.empty());
// Every face center, as --inspect-mesh reports it, selects its own face.
for (size_t i = 0; i < planes.size(); ++i)
CHECK(find_plane_at_point(planes, instance_matrix, planes[i].center, 0.01) == int(i));
const int bottom = find_plane_at_point(planes, instance_matrix, { 15, 15, 0 }, 0.01);
REQUIRE(bottom >= 0);
CHECK_THAT(planes[bottom].normal.z(), WithinAbs(-1., 1e-6));
CHECK(find_plane_by_normal(planes, { 0, 0, -1 }) == bottom);
// Above the bottom plane, and on a rib side that lies inside the hull.
CHECK(find_plane_at_point(planes, instance_matrix, { 15, 15, 0.5 }, 0.01) == -1);
CHECK(find_plane_at_point(planes, instance_matrix, { 14.5, 15, 12 }, 0.01) == -1);
}
TEST_CASE("A part too small to rest on offers no faces", "[LayOnFace]")
{
Model model;
CHECK(instance_planes(add_box_object(model, { 2, 2, 2 })).empty()); // every face is 4 mm², under the 5 mm² minimum
}
+2
View File
@@ -1,4 +1,6 @@
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <catch2/catch_all.hpp>
#include "test_utils.hpp"
@@ -0,0 +1,66 @@
#include <catch2/catch_all.hpp>
#include <algorithm>
#include "libslic3r/MinimumSpanningTree.hpp"
#include "libslic3r/Point.hpp"
using namespace Slic3r;
// A 5x5 lattice: at every step of Prim's algorithm several candidates sit at the same
// distance from the tree, so the tie-break decides the tree's shape.
static std::vector<Point> lattice()
{
std::vector<Point> vertices;
for (int y = 0; y < 5; ++y)
for (int x = 0; x < 5; ++x)
vertices.emplace_back(Point::new_scale(x, y));
return vertices;
}
static std::vector<Point> sorted_neighbours(const MinimumSpanningTree &mst, const Point &vertex)
{
std::vector<Point> neighbours = mst.adjacent_nodes(vertex);
std::sort(neighbours.begin(), neighbours.end());
return neighbours;
}
TEST_CASE("Minimum spanning tree connects every vertex", "[MinimumSpanningTree]")
{
const std::vector<Point> vertices = lattice();
const MinimumSpanningTree mst(vertices);
REQUIRE(mst.vertices().size() == vertices.size());
size_t adjacency_entries = 0;
for (const Point &vertex : vertices) {
const std::vector<Point> neighbours = mst.adjacent_nodes(vertex);
REQUIRE(! neighbours.empty());
adjacency_entries += neighbours.size();
}
// A tree on n vertices has n - 1 edges, each listed from both ends.
REQUIRE(adjacency_entries == 2 * (vertices.size() - 1));
}
TEST_CASE("Minimum spanning tree does not depend on the order of the non-root vertices", "[MinimumSpanningTree][Regression]")
{
const std::vector<Point> vertices = lattice();
const MinimumSpanningTree reference(vertices);
// The root stays first: Prim's tree legitimately depends on where it starts.
// Every other order of the remaining vertices must give the same tree.
std::vector<std::vector<Point>> orders;
orders.emplace_back(vertices);
std::reverse(orders.back().begin() + 1, orders.back().end());
for (size_t shift = 1; shift + 1 < vertices.size(); ++shift) {
orders.emplace_back(vertices);
std::rotate(orders.back().begin() + 1, orders.back().begin() + 1 + shift, orders.back().end());
}
for (const std::vector<Point> &order : orders) {
const MinimumSpanningTree mst(order);
for (const Point &vertex : vertices) {
INFO("vertex " << vertex.x() << "," << vertex.y());
REQUIRE(sorted_neighbours(mst, vertex) == sorted_neighbours(reference, vertex));
}
}
}
File diff suppressed because it is too large Load Diff
+17
View File
@@ -33,3 +33,20 @@ TEST_CASE("deep_diff flags new vector entries that duplicate values[0]", "[Prese
// specific to new indices rather than flagging the whole vector.
REQUIRE(std::find(diff.begin(), diff.end(), "nozzle_diameter#0") == diff.end());
}
TEST_CASE("deep_diff distinguishes absolute and percentage speeds for each variant", "[PresetDiff][Config]")
{
const size_t changed_index = GENERATE(size_t(0), size_t(1));
Preset reference(Preset::TYPE_PRINT, "ref");
reference.config.set_key_value("small_perimeter_speed", new ConfigOptionFloatsOrPercents{{50., false}, {50., false}});
Preset edited = reference;
edited.config.option<ConfigOptionFloatsOrPercents>("small_perimeter_speed")->values[changed_index].percent = true;
const auto diff = PresetCollection::dirty_options(&edited, &reference, /*deep_compare=*/true);
REQUIRE(diff == std::vector<std::string>{"small_perimeter_speed#" + std::to_string(changed_index)});
DynamicPrintConfig transferred = reference.config;
transferred.apply_only(edited.config, diff);
REQUIRE(*transferred.option("small_perimeter_speed") == *edited.config.option("small_perimeter_speed"));
}
+70
View File
@@ -0,0 +1,70 @@
// Regression test for the "option in def + UI but missing from preset key list"
// crash class.
//
// The print preset's DynamicPrintConfig is seeded with only the keys returned by
// Preset::print_options() (PresetBundle.cpp). A field added to PrintRegionConfig
// or PrintObjectConfig and registered via print_config_def plus a TabPrint
// optgroup, but left out of print_options(), still gets its control built; on tab
// activation reload_config -> get_config_value dispatches to opt_bool/opt_int on a
// DynamicPrintConfig with no entry for the key, and the accessor null-derefs the
// result of option<T>(key).
//
// The invariant asserted here is the inverse: every key declared on
// PrintRegionConfig and PrintObjectConfig appears in Preset::print_options() or
// Preset::filament_options(), the two preset key lists that seed a print preset's
// DynamicConfig.
#include <catch2/catch_all.hpp>
#include "libslic3r/Preset.hpp"
#include "libslic3r/PrintConfig.hpp"
#include <set>
using namespace Slic3r;
namespace {
// Deprecated keys renamed in handle_legacy() (ironing_direction ->
// ironing_angle, wall_infill_order -> wall_sequence); neither is in a
// preset list. Register new options in a preset list, not here.
const std::set<std::string> kDeprecatedRegionFields = {
"ironing_direction",
"wall_infill_order",
};
void check_keys_are_in_a_preset(const t_config_option_keys& keys, const std::string& class_name)
{
REQUIRE_FALSE(keys.empty());
const auto& print_options = Preset::print_options();
const auto& filament_options = Preset::filament_options();
const std::set<std::string> in_print(print_options.begin(), print_options.end());
const std::set<std::string> in_filament(filament_options.begin(), filament_options.end());
for (const std::string& key : keys) {
DYNAMIC_SECTION(class_name << "::" << key)
{
INFO("'" << key << "' on " << class_name
<< " is missing from "
"Preset::print_options()/filament_options(); add it to "
"s_Preset_print_options (or s_Preset_filament_options) in Preset.cpp.");
const bool registered = in_print.count(key) || in_filament.count(key) || kDeprecatedRegionFields.count(key);
REQUIRE(registered);
}
}
}
} // namespace
// Bodies are laid out like the rest of the test suite rather than collapsed
// onto the brace line.
// clang-format off
TEST_CASE("Every PrintRegionConfig field is registered in a preset key list", "[Preset][Config]")
{
check_keys_are_in_a_preset(PrintRegionConfig::defaults().keys(), "PrintRegionConfig");
}
TEST_CASE("Every PrintObjectConfig field is registered in a preset key list", "[Preset][Config]")
{
check_keys_are_in_a_preset(PrintObjectConfig::defaults().keys(), "PrintObjectConfig");
}
// clang-format on
+2 -2
View File
@@ -5,10 +5,10 @@
using namespace Slic3r;
// Golden vectors from the Python reference generate_preset_setting_id (defined in
// scripts/orca_id_tool.py). The C++ generate_preset_setting_id() MUST stay byte-identical
// scripts/orca_profile_tool.py). The C++ generate_preset_setting_id() MUST stay byte-identical
// to it, otherwise app-side on-the-fly ids would diverge from the
// script-assigned ones in the profiles. Regenerate a vector with:
// python3 -c "import sys; sys.path.insert(0, 'scripts'); from orca_id_tool import generate_preset_setting_id as g; print(g('Afinia','filament','Afinia ABS @Afinia H400'))"
// python3 -c "import sys; sys.path.insert(0, 'scripts'); from orca_profile_tool import generate_preset_setting_id as g; print(g('Afinia','filament','Afinia ABS @Afinia H400'))"
TEST_CASE("preset setting_id matches the Python reference", "[Preset][setting_id]") {
struct Vec { const char* vendor; const char* type; const char* name; const char* expected; };
const Vec vectors[] = {
@@ -163,6 +163,50 @@ TEST_CASE("H2C multi-nozzle: filaments get distinct nozzles on the 6-nozzle extr
}
}
TEST_CASE("Grouping context spans the filament count with mis-sized config arrays", "[ToolOrdering][H2C]")
{
// FilamentGroup indexes the grouping context's filament_info by filament id, so a short
// per-filament array must not shorten it: the reads run off the end.
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
// Single 6-nozzle extruder: opens the grouping engine without needing a BBL multi-extruder.
config.option<ConfigOptionFloats>("nozzle_diameter", true)->values = {0.4};
config.option<ConfigOptionIntsNullable>("extruder_max_nozzle_count", true)->values = {6};
config.option<ConfigOptionStrings>("extruder_nozzle_stats", true)->values = {"Standard#6"};
// Four filaments, with filament_type / filament_is_support left short on purpose.
config.option<ConfigOptionStrings>("filament_colour", true)->values = {"#FF0000", "#00FF00", "#0000FF", "#FFFF00"};
config.option<ConfigOptionStrings>("filament_type", true)->values = {"PLA"};
config.option<ConfigOptionBools>("filament_is_support", true)->values = {0};
config.option<ConfigOptionFloats>("filament_diameter", true)->values = {1.75, 1.75, 1.75, 1.75};
config.option<ConfigOptionInts>("filament_map", true)->values = {1, 1, 1, 1};
config.option<ConfigOptionFloats>("flush_volumes_matrix", true)->values = std::vector<double>(16, 140.);
config.option<ConfigOptionFloats>("flush_multiplier", true)->values = {1.};
Model model;
model.add_object("cube", "", make_cube(20, 20, 20))->add_instance();
Print print;
print.apply(model, config);
// apply() does not pad the per-filament arrays, so the mis-sizing survives into the engine.
REQUIRE(print.config().filament_type.values.size() < print.config().filament_colour.values.size());
std::vector<std::vector<unsigned int>> layer_filaments = {{0, 1}, {1, 2}, {2, 3}};
SECTION("short per-filament arrays still yield one entry per filament") {
auto result = ToolOrdering::get_recommended_filament_maps(layer_filaments, &print, FilamentMapMode::fmmAutoForFlush, {}, {});
REQUIRE(result.get_extruder_map(false).size() == 4);
for (int f = 0; f < 4; ++f)
REQUIRE(result.get_extruder_id(f) == 0);
}
SECTION("filament_ids longer than the filament count is truncated, not paired past the end") {
config.option<ConfigOptionStrings>("filament_ids", true)->values = {"a", "b", "c", "d", "e", "f"};
print.apply(model, config);
auto result = ToolOrdering::get_recommended_filament_maps(layer_filaments, &print, FilamentMapMode::fmmAutoForFlush, {}, {});
REQUIRE(result.get_extruder_map(false).size() == 4);
}
}
TEST_CASE("H2C dynamic selector: per-layer nozzle ids reach the g-code surface", "[ToolOrdering][H2C][Dynamic]")
{
// The per-layer regroup engine
@@ -981,3 +1025,41 @@ TEST_CASE("Selector slicing keeps the result valid across re-apply", "[Print][H2
REQUIRE(status != PrintBase::APPLY_STATUS_INVALIDATED);
REQUIRE(print.is_step_done(psSlicingFinished));
}
TEST_CASE("parse_cyclic_order parses user cyclic toolchange sequences", "[ToolOrdering][Cyclic]")
{
// Filament numbers are 1-based in the UI; the parser returns 0-based indices.
SECTION("well-formed sequence") {
REQUIRE(parse_cyclic_order("3,2,1,4", 4) == std::vector<unsigned int>({2, 1, 0, 3}));
}
SECTION("surrounding whitespace is tolerated") {
REQUIRE(parse_cyclic_order(" 3 , 2 ,1, 4 ", 4) == std::vector<unsigned int>({2, 1, 0, 3}));
}
SECTION("out-of-range and non-positive entries are dropped") {
// 0 is below the 1-based range, 5 is above it for a 4-filament setup, -1 is invalid.
REQUIRE(parse_cyclic_order("0,5,-1,2", 4) == std::vector<unsigned int>({1}));
}
SECTION("duplicates keep only the first occurrence") {
REQUIRE(parse_cyclic_order("2,2,1,2", 4) == std::vector<unsigned int>({1, 0}));
}
SECTION("garbage tokens are ignored") {
REQUIRE(parse_cyclic_order("3,abc,,2,x1", 4) == std::vector<unsigned int>({2, 1}));
}
SECTION("tokens that only start with a number are ignored") {
// "2x" must be dropped rather than parsed as filament 2.
REQUIRE(parse_cyclic_order("3,2x,1", 4) == std::vector<unsigned int>({2, 0}));
}
SECTION("empty string yields an empty order") {
REQUIRE(parse_cyclic_order("", 4).empty());
}
SECTION("a partial sequence only names the filaments it lists") {
REQUIRE(parse_cyclic_order("3,1", 4) == std::vector<unsigned int>({2, 0}));
}
}
+100
View File
@@ -2,6 +2,15 @@
#include "libslic3r/Utils.hpp"
#include "test_utils.hpp"
#include <boost/filesystem.hpp>
#include <algorithm>
#include <cctype>
#include <fstream>
#include <string>
#ifndef _WIN32
#include <unistd.h> // getuid
#endif
@@ -52,3 +61,94 @@ TEST_CASE("per-user temp root is unchanged on Windows, isolated elsewhere", "[ut
REQUIRE_THAT(root, Catch::Matchers::StartsWith(base + "/orcaslicer_"));
#endif
}
TEST_CASE("copy_file reports the OS error when the destination cannot be written", "[utils]") {
ScopedTemporaryFile source(".txt");
{
std::ofstream ofs(source.string(), std::ios::binary);
ofs << "orca";
}
REQUIRE(boost::filesystem::exists(source.path()));
// A directory that was never created, so the copy fails on every platform.
const boost::filesystem::path destination = source.path().parent_path() / "orca-missing-dir" / "copy.txt";
REQUIRE_FALSE(boost::filesystem::exists(destination.parent_path()));
std::string error_message;
REQUIRE(copy_file(source.string(), destination.string(), error_message) == FAIL_COPY_FILE);
REQUIRE_FALSE(error_message.empty());
#ifdef _WIN32
// The Windows branch formats GetLastError() itself. Writing that as
// "Error: " + errCode adds an integer to a string literal, which indexes into the
// literal instead of appending and runs off its end for any code above 7.
const std::string prefix = "Error: ";
REQUIRE(error_message.rfind(prefix, 0) == 0);
const std::string code = error_message.substr(prefix.size());
REQUIRE_FALSE(code.empty());
REQUIRE(std::all_of(code.begin(), code.end(), [](unsigned char c) { return std::isdigit(c) != 0; }));
#endif // _WIN32
}
TEST_CASE("A resolved input path still names the same file after the working directory changes", "[utils]") {
ScopedTemporaryFile model(".3mf");
{ std::ofstream out(model.string()); out << "3mf"; }
const std::string name = model.path().filename().string();
// Resolve the bare name from the directory holding the file, then move away from it. The guard
// restores the directory the test started in, wherever this leaves it.
ScopedWorkingDirectory cwd(model.path().parent_path());
const std::string resolved = resolve_cli_input_path(name);
boost::filesystem::current_path(boost::filesystem::path(TEST_DATA_DIR));
REQUIRE(boost::filesystem::exists(resolved));
REQUIRE(boost::filesystem::equivalent(resolved, model.path()));
// Control: the bare name finds nothing from here, so resolving it this late would have failed.
REQUIRE_FALSE(boost::filesystem::exists(name));
}
TEST_CASE("resolve_cli_input_path completes a relative path against the working directory", "[utils]") {
ScopedWorkingDirectory cwd(boost::filesystem::temp_directory_path());
// Read back rather than reusing temp_directory_path(): changing to it resolves any symlink.
const boost::filesystem::path here = boost::filesystem::current_path();
SECTION("a bare name") {
REQUIRE(resolve_cli_input_path("model.3mf") == (here / "model.3mf").make_preferred().string());
}
SECTION("a ./ prefix is dropped") {
REQUIRE(resolve_cli_input_path("./model.3mf") == (here / "model.3mf").make_preferred().string());
}
SECTION("a ../ traversal is collapsed") {
REQUIRE(resolve_cli_input_path("../model.3mf") == (here.parent_path() / "model.3mf").make_preferred().string());
}
}
TEST_CASE("resolve_cli_input_path leaves inputs that must not be completed unchanged", "[utils]") {
SECTION("an absolute path") {
const boost::filesystem::path absolute = (boost::filesystem::temp_directory_path() / "model.3mf").make_preferred();
REQUIRE(resolve_cli_input_path(absolute.string()) == absolute.string());
}
#ifdef _WIN32
// Every absolute form Windows accepts opens today, so each must come back byte for byte:
// normalizing them would rewrite the forward slashes and rebuild the \\?\ and UNC prefixes.
SECTION("an absolute Windows path of any form") {
for (const std::string absolute : {R"(C:\models\model.3mf)",
R"(C:/models/model.3mf)",
R"(\\server\share\model.3mf)",
R"(\\?\C:\models\model.3mf)"})
REQUIRE(resolve_cli_input_path(absolute) == absolute);
}
#endif
// These are downloaded rather than opened, and completing one would produce a path, not a URL.
SECTION("a custom open protocol URL") {
for (const std::string url : {"orcaslicer://open/?file=https://example.com/model.3mf",
"prusaslicer://open/?file=https://example.com/model.3mf",
"bambustudio://open/?file=https://example.com/model.3mf",
"cura://open/?file=https://example.com/model.3mf"})
REQUIRE(resolve_cli_input_path(url) == url);
}
SECTION("an empty argument") {
REQUIRE(resolve_cli_input_path("").empty());
}
}
File diff suppressed because it is too large Load Diff
+289
View File
@@ -0,0 +1,289 @@
#include <catch2/catch_all.hpp>
#include <cmath>
#include "libslic3r/BoundingBox.hpp"
#include "libslic3r/ClipperUtils.hpp"
#include "libslic3r/GCode/WipeTower.hpp"
#include "libslic3r/GCode/WipeTower2.hpp"
#include "libslic3r/Print.hpp"
#include "libslic3r/PrintConfig.hpp"
using namespace Slic3r;
using Catch::Matchers::WithinAbs;
// A Bambu P1S project that reproduced the off-plate brim: two PLAs priming 30 and 45 mm3 in
// separate adhesiveness categories on a 35 mm tower, 0.21 mm layers, 0.4 nozzle (0.5 mm lines),
// 150 % infill gap (0.75 mm line pitch), rib width 8, 16 mm tall.
static std::vector<WipeTower::PurgeEstimate> cube_purges(int first_category = 100)
{
return {{30.f, first_category}, {45.f, 0}};
}
TEST_CASE("Cone base polygon bulges past the body box", "[WipeTower]") {
// Zero angle: plain body box.
const Polygon box = WipeTower2::cone_base_polygon(35., 20., 100., 0.);
CHECK(box.points.size() == 4);
CHECK(get_extents(box).size() == Point::new_scale(Vec2d(35., 20.)));
// A 25-degree cone on a 100 mm tower: base radius R = tan(12.5deg)*100 = 22.2 mm,
// which exceeds the body half-depth, so the footprint bulges to center +- R in y
// (support_scale keeps the x extent compressed near the body).
const Polygon base = WipeTower2::cone_base_polygon(35., 20., 100., 25.);
const BoundingBox bb = get_extents(base);
const double R = std::tan(25. / 2. * M_PI / 180.) * 100.;
CHECK_THAT(unscaled(bb.min.y()), WithinAbs(10. - R, 0.1));
CHECK_THAT(unscaled(bb.max.y()), WithinAbs(10. + R, 0.1));
// The footprint always contains the body box.
CHECK(diff(Polygons{box}, Polygons{base}).empty());
}
TEST_CASE("Type1 block-stack depth quantizes each purge to whole lines", "[WipeTower]") {
// A 0.5 mm line at 0.21 mm carries 0.0955 mm3 per mm, so across the 34 mm between the
// perimeters 30 mm3 is 10 lines and 45 mm3 is 14: 7.5 + 10.5 at the 0.75 mm pitch behind
// one perimeter width. The generated mesh of the project measured exactly this.
CHECK_THAT(WipeTower::estimate_tower_blocks_depth(cube_purges(), 35.f, 0.21f, 0.4f, 1.5f), WithinAbs(18.5f, 0.01f));
// Sharing one category, a layer can never purge into every filament (one of them starts
// the layer), so the block is sized by its worst layer and the 10-line purge drops out.
CHECK_THAT(WipeTower::estimate_tower_blocks_depth(cube_purges(0), 35.f, 0.21f, 0.4f, 1.5f), WithinAbs(11.0f, 0.01f));
CHECK_THAT(WipeTower::estimate_tower_blocks_depth({}, 35.f, 0.2f, 0.4f, 1.f), WithinAbs(0.f, 1e-6f));
// A width narrower than two perimeter widths cannot hold purge lines.
CHECK_THAT(WipeTower::estimate_tower_blocks_depth({{45.f, 0}}, 0.9f, 0.2f, 0.4f, 1.f), WithinAbs(0.f, 1e-6f));
}
TEST_CASE("A nozzle change adds its ramming lines to the block", "[WipeTower]") {
// 10 mm of 1.75 mm filament (24.05 mm3) laid as 1.0 mm nozzle-change lines at 0.2 mm
// (0.1914 mm2 each) is 125.7 mm; across the 48.5 mm available that is 3 lines of 1.0 mm.
std::vector<WipeTower::PurgeEstimate> purges{{100.f, 0}, {100.f, 0}};
const float without_change = WipeTower::estimate_tower_blocks_depth(purges, 50.f, 0.2f, 0.4f, 1.f);
purges.front().filament_change_length = 10.f;
CHECK_THAT(WipeTower::estimate_tower_blocks_depth(purges, 50.f, 0.2f, 0.4f, 1.f) - without_change, WithinAbs(3.f, 1e-4f));
}
TEST_CASE("Rib tower footprint estimate covers the generated footprint", "[WipeTower]") {
// The generated first-layer wall bbox of the project measured 29.56 mm from the sliced
// G-code; the volume-only estimate said 23.585 mm.
const float side = WipeTower::estimate_rib_tower_bbox_side(cube_purges(), 35.f, 0.21f, 0.4f, 1.5f, 8.f, 0.f, 16.f);
CHECK(side >= 29.56f);
CHECK(side <= 29.56f + 4.f); // without grossly over-reserving plate space
// Separate categories stack their blocks, so the footprint must not shrink when they differ.
CHECK(side >= WipeTower::estimate_rib_tower_bbox_side(cube_purges(0), 35.f, 0.21f, 0.4f, 1.5f, 8.f, 0.f, 16.f));
CHECK_THAT(WipeTower::estimate_rib_tower_bbox_side({}, 35.f, 0.2f, 0.4f, 1.f, 8.f, 0.f, 16.f), WithinAbs(0.f, 1e-6f));
}
TEST_CASE("Rib footprint extends the ribs, not the body, below the stability minimum", "[WipeTower]") {
// A 10 mm body under a 90 mm print: the ribs stretch to the minimum depth's diagonal, and
// the rib width is capped at half the body, so the square grows to minimum + 5 / sqrt(2).
const float min_depth = WipeTower::get_limit_depth_by_height(90.f);
REQUIRE(min_depth > 10.f);
CHECK_THAT(WipeTower::rib_footprint_side(10.f, 10.f, 8.f, 0.f, 90.f), WithinAbs(min_depth + 5.f / std::sqrt(2.f), 1e-4f));
// The extra rib length runs along the diagonal, so it shows as its projection on each axis.
const float plain = WipeTower::rib_footprint_side(30.f, 30.f, 8.f, 0.f, 5.f);
CHECK_THAT(plain, WithinAbs(30.f + 8.f / std::sqrt(2.f), 1e-4f));
CHECK_THAT(WipeTower::rib_footprint_side(30.f, 30.f, 8.f, 4.f, 5.f) - plain, WithinAbs(4.f / std::sqrt(2.f), 1e-4f));
// A negative extra length cannot pull the ribs inside the diagonal.
CHECK_THAT(WipeTower::rib_footprint_side(30.f, 30.f, 8.f, -4.f, 5.f), WithinAbs(plain, 1e-4f));
CHECK_THAT(WipeTower::rib_footprint_side(0.f, 30.f, 8.f, 0.f, 5.f), WithinAbs(0.f, 1e-6f));
}
TEST_CASE("Brim width estimate matches each generator's loop quantization", "[WipeTower]") {
// 3 mm configured, 0.4 nozzle, 0.2 first layer: 0.4571 mm spacing, 7 loops. WipeTower2
// prints and reports the 7 loops; WipeTower reports half a spacing of line width on top.
const float spacing = 0.5f - 0.2f * float(1. - M_PI_4);
CHECK_THAT(WipeTower::estimate_brim_real_width(3.f, 0.4f, 0.2f, true), WithinAbs(7.f * spacing, 1e-4f));
CHECK_THAT(WipeTower::estimate_brim_real_width(3.f, 0.4f, 0.2f, false), WithinAbs(7.5f * spacing, 1e-4f));
CHECK_THAT(WipeTower::estimate_brim_real_width(0.f, 0.4f, 0.2f, true), WithinAbs(0.f, 1e-6f));
}
// ---------------------------------------------------------------------------------------------
// "No sparse layers": the compaction rule and the clearance it demands of the plate.
// ---------------------------------------------------------------------------------------------
// A square of side mm centred on (cx, cy), in bed coordinates.
static Polygon centered_square(double cx, double cy, double side)
{
const double h = 0.5 * side;
Polygon poly;
poly.points = {Point::new_scale(cx - h, cy - h), Point::new_scale(cx + h, cy - h),
Point::new_scale(cx + h, cy + h), Point::new_scale(cx - h, cy + h)};
return poly;
}
static WipeTower::ToolChangeResult make_tcr(int initial_tool, int new_tool, float layer_height)
{
WipeTower::ToolChangeResult tcr{};
tcr.initial_tool = initial_tool;
tcr.new_tool = new_tool;
tcr.layer_height = layer_height;
return tcr;
}
// A 20 mm square tower at the bed origin, no spiral z-hop, so the keep-out zone is the bare
// footprint and every distance below is one the test sets.
static PrintConfig clearance_config()
{
PrintConfig cfg;
cfg.extruder_clearance_radius.value = 40.;
cfg.extruder_clearance_dist_to_rod.value = 20.;
cfg.extruder_clearance_height_to_rod.value = 25.;
cfg.extruder_clearance_height_to_lid.value = 120.;
cfg.nozzle_height.value = 5.;
cfg.nozzle_diameter.values = {0.4};
cfg.z_hop.values = {0.};
cfg.travel_slope.values = {3.};
return cfg;
}
TEST_CASE("Sparse layers are skipped only when nothing else needs a tower on every layer", "[WipeTower][NoSparseLayers]") {
PrintConfig cfg;
cfg.timelapse_type.value = TimelapseType::tlTraditional;
cfg.enable_wrapping_detection.value = false;
cfg.wipe_tower_no_sparse_layers.value = false;
CHECK_FALSE(wipe_tower_sparse_layers_skipped(cfg));
cfg.wipe_tower_no_sparse_layers.value = true;
CHECK(wipe_tower_sparse_layers_skipped(cfg));
// Both park the nozzle on the tower every layer, so no layer is ever dropped and the option
// must read as off everywhere rather than compact in one place and not another.
cfg.timelapse_type.value = TimelapseType::tlSmooth;
CHECK_FALSE(wipe_tower_sparse_layers_skipped(cfg));
cfg.timelapse_type.value = TimelapseType::tlTraditional;
cfg.enable_wrapping_detection.value = true;
CHECK_FALSE(wipe_tower_sparse_layers_skipped(cfg));
}
TEST_CASE("A planned layer is sparse only when its single tool change keeps the filament", "[WipeTower][NoSparseLayers]") {
CHECK(wipe_tower_layer_is_sparse({make_tcr(1, 1, 0.2f)}));
CHECK_FALSE(wipe_tower_layer_is_sparse({make_tcr(0, 1, 0.2f)}));
// A second entry means the layer carries real work whatever the tools are.
CHECK_FALSE(wipe_tower_layer_is_sparse({make_tcr(1, 1, 0.2f), make_tcr(1, 1, 0.2f)}));
CHECK_FALSE(wipe_tower_layer_is_sparse({}));
}
TEST_CASE("The compacted tower falls one layer height behind the object per sparse layer", "[WipeTower][NoSparseLayers]") {
// Five 0.2 mm layers off a 0.1 mm z offset, the middle two sparse. The object reaches
// 0.1 + 5 * 0.2 = 1.1; the tower only grows on the three printed layers, so it ends at
// 0.1 + 3 * 0.2 = 0.7 and a sparse layer carries the previous value rather than its own.
const std::vector<std::vector<WipeTower::ToolChangeResult>> tool_changes{
{make_tcr(0, 1, 0.2f)}, {make_tcr(1, 1, 0.2f)}, {make_tcr(1, 1, 0.2f)},
{make_tcr(1, 0, 0.2f)}, {make_tcr(0, 1, 0.2f)}};
const std::vector<float> tower_z = compute_compacted_wipe_tower_z(tool_changes, 0.1f);
REQUIRE(tower_z.size() == tool_changes.size());
CHECK_THAT(tower_z[0], WithinAbs(0.3f, 1e-5f));
CHECK_THAT(tower_z[1], WithinAbs(0.3f, 1e-5f));
CHECK_THAT(tower_z[2], WithinAbs(0.3f, 1e-5f));
CHECK_THAT(tower_z[3], WithinAbs(0.5f, 1e-5f));
CHECK_THAT(tower_z[4], WithinAbs(0.7f, 1e-5f));
CHECK_THAT(1.1f - tower_z.back(), WithinAbs(2 * 0.2f, 1e-5f));
// Without a base the tower starts at the bed, and an empty layer carries over like a sparse one.
const std::vector<float> no_offset = compute_compacted_wipe_tower_z({{make_tcr(0, 1, 0.2f)}, {}}, 0.f);
CHECK_THAT(no_offset[0], WithinAbs(0.2f, 1e-5f));
CHECK_THAT(no_offset[1], WithinAbs(0.2f, 1e-5f));
}
TEST_CASE("The tower keep-out zone grows by the spiral z-hop envelope", "[WipeTower][NoSparseLayers]") {
PrintConfig cfg = clearance_config();
const Polygon footprint = centered_square(0., 0., 20.);
// No lift, no envelope: the zone works on the bare footprint.
CHECK_THAT(unscaled(compacted_wipe_tower_zone(cfg, footprint).hull.bounding_box().max.x()), WithinAbs(10., 1e-6));
// A spiral lift leaves the outline at low z, so it counts as tower. The circle reaches
// 2 * lift / (2*pi*atan(slope)) past the outline, matching GCodeWriter: 2*2/(2*pi*atan(3)) = 0.51 mm.
cfg.z_hop.values = {2.};
const CompactedTowerZone lifted = compacted_wipe_tower_zone(cfg, footprint);
CHECK_THAT(unscaled(lifted.hull.bounding_box().max.x()), WithinAbs(10.51, 0.02));
CHECK_THAT(unscaled(lifted.hull.bounding_box().min.y()), WithinAbs(-10.51, 0.02));
CHECK(diff(Polygons{footprint}, Polygons{lifted.hull}).empty());
// z_hop is capped at 5 mm by the option, so a taller lift cannot widen the zone further.
cfg.z_hop.values = {10.};
const double capped = unscaled(compacted_wipe_tower_zone(cfg, footprint).hull.bounding_box().max.x());
CHECK_THAT(capped, WithinAbs(10. + 2. * 5. / (2. * M_PI * std::atan(3.)), 0.02));
// The rod sweeps the whole X axis, so its band is the tower's y span plus half the rod offset.
CHECK_THAT(unscaled(lifted.bbox_rod.max.y()), WithinAbs(10.51 + 10., 0.02));
}
TEST_CASE("An object beside a compacted tower is limited by the nearest part of the toolhead", "[WipeTower][NoSparseLayers]") {
const PrintConfig cfg = clearance_config();
const CompactedTowerZone zone = compacted_wipe_tower_zone(cfg, centered_square(0., 0., 20.));
// Each side carries half its clearance less 0.1 mm slack, so the two outlines meet when the
// objects are a full clearance apart: 2 * (4 - 0.2) / 2 = 3.8 mm for the bare nozzle cone,
// 2 * (40 - 0.2) / 2 = 39.8 mm for the head body. A 10 mm object at x leaves a gap of x - 15.
const double tall = 50., shortish = 3.;
// Gap 1 mm, inside the nozzle cone: the object may not rise above the tower at all.
const CompactedTowerClearance touching = compacted_wipe_tower_clearance(cfg, zone, centered_square(16., 0., 10.), tall);
CHECK_THAT(touching.allowed_rise, WithinAbs(0., 1e-9));
// Gap 10 mm: clear of the cone but inside the head body, which starts at nozzle_height.
const CompactedTowerClearance near_body = compacted_wipe_tower_clearance(cfg, zone, centered_square(25., 0., 10.), tall);
CHECK(near_body.near_body);
CHECK_THAT(near_body.allowed_rise, WithinAbs(5., 1e-9));
CHECK_THAT(near_body.body_clearance, WithinAbs(40., 1e-9));
// The same spot, but an object that never rises past the cone. The body sits above the cone, so
// it cannot reach this object however close it stands, and only the narrow tier applies.
const CompactedTowerClearance low = compacted_wipe_tower_clearance(cfg, zone, centered_square(25., 0., 10.), shortish);
CHECK_FALSE(low.near_body);
CHECK_THAT(low.body_clearance, WithinAbs(4., 1e-9));
CHECK_THAT(low.allowed_rise, WithinAbs(25., 1e-9));
// Gap 55 mm, clear of the head entirely: the rod is the obstacle, since the object shares the
// tower's y band and the rod spans the whole x axis however far apart the two stand.
const CompactedTowerClearance far_in_band = compacted_wipe_tower_clearance(cfg, zone, centered_square(70., 0., 10.), tall);
CHECK_FALSE(far_in_band.near_body);
CHECK_THAT(far_in_band.far_clearance, WithinAbs(25., 1e-9));
CHECK_THAT(far_in_band.allowed_rise, WithinAbs(25., 1e-9));
// Out of the band the rod passes over it and only the lid is left.
const CompactedTowerClearance out_of_band = compacted_wipe_tower_clearance(cfg, zone, centered_square(70., 60., 10.), tall);
CHECK_THAT(out_of_band.allowed_rise, WithinAbs(120., 1e-9));
}
TEST_CASE("The ring drawn around the tower meets the outline drawn around an offender", "[WipeTower][NoSparseLayers]") {
const PrintConfig cfg = clearance_config();
const CompactedTowerZone zone = compacted_wipe_tower_zone(cfg, centered_square(0., 0., 20.));
// What the plater draws has to be what the check tested, otherwise a user moves an object until
// the outlines part and slicing still refuses the plate. Both halves of the 3.8 mm nozzle
// clearance: at a 3 mm gap the rings overlap and the rise limit is zero, at 5 mm neither holds.
for (const auto &c : {std::make_pair(18., true), std::make_pair(20., false)}) {
DYNAMIC_SECTION("object at x = " << c.first) {
const Polygon hull = centered_square(c.first, 0., 10.);
const CompactedTowerClearance clearance = compacted_wipe_tower_clearance(cfg, zone, hull, 3.);
const Polygons rings = compacted_wipe_tower_rings(zone, compacted_tower_body_tier(clearance));
const Polygon outline = compacted_wipe_tower_offender_outline(hull, clearance.body_clearance);
const bool outlines_meet = ! intersection(rings, Polygons{outline}).empty();
const bool rise_denied = clearance.allowed_rise < EPSILON;
CHECK(outlines_meet == c.second);
CHECK(rise_denied == c.second);
}
}
}
TEST_CASE("Only the keep-out ring an object is measured against is drawn", "[WipeTower][NoSparseLayers]") {
const PrintConfig cfg = clearance_config();
const CompactedTowerZone zone = compacted_wipe_tower_zone(cfg, centered_square(0., 0., 20.));
// Drawing the wide ring when no object is judged on it would show a keep-out zone the check can
// never trip, so it is added only once some object reaches past the nozzle cone.
CHECK(compacted_wipe_tower_rings(zone, false).size() == zone.grown_nozzle.size());
CHECK(compacted_wipe_tower_rings(zone, true).size() == zone.grown_nozzle.size() + zone.grown_body.size());
CHECK_THAT(unscaled(get_extents(zone.grown_nozzle).max.x()), WithinAbs(10. + 0.5 * (4. - 0.2), 0.02));
CHECK_THAT(unscaled(get_extents(zone.grown_body).max.x()), WithinAbs(10. + 0.5 * (40. - 0.2), 0.02));
}
TEST_CASE("Footprint padding covers the brim and the extrusion half width on each side", "[WipeTower][NoSparseLayers]") {
// A nominal outline hulls extrusion centre lines and is re-centred once the real wall is known,
// so a line width per side on top of the brim is what keeps an estimate enclosing the real tower.
const PrintConfig cfg = clearance_config();
CHECK_THAT(compacted_tower_footprint_padding(cfg, 2.), WithinAbs(2. + 2. * 0.4, 1e-9));
CHECK_THAT(compacted_tower_footprint_padding(cfg, 0.), WithinAbs(2. * 0.4, 1e-9));
// Callers whose outline already carries the brim pass zero, and a negative one cannot shrink it.
CHECK_THAT(compacted_tower_footprint_padding(cfg, -5.), WithinAbs(2. * 0.4, 1e-9));
}
@@ -0,0 +1,351 @@
#include <catch2/catch_all.hpp>
#include "libslic3r/BoundingBox.hpp"
#include "libslic3r/ClipperUtils.hpp"
#include "libslic3r/GCode/WipeTower.hpp"
#include "libslic3r/GCode/WipeTower2.hpp"
#include "libslic3r/GCode/WipeTowerEstimate.hpp"
#include "libslic3r/PrintConfig.hpp"
#include <cmath>
#include <numeric>
#include <string>
using namespace Slic3r;
using Catch::Matchers::WithinAbs;
// Rectangle wall, one nozzle, 100 mm3 prime volume on a 50 mm wide tower at 0.2 mm layers: one
// purge is 10 mm of depth. The flush matrix is off here; the shipped-default case covers it.
// Built as PresetBundle::full_config builds the GUI's: apply() creates each enum as a
// ConfigOptionEnumGeneric, where full_print_config() would clone the static defaults'
// ConfigOptionEnum<T>. The estimate has to read either.
static DynamicPrintConfig preset_shaped_defaults()
{
DynamicPrintConfig config;
config.apply(FullPrintConfig::defaults());
return config;
}
static DynamicPrintConfig make_config(const char *wall_type = "rectangle")
{
DynamicPrintConfig config = preset_shaped_defaults();
config.set_key_value("prime_tower_width", new ConfigOptionFloat(50.));
config.set_key_value("prime_volume", new ConfigOptionFloat(100.));
config.set_key_value("filament_prime_volume", new ConfigOptionFloats({100.}));
config.set_key_value("filament_adhesiveness_category", new ConfigOptionInts({0}));
config.set_key_value("prime_tower_infill_gap", new ConfigOptionPercent(100.));
config.set_key_value("wipe_tower_extra_spacing", new ConfigOptionPercent(100.));
config.set_key_value("prime_tower_brim_width", new ConfigOptionFloat(3.));
config.set_deserialize_strict("wipe_tower_wall_type", wall_type);
config.set_key_value("wipe_tower_rib_width", new ConfigOptionFloat(8.));
config.set_key_value("wipe_tower_extra_rib_length", new ConfigOptionFloat(0.));
config.set_key_value("nozzle_diameter", new ConfigOptionFloats({0.4}));
config.set_key_value("initial_layer_print_height", new ConfigOptionFloat(0.2));
config.set_deserialize_strict("timelapse_type", "0");
config.set_key_value("enable_wrapping_detection", new ConfigOptionBool(false));
config.set_key_value("raft_layers", new ConfigOptionInt(0));
config.set_key_value("purge_in_prime_tower", new ConfigOptionBool(false));
config.set_key_value("single_extruder_multi_material", new ConfigOptionBool(false));
return config;
}
static std::vector<unsigned int> filaments(size_t count)
{
std::vector<unsigned int> ids(count);
std::iota(ids.begin(), ids.end(), 0u);
return ids;
}
// The first `count` filaments on the given planner; Type2 unless a case says otherwise.
static WipeTowerFootprint estimate(const ConfigBase &config, size_t count, double layer_height, double height, WipeTowerType type = WipeTowerType::Type2)
{
return estimate_wipe_tower_footprint(config, type, filaments(count), layer_height, height);
}
// What both planners print for a 3 mm brim at 0.4 nozzle and 0.2 first layer (0.4571 mm loops).
static double printed_brim(double configured, WipeTowerType type)
{
return WipeTower::estimate_brim_real_width(float(configured), 0.4f, 0.2f, type == WipeTowerType::Type2);
}
TEST_CASE("A rectangle wall tower is sized by the purge volume", "[WipeTowerEstimate]") {
const DynamicPrintConfig config = make_config();
// Three filaments purge twice per layer; a 5 mm object keeps the stability floor at 5 mm.
const WipeTowerFootprint fp = estimate(config, 3, 0.2, 5.);
CHECK_THAT(fp.width, WithinAbs(50., 1e-9));
CHECK_THAT(fp.depth, WithinAbs(20., 1e-9));
CHECK_THAT(fp.height, WithinAbs(5., 1e-9));
CHECK_THAT(fp.brim_width, WithinAbs(printed_brim(3., WipeTowerType::Type2), 1e-6));
// Thinner layers need more depth for the same volume.
CHECK_THAT(estimate(config, 3, 0.1, 5.).depth, WithinAbs(40., 1e-9));
}
TEST_CASE("Each planner spaces its purge lines by its own option", "[WipeTowerEstimate]") {
// Type2 reads wipe_tower_extra_spacing and Type1 prime_tower_infill_gap; neither sees the
// other's key. Type2's extra flow cancels out of its depth.
DynamicPrintConfig config = make_config();
config.set_key_value("wipe_tower_extra_flow", new ConfigOptionPercent(250.));
CHECK_THAT(estimate(config, 3, 0.2, 5.).depth, WithinAbs(20., 1e-9));
config.set_key_value("wipe_tower_extra_spacing", new ConfigOptionPercent(150.));
CHECK_THAT(estimate(config, 3, 0.2, 5.).depth, WithinAbs(30., 1e-9));
const double type1_spaced = estimate(config, 3, 0.2, 5., WipeTowerType::Type1).depth;
config.set_key_value("prime_tower_infill_gap", new ConfigOptionPercent(150.));
CHECK_THAT(estimate(config, 3, 0.2, 5.).depth, WithinAbs(30., 1e-9));
// Type1 stacks whole lines behind one 0.5 mm perimeter width, so only the stack scales.
CHECK_THAT(estimate(config, 3, 0.2, 5., WipeTowerType::Type1).depth - 0.5, WithinAbs(1.5 * (type1_spaced - 0.5), 1e-6));
}
TEST_CASE("Type1 sizes the tower from each filament's own prime volume", "[WipeTowerEstimate]") {
// The Bambu P1S project of the WipeTower cases: 30 and 45 mm3 in two categories on a 35 mm
// tower at 0.21 mm, 150 % gap, is 18.5 mm of stacked blocks (11 mm sharing one category).
DynamicPrintConfig config = make_config();
config.set_key_value("prime_tower_width", new ConfigOptionFloat(35.));
config.set_key_value("prime_tower_infill_gap", new ConfigOptionPercent(150.));
config.set_key_value("initial_layer_print_height", new ConfigOptionFloat(0.21));
config.set_key_value("filament_prime_volume", new ConfigOptionFloats({30., 45.}));
config.set_key_value("filament_adhesiveness_category", new ConfigOptionInts({100, 0}));
const std::vector<WipeTower::PurgeEstimate> purges{{30.f, 100}, {45.f, 0}};
const double blocks = WipeTower::estimate_tower_blocks_depth(purges, 35.f, 0.21f, 0.4f, 1.5f);
REQUIRE_THAT(blocks, WithinAbs(18.5, 0.01));
CHECK_THAT(estimate(config, 2, 0.21, 5., WipeTowerType::Type1).depth, WithinAbs(blocks, 1e-4));
// The ids pick the volumes, so their order does not matter and a lone filament has no purge.
CHECK_THAT(estimate_wipe_tower_footprint(config, WipeTowerType::Type1, {1, 0}, 0.21, 5.).depth, WithinAbs(blocks, 1e-4));
CHECK_THAT(estimate(config, 1, 0.21, 5., WipeTowerType::Type1).depth, WithinAbs(0., 1e-9));
config.set_key_value("filament_adhesiveness_category", new ConfigOptionInts({0, 0}));
CHECK_THAT(estimate(config, 2, 0.21, 5., WipeTowerType::Type1).depth, WithinAbs(11., 0.01));
// A rib wall squares the same stack.
config.set_deserialize_strict("wipe_tower_wall_type", "rib");
const WipeTowerFootprint rib = estimate(config, 2, 0.21, 5., WipeTowerType::Type1);
CHECK_THAT(rib.width, WithinAbs(rib.depth, 1e-9));
CHECK_THAT(rib.depth, WithinAbs(WipeTower::estimate_rib_tower_bbox_side({{30.f, 0}, {45.f, 0}}, 35.f, 0.21f, 0.4f, 1.5f, 8.f, 0.f, 5.f), 1e-4));
}
TEST_CASE("A second nozzle adds the ramming of one nozzle change per layer", "[WipeTowerEstimate]") {
// Two filaments on two nozzles: the tool order crosses once per layer, and Type1 rams 10 mm
// of filament as three 1.0 mm nozzle-change lines (see the WipeTower case).
DynamicPrintConfig config = make_config();
config.set_key_value("nozzle_diameter", new ConfigOptionFloats({0.4, 0.4}));
config.set_key_value("filament_change_length", new ConfigOptionFloats({10., 10.}));
config.set_key_value("filament_diameter", new ConfigOptionFloats({1.75, 1.75}));
config.set_key_value("filament_map", new ConfigOptionInts({1, 1}));
const double same_nozzle = estimate(config, 2, 0.2, 5., WipeTowerType::Type1).depth;
config.set_key_value("filament_map", new ConfigOptionInts({1, 2}));
CHECK_THAT(estimate(config, 2, 0.2, 5., WipeTowerType::Type1).depth - same_nozzle, WithinAbs(3., 1e-4));
}
TEST_CASE("The tower is sized for the first layer when it is the thinnest", "[WipeTowerEstimate]") {
// Both planners reserve the worst layer: a 0.28 mm print with a 0.2 mm first layer needs
// the 0.2 mm depth, while a thicker first layer changes nothing.
DynamicPrintConfig config = make_config();
const double at_thinnest = estimate(config, 3, 0.2, 5.).depth;
CHECK_THAT(estimate(config, 3, 0.28, 5.).depth, WithinAbs(at_thinnest, 1e-9));
config.set_key_value("initial_layer_print_height", new ConfigOptionFloat(0.3));
CHECK(estimate(config, 3, 0.28, 5.).depth < at_thinnest);
}
TEST_CASE("Object height sets the stability floor and the auto brim", "[WipeTowerEstimate]") {
DynamicPrintConfig config = make_config();
// Two filaments purge once: 10 mm, lifted to the 20 mm floor of a 100 mm tower.
CHECK_THAT(estimate(config, 2, 0.2, 100.).depth, WithinAbs(20., 1e-9));
config.set_key_value("prime_tower_brim_width", new ConfigOptionFloat(-1.));
const double auto_brim = WipeTower::get_auto_brim_by_height(50.f);
CHECK_THAT(estimate(config, 2, 0.2, 50.).brim_width, WithinAbs(printed_brim(auto_brim, WipeTowerType::Type2), 1e-6));
CHECK_THAT(estimate(config, 2, 0.2, 50., WipeTowerType::Type1).brim_width, WithinAbs(printed_brim(auto_brim, WipeTowerType::Type1), 1e-6));
}
TEST_CASE("A single filament only gets a tower when one is printed anyway", "[WipeTowerEstimate]") {
DynamicPrintConfig config = make_config();
CHECK_THAT(estimate(config, 1, 0.2, 100.).depth, WithinAbs(0., 1e-9));
CHECK_THAT(estimate(config, 0, 0.2, 100.).width, WithinAbs(0., 1e-9));
// Wrapping detection prints a tower on the first layers whatever the filament count: the
// Type1 planner's fixed 10 mm, the stability floor otherwise.
config.set_key_value("enable_wrapping_detection", new ConfigOptionBool(true));
CHECK_THAT(estimate(config, 1, 0.2, 100.).depth, WithinAbs(20., 1e-9));
CHECK_THAT(estimate(config, 1, 0.2, 100., WipeTowerType::Type1).depth, WithinAbs(WipeTower::get_wrapping_detection_depth(), 1e-9));
config.set_key_value("enable_wrapping_detection", new ConfigOptionBool(false));
// A raft is not one of them: normalize_fdm_2 clears enable_prime_tower for a plate that
// purges one filament unless smooth timelapse or wrapping detection is on, so a raft
// alone leaves no tower to reserve for.
config.set_key_value("raft_layers", new ConfigOptionInt(3));
CHECK_THAT(estimate(config, 1, 0.2, 100.).depth, WithinAbs(0., 1e-9));
config.set_key_value("raft_layers", new ConfigOptionInt(0));
config.set_deserialize_strict("timelapse_type", "1");
// A tower printed with no tool change is exactly the planner's idle depth: there is
// nothing to purge, and WipeTower2 sizes it at the stability floor.
CHECK_THAT(estimate(config, 1, 0.2, 100.).depth, WithinAbs(20., 1e-9));
CHECK_THAT(estimate(config, 1, 0.2, 5.).depth, WithinAbs(WipeTower::get_limit_depth_by_height(5.f), 1e-9));
}
TEST_CASE("A tool change reserves a tower even with nothing to purge", "[WipeTowerEstimate]") {
// The purge volumes are configurable down to zero, but the tool changes are still printed
// on the tower and both planners still floor it - so the estimate has to floor it too.
// Type1 plans per filament and already reserves one; Type2 has only the volume to go on.
const double height = GENERATE(5., 100.);
const float floor = WipeTower::get_limit_depth_by_height(float(height));
const char *wall = GENERATE("rectangle", "rib");
DynamicPrintConfig config = make_config(wall);
config.set_key_value("prime_volume", new ConfigOptionFloat(0.));
config.set_key_value("filament_prime_volume", new ConfigOptionFloats({0.}));
CHECK(estimate(config, 3, 0.2, height, WipeTowerType::Type2).depth >= floor);
CHECK(estimate(config, 3, 0.2, height, WipeTowerType::Type1).depth >= floor);
// Still nothing for a lone filament with no other reason.
CHECK_THAT(estimate(config, 1, 0.2, height, WipeTowerType::Type2).depth, WithinAbs(0., 1e-9));
CHECK_THAT(estimate(config, 1, 0.2, height, WipeTowerType::Type1).depth, WithinAbs(0., 1e-9));
}
TEST_CASE("Both wall types agree on whether there is a tower at all", "[WipeTowerEstimate]") {
// A wall type may only change the shape of the tower, never whether one is reserved:
// reporting no tower for one that is built collapses the validation hull to a point.
const double height = GENERATE(5., 100.);
DynamicPrintConfig rect = make_config();
DynamicPrintConfig rib = make_config("rib");
// No tool change and nothing else that prints a tower - neither wall type reserves one.
CHECK_THAT(estimate(rect, 1, 0.2, height).depth, WithinAbs(0., 1e-9));
CHECK_THAT(estimate(rib, 1, 0.2, height).depth, WithinAbs(0., 1e-9));
// Not even on a dual-nozzle printer, where a lone filament still needs no purge.
rect.set_key_value("nozzle_diameter", new ConfigOptionFloats({0.4, 0.4}));
rib.set_key_value("nozzle_diameter", new ConfigOptionFloats({0.4, 0.4}));
CHECK_THAT(estimate(rect, 1, 0.2, height).depth, WithinAbs(0., 1e-9));
CHECK_THAT(estimate(rib, 1, 0.2, height).depth, WithinAbs(0., 1e-9));
// With a tool change both reserve one, and both respect the stability floor.
CHECK(estimate(rect, 2, 0.2, height).depth >= WipeTower::get_limit_depth_by_height(float(height)));
CHECK(estimate(rib, 2, 0.2, height).depth >= WipeTower::get_limit_depth_by_height(float(height)));
}
TEST_CASE("A rib wall squares the tower and caps the rib width", "[WipeTowerEstimate]") {
DynamicPrintConfig config = make_config("rib");
// sqrt(200 / 0.2) = 31.62 mm square, plus the 8 mm rib bulge along the diagonal.
const double body = std::sqrt(1000.);
WipeTowerFootprint fp = estimate(config, 3, 0.2, 5.);
CHECK_THAT(fp.depth, WithinAbs(8. / std::sqrt(2.) + body, 1e-5));
CHECK_THAT(fp.width, WithinAbs(fp.depth, 1e-9));
// The extra rib length runs along the diagonal and grows the footprint by its projection.
config.set_key_value("wipe_tower_extra_rib_length", new ConfigOptionFloat(4.));
CHECK_THAT(estimate(config, 3, 0.2, 5.).depth, WithinAbs((8. + 4.) / std::sqrt(2.) + body, 1e-5));
// A tiny tower caps the rib width at half its depth: 5 mm body, 2.5 mm rib.
config.set_key_value("wipe_tower_extra_rib_length", new ConfigOptionFloat(0.));
config.set_key_value("prime_volume", new ConfigOptionFloat(5.));
CHECK_THAT(estimate(config, 2, 0.2, 5.).depth, WithinAbs(2.5 / std::sqrt(2.) + 5., 1e-5));
}
TEST_CASE("Every wall and tower type is read the same from a preset and a static config", "[WipeTowerEstimate]") {
// The GUI, arrange and the CLI pass a DynamicPrintConfig whose enums are
// ConfigOptionEnumGeneric; Print passes a static config whose enums are ConfigOptionEnum<T>.
// Both the wall type and the planner selection are read by value, so both give the same shape.
const char *wall_type = GENERATE("rectangle", "cone", "rib");
const char *tower_type = GENERATE("type1", "type2");
DynamicPrintConfig preset = make_config(wall_type);
preset.set_deserialize_strict("wipe_tower_type", tower_type);
REQUIRE(dynamic_cast<const ConfigOptionEnumGeneric *>(preset.option("wipe_tower_wall_type")) != nullptr);
FullPrintConfig static_config;
static_config.apply(preset, true);
REQUIRE(static_config.wipe_tower_wall_type.serialize() == wall_type);
REQUIRE(static_config.wipe_tower_type.serialize() == tower_type);
const WipeTowerType type = resolve_wipe_tower_type(preset);
CHECK(type == (std::string(tower_type) == "type1" ? WipeTowerType::Type1 : WipeTowerType::Type2));
CHECK(resolve_wipe_tower_type(static_config) == type);
// Three filaments purge twice per layer on a 5 mm object.
const WipeTowerFootprint fp = estimate(preset, 3, 0.2, 5., type);
const WipeTowerFootprint from_static = estimate(static_config, 3, 0.2, 5., type);
CHECK(fp.depth > 0.);
if (std::string(wall_type) == "rib")
CHECK_THAT(fp.width, WithinAbs(fp.depth, 1e-9));
else
CHECK_THAT(fp.width, WithinAbs(50., 1e-9));
CHECK_THAT(from_static.width, WithinAbs(fp.width, 1e-9));
CHECK_THAT(from_static.depth, WithinAbs(fp.depth, 1e-9));
CHECK_THAT(from_static.brim_width, WithinAbs(fp.brim_width, 1e-9));
// Smooth timelapse is the other enum the estimate reads: a lone filament gets a tower
// through both storages too.
preset.set_deserialize_strict("timelapse_type", "1");
static_config.apply(preset, true);
CHECK(estimate(preset, 1, 0.2, 5., type).depth > 0.);
CHECK(estimate(static_config, 1, 0.2, 5., type).depth > 0.);
}
TEST_CASE("The first-layer outline bulges only for a Type2 cone wall", "[WipeTowerEstimate]") {
// Read off a preset-shaped config, whose enums are ConfigOptionEnumGeneric: a cast to
// ConfigOptionEnum<T> sees no wall type there and would never find the cone.
DynamicPrintConfig config = make_config("cone");
config.set_key_value("wipe_tower_cone_angle", new ConfigOptionFloat(25.));
REQUIRE(dynamic_cast<const ConfigOptionEnumGeneric *>(config.option("wipe_tower_wall_type")) != nullptr);
const Polygon box = Polygon::new_scale({{0., 0.}, {35., 0.}, {35., 20.}, {0., 20.}});
auto is_box = [&box](const Polygon &outline) { return diff(Polygons{outline}, Polygons{box}).empty(); };
// A 25-degree cone on a 100 mm tower has a 22 mm base radius, past the 10 mm half-depth.
const Polygon cone = estimate_wipe_tower_first_layer_outline(config, WipeTowerType::Type2, 35., 20., 100.);
CHECK(unscaled(get_extents(cone).max.y()) > 20. + 1.);
CHECK(diff(Polygons{box}, Polygons{cone}).empty());
// Type1 ignores the cone option, and the other wall types have no cone.
CHECK(is_box(estimate_wipe_tower_first_layer_outline(config, WipeTowerType::Type1, 35., 20., 100.)));
for (const char *wall_type : {"rectangle", "rib"}) {
config.set_deserialize_strict("wipe_tower_wall_type", wall_type);
CHECK(is_box(estimate_wipe_tower_first_layer_outline(config, WipeTowerType::Type2, 35., 20., 100.)));
}
// The static config Print holds gives the same outline.
config.set_deserialize_strict("wipe_tower_wall_type", "cone");
FullPrintConfig static_config;
static_config.apply(config, true);
const Polygon from_static = estimate_wipe_tower_first_layer_outline(static_config, WipeTowerType::Type2, 35., 20., 100.);
CHECK(from_static.points == cone.points);
}
TEST_CASE("A Bambu Lab printer always gets the Type1 planner", "[WipeTowerEstimate]") {
DynamicPrintConfig config = make_config();
config.set_deserialize_strict("wipe_tower_type", "type2");
config.set_key_value("printer_model", new ConfigOptionString("Bambu Lab X1 Carbon"));
CHECK(resolve_wipe_tower_type(config) == WipeTowerType::Type1);
config.set_key_value("printer_model", new ConfigOptionString("Voron 2.4"));
CHECK(resolve_wipe_tower_type(config) == WipeTowerType::Type2);
config.erase("wipe_tower_type");
CHECK(resolve_wipe_tower_type(config) == WipeTowerType::Type2);
}
TEST_CASE("A dual nozzle purges every filament plus the filament change", "[WipeTowerEstimate]") {
DynamicPrintConfig config = make_config();
config.set_key_value("nozzle_diameter", new ConfigOptionFloats({0.4, 0.4}));
config.set_key_value("filament_change_length", new ConfigOptionFloats({10., 10.}));
config.set_key_value("filament_diameter", new ConfigOptionFloats({1.75, 1.75}));
// Two purges of 100 mm3 plus one 10 mm filament change: (200 + 10 * pi * 1.75^2 / 4) / (0.2 * 50).
const double change_volume = 10. * PI * 1.75 * 1.75 / 4.;
CHECK_THAT(estimate(config, 2, 0.2, 5.).depth, WithinAbs((200. + change_volume) / 10., 1e-9));
}
TEST_CASE("The shipped defaults size the tower from the flush matrix", "[WipeTowerEstimate]") {
// Both keys default to true, so the shipped configuration purges the flush volumes rather
// than the prime volume, with no infill gap on top - the flush volumes already hold it.
DynamicPrintConfig config = preset_shaped_defaults();
REQUIRE(config.opt_bool("purge_in_prime_tower"));
REQUIRE(config.opt_bool("single_extruder_multi_material"));
config.set_key_value("prime_tower_width", new ConfigOptionFloat(50.));
config.set_deserialize_strict("wipe_tower_wall_type", "rectangle");
config.set_key_value("nozzle_diameter", new ConfigOptionFloats({0.4}));
const double flush_volume = WipeTower2::estimate_semm_flush_volume(config, 2);
const double expected = std::max(double(WipeTower::get_limit_depth_by_height(5.f)), flush_volume / (0.2 * 50.));
CHECK_THAT(estimate(config, 2, 0.2, 5.).depth, WithinAbs(expected, 1e-6));
}
TEST_CASE("A config missing a tower key falls back to that key's default", "[WipeTowerEstimate]") {
// The signature takes any ConfigBase: an absent key must read as its declared default.
const DynamicPrintConfig full = make_config();
DynamicPrintConfig partial = full;
partial.erase("wipe_tower_extra_spacing");
REQUIRE(partial.option("wipe_tower_extra_spacing") == nullptr);
DynamicPrintConfig defaulted = full;
defaulted.set_key_value("wipe_tower_extra_spacing",
print_config_def.get("wipe_tower_extra_spacing")->default_value->clone());
CHECK_THAT(estimate(partial, 3, 0.2, 5.).depth, WithinAbs(estimate(defaulted, 3, 0.2, 5.).depth, 1e-9));
}