From 40f43febbdc777e8233b54a9c4449e30110f65fc Mon Sep 17 00:00:00 2001 From: SoftFever <103989404+SoftFever@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:32:10 +0800 Subject: [PATCH 01/26] Register Fill bed instances with the plate they land on (#17480) --- src/slic3r/GUI/Jobs/FillBedJob.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/slic3r/GUI/Jobs/FillBedJob.cpp b/src/slic3r/GUI/Jobs/FillBedJob.cpp index f3da5e631b..e30d3df9c4 100644 --- a/src/slic3r/GUI/Jobs/FillBedJob.cpp +++ b/src/slic3r/GUI/Jobs/FillBedJob.cpp @@ -396,6 +396,11 @@ void FillBedJob::finalize(bool canceled, std::exception_ptr &eptr) if (m_instances && model_object->instances.size() > inst_cnt) { const size_t new_instance_count = model_object->instances.size() - inst_cnt; + // Register the copies with the plate they land on, which is what plate lookups and + // object labels read. As new instances they take a spiral-vase plate's settings + // without asking once per copy, as the objects Fill bed with copies adds do. + for (size_t i = inst_cnt; i < model_object->instances.size(); ++i) + plate_list.notify_instance_update(m_object_idx, int(i), true); // Match the normal add-instance flow: update the scene before the // object tree starts referring to the newly created instances. m_plater->update(); From d7534d7fb9fc8e788313b81a80a83e598450d6c8 Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:53:37 +0800 Subject: [PATCH 02/26] Fix the Crash When the Per-Extruder Printable Areas Do Not Overlap (#17439) When the per-extruder printable areas only touched or did not overlap, get_shared_poly read the first polygon of an empty intersection. That crashed the CLI on the bed shape, and the GUI in scale to fit, fill bed and prime tower placement. The shared area is now empty in that case. An area with fewer than three points leaves its extruder the whole bed. Placement (get_bed_shape with use_share, PartPlate::get_build_volume(true)) falls back to the whole bed. The prime tower's default position and drag fall back to the plate's shape. Validation now says the extruder printable areas share no common area, instead of reporting the tower as partially outside the printable area. Profiles whose areas overlap, and profiles without areas, get the same shapes as before. --- src/libslic3r/Print.cpp | 6 +- src/libslic3r/PrintConfig.cpp | 68 ++++++++++----------- src/libslic3r/PrintConfig.hpp | 5 +- src/slic3r/GUI/PartPlate.cpp | 10 ++- src/slic3r/GUI/PartPlate.hpp | 7 ++- src/slic3r/GUI/Selection.cpp | 6 +- tests/fff_print/test_wipe_tower.cpp | 50 +++++++++++++++ tests/libslic3r/test_arrange.cpp | 27 ++++++++ tests/libslic3r/test_config.cpp | 95 +++++++++++++++++++++++++++++ 9 files changed, 231 insertions(+), 43 deletions(-) diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 1c90f33458..a2400c4905 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -1819,8 +1819,12 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, const Point plate_shift(scale_(plate_origin.x()), scale_(plate_origin.y())); for (Polygon &p : printable_polys) p.translate(plate_shift); - if (!diff(tower_polys_checked, printable_polys).empty()) + if (!diff(tower_polys_checked, printable_polys).empty()) { + // Moving the tower does not help when no area is reached by every extruder. + if (printable_polys.empty()) + return {L("The extruder printable areas share no common area, so the prime tower cannot be printed.\n")}; return {L("Prime tower is partially outside the printable area, and it cannot be printed.\n")}; + } if (warning && !diff(tower_polys_estimated, printable_polys).empty()) warning->string += L("Prime tower is partially outside the printable area, and it cannot be printed.\n"); return {}; diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 42dbe730b3..60d2fdc03a 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -13788,23 +13788,39 @@ static Points to_points(const std::vector &dpts) return pts; } -Polygon get_shared_poly(const std::vector& extruder_polys) +Polygon get_shared_poly(const std::vector& extruder_polys, const Pointfs& bed) { Polygon result; - for (int index = 0; index < extruder_polys.size(); index++) - { - const Pointfs& extruder_area = extruder_polys[index]; - if (index == 0) - result.points = to_points(extruder_area); - else { - Polygon extruer_poly; - extruer_poly.points = to_points(extruder_area); - Polygons result_polygon = intersection(extruer_poly, result); - result = result_polygon[0]; + bool limited = false; + for (const Pointfs& extruder_area : extruder_polys) { + // Not a shape: this extruder reaches the whole bed. + if (extruder_area.size() < 3) + continue; + Polygon extruder_poly; + extruder_poly.points = to_points(extruder_area); + if (!limited) { + result = std::move(extruder_poly); + limited = true; + continue; } + Polygons shared = intersection(extruder_poly, result); + if (shared.empty()) + return {}; + result = shared.front(); } + if (!limited) + result.points = to_points(make_counter_clockwise(bed)); return result; } + +// Objects are placed on the area every extruder reaches. Without one, an object can still be printed +// by the extruders that reach it, so place on the whole bed: slicing rejects what cannot be reached. +static Points placement_bed_shape(const std::vector& extruder_polys, const Pointfs& bed) +{ + Points shared = get_shared_poly(extruder_polys, bed).points; + return shared.empty() ? to_points(make_counter_clockwise(bed)) : shared; +} + Points get_bed_shape(const DynamicPrintConfig &config, bool use_share) { const ConfigOptionPoints *bed_shape_opt = config.opt("printable_area"); @@ -13818,37 +13834,19 @@ Points get_bed_shape(const DynamicPrintConfig &config, bool use_share) return {}; } - Polygon bed_poly; if (use_share) { const ConfigOptionPointsGroups *extruder_area_opt = config.opt("extruder_printable_area"); - if (extruder_area_opt && (extruder_area_opt->size() > 0)) { - const std::vector& extruder_areas = extruder_area_opt->values; - bed_poly = get_shared_poly(extruder_areas); - } - else - bed_poly.points = to_points(make_counter_clockwise(bed_shape_opt->values)); + if (extruder_area_opt) + return placement_bed_shape(extruder_area_opt->values, bed_shape_opt->values); } - else - bed_poly.points = to_points(make_counter_clockwise(bed_shape_opt->values)); - - return bed_poly.points; + return to_points(make_counter_clockwise(bed_shape_opt->values)); } Points get_bed_shape(const PrintConfig &cfg, bool use_share) { - Polygon bed_poly; - if (use_share) { - const std::vector& extruder_areas = cfg.extruder_printable_area.values; - if (extruder_areas.size() > 0) { - bed_poly = get_shared_poly(extruder_areas); - } - else - bed_poly.points = to_points(make_counter_clockwise(cfg.printable_area.values)); - } - else - bed_poly.points = to_points(make_counter_clockwise(cfg.printable_area.values)); - - return bed_poly.points; + if (use_share) + return placement_bed_shape(cfg.extruder_printable_area.values, cfg.printable_area.values); + return to_points(make_counter_clockwise(cfg.printable_area.values)); } Points get_bed_shape(const SLAPrinterConfig &cfg) { return to_points(make_counter_clockwise(cfg.printable_area.values)); } diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index c355bae7d7..da8d6eb56e 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -2546,7 +2546,10 @@ private: bool is_XL_printer(const DynamicPrintConfig &cfg); bool is_XL_printer(const PrintConfig &cfg); -Polygon get_shared_poly(const std::vector& extruder_polys); +// The area every extruder can reach: the whole bed when no extruder has an area of its own, and empty +// when the extruder areas do not overlap. +Polygon get_shared_poly(const std::vector& extruder_polys, const Pointfs& bed); +// The bed to place objects on. With use_share it is the shared area, or the whole bed when there is none. Points get_bed_shape(const DynamicPrintConfig &cfg, bool use_share = true); Points get_bed_shape(const PrintConfig &cfg, bool use_share = false); Points get_bed_shape(const SLAPrinterConfig &cfg); diff --git a/src/slic3r/GUI/PartPlate.cpp b/src/slic3r/GUI/PartPlate.cpp index 801474549c..35c38e4820 100644 --- a/src/slic3r/GUI/PartPlate.cpp +++ b/src/slic3r/GUI/PartPlate.cpp @@ -5190,8 +5190,9 @@ BoundingBoxf3 PartPlate::get_build_volume(bool use_share) auto eps=Slic3r::BuildVolume::SceneEpsilon; Vec3d up_point; Vec3d low_point; - if (use_share && !m_extruder_areas.empty()) { - Polygon bed_poly = get_shared_poly(m_extruder_areas); + // Extruder areas that share nothing leave the whole plate to place on. + const Polygon bed_poly = use_share && !m_extruder_areas.empty() ? get_shared_poly(m_extruder_areas, m_shape) : Polygon(); + if (!bed_poly.points.empty()) { BoundingBox bbox = bed_poly.bounding_box(); up_point = Vec3d(unscale_(bbox.max.x()) + eps, unscale_(bbox.max.y()) + eps, m_origin.z() + m_height + eps); @@ -5208,7 +5209,7 @@ BoundingBoxf3 PartPlate::get_build_volume(bool use_share) Polygon PartPlate::get_shared_printable_polygon() const { - return m_extruder_areas.empty() ? Polygon::new_scale(m_shape) : get_shared_poly(m_extruder_areas); + return m_extruder_areas.empty() ? Polygon::new_scale(m_shape) : get_shared_poly(m_extruder_areas, m_shape); } @@ -6340,6 +6341,9 @@ void PartPlateList::set_default_wipe_tower_pos_for_plate(int plate_idx, bool ini // prime tower is validated against the real outline — pull it onto the bed before storing. { Polygons bed{part_plate->get_shared_printable_polygon()}; + // Without an area every extruder reaches the tower cannot be printed, but it still stays on the plate. + if (bed.front().points.empty()) + bed.front() = Polygon::new_scale(part_plate->get_shape()); bed.front().translate(Point(-scaled(plate_origin.x()), -scaled(plate_origin.y()))); // into the frame x/y live in const BoundingBox tower(Point::new_scale(x, y), Point::new_scale(x + wipe_tower_size(0), y + wipe_tower_size(1))); diff --git a/src/slic3r/GUI/PartPlate.hpp b/src/slic3r/GUI/PartPlate.hpp index 7ae0ce2d3a..32b344774b 100644 --- a/src/slic3r/GUI/PartPlate.hpp +++ b/src/slic3r/GUI/PartPlate.hpp @@ -613,9 +613,12 @@ public: const BoundingBoxf3& get_bounding_box(bool extended = false) { return extended ? m_extended_bounding_box : m_bounding_box; } const BoundingBox get_bounding_box_crd(); BoundingBoxf3 get_plate_box() {return get_build_volume();} + // The volume to place objects in. With use_share it is bounded by the area every extruder + // reaches, or by the whole plate when there is none. BoundingBoxf3 get_build_volume(bool use_share = false); - // Polygon counterpart of get_build_volume(true), in scaled world coordinates. The bounding box - // that one returns hides the corners a non-rectangular bed does not have. + // The area every extruder reaches, in scaled world coordinates: unlike the bounding box of + // get_build_volume(true) it keeps the corners a non-rectangular bed does not have, and it is + // empty when the extruder areas do not overlap. Polygon get_shared_printable_polygon() const; const std::vector& get_exclude_areas() { return m_exclude_bounding_box; } diff --git a/src/slic3r/GUI/Selection.cpp b/src/slic3r/GUI/Selection.cpp index 7d5264e997..57c40059ce 100644 --- a/src/slic3r/GUI/Selection.cpp +++ b/src/slic3r/GUI/Selection.cpp @@ -1293,7 +1293,11 @@ void Selection::translate(const Vec3d &displacement, TransformationType transfor } else { if (v.is_wipe_tower) {//in world cs int plate_idx = v.object_idx() - 1000; - const Polygons bed_polys{wxGetApp().plater()->get_partplate_list().get_plate(plate_idx)->get_shared_printable_polygon()}; + PartPlate* plate = wxGetApp().plater()->get_partplate_list().get_plate(plate_idx); + Polygons bed_polys{plate->get_shared_printable_polygon()}; + // Without an area every extruder reaches the tower cannot be printed, but it still stays on the plate. + if (bed_polys.front().points.empty()) + bed_polys.front() = Polygon::new_scale(plate->get_shape()); Vec3d tower_origin = m_cache.volumes_data[i].get_volume_position(); Vec3d actual_displacement = displacement; // Both preview volumes carry the brim in their bounding box, and the release diff --git a/tests/fff_print/test_wipe_tower.cpp b/tests/fff_print/test_wipe_tower.cpp index ece5c4a87d..03f44e851f 100644 --- a/tests/fff_print/test_wipe_tower.cpp +++ b/tests/fff_print/test_wipe_tower.cpp @@ -770,6 +770,56 @@ TEST_CASE("A tower printed without a tool change is still validated against the CHECK_THAT(print.validate().string, Catch::Matchers::ContainsSubstring("printable area")); } +// Two nozzles over a 200 mm bed, nozzle 1 reaching x up to `left_max` and nozzle 2 x from `right_min`, +// with a 20 mm cube at the bed's left and, when `filaments` is 2, a prime tower at (30, 150). +static StringObjectException validate_on_two_nozzle_areas(double left_max, double right_min, unsigned int filaments) +{ + DynamicPrintConfig config = tower_estimate_config("rectangle", filaments); + config.set_num_extruders(2); + config.set_deserialize_strict({ + { "nozzle_diameter", "0.4,0.4" }, + { "printer_extruder_id", "1,2" }, + { "printer_extruder_variant", "Direct Drive Standard,Direct Drive Standard" }, + { "printable_area", "0x0,200x0,200x200,0x200" }, + { "extruder_printable_height", "0,0" }, + { "filament_map_mode", "Manual" }, + { "filament_map", filaments == 2 ? "1,2" : "1" }, + { "wipe_tower_x", "30" }, + { "wipe_tower_y", "150" }, + { "layer_change_gcode", "G92 E0\n" } }); // validate() relative-E reset + size_flush_to_nozzles(config); + config.set_key_value("extruder_printable_area", new ConfigOptionPointsGroups{ + { { 0., 0. }, { left_max, 0. }, { left_max, 200. }, { 0., 200. } }, + { { right_min, 0. }, { 200., 0. }, { 200., 200. }, { right_min, 200. } } }); + + TriangleMesh mesh = cube(20); + mesh.translate(20.f, 20.f, 0.f); + Print print; + Model model; + init_print({ std::move(mesh) }, print, model, config, nullptr, false); + print.apply(model, config); + REQUIRE(print.has_wipe_tower() == (filaments == 2)); + return print.validate(); +} + +TEST_CASE("A prime tower is rejected when the extruders share no printable area", "[WipeTower]") +{ + SECTION("areas that overlap under the tower accept it") { + CHECK_THAT(validate_on_two_nozzle_areas(150., 10., 2).string, Catch::Matchers::Equals(std::string())); + } + SECTION("a tower outside the shared area is told so") { + CHECK_THAT(validate_on_two_nozzle_areas(150., 120., 2).string, Catch::Matchers::ContainsSubstring("partially outside")); + } + SECTION("areas that only touch leave the tower nowhere to go") { + const std::string error = validate_on_two_nozzle_areas(100., 100., 2).string; + CHECK_THAT(error, Catch::Matchers::ContainsSubstring("share no common area")); + CHECK_THAT(error, !Catch::Matchers::ContainsSubstring("partially outside")); + } + SECTION("one filament inside its nozzle's area needs no tower and is accepted") { + CHECK_THAT(validate_on_two_nozzle_areas(100., 100., 1).string, Catch::Matchers::Equals(std::string())); + } +} + TEST_CASE("Only a cone wall gives the tower a stabilization cone", "[WipeTower]") { // The cone angle stays in the config for every wall type, but only a cone wall prints the diff --git a/tests/libslic3r/test_arrange.cpp b/tests/libslic3r/test_arrange.cpp index 69d9e87c41..5c840c35b6 100644 --- a/tests/libslic3r/test_arrange.cpp +++ b/tests/libslic3r/test_arrange.cpp @@ -289,6 +289,33 @@ TEST_CASE("An item filling the printable area is arranged", "[Arrange]") REQUIRE(large.front().bed_idx == UNARRANGED); } +TEST_CASE("Arranging uses the whole bed when the extruders share no printable area", "[Arrange]") +{ + // Two half-bed areas that only touch. An item wider than either half still fits the bed. + DynamicPrintConfig cfg = bed_config(); // 200 x 200 + cfg.set_key_value("extruder_printable_area", new ConfigOptionPointsGroups{ + { { 0., 0. }, { 100., 0. }, { 100., 200. }, { 0., 200. } }, + { { 100., 0. }, { 200., 0. }, { 200., 200. }, { 100., 200. } } }); + ArrangeParams p = quiet_params(); + + ArrangePolygons items = squares(1, 150.); + update_arrange_params(p, &cfg, items); + update_selected_items_inflation(items, &cfg, p); + const Points bedpts = get_shrink_bedpts(&cfg, p); + // The arrange jobs read the four corners. + REQUIRE(bedpts.size() == 4); + arrange(items, bedpts, p); + CHECK(items.front().bed_idx == 0); + + // The bed still bounds the arrangement. + ArrangeParams p_large = quiet_params(); + ArrangePolygons large = squares(1, 201.); + update_arrange_params(p_large, &cfg, large); + update_selected_items_inflation(large, &cfg, p_large); + arrange(large, get_shrink_bedpts(&cfg, p_large), p_large); + CHECK(large.front().bed_idx == UNARRANGED); +} + TEST_CASE("Items overflowing one bed spill onto virtual beds", "[Arrange]") { ArrangePolygons items = squares(8, 90.); // eight 90mm squares cannot share a 200x200 bed diff --git a/tests/libslic3r/test_config.cpp b/tests/libslic3r/test_config.cpp index 6d846389ad..ae3948a7b3 100644 --- a/tests/libslic3r/test_config.cpp +++ b/tests/libslic3r/test_config.cpp @@ -6,6 +6,9 @@ #include #include #include "catch2/catch_approx.hpp" +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/Point.hpp" #include "libslic3r/PrintConfig.hpp" #include "libslic3r/PrintConfigConstants.hpp" #include "libslic3r/LocalesUtils.hpp" @@ -1932,3 +1935,95 @@ TEST_CASE("An empty list applied by index replaces the target list", "[Config][R edited.apply_only(saved, {"filament_ids#0"}); CHECK(edited.option("filament_ids")->values.empty()); } + +namespace { + +const Pointfs shared_area_bed = { { 0., 0. }, { 350., 0. }, { 350., 350. }, { 0., 350. } }; + +// A full-depth strip of the 350 mm bed from x = `left` to x = `right`. +Pointfs bed_strip(double left, double right) { return { { left, 0. }, { right, 0. }, { right, 350. }, { left, 350. } }; } + +DynamicPrintConfig shared_area_config(const std::vector &extruder_areas) +{ + DynamicPrintConfig config; + config.set_key_value("printable_area", new ConfigOptionPoints(shared_area_bed)); + config.set_key_value("extruder_printable_area", new ConfigOptionPointsGroups(extruder_areas)); + return config; +} + +} // namespace + +TEST_CASE("Overlapping extruder printable areas share their intersection", "[Config][BedShape]") +{ + const std::vector areas = { bed_strip(0., 200.), bed_strip(150., 350.) }; + const DynamicPrintConfig config = shared_area_config(areas); + + const BoundingBox shared(get_shared_poly(areas, shared_area_bed).points); + CHECK(shared.min == Point(scaled(150.), 0)); + CHECK(shared.max == Point(scaled(200.), scaled(350.))); + // Objects are placed on that area. + CHECK(get_bed_shape(config, true) == get_shared_poly(areas, shared_area_bed).points); +} + +TEST_CASE("Extruder printable areas that do not overlap share no area", "[Config][BedShape]") +{ + const std::vector areas = GENERATE( + std::vector{ bed_strip(0., 175.), bed_strip(175., 350.) }, // touching + std::vector{ bed_strip(0., 100.), bed_strip(250., 350.) }, // apart + std::vector{ bed_strip(0., 200.), bed_strip(150., 350.), bed_strip(300., 350.) } // only the third is apart + ); + CHECK(get_shared_poly(areas, shared_area_bed).points.empty()); +} + +TEST_CASE("An extruder printable area that is not a shape does not limit the shared area", "[Config][BedShape]") +{ + const Points whole_bed = get_bed_shape(shared_area_config({}), false); + REQUIRE(whole_bed.size() == shared_area_bed.size()); + + SECTION("no areas at all") + { + CHECK(get_shared_poly({}, shared_area_bed).points == whole_bed); + } + SECTION("a lone area with too few points") + { + const size_t points = GENERATE(size_t(0), size_t(1), size_t(2)); + const Pointfs area(points, Vec2d(10., 10.)); + CHECK(get_shared_poly({ area }, shared_area_bed).points == whole_bed); + } + SECTION("such an area next to a real one leaves the real one") + { + const bool malformed_first = GENERATE(false, true); + const Pointfs left = bed_strip(0., 200.); + const std::vector areas = malformed_first ? std::vector{ Pointfs{}, left } : std::vector{ left, Pointfs{} }; + const BoundingBox shared(get_shared_poly(areas, shared_area_bed).points); + CHECK(shared.min == Point(0, 0)); + CHECK(shared.max == Point(scaled(200.), scaled(350.))); + } +} + +TEST_CASE("Objects are placed on the whole bed when the extruders share no area", "[Config][BedShape]") +{ + const DynamicPrintConfig config = shared_area_config({ bed_strip(0., 175.), bed_strip(175., 350.) }); + const Points whole_bed = get_bed_shape(config, false); + REQUIRE(whole_bed.size() == shared_area_bed.size()); + + CHECK(get_bed_shape(config, true) == whole_bed); + + PrintConfig print_config; + print_config.apply(config, true); + CHECK(get_bed_shape(print_config, true) == whole_bed); +} + +TEST_CASE("The print speed table keeps a bed outline when the extruders share no area", "[Config][BedShape]") +{ + // The outline is the placement bed less the exclusion areas, and its first piece is read. + DynamicPrintConfig config = shared_area_config({ bed_strip(0., 175.), bed_strip(175., 350.) }); + config.set_key_value("bed_exclude_area", new ConfigOptionPoints({ { 0., 0. }, { 20., 0. }, { 20., 20. }, { 0., 20. } })); + PrintConfig print_config; + print_config.apply(config, true); + + Model::setPrintSpeedTable(config, print_config); + const BoundingBox outline(Model::getBedPolygon().points); + CHECK(outline.min == Point(0, 0)); + CHECK(outline.max == Point(scaled(350.), scaled(350.))); +} From 478cc90ae7b26da950a38d14cb0579a55198015e Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:56:36 +0800 Subject: [PATCH 03/26] Write One Nozzle Volume Type per Nozzle From the CLI (#17440) The CLI now sets one nozzle_volume_type per nozzle, as the GUI does. A command-line value wins, then the project's own types, then the printer's defaults. A short list repeats its first entry and a long one is cut to the nozzle count. The sized list is written to the project config and over the command-line value, so the export has one type per nozzle, and reopening it in the CLI keeps the flush matrix the user set. The flush volume setup reads the sized types instead of indexing a short command-line list past its end. Adds the cli_nozzle_volume_type test. --- src/OrcaSlicer.cpp | 62 ++++++----- tests/cli/CMakeLists.txt | 8 ++ tests/cli/test_cli_nozzle_volume_type.sh | 129 +++++++++++++++++++++++ 3 files changed, 167 insertions(+), 32 deletions(-) create mode 100755 tests/cli/test_cli_nozzle_volume_type.sh diff --git a/src/OrcaSlicer.cpp b/src/OrcaSlicer.cpp index 9d799f54e9..672906e06a 100644 --- a/src/OrcaSlicer.cpp +++ b/src/OrcaSlicer.cpp @@ -482,6 +482,21 @@ static PrinterTechnology get_printer_technology(const DynamicConfig &config) return (opt == nullptr) ? ptUnknown : opt->value; } +// One volume type per nozzle: the config's own types when it has any, else the printer's defaults, as the GUI +// seeds a project. A nozzle the list leaves out takes its first entry, as a short list is read elsewhere, and +// extra entries are dropped. +static std::vector nozzle_volume_types_per_nozzle(const DynamicPrintConfig &config, int nozzle_count) +{ + const auto *types = config.option("nozzle_volume_type"); + if (types == nullptr || types->values.empty()) + types = config.option("default_nozzle_volume_type"); + std::vector result(nozzle_count, nvtStandard); + if (types != nullptr && !types->values.empty()) + for (int index = 0; index < nozzle_count; index++) + result[index] = static_cast(types->get_at(index)); + return result; +} + //BBS: add flush and exit #if defined(__linux__) || defined(__LINUX__) #define flush_and_exit(ret) { boost::nowide::cout << __FUNCTION__ << " found error, return "< 1)) { auto opt_extruder_type = dynamic_cast(config.option("extruder_type")); auto opt_nozzle_volume_type = dynamic_cast(config.option("nozzle_volume_type")); - if (opt_nozzle_volume_type) { - int nozzle_volume_type_size = opt_nozzle_volume_type->values.size(); - current_nozzle_volume_type.resize(nozzle_volume_type_size, nvtStandard); - for (int i = 0; i < nozzle_volume_type_size; i++) - { - current_nozzle_volume_type[i] = (NozzleVolumeType)(opt_nozzle_volume_type->values[i]); - } - } + // Sized by the rule the new types follow, so types the project keeps compare equal. + current_nozzle_volume_type = nozzle_volume_types_per_nozzle(config, current_extruder_count); current_extruder_variants.resize(current_extruder_count, ""); for (int e_index = 0; e_index < current_extruder_count; e_index++) @@ -3438,20 +3447,17 @@ int CLI::run(int argc, char **argv) } //get nozzle_volume_type - if(m_extra_config.has("nozzle_volume_type")) { - auto opt_nozzle_volume_type = dynamic_cast(m_extra_config.option("nozzle_volume_type")); - if (opt_nozzle_volume_type) { - int nozzle_volume_type_size = opt_nozzle_volume_type->values.size(); - new_nozzle_volume_type.resize(nozzle_volume_type_size, nvtStandard); - for (int i = 0; i < nozzle_volume_type_size; i++) - { - new_nozzle_volume_type[i] = (NozzleVolumeType) (opt_nozzle_volume_type->values[i]); - } - } - } - else { - new_nozzle_volume_type.resize(new_extruder_count, nvtStandard); - } + // A value on the command line wins, else the project's types or the printer's defaults. + auto *cli_nozzle_volume_type = m_extra_config.option("nozzle_volume_type"); + const bool cli_has_nozzle_volume_type = cli_nozzle_volume_type != nullptr && !cli_nozzle_volume_type->values.empty(); + new_nozzle_volume_type = nozzle_volume_types_per_nozzle(cli_has_nozzle_volume_type ? m_extra_config : m_print_config, new_extruder_count); + // The project carries one volume type per nozzle, as the GUI writes it, so an export reopens with the + // types it was sliced with. The command-line options are applied over the project later, so their value + // is sized as well. + std::vector &project_nozzle_volume_type = m_print_config.option("nozzle_volume_type", true)->values; + project_nozzle_volume_type.assign(new_nozzle_volume_type.begin(), new_nozzle_volume_type.end()); + if (cli_nozzle_volume_type != nullptr) + cli_nozzle_volume_type->values = project_nozzle_volume_type; new_extruder_variants.resize(new_extruder_count, ""); const ConfigOptionEnumsGeneric *opt_extruder_type = dynamic_cast(m_print_config.option("extruder_type")); for (int e_index = 0; e_index < new_extruder_count; e_index++) { @@ -3990,19 +3996,11 @@ int CLI::run(int argc, char **argv) else extruders.resize(1,int(ExtruderType::etDirectDrive)); - std::vector volume_types; - if (m_print_config.has("nozzle_volume_type")) - volume_types = m_print_config.option("nozzle_volume_type")->values; // get volume type from 3mf - else - volume_types.resize(1, int(NozzleVolumeType::nvtStandard)); - - if(m_extra_config.has("nozzle_volume_type")) // get volume type from input - volume_types = m_extra_config.option("nozzle_volume_type")->values; - + // new_nozzle_volume_type holds one type per nozzle, the command-line value included. for (int eidx = 0; eidx < new_extruder_count; ++eidx) { int index = 0; if (m_print_config.has("printer_extruder_id") && m_print_config.has("printer_extruder_variant")) - index = m_print_config.get_index_for_extruder(eidx + 1, "printer_extruder_id", ExtruderType(extruders[eidx]), NozzleVolumeType(volume_types[eidx]), "printer_extruder_variant"); + index = m_print_config.get_index_for_extruder(eidx + 1, "printer_extruder_id", ExtruderType(extruders[eidx]), new_nozzle_volume_type[eidx], "printer_extruder_variant"); nozzle_flush_dataset[eidx] = nozzle_flush_dataset_full[index]; } } diff --git a/tests/cli/CMakeLists.txt b/tests/cli/CMakeLists.txt index b108599aca..490cb731a6 100644 --- a/tests/cli/CMakeLists.txt +++ b/tests/cli/CMakeLists.txt @@ -69,3 +69,11 @@ set_tests_properties(cli_malformed_input PROPERTIES LABELS "CLI;RequiresApp" SKIP_RETURN_CODE 77 TIMEOUT 900) + +add_test(NAME cli_nozzle_volume_type + COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/test_cli_nozzle_volume_type.sh $ ${ORCA_CLI_TEST_PYTHON} + ${CMAKE_SOURCE_DIR}/resources/profiles) +set_tests_properties(cli_nozzle_volume_type PROPERTIES + LABELS "CLI;RequiresApp" + SKIP_RETURN_CODE 77 + TIMEOUT 900) diff --git a/tests/cli/test_cli_nozzle_volume_type.sh b/tests/cli/test_cli_nozzle_volume_type.sh new file mode 100755 index 0000000000..5edcb1c8ba --- /dev/null +++ b/tests/cli/test_cli_nozzle_volume_type.sh @@ -0,0 +1,129 @@ +#!/usr/bin/env bash +# End-to-end check that the CLI slices with, and exports, one nozzle_volume_type per nozzle, as the GUI +# does: the command-line value, else the project's own types, else the printer's defaults. Reopening an +# export whose types are unchanged keeps the flush matrix it carries instead of recomputing it. +# +# usage: test_cli_nozzle_volume_type.sh +set -u + +BIN="${1:-}" +PY="${2:-python3}" +PROFILES="${3:-}" +# 77 is the test's SKIP_RETURN_CODE. +[ -x "$BIN" ] || { echo "SKIP: orca-slicer binary not found: $BIN"; exit 77; } +[ -d "$PROFILES" ] || { echo "FAIL: profiles directory not found: $PROFILES"; exit 1; } + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/orca-cli-nozzle-volume-type.XXXXXX")" +trap 'rm -rf "$WORK"' EXIT + +"$PY" - "$WORK/cube.stl" <<'EOF2' +import sys + +v = [(x, y, z) for z in (0, 10) for y in (0, 10) for x in (0, 10)] +with open(sys.argv[1], "w") as f: + f.write("solid cube\n") + for a, b, c, d in ((0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)): + for tri in ((v[a], v[b], v[c]), (v[a], v[c], v[d])): + f.write("facet normal 0 0 0\nouter loop\n") + for p in tri: + f.write("vertex %g %g %g\n" % p) + f.write("endloop\nendfacet\n") + f.write("endsolid cube\n") +EOF2 + +# project.py author [types]: set the flush volume from filament 1 to 2 of every nozzle block to +# 777 and, given a comma-separated list, replace the project's nozzle_volume_type with it. +# project.py check <3mf> [authored]: the export names these types and, if authored, still +# carries the 777 of every nozzle block. +cat > "$WORK/project.py" <<'EOF2' +import json, sys, zipfile + +def flush_cells(config): + matrix = config["flush_volumes_matrix"] + nozzles = len(config["nozzle_diameter"]) + block = len(matrix) // nozzles + return matrix, [nozzle * block + 1 for nozzle in range(nozzles)] + +if sys.argv[1] == "author": + src, dst = sys.argv[2], sys.argv[3] + with zipfile.ZipFile(src) as zin, zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED) as zout: + for item in zin.infolist(): + data = zin.read(item.filename) + if item.filename == "Metadata/project_settings.config": + config = json.loads(data) + matrix, cells = flush_cells(config) + for cell in cells: + matrix[cell] = "777" + if len(sys.argv) > 4: + config["nozzle_volume_type"] = sys.argv[4].split(",") + data = json.dumps(config, indent=4) + zout.writestr(item, data) + sys.exit(0) + +tag, path, expected = sys.argv[2], sys.argv[3], sys.argv[4].split(",") +with zipfile.ZipFile(path) as z: + config = json.loads(z.read("Metadata/project_settings.config")) +errors = [] +if config.get("nozzle_volume_type") != expected: + errors.append("nozzle_volume_type is %s, expected %s" % (config.get("nozzle_volume_type"), expected)) +if len(sys.argv) > 5: + matrix, cells = flush_cells(config) + for nozzle, cell in enumerate(cells): + if float(matrix[cell]) != 777: + errors.append("the authored flush volume of nozzle %d was recomputed: %s" % (nozzle + 1, matrix[cell])) +for e in errors: + print("FAIL: %s: %s" % (tag, e)) +sys.exit(1 if errors else 0) +EOF2 + +# slice [option...]: slice into $WORK//out.3mf with a fresh data directory. +slice() { + local out="$WORK/$1" input="$2"; shift 2 + mkdir -p "$out" + timeout 300 "$BIN" --datadir "$out/datadir" "$@" --slice 0 --outputdir "$out" --export-3mf out.3mf "$input" \ + > "$out/log" 2>&1 || { echo "FAIL: $1: orca-slicer exited $?"; tail -n 40 "$out/log"; exit 1; } +} + +failed=0 +check() { + "$PY" "$WORK/project.py" check "$@" || failed=1 +} + +BBL="$PROFILES/BBL" +H2D=(--load-settings "$BBL/machine/Bambu Lab H2D 0.4 nozzle.json;$BBL/process/0.20mm Standard @BBL H2D.json" + --load-filaments "$BBL/filament/Bambu PLA Basic @BBL H2D.json;$BBL/filament/Bambu PLA Basic @BBL H2D.json") + +# A two-nozzle printer with two filaments takes the printer's default per nozzle. +slice base "$WORK/cube.stl" "${H2D[@]}" +check base "$WORK/base/out.3mf" "Standard,Standard" + +# Printer defaults other than Standard. +PRUSA="$PROFILES/Prusa" +slice defaults "$WORK/cube.stl" \ + --load-settings "$PRUSA/machine/Prusa CORE One INDX 4T HF 0.4 nozzle.json;$PRUSA/process/0.20mm Balanced @Prusa CORE One INDX HF 0.4.json" \ + --load-filaments "$PRUSA/filament/Generic PLA @Prusa CORE One INDX.json;$PRUSA/filament/Generic PLA @Prusa CORE One INDX.json" +check defaults "$WORK/defaults/out.3mf" "High Flow,High Flow,High Flow,High Flow" + +# A command-line value naming fewer nozzles than the printer has applies its first entry to the rest. +slice command_line "$WORK/cube.stl" "${H2D[@]}" --nozzle-volume-type "High Flow" +check command_line "$WORK/command_line/out.3mf" "High Flow,High Flow" + +# Reopened with an authored flush matrix, a project keeps it as long as its types stay the same: the types +# as exported, High Flow ones, fewer than the nozzles (as from a printer whose defaults name one), or more. +# A nozzle the project's list leaves out takes its first entry. +"$PY" "$WORK/project.py" author "$WORK/base/out.3mf" "$WORK/authored.3mf" || exit 1 +"$PY" "$WORK/project.py" author "$WORK/base/out.3mf" "$WORK/high_flow.3mf" "High Flow,High Flow" || exit 1 +"$PY" "$WORK/project.py" author "$WORK/base/out.3mf" "$WORK/short.3mf" "Standard" || exit 1 +"$PY" "$WORK/project.py" author "$WORK/base/out.3mf" "$WORK/short_high_flow.3mf" "High Flow" || exit 1 +"$PY" "$WORK/project.py" author "$WORK/base/out.3mf" "$WORK/long.3mf" "High Flow,High Flow,Standard" || exit 1 +for project in authored high_flow short short_high_flow long; do + slice "$project" "$WORK/$project.3mf" +done +check authored "$WORK/authored/out.3mf" "Standard,Standard" authored +check high_flow "$WORK/high_flow/out.3mf" "High Flow,High Flow" authored +check short "$WORK/short/out.3mf" "Standard,Standard" authored +check short_high_flow "$WORK/short_high_flow/out.3mf" "High Flow,High Flow" authored +check long "$WORK/long/out.3mf" "High Flow,High Flow" authored + +[ "$failed" = 0 ] || exit 1 +echo "PASS" From 351c19354ae55b0ccc4d11c4b8c7f3926058bccb Mon Sep 17 00:00:00 2001 From: yw4z Date: Wed, 11 Nov 2026 20:44:33 +0300 Subject: [PATCH 04/26] OCCT: build with precompiled headers and only the toolkits Orca links (#17415) OCCT now builds only the toolkits libslic3r links, 26 with SLIC3R_CAD and 23 without, instead of whole modules. Every module is off and the list is passed in BUILD_ADDITIONAL_TOOLKITS, and OCCT adds their dependencies itself. The list must match OCCT_LIBS in src/libslic3r/CMakeLists.txt. OCCT's own precompiled headers are on. clang-cl can break exception copies with a precompiled header (llvm/llvm-project#53486), so clang-cl Ninja builds compile OCCT with cl, as Windows ARM64 already did. With the Visual Studio generator OCCT may stay on clang-cl, so precompiled headers are off there. The .pch files are deleted after install. libslic3r clears INTERFACE_PRECOMPILE_HEADERS on the OCCT targets so OCCT's headers are not merged into its own. The Windows x64 OCCT DLLs are now built with cl instead of clang-cl. OCCT's build time drops by about 45% on Windows and from 6m28 to 1m58 on Linux. --- CMakeLists.txt | 2 +- deps/CMakeLists.txt | 2 +- deps/OCCT/OCCT.cmake | 60 ++++++++++++++++++++++++++---------- deps/OCCT/remove_pch.cmake | 5 +++ docs/HLSD/design-tab.md | 24 +++++++-------- src/libslic3r/CMakeLists.txt | 26 +++++++++++----- 6 files changed, 81 insertions(+), 38 deletions(-) create mode 100644 deps/OCCT/remove_pch.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index e42021134c..ae29f2fd5c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -110,7 +110,7 @@ endif() option(SLIC3R_STATIC "Compile OrcaSlicer with static libraries (Boost, TBB)" ${SLIC3R_STATIC_INITIAL}) option(SLIC3R_GUI "Compile OrcaSlicer with GUI components (OpenGL, wxWidgets)" 1) -option(SLIC3R_CAD "Compile OrcaSlicer with the parametric Design/CAD tab (needs OCCT ModelingAlgorithms)" 1) +option(SLIC3R_CAD "Compile OrcaSlicer with the parametric Design/CAD tab (needs OCCT's TKFillet, TKOffset and TKBool)" 1) option(SLIC3R_FHS "Assume OrcaSlicer is to be installed in a FHS directory structure" 0) option(SLIC3R_PROFILE "Compile OrcaSlicer with an invasive Shiny profiler" 0) option(SLIC3R_PCH "Use precompiled headers" 1) diff --git a/deps/CMakeLists.txt b/deps/CMakeLists.txt index fa4c4b6219..99ce416574 100644 --- a/deps/CMakeLists.txt +++ b/deps/CMakeLists.txt @@ -63,7 +63,7 @@ endif () set(DEP_DOWNLOAD_DIR ${CMAKE_CURRENT_SOURCE_DIR}/DL_CACHE CACHE PATH "Path for downloaded source packages.") set(FLATPAK FALSE CACHE BOOL "Toggles various build settings for flatpak, like /usr/local in DESTDIR or not building wxwidgets") -option(SLIC3R_CAD "Build the SolveSpace solver and OCCT ModelingAlgorithms module the parametric Design/CAD tab needs. Must match the main project's SLIC3R_CAD." ON) +option(SLIC3R_CAD "Build the SolveSpace solver and the OCCT toolkits (TKFillet, TKOffset, TKBool) the parametric Design/CAD tab needs. Must match the main project's SLIC3R_CAD." ON) if ("${DESTDIR}" STREQUAL "" OR "${DESTDIR}" STREQUAL "${AUTOGENERATED_DESTDIR}") if (LINUX AND (NOT DEFINED USE_OLD_DESTDIR_PREV OR USE_OLD_DESTDIR_PREV) AND EXISTS "${CMAKE_BINARY_DIR}/destdir/usr/local" AND NOT EXISTS "${CMAKE_BINARY_DIR}/OrcaSlicer_dep/usr/local") diff --git a/deps/OCCT/OCCT.cmake b/deps/OCCT/OCCT.cmake index 1f63615034..c0bd0e1608 100644 --- a/deps/OCCT/OCCT.cmake +++ b/deps/OCCT/OCCT.cmake @@ -1,8 +1,16 @@ -# clang-cl cannot emit some OCCT sources for ARM64 (llvm/llvm-project#62081). -# cl and clang-cl share an ABI. +# clang-cl cannot emit some OCCT sources for ARM64 (llvm/llvm-project#62081), and with OCCT's +# precompiled headers it can break exception copies (llvm/llvm-project#53486). cl and clang-cl +# share an ABI, so clang-cl builds compile OCCT with cl. The Visual Studio generator picks the +# compiler by toolset, so there OCCT may stay on clang-cl; keep precompiled headers off there. set(_occt_compiler_args "") -if ("${DEPS_ARCH}" STREQUAL "arm64" AND CMAKE_CXX_COMPILER_ID STREQUAL Clang) - set(_occt_compiler_args -DCMAKE_C_COMPILER:STRING=cl -DCMAKE_CXX_COMPILER:STRING=cl) +set(_occt_pch ON) +if (MSVC AND CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + if ("${DEPS_ARCH}" STREQUAL "arm64" OR NOT CMAKE_GENERATOR MATCHES "Visual Studio") + set(_occt_compiler_args -DCMAKE_C_COMPILER:STRING=cl -DCMAKE_CXX_COMPILER:STRING=cl) + endif () + if (CMAKE_GENERATOR MATCHES "Visual Studio") + set(_occt_pch OFF) + endif () endif () if(WIN32) @@ -11,19 +19,27 @@ else() set(library_build_type "Static") endif() -# SLIC3R_CAD (declared in deps/CMakeLists.txt) builds OCCT's ModelingAlgorithms module -# (fillet/offset/loft), whose only consumer is the parametric Design/CAD tab. With it OFF -# the deps prefix matches upstream exactly. +# Only the toolkits libslic3r links are built, rather than whole modules. OCCT's module +# flags are all-or-nothing: the DataExchange module alone also builds the IGES, VRML, OBJ, +# STL and PLY readers and the XML/binary document formats, none of which Orca uses. With +# every module OFF, OCCT builds BUILD_ADDITIONAL_TOOLKITS plus their dependencies. # -# With it ON OCCT also builds TKFillet (used via BRepFilletAPI), TKOffset (used via -# BRepOffsetAPI), and TKFeat, TKHelix, TKXMesh and TKExpress, which nothing here references -# but which the module flag builds anyway, since module flags are all-or-nothing. The -# module's other toolkits are built either way, because DataExchange (the STEP path) -# depends on them. +# This list must match OCCT_LIBS in src/libslic3r/CMakeLists.txt. A toolkit missing here +# fails the app configure or link; one left here after libslic3r stops using it only costs +# build time. # -# On macOS/Linux OCCT links statically, so an unreferenced toolkit costs build time and no -# shipped bytes. Windows ships only the DLLs libslic3r links, so the tab adds the TKFillet, -# TKOffset and TKBool DLLs. See docs/HLSD/design-tab.md. +# SLIC3R_CAD (declared in deps/CMakeLists.txt) adds TKFillet (BRepFilletAPI), TKOffset +# (BRepOffsetAPI) and TKBool, which they need. Their only consumer is the parametric +# Design/CAD tab. On Windows OCCT builds shared and only the linked toolkits ship, so the +# tab adds those three DLLs. See docs/HLSD/design-tab.md. +set(_occt_toolkits + TKDESTEP TKDE TKXCAF TKXSBase TKVCAF TKCAF TKLCAF TKCDF TKV3d TKService TKMesh TKBO + TKPrim TKHLR TKShHealing TKTopAlgo TKGeomAlgo TKBRep TKGeomBase TKG3d TKG2d TKMath TKernel) +if (SLIC3R_CAD) + list(APPEND _occt_toolkits TKFillet TKOffset TKBool) +endif () +# OCCT reads BUILD_ADDITIONAL_TOOLKITS as a space-separated string. +string(REPLACE ";" " " _occt_toolkits "${_occt_toolkits}") if (IN_GIT_REPO) set(OCCT_DIRECTORY_FLAG --directory ${BINARY_DIR_REL}/dep_OCCT-prefix/src/dep_OCCT) @@ -52,12 +68,22 @@ orcaslicer_add_cmake_project(OCCT -DUSE_FFMPEG=OFF -DUSE_VTK=OFF -DBUILD_DOC_Overview=OFF + -DBUILD_USE_PCH=${_occt_pch} -DBUILD_MODULE_ApplicationFramework=OFF - #-DBUILD_MODULE_DataExchange=OFF + -DBUILD_MODULE_DataExchange=OFF -DBUILD_MODULE_Draw=OFF -DBUILD_MODULE_FoundationClasses=OFF - -DBUILD_MODULE_ModelingAlgorithms=${SLIC3R_CAD} + -DBUILD_MODULE_ModelingAlgorithms=OFF -DBUILD_MODULE_ModelingData=OFF -DBUILD_MODULE_Visualization=OFF + "-DBUILD_ADDITIONAL_TOOLKITS=${_occt_toolkits}" ${_occt_compiler_args} ) + +# The precompiled headers (~2.2 GB with cl) are only needed while OCCT compiles; none are installed. +if (_occt_pch) + ExternalProject_Add_Step(dep_OCCT remove_pch + DEPENDEES install + COMMENT "Removing OCCT's precompiled headers" + COMMAND ${CMAKE_COMMAND} -DDIR= -P ${CMAKE_CURRENT_LIST_DIR}/remove_pch.cmake) +endif () diff --git a/deps/OCCT/remove_pch.cmake b/deps/OCCT/remove_pch.cmake new file mode 100644 index 0000000000..e25ad2dbbb --- /dev/null +++ b/deps/OCCT/remove_pch.cmake @@ -0,0 +1,5 @@ +# Deletes the precompiled headers OCCT leaves in its build tree (see OCCT.cmake). +file(GLOB_RECURSE _pch "${DIR}/*.pch" "${DIR}/*.gch") +if (_pch) + file(REMOVE ${_pch}) +endif () \ No newline at end of file diff --git a/docs/HLSD/design-tab.md b/docs/HLSD/design-tab.md index 8aeaea86dd..93473bbe34 100644 --- a/docs/HLSD/design-tab.md +++ b/docs/HLSD/design-tab.md @@ -45,20 +45,20 @@ Two consequences follow from deriving rather than storing: ## Geometry kernel and dependency surface The kernel is OCCT, which OrcaSlicer **already** links — `Format/STEP.cpp` and `Format/svg.cpp` -use it upstream. The Design tab adds no third-party dependency; it -widens the existing OCCT build by one module flag in `deps/OCCT/OCCT.cmake`: +use it upstream. The Design tab adds no third-party dependency; it adds three toolkits to the +list `deps/OCCT/OCCT.cmake` builds: ```cmake --DBUILD_MODULE_ModelingAlgorithms=${SLIC3R_CAD} +if (SLIC3R_CAD) + list(APPEND _occt_toolkits TKFillet TKOffset TKBool) +endif () ``` -Most of that module's toolkits are built either way, because `DataExchange`, which the STEP -importer uses, depends on them. With the flag on, OCCT also builds `TKFillet` (used through -`BRepFilletAPI`), `TKOffset` (`BRepOffsetAPI`), and `TKFeat`, `TKHelix`, `TKXMesh` and -`TKExpress`, which nothing here references but which the module flag builds anyway, because -OCCT's module flags are all-or-nothing. On macOS and Linux OCCT links statically, so an -unreferenced toolkit costs build time and no shipped bytes. On Windows OCCT builds shared and -only the linked toolkits ship, so the tab adds the `TKFillet`, `TKOffset` and `TKBool` DLLs. +`deps/OCCT/OCCT.cmake` turns every OCCT module off and builds only the toolkits libslic3r links +(`BUILD_ADDITIONAL_TOOLKITS`), plus their dependencies. The tab's toolkits are `TKFillet` (used +through `BRepFilletAPI`), `TKOffset` (`BRepOffsetAPI`) and `TKBool`, which they need. On macOS +and Linux OCCT links statically. On Windows OCCT builds shared and only the linked toolkits +ship, so the tab adds the `TKFillet`, `TKOffset` and `TKBool` DLLs. On Windows the packaging step asserts that every linked OCCT toolkit has a shipped DLL and fails the configure with the name of any that is missing, because the alternative failure — a @@ -79,8 +79,8 @@ upstream-sync burden, paid deliberately to keep `deps/` unchanged. ## The SLIC3R_CAD gate -`SLIC3R_CAD` (default ON) compiles the tab and selects the OCCT module flag above. With it OFF -the tab is not built and the deps prefix matches upstream exactly. The gate is cheap because +`SLIC3R_CAD` (default ON) compiles the tab and adds the three OCCT toolkits above. With it OFF +the tab is not built and the deps prefix has none of the tab's toolkits. The gate is cheap because the hooks the Design tab adds to shared GUI code — chiefly the `m_design_sketch_tool` member and the render, mouse and key hooks in `GLCanvas3D` — are null-guarded on the path they extend, so removing the tab removes behaviour rather than requiring the host code to be rewritten. diff --git a/src/libslic3r/CMakeLists.txt b/src/libslic3r/CMakeLists.txt index 8aee027b64..27ccb29033 100644 --- a/src/libslic3r/CMakeLists.txt +++ b/src/libslic3r/CMakeLists.txt @@ -580,7 +580,7 @@ set(lisbslic3r_sources FlushVolPredictor.cpp ) -# Parametric Design/CAD kernel. Needs OCCT's ModelingAlgorithms module and the +# Parametric Design/CAD kernel. Needs the OCCT toolkits TKFillet, TKOffset and TKBool and the # vendored SolveSpace solver; both are pulled in only when SLIC3R_CAD is ON. if (SLIC3R_CAD) list(APPEND lisbslic3r_sources @@ -697,6 +697,7 @@ target_include_directories(libslic3r SYSTEM PUBLIC ${OpenCASCADE_INCLUDE_DIR}) find_package(JPEG REQUIRED) find_package(Draco REQUIRED) +# deps/OCCT/OCCT.cmake builds exactly these toolkits; keep its _occt_toolkits list in step. set(OCCT_LIBS TKDESTEP TKDE @@ -722,8 +723,8 @@ set(OCCT_LIBS TKMath TKernel ) -# The CAD kernel is the only consumer of OCCT's ModelingAlgorithms module: TKFillet -# (BRepFilletAPI), TKOffset (BRepOffsetAPI) and TKBool, which the other two need. +# The CAD kernel is the only consumer of TKFillet (BRepFilletAPI), TKOffset (BRepOffsetAPI) +# and TKBool, which the other two need. # # PREPEND, never append: this list is single-pass static link order, dependents before # dependencies — note TKernel, which everything needs, is deliberately last. TKOffset @@ -735,17 +736,28 @@ set(OCCT_LIBS # than list(PREPEND), which needs CMake 3.15 and this project supports 3.13. if (SLIC3R_CAD) set(OCCT_LIBS TKFillet TKOffset TKBool ${OCCT_LIBS}) - # deps is configured separately, so its SLIC3R_CAD can differ from ours. The module is - # all-or-nothing, so one absent toolkit proves it; fail here rather than at link time. + # deps is configured separately, so its SLIC3R_CAD can differ from ours. deps/OCCT/OCCT.cmake + # builds the three CAD toolkits together under SLIC3R_CAD, so one absent toolkit proves it + # was OFF there; fail here rather than at link time. if (NOT TARGET TKFillet) message(FATAL_ERROR - "SLIC3R_CAD is ON, but the OpenCASCADE in ${CMAKE_PREFIX_PATH} was built without " - "BUILD_MODULE_ModelingAlgorithms. Rebuild the dependencies with -DSLIC3R_CAD=ON, " + "SLIC3R_CAD is ON, but the dependencies in ${CMAKE_PREFIX_PATH} were built with " + "SLIC3R_CAD=OFF (OpenCASCADE has no TKFillet). Rebuild the dependencies with -DSLIC3R_CAD=ON, " "or configure this project with -DSLIC3R_CAD=OFF.") endif () endif () # Published for the Windows packaging step in the top-level CMakeLists.txt. set(OCCT_LIBS "${OCCT_LIBS}" CACHE INTERNAL "OCCT toolkits linked by libslic3r") +# OCCT built with BUILD_USE_PCH exports the precompiled headers of TKernel, TKMath, TKBRep +# and TKBool to consumers, so CMake would merge them into libslic3r's own precompiled header +# (pulling into every libslic3r source on Windows). They only speed up OCCT's +# own build; keep them out of ours. OpenCASCADE_LIBRARIES lists every installed toolkit, so +# this also covers toolkits reached only through another toolkit's link interface. +foreach (_occt_lib IN LISTS OpenCASCADE_LIBRARIES OCCT_LIBS) + if (TARGET ${_occt_lib}) + set_property(TARGET ${_occt_lib} PROPERTY INTERFACE_PRECOMPILE_HEADERS "") + endif () +endforeach () if (WIN32) # OCCT installs RelWithDebInfo and Debug builds to bin/occti and bin/occtd, so each build # type's DLL directory is read from the imported target, falling back to the first installed From 19b0e92dbab298da8f126a7e612db4ff04d64871 Mon Sep 17 00:00:00 2001 From: yw4z Date: Wed, 11 Nov 2026 20:56:45 +0300 Subject: [PATCH 05/26] Don't ship stb_dxt header and CMake targets in release packages (#17452) Remove the install rules from deps_src/stb_dxt/CMakeLists.txt. The Windows packages and the Flatpak are built from the install output, so they shipped include/stb_dxt/stb_dxt.h and lib/cmake/stb_dxt/stb_dxtTargets.cmake. The Flatpak shipped only the .cmake file, because its cleanup step removes /include. Nothing uses either file. The header is only needed at compile time, and the build still finds it in deps_src. Also drop the "Install Support" line from deps_src/README_CMAKE_INTERFACES.md, since no library in deps_src has install rules now. --- deps_src/README_CMAKE_INTERFACES.md | 3 +-- deps_src/stb_dxt/CMakeLists.txt | 24 ++---------------------- 2 files changed, 3 insertions(+), 24 deletions(-) diff --git a/deps_src/README_CMAKE_INTERFACES.md b/deps_src/README_CMAKE_INTERFACES.md index 6ab88c63af..27a78d522d 100644 --- a/deps_src/README_CMAKE_INTERFACES.md +++ b/deps_src/README_CMAKE_INTERFACES.md @@ -67,8 +67,7 @@ target_link_libraries(my_app 2. **Proper Include Paths**: Automatically sets up include directories 3. **Namespace Aliases**: Provides namespaced aliases (e.g., `spline::spline`) for clarity 4. **Position Independent Code**: Static libraries are built with `-fPIC` for compatibility -5. **Install Support**: Libraries can be installed and used by external projects -6. **Build/Install Interface**: Separates build-time and install-time include paths +5. **Build/Install Interface**: Separates build-time and install-time include paths ## Example Integration diff --git a/deps_src/stb_dxt/CMakeLists.txt b/deps_src/stb_dxt/CMakeLists.txt index 749030be33..0d8a968065 100644 --- a/deps_src/stb_dxt/CMakeLists.txt +++ b/deps_src/stb_dxt/CMakeLists.txt @@ -6,9 +6,8 @@ add_library(stb_dxt INTERFACE) # Set include directories for the interface library target_include_directories(stb_dxt SYSTEM - INTERFACE - $ - $ + INTERFACE + ${CMAKE_CURRENT_SOURCE_DIR} ) # Add compile features @@ -16,22 +15,3 @@ target_compile_features(stb_dxt INTERFACE cxx_std_11) # Create an alias for consistent naming add_library(stb_dxt::stb_dxt ALIAS stb_dxt) - -# Install headers if needed -install(FILES - stb_dxt.h - DESTINATION include/stb_dxt -) - -# Install the interface library -install(TARGETS stb_dxt - EXPORT stb_dxtTargets - INCLUDES DESTINATION include -) - -# Export the targets -install(EXPORT stb_dxtTargets - FILE stb_dxtTargets.cmake - NAMESPACE stb_dxt:: - DESTINATION lib/cmake/stb_dxt -) From 32dbacb4231c772af9837ff08e2945625067f1ba Mon Sep 17 00:00:00 2001 From: Arthur Porto <227830219+Art-Porto@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:34:10 -0300 Subject: [PATCH 06/26] Variable layer height on several objects, and with the prime tower on objects of different heights (#16462) * Variable layer height on several objects, and with the prime tower on objects of different heights The variable layer height tool now opens with several objects selected. Adaptive, Smooth, Reset and manual edits apply to all of them: they share one profile, the finest layer height any of them asks for at each Z, unless "Each object separately" is ticked. Every selected object is painted with its layer heights. With a profile each, up to three objects get a bar of their own, drawn to one scale, and the bar under the mouse is the one edited. The prime tower check compares the layers objects are sliced at over the height they share, rather than the raw profiles, which never matched once the profile of a lower object ended at its own top. Precise Z height, which fits the last layers of each object to its own height, is left out of such a print, with a warning. * Check the prime tower layers on the sliced objects, and note the new strings for translators * Include what the new tests use * Compare the layers as sliced, before the prime tower is generated from them * Check that precise Z height stays on without a prime tower * Keep each object's layer height texture on the GPU, and mark only lower tops The variable layer height tool sent a 1024x1024 texture to the GPU for every selected object on every frame, and set_config(), run after every edit, dropped the other objects' textures so that each was generated again. Each other object now has a texture of its own on the GPU. It is generated and sent only when its profile, its height or the slicing parameters it shows change, which set_config() now only asks to check. The object shown sends its texture only when it is generated, and while the objects share one profile, those on its layers are drawn with its texture and need none of their own. The textures of objects no longer selected are freed. The bars and the layer height curves are built again only when what they show changes, and each bar is scaled with its own object's layer heights. A lower object's top is marked only when it is lower than the object shown, objects ending at the same height share one label, and a label stays on the canvas and below the one above it. The comment on precise_z_height_overridden() now says what the override trades: the tower can join the off-grid layers to the tower layer below, but a joined layer holds two purges, which makes the tower deeper. * Fix the precise Z warning, shared profiles across first layers and the bar clicked - The precise Z override, and its warning, now need an object with precise Z height on. Every plate with a prime tower and variable layer height on objects of different heights warned about a setting that is off by default. - The objects the override slices again get their slicing parameters back at once, since validate() reads them before slicing. - When the objects share one profile, an object that starts its layers elsewhere than the object shown, with a raft of its own say, keeps its own. The shared profile starts with the first layer of the object shown, and PrintObject::update_layer_height_profile() dropped it on such an object, which then printed at the preset layer height. - Clicking a bar edits its object, even when no frame was drawn since the mouse got there. - Select all is ignored while a profile is painted, and select all plates while the tool is open. - The bars' models are made again, not copied, when their number changes: a copy shares the GPU buffers that the original deletes. - Objects with no height above the bed are left out of the tool, and a profile fitted within EPSILON above one of its entries no longer runs past it. * Keep the object top labels below the toolbar row When the toolbar row ends next to the bar, the label of an object that ends near the top of the tallest one covered the toolbar's last buttons. Such a label now starts below the row, with its arrow pointing up to the line on the bar. * Fill the layer height texture up to the top of the object The last layer can end under the top of the object, by up to half a layer, and no layer wrote the cells there. The top face is drawn with them, so it showed what the buffer held before: black on the texture of an object made for the first time, or the colours of another object. The last layer now fills them, with the shade of its top. * Draw horizontal faces without the layer stripes A horizontal face lies at one height, so the stripes cannot show on it, only the shade they have there. That shade changed whenever a layer under it moved, and the tops flickered at every stroke. Such a face now gets the plain colour of its layer height, from the 2nd level of the texture. That level is now read at its own level of detail instead of with a bias. On a horizontal face the texture coordinates do not change, so the GPU picks the 1st level however large the bias, and read it at the coordinates of the 2nd: the tops showed black, or the colour of another height. The 110 shader does so where GL_ARB_shader_texture_lod is available, and keeps the stripes elsewhere. * Include ObjectID.hpp where ObjectWithTimestamp is used clang-tidy (misc-include-cleaner) asks for the header to be included directly. * Find the horizontal faces with the inverse transpose of the world matrix The variable layer height shader took the normals to world space with the world matrix itself, which is only right under a uniform scale. With a non-uniform scale it drew sloped faces as flat, and once the object was also rotated it missed real flat ones. The normals now go through the inverse transpose of the world matrix, which render_object_volumes() already built for the view normal matrix. * Note why the precise Z override keys on has_wipe_tower() Since #16999 the tower is printed only when slicing finds it is needed, so the override also applies on plates where no tower is printed in the end. --- .../shaders/110/variable_layer_height.fs | 24 +- .../shaders/110/variable_layer_height.vs | 7 + .../shaders/140/variable_layer_height.fs | 10 +- .../shaders/140/variable_layer_height.vs | 7 + src/libslic3r/Print.cpp | 28 +- src/libslic3r/Print.hpp | 15 + src/libslic3r/PrintApply.cpp | 22 + src/libslic3r/PrintObject.cpp | 5 + src/libslic3r/PrintObjectSlice.cpp | 2 +- src/libslic3r/Slicing.cpp | 101 ++- src/libslic3r/Slicing.hpp | 14 + src/slic3r/GUI/GLCanvas3D.cpp | 761 +++++++++++++++--- src/slic3r/GUI/GLCanvas3D.hpp | 109 ++- src/slic3r/GUI/Plater.cpp | 4 +- tests/fff_print/test_wipe_tower.cpp | 222 +++++ tests/libslic3r/CMakeLists.txt | 1 + tests/libslic3r/test_slicing.cpp | 129 +++ 17 files changed, 1312 insertions(+), 149 deletions(-) create mode 100644 tests/libslic3r/test_slicing.cpp diff --git a/resources/shaders/110/variable_layer_height.fs b/resources/shaders/110/variable_layer_height.fs index 693c1c6a0b..7269751050 100644 --- a/resources/shaders/110/variable_layer_height.fs +++ b/resources/shaders/110/variable_layer_height.fs @@ -1,4 +1,6 @@ #version 110 +// Orca: texture2DLod() in a fragment shader. +#extension GL_ARB_shader_texture_lod : enable #define M_PI 3.1415926535897932384626433832795 @@ -9,11 +11,14 @@ uniform float z_to_texture_row; uniform float z_texture_row_to_normalized; uniform float z_cursor; uniform float z_cursor_band_width; +// Orca: 0 leaves the colour as it is, 1 turns it into a flat grey. +uniform float dimming; // x = tainted, y = specular; varying vec2 intensity; varying float object_z; +varying float horizontal; void main() { @@ -31,11 +36,24 @@ void main() float dx_vtc = dFdx(z_in_cells); float dy_vtc = dFdy(z_in_cells); float lod = clamp(0.5 * log2(max(dx_vtc * dx_vtc, dy_vtc * dy_vtc)), 0., 1.); +#ifdef GL_ARB_shader_texture_lod + // Orca: a horizontal face gets the colour of the layer height alone, without the stripes. + lod = max(lod, horizontal); +#endif // Sample the Z texture. Texture coordinates are normalized to <0, 1>. vec4 color = vec4(0.25, 0.25, 0.25, 1.0); - if (z_texture_row >= 0.0) - color = mix(texture2D(z_texture, vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row + 0.5 )), -10000.), - texture2D(z_texture, vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row * 2. + 1.)), 10000.), lod); + if (z_texture_row >= 0.0) { + vec2 level1 = vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row * 2. + 1.)); +#ifdef GL_ARB_shader_texture_lod + // Orca: the 2nd level is read at its own level of detail, not with a bias. On a horizontal face the texture + // coordinates do not change, so the GPU picks the 1st level however large the bias, read at the coordinates of the 2nd. + vec4 color1 = texture2DLod(z_texture, level1, 1.); +#else + vec4 color1 = texture2D(z_texture, level1, 10000.); +#endif + color = mix(texture2D(z_texture, vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row + 0.5 )), -10000.), color1, lod); + } // Mix the final color. gl_FragColor = vec4(vec3(intensity.y), 1.0) + intensity.x * mix(color, vec4(1.0, 1.0, 0.0, 1.0), z_blend); + gl_FragColor.rgb = mix(gl_FragColor.rgb, vec3(0.3), dimming); } diff --git a/resources/shaders/110/variable_layer_height.vs b/resources/shaders/110/variable_layer_height.vs index 2d6334f44e..539ea8cd71 100644 --- a/resources/shaders/110/variable_layer_height.vs +++ b/resources/shaders/110/variable_layer_height.vs @@ -18,6 +18,8 @@ uniform mat4 view_model_matrix; uniform mat4 projection_matrix; uniform mat3 view_normal_matrix; uniform mat4 volume_world_matrix; +// Orca: the inverse transpose of volume_world_matrix, which takes the normals to world space under any scale or rotation. +uniform mat3 volume_world_normal_matrix; uniform float object_max_z; attribute vec3 v_position; @@ -29,6 +31,10 @@ varying vec2 intensity; varying float object_z; +// Orca: 1 on a horizontal face, which lies at one height: the stripes of the layers cannot show on it, +// only the shade they have there, which changes whenever a layer under it moves. +varying float horizontal; + void main() { // ===================================================== @@ -55,6 +61,7 @@ void main() // Scaled to widths of the Z texture. object_z = (object_max_z > 0.0) ? object_max_z * v_tex_coord.y : (volume_world_matrix * vec4(v_position, 1.0)).z; + horizontal = (object_max_z > 0.0) ? 0.0 : step(0.999, abs(normalize(volume_world_normal_matrix * v_normal).z)); gl_Position = projection_matrix * position; } diff --git a/resources/shaders/140/variable_layer_height.fs b/resources/shaders/140/variable_layer_height.fs index 658f812286..acb508c274 100644 --- a/resources/shaders/140/variable_layer_height.fs +++ b/resources/shaders/140/variable_layer_height.fs @@ -9,11 +9,14 @@ uniform float z_to_texture_row; uniform float z_texture_row_to_normalized; uniform float z_cursor; uniform float z_cursor_band_width; +// Orca: 0 leaves the colour as it is, 1 turns it into a flat grey. +uniform float dimming; // x = tainted, y = specular; in vec2 intensity; in float object_z; +in float horizontal; out vec4 out_color; @@ -33,11 +36,16 @@ void main() float dx_vtc = dFdx(z_in_cells); float dy_vtc = dFdy(z_in_cells); float lod = clamp(0.5 * log2(max(dx_vtc * dx_vtc, dy_vtc * dy_vtc)), 0., 1.); + // Orca: a horizontal face gets the colour of the layer height alone, without the stripes. + lod = max(lod, horizontal); // Sample the Z texture. Texture coordinates are normalized to <0, 1>. + // Orca: the 2nd level is read at its own level of detail, not with a bias. On a horizontal face the texture + // coordinates do not change, so the GPU picks the 1st level however large the bias, read at the coordinates of the 2nd. vec4 color = vec4(0.25, 0.25, 0.25, 1.0); if (z_texture_row >= 0.0) color = mix(texture(z_texture, vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row + 0.5 )), -10000.), - texture(z_texture, vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row * 2. + 1.)), 10000.), lod); + textureLod(z_texture, vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row * 2. + 1.)), 1.), lod); // Mix the final color. out_color = vec4(vec3(intensity.y), 1.0) + intensity.x * mix(color, vec4(1.0, 1.0, 0.0, 1.0), z_blend); + out_color.rgb = mix(out_color.rgb, vec3(0.3), dimming); } diff --git a/resources/shaders/140/variable_layer_height.vs b/resources/shaders/140/variable_layer_height.vs index d8deb2f9ee..d6904bcc1b 100644 --- a/resources/shaders/140/variable_layer_height.vs +++ b/resources/shaders/140/variable_layer_height.vs @@ -18,6 +18,8 @@ uniform mat4 view_model_matrix; uniform mat4 projection_matrix; uniform mat3 view_normal_matrix; uniform mat4 volume_world_matrix; +// Orca: the inverse transpose of volume_world_matrix, which takes the normals to world space under any scale or rotation. +uniform mat3 volume_world_normal_matrix; uniform float object_max_z; in vec3 v_position; @@ -29,6 +31,10 @@ out vec2 intensity; out float object_z; +// Orca: 1 on a horizontal face, which lies at one height: the stripes of the layers cannot show on it, +// only the shade they have there, which changes whenever a layer under it moves. +out float horizontal; + void main() { // ===================================================== @@ -55,6 +61,7 @@ void main() // Scaled to widths of the Z texture. object_z = (object_max_z > 0.0) ? object_max_z * v_tex_coord.y : (volume_world_matrix * vec4(v_position, 1.0)).z; + horizontal = (object_max_z > 0.0) ? 0.0 : step(0.999, abs(normalize(volume_world_normal_matrix * v_normal).z)); gl_Position = projection_matrix * position; } diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index a2400c4905..129f67c39c 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -2106,26 +2106,21 @@ StringObjectException Print::validate_wipe_tower_layering() const layer_z_series.assign(m_objects.size(), std::vector()); for (size_t idx_object = 0; idx_object < m_objects.size(); ++idx_object) { - layer_z_series[idx_object] = generate_object_layers(m_objects[idx_object]->slicing_parameters(), layer_height_profile(idx_object), m_objects[idx_object]->config().precise_z_height.value); + layer_z_series[idx_object] = generate_object_layers(m_objects[idx_object]->slicing_parameters(), layer_height_profile(idx_object), m_objects[idx_object]->precise_z_height()); } for (size_t idx_object = 0; idx_object < m_objects.size(); ++idx_object) { if (idx_object == tallest_object_idx) continue; - // Check that the layer height profiles are equal. This will happen when one object is - // a copy of another, or when a layer height modifier is used the same way on both objects. - // The latter case might create a floating point inaccuracy mismatch, so compare - // element-wise using an epsilon check. - size_t i = 0; + // Orca: check that the objects are sliced at the same Z over the height they share. The + // profiles themselves cannot be compared: one that ends at a lower object's top has an + // entry there that the tallest object's profile lacks, though both give the same layers. + const std::vector &layers = layer_z_series[idx_object]; + const std::vector &layers_tallest = layer_z_series[tallest_object_idx]; const coordf_t eps = 0.5 * EPSILON; // layers closer than EPSILON will be merged later. Let's make // this check a bit more sensitive to make sure we never consider two different layers as one. - while (i < layer_height_profiles[idx_object].size() && i < layer_height_profiles[tallest_object_idx].size()) { - // BBS: remove the break condition, because a variable layer height object and a new object will not be checked when slicing - //if (i % 2 == 0 && layer_height_profiles[tallest_object_idx][i] > layer_height_profiles[idx_object][layer_height_profiles[idx_object].size() - 2]) - // break; - if (std::abs(layer_height_profiles[idx_object][i] - layer_height_profiles[tallest_object_idx][i]) > eps) + for (size_t i = 0; i < layers.size() && i < layers_tallest.size(); ++i) + if (std::abs(layers[i] - layers_tallest[i]) > eps) return {L("The prime tower is only supported if all objects have the same variable layer height.")}; - ++i; - } } } return {}; @@ -2489,7 +2484,10 @@ StringObjectException Print::validate(std::vector *warnin return {L("The project contains multiple managed belt purge towers. Reload the plate or toggle the belt purge tower off and on to regenerate it.")}; } - if (m_config.enable_prime_tower) { + if (m_precise_z_height_overridden) + // TRN "Precise Z height" is a print setting, "prime tower" the tower that purges the nozzle between filaments. + warn(L("Precise Z height is not applied: with the prime tower, objects of different heights that use variable layer height have to share their layers."), "precise_z_height"); + else if (m_config.enable_prime_tower) { for (const PrintObject* object : m_objects) { if (object->config().precise_z_height.value) { warn(L("Enabling both precise Z height and the prime tower may cause slicing errors."), "precise_z_height"); @@ -2575,7 +2573,7 @@ StringObjectException Print::validate(std::vector *warnin have_height = raw_z > 0; } else { //FIXME It is quite expensive to generate object layers just to get the print height! - auto layers = generate_object_layers(print_object.slicing_parameters(), layer_height_profile(print_object_idx), print_object.config().precise_z_height.value); + auto layers = generate_object_layers(print_object.slicing_parameters(), layer_height_profile(print_object_idx), print_object.precise_z_height()); if (!layers.empty()) { // The object layers start above the raft. const double raft_z = print_object.slicing_parameters().object_print_z_min; diff --git a/src/libslic3r/Print.hpp b/src/libslic3r/Print.hpp index be4fe4df33..e7545739d9 100644 --- a/src/libslic3r/Print.hpp +++ b/src/libslic3r/Print.hpp @@ -498,6 +498,8 @@ public: // The slicing parameters are dependent on various configuration values // (layer height, first layer height, raft settings, print nozzle diameter etc). const SlicingParameters& slicing_parameters() const { return m_slicing_params; } + // Orca: whether precise Z height shapes the layers of this object; see Print::precise_z_height_overridden(). + bool precise_z_height() const; // Orca: XYZ shrinkage compensation has introduced the const Vec3d &object_shrinkage_compensation parameter to the function below static SlicingParameters slicing_parameters(const DynamicPrintConfig &full_config, const ModelObject &model_object, float object_max_z, const Vec3d &object_shrinkage_compensation, std::vector variant_index = std::vector()); @@ -1200,6 +1202,18 @@ public: StringObjectException validate_wipe_tower_layering() const; // Belt purge prism (belt-mode replacement for the wipe tower). bool has_belt_purge_tower() const; + // Orca: precise Z height fits the last layers of each object to its own height. With a prime tower + // and variable layer height on objects of different heights, that puts the last layers of a lower + // object between the layers of the others. The tower can still print them, each joined to the tower + // layer below (ToolOrdering::fill_wipe_tower_partitions()), but a joined layer holds the purges of + // both, which makes the tower deeper. So precise Z height is left out of the whole print instead: + // the objects stay on the same layers, and the last layer of a lower object ends where the shared + // layers do, a fraction of a layer off its own top. + // It keys on has_wipe_tower(), which reads the config, so it also applies when the tower turns out + // not to be needed after slicing, such as support in another filament that no object needs. Keying + // it on wipe_tower_certain_before_slicing() would keep precise Z there, but a plate whose support + // does need the tower would then be refused after slicing. + bool precise_z_height_overridden() const { return m_precise_z_height_overridden; } const WipeTowerData& wipe_tower_data(size_t filaments_cnt = 0) const; const ToolOrdering& tool_ordering() const { return m_tool_ordering; } @@ -1587,6 +1601,7 @@ private: // Estimated print time, filament consumed. PrintStatistics m_print_statistics; bool m_support_used {false}; + bool m_precise_z_height_overridden {false}; StatisticsByExtruderCount m_statistics_by_extruder_count; std::vector m_slice_used_filaments; diff --git a/src/libslic3r/PrintApply.cpp b/src/libslic3r/PrintApply.cpp index a19f23c60c..551645054e 100644 --- a/src/libslic3r/PrintApply.cpp +++ b/src/libslic3r/PrintApply.cpp @@ -2304,6 +2304,28 @@ Print::ApplyStatus Print::apply(const Model &model, DynamicPrintConfig new_full_ m_support_used |= object->config().enable_support; } + // Orca: see precise_z_height_overridden(). The objects it applies to are sliced again when it flips. + { + const auto precise_z_height = [](const PrintObject *object) { return object->config().precise_z_height.value; }; + const auto custom_layering = [](const PrintObject *object) { return object->model_object()->has_custom_layering(); }; + const auto other_height = [this](const PrintObject *object) { + return std::abs(object->slicing_parameters().object_print_z_height() - m_objects.front()->slicing_parameters().object_print_z_height()) > EPSILON; + }; + const bool overridden = this->has_wipe_tower() && + std::any_of(m_objects.begin(), m_objects.end(), precise_z_height) && + std::any_of(m_objects.begin(), m_objects.end(), custom_layering) && + std::any_of(m_objects.begin(), m_objects.end(), other_height); + if (overridden != m_precise_z_height_overridden) { + m_precise_z_height_overridden = overridden; + for (PrintObject *object : m_objects) + if (precise_z_height(object)) { + update_apply_status(object->invalidate_step(posSlice)); + // invalidate_step() drops the slicing parameters, and validate() reads them before slicing. + object->update_slicing_parameters(); + } + } + } + #ifdef _DEBUG check_model_ids_equal(m_model, model); #endif /* _DEBUG */ diff --git a/src/libslic3r/PrintObject.cpp b/src/libslic3r/PrintObject.cpp index 1265b0856b..4ae026a0ca 100644 --- a/src/libslic3r/PrintObject.cpp +++ b/src/libslic3r/PrintObject.cpp @@ -874,6 +874,11 @@ void PrintObject::ironing() } } +bool PrintObject::precise_z_height() const +{ + return m_config.precise_z_height.value && !m_print->precise_z_height_overridden(); +} + bool PrintObject::need_z_contouring() const { size_t num_regions = this->num_printing_regions(); diff --git a/src/libslic3r/PrintObjectSlice.cpp b/src/libslic3r/PrintObjectSlice.cpp index 701231a7e0..c5e99348af 100644 --- a/src/libslic3r/PrintObjectSlice.cpp +++ b/src/libslic3r/PrintObjectSlice.cpp @@ -908,7 +908,7 @@ void PrintObject::slice() m_belt_min_z = 0.; m_belt_global_z_offset = 0.; this->clear_layers(); - m_layers = new_layers(this, generate_object_layers(m_slicing_params, layer_height_profile, m_config.precise_z_height.value)); + m_layers = new_layers(this, generate_object_layers(m_slicing_params, layer_height_profile, this->precise_z_height())); this->slice_volumes(); m_print->throw_if_canceled(); diff --git a/src/libslic3r/Slicing.cpp b/src/libslic3r/Slicing.cpp index 209050e4ed..476b096863 100644 --- a/src/libslic3r/Slicing.cpp +++ b/src/libslic3r/Slicing.cpp @@ -816,6 +816,96 @@ bool adjust_layer_series_to_align_object_height(const SlicingParameters &slicing return true; } +std::vector layer_height_profile_fit_to_height( + const std::vector &layer_height_profile, + coordf_t object_height) +{ + assert(layer_height_profile.size() >= 2); + assert(layer_height_profile.size() % 2 == 0); + assert(layer_height_profile[0] == 0); + assert(object_height > EPSILON); + + std::vector out; + out.reserve(layer_height_profile.size() + 2); + size_t i = 0; + for (; i < layer_height_profile.size() && layer_height_profile[i] < object_height - EPSILON; i += 2) { + out.push_back(layer_height_profile[i]); + out.push_back(layer_height_profile[i + 1]); + } + + // The last entry has to sit exactly at the top of the object, see PrintObject::update_layer_height_profile(). + coordf_t height = layer_height_profile.back(); + if (i < layer_height_profile.size() && i >= 2) { + const coordf_t z1 = layer_height_profile[i - 2]; + const coordf_t z2 = layer_height_profile[i]; + // The next entry can lie a hair under the top, within the EPSILON the loop above allows. + height = lerp(layer_height_profile[i - 1], layer_height_profile[i + 1], std::clamp((object_height - z1) / (z2 - z1), 0., 1.)); + } + out.push_back(object_height); + out.push_back(height); + return out; +} + +std::vector layer_height_profile_merge_finest( + const std::vector> &layer_height_profiles) +{ + assert(! layer_height_profiles.empty()); + const std::vector *tallest = &layer_height_profiles.front(); + for (const std::vector &profile : layer_height_profiles) { + assert(profile.size() >= 4); + assert(profile.size() % 2 == 0); + if (profile[profile.size() - 2] > (*tallest)[tallest->size() - 2]) + tallest = &profile; + } + const coordf_t top = (*tallest)[tallest->size() - 2]; + + // Index of the entry each profile was last read at. The Zs only grow, so it never moves back. + std::vector cursors(layer_height_profiles.size(), 0); + // The finest layer height asked for at z. Above its own top an object asks for nothing, but its + // last layer height is eased back up at the rate the adaptive profile allows from one layer to + // the next, rather than released at once: a jump there is a seam on the taller objects. + const auto finest_at = [&layer_height_profiles, &cursors](coordf_t z) { + coordf_t height = std::numeric_limits::max(); + for (size_t idx_profile = 0; idx_profile < layer_height_profiles.size(); ++idx_profile) { + const std::vector &profile = layer_height_profiles[idx_profile]; + const size_t end = profile.size() - 2; + const coordf_t profile_top = profile[end]; + if (z > profile_top + EPSILON) { + const coordf_t last = profile[end - 1]; + height = std::min(height, std::sqrt(last * last + 2. * LAYER_HEIGHT_CHANGE_STEP * (z - profile_top))); + continue; + } + size_t &i = cursors[idx_profile]; + while (i + 2 < end && profile[i + 2] <= z) + i += 2; + height = std::min(height, i + 2 < end ? + lerp(profile[i + 1], profile[i + 3], (z - profile[i]) / (profile[i + 2] - profile[i])) : + profile[i + 1]); + } + return height; + }; + + // One entry per layer, as layer_height_profile_adaptive() lays its profile out, which is the + // spacing smooth_height_profile() counts on. A fixed first layer keeps its own two entries. + std::vector out{ 0., (*tallest)[1] }; + coordf_t print_z = (*tallest)[1]; + if (std::abs((*tallest)[2] - print_z) < EPSILON && std::abs((*tallest)[3] - print_z) < EPSILON) { + out.push_back(print_z); + out.push_back(print_z); + } + while (print_z + EPSILON < top) { + const coordf_t height = finest_at(print_z); + if (height < EPSILON) + break; + out.push_back(print_z); + out.push_back(height); + print_z += height; + } + out.push_back(top); + out.push_back(out[out.size() - 2]); + return out; +} + // Produce object layers as pairs of low / high layer boundaries, stored into a linear vector. std::vector generate_object_layers( const SlicingParameters &slicing_params, @@ -951,8 +1041,12 @@ int generate_layer_height_texture( assert(mid <= slicing_params.object_print_z_height()); coordf_t h = hi - lo; hi = std::min(hi, slicing_params.object_print_z_height()); + // Orca: the last layer can end under the top of the object, by up to half a layer, and the top face is + // drawn with the cells there. The last layer fills them, which no layer did: they kept what the buffer + // held before, black or the colours of another object. + const bool last_layer = idx_layer + 2 >= layers.size(); int cell_first = std::clamp(int(ceil(lo * z_to_cell)), 0, ncells-1); - int cell_last = std::clamp(int(floor(hi * z_to_cell)), 0, ncells-1); + int cell_last = last_layer ? ncells - 1 : std::clamp(int(floor(hi * z_to_cell)), 0, ncells-1); for (int cell = cell_first; cell <= cell_last; ++ cell) { coordf_t idxf = (0.5 * hscale + (h - slicing_params.layer_height)) * coordf_t(palette_raw.size()-1) / hscale; int idx1 = std::clamp(int(floor(idxf)), 0, int(palette_raw.size() - 1)); @@ -960,7 +1054,8 @@ int generate_layer_height_texture( coordf_t t = idxf - coordf_t(idx1); const Vec3crd &color1 = palette_raw[idx1]; const Vec3crd &color2 = palette_raw[idx2]; - coordf_t z = cell_to_z * coordf_t(cell); + // Above the last layer, the shade of its top. + coordf_t z = std::min(cell_to_z * coordf_t(cell), hi); assert(lo - EPSILON <= z && z <= hi + EPSILON); // Intensity profile to visualize the layers. coordf_t intensity = cos(M_PI * 0.7 * (mid - z) / h); @@ -988,7 +1083,7 @@ int generate_layer_height_texture( } if (level_of_detail_2nd_level) { cell_first = std::clamp(int(ceil(lo * z_to_cell1)), 0, ncells1-1); - cell_last = std::clamp(int(floor(hi * z_to_cell1)), 0, ncells1-1); + cell_last = last_layer ? ncells1 - 1 : std::clamp(int(floor(hi * z_to_cell1)), 0, ncells1-1); for (int cell = cell_first; cell <= cell_last; ++ cell) { coordf_t idxf = (0.5 * hscale + (h - slicing_params.layer_height)) * coordf_t(palette_raw.size()-1) / hscale; int idx1 = std::clamp(int(floor(idxf)), 0, int(palette_raw.size() - 1)); diff --git a/src/libslic3r/Slicing.hpp b/src/libslic3r/Slicing.hpp index 344dfafb99..79bd4a6b76 100644 --- a/src/libslic3r/Slicing.hpp +++ b/src/libslic3r/Slicing.hpp @@ -162,6 +162,20 @@ std::vector layer_height_profile_from_ranges( const SlicingParameters &slicing_params, const t_layer_config_ranges &layer_config_ranges); +// Orca: fit a layer height profile onto an object of another height, so that both objects are sliced +// at the same Z over the height they share. The profile is cut at object_height, or its last +// layer height is carried up to it. +std::vector layer_height_profile_fit_to_height( + const std::vector &layer_height_profile, + coordf_t object_height); + +// Orca: one profile for several objects, taking the finest of their layer heights at every Z, up to +// the top of the tallest one, with one entry per layer. The entry at the top of a profile only +// closes it, so each profile counts with its last layer height before it, and above that top the +// layer height is eased back up rather than released at once. +std::vector layer_height_profile_merge_finest( + const std::vector> &layer_height_profiles); + std::vector layer_height_profile_adaptive( const SlicingParameters& slicing_params, const ModelObject& object, float quality_factor); diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index 8ca886ee50..ff37a9b81f 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -24,6 +24,7 @@ #include "slic3r/GUI/IMSlider.hpp" #include "libslic3r/Preset.hpp" #include "libslic3r/Model.hpp" +#include "libslic3r/ObjectID.hpp" #include #include "slic3r/GUI/SceneRaycaster.hpp" #include "slic3r/GUI/Camera.hpp" @@ -308,6 +309,8 @@ GLCanvas3D::LayersEditing::~LayersEditing() glsafe(::glDeleteTextures(1, &m_z_texture_id)); m_z_texture_id = 0; } + for (auto &[object_id, object] : m_other_textures) + this->release_object_texture(object); delete m_slicing_parameters; } @@ -315,8 +318,14 @@ const float GLCanvas3D::LayersEditing::THICKNESS_BAR_WIDTH = 70.0f; void GLCanvas3D::LayersEditing::init() { - glsafe(::glGenTextures(1, (GLuint*)&m_z_texture_id)); - glsafe(::glBindTexture(GL_TEXTURE_2D, m_z_texture_id)); + m_z_texture_id = create_texture(); +} + +unsigned int GLCanvas3D::LayersEditing::create_texture() +{ + GLuint texture_id = 0; + glsafe(::glGenTextures(1, &texture_id)); + glsafe(::glBindTexture(GL_TEXTURE_2D, texture_id)); if (!OpenGLManager::get_gl_info().is_core_profile() || !OpenGLManager::get_gl_info().is_mesa()) { glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); @@ -325,6 +334,7 @@ void GLCanvas3D::LayersEditing::init() glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST)); glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1)); glsafe(::glBindTexture(GL_TEXTURE_2D, 0)); + return texture_id; } void GLCanvas3D::LayersEditing::set_config(const DynamicPrintConfig* config) @@ -334,6 +344,9 @@ void GLCanvas3D::LayersEditing::set_config(const DynamicPrintConfig* config) m_slicing_parameters = nullptr; m_layers_texture.valid = false; m_layer_height_profile.clear(); + // The other objects read their slicing parameters and profiles again the next time they are drawn. + // Their textures stay: they are regenerated only if what they show has changed. + ++m_config_version; } void GLCanvas3D::LayersEditing::select_object(const Model& model, int object_id) @@ -354,6 +367,7 @@ void GLCanvas3D::LayersEditing::select_object(const Model& model, int object_id) m_model_object = model_object_new; m_object_max_z = new_max_z; } + m_model = &model; } bool GLCanvas3D::LayersEditing::is_allowed() const @@ -363,6 +377,59 @@ bool GLCanvas3D::LayersEditing::is_allowed() const float GLCanvas3D::LayersEditing::s_overlay_window_width; +// Orca: on a bar shared by several objects, the height at which lower ones end: a line across the +// bar, and an arrow pointing at it from the names of the objects. The label is kept on the canvas, +// below min_label_top, the bottom of the label above it, and below the toolbar row when it would reach +// into that row: toolbar_end is the bottom right corner of the row. Returns the bottom of this label. +static float render_object_top_mark(const std::string& label, float bar_left, float bar_right, float y, float min_label_top, float canvas_height, + const ImVec2& toolbar_end) +{ + ImDrawList* draw_list = ImGui::GetBackgroundDrawList(); + const ImU32 color = ImGui::GetColorU32(ImGuiWrapper::COL_ORCA); + const float arrow = 0.6f * ImGui::GetFontSize(); + const float tip = bar_left - 2.0f; + draw_list->AddLine({ bar_left, y }, { bar_right, y }, color, 2.0f); + + const ImVec2 text_size = ImGui::CalcTextSize(label.c_str()); + const ImVec2 padding = { 0.4f * ImGui::GetFontSize(), 0.2f * ImGui::GetFontSize() }; + const float half_box = 0.5f * text_size.y + padding.y; + const float text_x = tip - arrow - 2.0f * padding.x - text_size.x; + const float min_top = text_x - padding.x < toolbar_end.x ? std::max(min_label_top, toolbar_end.y) : min_label_top; + const float label_y = std::min(std::max(y, std::max(min_top, 0.0f) + half_box), canvas_height - half_box); + draw_list->AddTriangleFilled({ tip, y }, { tip - arrow, label_y - 0.6f * arrow }, { tip - arrow, label_y + 0.6f * arrow }, color); + + const ImVec2 text_pos = { text_x, label_y - 0.5f * text_size.y }; + draw_list->AddRectFilled({ text_pos.x - padding.x, text_pos.y - padding.y }, { text_pos.x + text_size.x + padding.x, text_pos.y + text_size.y + padding.y }, + color, padding.y); + draw_list->AddText(text_pos, IM_COL32_WHITE, label.c_str()); + return label_y + half_box; +} + +// Orca: the names of the objects that end at one height, such as "Cube x3, Cone" with a multiplication +// sign: the first three names, then how many objects are left. +static std::string object_top_mark_label(const std::vector>& names) +{ + static constexpr size_t max_names = 3; + std::string label; + size_t listed = 0; + size_t total = 0; + for (size_t i = 0; i < names.size(); ++i) { + total += names[i].second; + if (i >= max_names) + continue; + if (i > 0) + label += ", "; + label += names[i].first; + if (names[i].second > 1) + // U+00D7 MULTIPLICATION SIGN, in the default ImGui glyph range. + label += " \xC3\x97" + std::to_string(names[i].second); + listed += names[i].second; + } + if (listed < total) + label += " +" + std::to_string(total - listed); + return label; +} + void GLCanvas3D::LayersEditing::render_variable_layer_height_dialog(GLCanvas3D& canvas) { if (!m_enabled) return; @@ -458,6 +525,19 @@ void GLCanvas3D::LayersEditing::render_variable_layer_height_dialog(GLCanvas3D& ImGui::AlignTextToFramePadding(); imgui.text(_L("Keep min")); + if (!m_other_object_ids.empty()) { + // Several objects are selected: by default they share one profile, which the prime tower requires. + imgui.bbl_checkbox("##each_separately", m_each_separately); + ImGui::SameLine(); + ImGui::AlignTextToFramePadding(); + // TRN Variable layer height tool, checkbox shown with several objects selected: give each object its own + // layer heights instead of one profile they all share. + imgui.text(_L("Each object separately")); + if (m_bar_object_ids.size() > 1) + // TRN Variable layer height tool: each selected object has a layer height bar at the right edge of the 3D view. + imgui.text(_L("Point at a bar to edit its object.")); + } + ImGui::Separator(); const wxString shift = GUI::shortkey_shift_prefix(); @@ -473,7 +553,7 @@ void GLCanvas3D::LayersEditing::render_variable_layer_height_dialog(GLCanvas3D& GLGizmoUtils::render_tooltip_button(&imgui, canvas, shortcuts, x, y); ImGui::SameLine(); - imgui.disabled_begin(check_object_layers_fixed(*m_slicing_parameters, m_layer_height_profile)); + imgui.disabled_begin(m_other_object_ids.empty() && check_object_layers_fixed(*m_slicing_parameters, m_layer_height_profile)); if (imgui.button(_L("Reset"))) { wxPostEvent((wxEvtHandler*) canvas.get_wxglcanvas(), SimpleEvent(EVT_GLCANVAS_RESET_LAYER_HEIGHT_PROFILE)); } @@ -495,6 +575,47 @@ void GLCanvas3D::LayersEditing::render_variable_layer_height_dialog(GLCanvas3D& imgui.end(); ImGui::PopStyleVar(2); imgui.pop_toolbar_style(); + + if (m_bar_object_ids.size() <= 1 && m_object_max_z > 0.0f) { + // One mark for each height at which other objects end. An object as tall as the one shown ends at + // the top of the bar and needs none, and objects that end at the same height share one. + struct TopMark + { + double z; + std::vector> names; + }; + std::vector marks; + for (int object_id : m_other_object_ids) { + if (object_id < 0 || object_id >= int(m_model->objects.size())) + continue; + const ModelObject& object = *m_model->objects[object_id]; + const double z = object.max_z(); + if (z > double(m_object_max_z) - EPSILON) + continue; + auto mark = std::find_if(marks.begin(), marks.end(), [z](const TopMark& m) { return std::abs(m.z - z) < EPSILON; }); + if (mark == marks.end()) + mark = marks.insert(marks.end(), TopMark{ z, {} }); + auto name = std::find_if(mark->names.begin(), mark->names.end(), [&object](const auto& n) { return n.first == object.name; }); + if (name == mark->names.end()) + mark->names.emplace_back(object.name, 1); + else + ++name->second; + } + // From the top down, so that a label pushed down by the one above it does not cover the next. + std::sort(marks.begin(), marks.end(), [](const TopMark& lhs, const TopMark& rhs) { return lhs.z > rhs.z; }); + const float cnv_width = float(cnv_size.get_width()); + const float cnv_height = float(cnv_size.get_height()); + float label_bottom = 0.0f; + // The toolbar row can end next to the bar, where the labels near its top would cover its last buttons. + ImVec2 toolbar_end(0.0f, 0.0f); + if (canvas.m_main_toolbar.is_enabled()) + toolbar_end = ImVec2(float(canvas.get_main_toolbar_offset()) + canvas.m_main_toolbar.get_width() + canvas.m_separator_toolbar.get_width() + + canvas.m_gizmos.get_scaled_total_width() + canvas.m_assemble_view_toolbar.get_width(), + std::max(canvas.m_main_toolbar.get_height(), canvas.m_gizmos.get_scaled_total_height())); + for (const TopMark& mark : marks) + label_bottom = render_object_top_mark(object_top_mark_label(mark.names), cnv_width - thickness_bar_width(canvas), cnv_width, + cnv_height * (1.0f - float(mark.z) / m_object_max_z), label_bottom, cnv_height, toolbar_end); + } } void GLCanvas3D::LayersEditing::render_overlay(GLCanvas3D& canvas) @@ -519,19 +640,99 @@ float GLCanvas3D::LayersEditing::get_cursor_z_relative(const GLCanvas3D& canvas) -1000.0f; } +// Whether the point is on any of the bars. bool GLCanvas3D::LayersEditing::bar_rect_contains(const GLCanvas3D& canvas, float x, float y) { - const Rect& rect = get_bar_rect_screen(canvas); - return rect.get_left() <= x && x <= rect.get_right() && rect.get_top() <= y && y <= rect.get_bottom(); + return bar_at(canvas, x, y) >= 0; } +int GLCanvas3D::LayersEditing::bar_at(const GLCanvas3D& canvas, float x, float y) +{ + const Size& cnv_size = canvas.get_canvas_size(); + const float w = (float)cnv_size.get_width(); + const float h = (float)cnv_size.get_height(); + const float bar_w = thickness_bar_width(canvas); + const int bars = std::max(1, int(canvas.m_layers_editing.m_bar_object_ids.size())); + if (x < w - float(bars) * bar_w || x > w || y < 0.0f || y > h) + return -1; + const int bar = std::min(bars - 1, int((w - x) / bar_w)); + // Above a lower bar the scene shows through, and the mouse belongs to it. + return y < h * (1.0f - canvas.m_layers_editing.bar_fraction(size_t(bar))) ? -1 : bar; +} + +// Whether a bar is being pointed at or painted. +bool GLCanvas3D::LayersEditing::bar_in_focus(const GLCanvas3D& canvas) const +{ + const Vec2d mouse_pos = canvas.get_local_mouse_position(); + return state == Editing || bar_at(canvas, float(mouse_pos.x()), float(mouse_pos.y())) >= 0; +} + +size_t GLCanvas3D::LayersEditing::active_bar() const +{ + const auto it = std::find(m_bar_object_ids.begin(), m_bar_object_ids.end(), last_object_id); + return it == m_bar_object_ids.end() ? 0 : size_t(it - m_bar_object_ids.begin()); +} + +// The bar of the object shown, which is the one the mouse edits. Rect GLCanvas3D::LayersEditing::get_bar_rect_screen(const GLCanvas3D& canvas) { const Size& cnv_size = canvas.get_canvas_size(); float w = (float)cnv_size.get_width(); float h = (float)cnv_size.get_height(); + const float bar_w = thickness_bar_width(canvas); + const size_t active = canvas.m_layers_editing.active_bar(); + const float right = w - float(active) * bar_w; - return { w - thickness_bar_width(canvas), 0.0f, w, h }; + return { right - bar_w, h * (1.0f - canvas.m_layers_editing.bar_fraction(active)), right, h }; +} + +int GLCanvas3D::LayersEditing::choose_shown_object(const GLCanvas3D& canvas, const Model& model, const std::vector& object_ids) +{ + // Objects past MAX_BARS still get Adaptive, Smooth and Reset, but have no bar to show or paint. + const bool bars_notice = m_each_separately && object_ids.size() > MAX_BARS; + if (bars_notice != m_bars_notice_shown) { + m_bars_notice_shown = bars_notice; + // TRN "Adaptive", "Smooth" and "Reset" are the buttons of the variable layer height tool. + const std::string notice_text = _u8L("Variable layer height: only the three tallest selected objects have a bar. The others still take Adaptive, Smooth and Reset."); + NotificationManager& notification_manager = *wxGetApp().plater()->get_notification_manager(); + if (bars_notice) + notification_manager.push_plater_warning_notification(notice_text); + else + notification_manager.close_plater_warning_notification(notice_text); + } + + m_bar_object_ids.clear(); + m_bar_fractions.clear(); + if (object_ids.empty()) + return -1; + + m_bar_object_ids.assign(object_ids.begin(), object_ids.begin() + (m_each_separately ? std::min(object_ids.size(), MAX_BARS) : 1)); + const double tallest = model.objects[m_bar_object_ids.front()]->max_z(); + for (int object_id : m_bar_object_ids) + m_bar_fractions.emplace_back(tallest > 0. ? float(std::min(1., model.objects[object_id]->max_z() / tallest)) : 1.0f); + int shown = std::find(m_bar_object_ids.begin(), m_bar_object_ids.end(), last_object_id) != m_bar_object_ids.end() ? + last_object_id : m_bar_object_ids.front(); + // A profile being painted stays with its object, wherever the mouse wanders. + if (state != Editing) { + const Vec2d mouse_pos = canvas.get_local_mouse_position(); + if (const int bar = bar_at(canvas, float(mouse_pos.x()), float(mouse_pos.y())); bar >= 0) + shown = m_bar_object_ids[bar]; + } + return shown; +} + +void GLCanvas3D::LayersEditing::release_unselected_textures(const Model& model, const std::vector& object_ids) +{ + for (auto it = m_other_textures.begin(); it != m_other_textures.end();) { + const size_t id = it->first; + const bool selected = std::any_of(object_ids.begin(), object_ids.end(), [&model, id](int object_id) { return model.objects[object_id]->id().id == id; }); + if (selected) + ++it; + else { + this->release_object_texture(it->second); + it = m_other_textures.erase(it); + } + } } bool GLCanvas3D::LayersEditing::is_initialized() const @@ -577,6 +778,8 @@ void GLCanvas3D::LayersEditing::render_active_object_annotations(const GLCanvas3 return; const float cnv_inv_width = 1.0f / cnv_width; + // The width the mouse is tested against, so that every bar is drawn where it is hit. + const float bar_w = thickness_bar_width(canvas); GLShaderProgram* shader = wxGetApp().get_shader("variable_layer_height"); if (shader == nullptr) @@ -584,47 +787,64 @@ void GLCanvas3D::LayersEditing::render_active_object_annotations(const GLCanvas3 shader->start_using(); - shader->set_uniform("z_to_texture_row", float(m_layers_texture.cells - 1) / (float(m_layers_texture.width) * m_object_max_z)); + generate_layer_height_texture(); + shader->set_uniform("z_texture_row_to_normalized", 1.0f / (float)m_layers_texture.height); - shader->set_uniform("z_cursor", m_object_max_z * this->get_cursor_z_relative(canvas)); shader->set_uniform("z_cursor_band_width", band_width); - shader->set_uniform("object_max_z", m_object_max_z); + shader->set_uniform("dimming", 0.0f); shader->set_uniform("view_model_matrix", Transform3d::Identity()); shader->set_uniform("projection_matrix", Transform3d::Identity()); shader->set_uniform("view_normal_matrix", (Matrix3d)Matrix3d::Identity()); - glsafe(::glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); - glsafe(::glBindTexture(GL_TEXTURE_2D, m_z_texture_id)); + // Render the color bars, one per object that has one. Each is drawn at the scale of its own object. + const size_t active = this->active_bar(); + const size_t bars = std::max(1, m_bar_object_ids.size()); + this->reset_bar_models(bars); + for (size_t bar = 0; bar < bars; ++bar) { + const LayersTexture* texture = &m_layers_texture; + float max_z = m_object_max_z; + if (bar == active) + this->bind_shown_texture(); + else { + ObjectTexture& other = this->other_object(m_bar_object_ids[bar]); + texture = &this->bind_object_texture(other); + max_z = float(other.max_z); + } - // Render the color bar - if (!m_profile.background.is_initialized() || m_profile.old_canvas_width != cnv_width) { - m_profile.old_canvas_width = cnv_width; - m_profile.background.reset(); + shader->set_uniform("z_to_texture_row", float(texture->cells - 1) / (float(texture->width) * max_z)); + shader->set_uniform("z_cursor", bar == active ? max_z * this->get_cursor_z_relative(canvas) : -1000.0f * max_z); + shader->set_uniform("object_max_z", max_z); - GLModel::Geometry init_data; - init_data.format = { GLModel::Geometry::EPrimitiveType::Triangles, GLModel::Geometry::EVertexLayout::P3N3T2 }; - init_data.reserve_vertices(4); - init_data.reserve_indices(6); + BarModels& models = m_bar_models[bar]; + const std::vector layout{ cnv_width, bar_w, this->bar_fraction(bar) }; + if (models.background_layout != layout) { + models.background_layout = layout; + models.background.reset(); - // vertices - const float l = 1.0f - 2.0f * THICKNESS_BAR_WIDTH * cnv_inv_width; - const float r = 1.0f; - const float t = 1.0f; - const float b = -1.0f; - init_data.add_vertex(Vec3f(l, b, 0.0f), Vec3f::UnitZ(), Vec2f(0.0f, 0.0f)); - init_data.add_vertex(Vec3f(r, b, 0.0f), Vec3f::UnitZ(), Vec2f(1.0f, 0.0f)); - init_data.add_vertex(Vec3f(r, t, 0.0f), Vec3f::UnitZ(), Vec2f(1.0f, 1.0f)); - init_data.add_vertex(Vec3f(l, t, 0.0f), Vec3f::UnitZ(), Vec2f(0.0f, 1.0f)); + GLModel::Geometry init_data; + init_data.format = { GLModel::Geometry::EPrimitiveType::Triangles, GLModel::Geometry::EVertexLayout::P3N3T2 }; + init_data.reserve_vertices(4); + init_data.reserve_indices(6); - // indices - init_data.add_triangle(0, 1, 2); - init_data.add_triangle(2, 3, 0); + // vertices + const float l = 1.0f - 2.0f * float(bar + 1) * bar_w * cnv_inv_width; + const float r = 1.0f - 2.0f * float(bar) * bar_w * cnv_inv_width; + const float t = -1.0f + 2.0f * this->bar_fraction(bar); + const float b = -1.0f; + init_data.add_vertex(Vec3f(l, b, 0.0f), Vec3f::UnitZ(), Vec2f(0.0f, 0.0f)); + init_data.add_vertex(Vec3f(r, b, 0.0f), Vec3f::UnitZ(), Vec2f(1.0f, 0.0f)); + init_data.add_vertex(Vec3f(r, t, 0.0f), Vec3f::UnitZ(), Vec2f(1.0f, 1.0f)); + init_data.add_vertex(Vec3f(l, t, 0.0f), Vec3f::UnitZ(), Vec2f(0.0f, 1.0f)); - m_profile.background.init_from(std::move(init_data)); + // indices + init_data.add_triangle(0, 1, 2); + init_data.add_triangle(2, 3, 0); + + models.background.init_from(std::move(init_data)); + } + models.background.render(); } - m_profile.background.render(); - glsafe(::glBindTexture(GL_TEXTURE_2D, 0)); shader->stop_using(); @@ -646,52 +866,102 @@ void GLCanvas3D::LayersEditing::render_profile(const GLCanvas3D& canvas) if (cnv_width == 0.0f || cnv_height == 0.0f) return; - // Make the vertical bar a bit wider so the layer height curve does not touch the edge of the bar region. - const float scale_x = THICKNESS_BAR_WIDTH / float(1.12 * m_slicing_parameters->max_layer_height); - const float scale_y = cnv_height / m_object_max_z; - + const float bar_w = thickness_bar_width(canvas); const float cnv_inv_width = 1.0f / cnv_width; const float cnv_inv_height = 1.0f / cnv_height; + const auto to_ndc_x = [cnv_inv_width](float x) { return 2.0f * (x * cnv_inv_width - 0.5f); }; + const auto to_ndc_y = [cnv_inv_height](float y) { return 2.0f * (y * cnv_inv_height - 0.5f); }; - // Baseline - if (!m_profile.baseline.is_initialized() || m_profile.old_layer_height_profile != m_layer_height_profile) { - m_profile.baseline.reset(); + const size_t active = this->active_bar(); + const size_t bars = std::max(1, m_bar_object_ids.size()); + this->reset_bar_models(bars); - GLModel::Geometry init_data; - init_data.format = { GLModel::Geometry::EPrimitiveType::Lines, GLModel::Geometry::EVertexLayout::P2}; - init_data.color = ColorRGBA::BLACK(); - init_data.reserve_vertices(2); - init_data.reserve_indices(2); + // The layer height curve of each bar, at the scale of its own object and of its own layer heights. + // The straight lines are laid out from the canvas, the active bar, and the axis and the top of each bar. + std::vector lines_layout{ cnv_width, cnv_height, bar_w, float(active) }; + for (size_t bar = 0; bar < bars; ++bar) { + const ObjectTexture* other = bar == active ? nullptr : &this->other_object(m_bar_object_ids[bar]); + const SlicingParameters& params = other == nullptr ? *m_slicing_parameters : other->slicing_parameters; + const std::vector& profile = other == nullptr ? m_layer_height_profile : other->profile; + const float max_z = other == nullptr ? m_object_max_z : float(other->max_z); + // Make the vertical bar a bit wider so the layer height curve does not touch the edge of the bar region. + const float scale_x = bar_w / float(1.12 * params.max_layer_height); + const float scale_y = cnv_height * this->bar_fraction(bar) / max_z; + const float left = cnv_width - float(bar + 1) * bar_w; + lines_layout.push_back(to_ndc_x(left + float(params.layer_height) * scale_x)); + lines_layout.push_back(this->bar_fraction(bar)); - // vertices - const float axis_x = 2.0f * ((cnv_width - THICKNESS_BAR_WIDTH + float(m_slicing_parameters->layer_height) * scale_x) * cnv_inv_width - 0.5f); - init_data.add_vertex(Vec2f(axis_x, -1.0f)); - init_data.add_vertex(Vec2f(axis_x, 1.0f)); + BarModels& models = m_bar_models[bar]; + const std::vector layout{ cnv_width, cnv_height, bar_w, this->bar_fraction(bar), max_z, float(params.max_layer_height) }; + if (models.profile_layout != layout || models.profile_source != profile) { + models.profile_layout = layout; + models.profile_source = profile; + models.profile.reset(); + if (profile.size() >= 4) { + GLModel::Geometry init_data; + init_data.format = { GLModel::Geometry::EPrimitiveType::LineStrip, GLModel::Geometry::EVertexLayout::P2 }; + init_data.color = ColorRGBA::BLUE(); + init_data.reserve_vertices(profile.size() / 2); + init_data.reserve_indices(profile.size() / 2); - // indices - init_data.add_line(0, 1); - - m_profile.baseline.init_from(std::move(init_data)); + // vertices + indices + for (unsigned int i = 0; i + 1 < (unsigned int)profile.size(); i += 2) { + init_data.add_vertex(Vec2f(to_ndc_x(left + float(profile[i + 1]) * scale_x), to_ndc_y(float(profile[i]) * scale_y))); + init_data.add_index(i / 2); + } + models.profile.init_from(std::move(init_data)); + } + } } - if (!m_profile.profile.is_initialized() || m_profile.old_layer_height_profile != m_layer_height_profile) { - m_profile.old_layer_height_profile = m_layer_height_profile; - m_profile.profile.reset(); + if (m_bar_lines_layout != lines_layout) { + m_bar_lines_layout = lines_layout; - GLModel::Geometry init_data; - init_data.format = { GLModel::Geometry::EPrimitiveType::LineStrip, GLModel::Geometry::EVertexLayout::P2 }; - init_data.color = ColorRGBA::BLUE(); - init_data.reserve_vertices(m_layer_height_profile.size() / 2); - init_data.reserve_indices(m_layer_height_profile.size() / 2); - - // vertices + indices - for (unsigned int i = 0; i < (unsigned int)m_layer_height_profile.size(); i += 2) { - init_data.add_vertex(Vec2f(2.0f * ((cnv_width - THICKNESS_BAR_WIDTH + float(m_layer_height_profile[i + 1]) * scale_x) * cnv_inv_width - 0.5f), - 2.0f * (float(m_layer_height_profile[i]) * scale_y * cnv_inv_height - 0.5))); - init_data.add_index(i / 2); + // Straight lines: the baseline of each bar and, with several bars, the outline of each. + GLModel::Geometry lines_data; + lines_data.format = { GLModel::Geometry::EPrimitiveType::Lines, GLModel::Geometry::EVertexLayout::P2 }; + lines_data.color = ColorRGBA::BLACK(); + unsigned int lines_count = 0; + const auto add_line = [&lines_data, &lines_count](const Vec2f& from, const Vec2f& to) { + lines_data.add_vertex(from); + lines_data.add_vertex(to); + lines_data.add_line(2 * lines_count, 2 * lines_count + 1); + ++lines_count; + }; + for (size_t bar = 0; bar < bars; ++bar) { + const float axis_x = lines_layout[4 + 2 * bar]; + const float top = -1.0f + 2.0f * lines_layout[5 + 2 * bar]; + add_line(Vec2f(axis_x, -1.0f), Vec2f(axis_x, top)); + if (bars > 1) { + // The outline of the bar: its left edge and its top. The next bar to the right is at least as tall. + const float left = to_ndc_x(cnv_width - float(bar + 1) * bar_w); + const float right = to_ndc_x(cnv_width - float(bar) * bar_w); + add_line(Vec2f(left, -1.0f), Vec2f(left, top)); + add_line(Vec2f(left, top), Vec2f(right, top)); + } } + m_bar_lines.reset(); + m_bar_lines.init_from(std::move(lines_data)); - m_profile.profile.init_from(std::move(init_data)); + // With several bars, the one pointed at is framed in white. + m_bar_frame.reset(); + if (bars > 1) { + GLModel::Geometry frame_data; + frame_data.format = { GLModel::Geometry::EPrimitiveType::Lines, GLModel::Geometry::EVertexLayout::P2 }; + frame_data.color = ColorRGBA::WHITE(); + // Kept a pixel inside the bar, so the frame is not drawn over by the edge between bars. + const float l = to_ndc_x(cnv_width - float(active + 1) * bar_w + 1.0f); + const float r = to_ndc_x(cnv_width - float(active) * bar_w - 1.0f); + const float t = to_ndc_y(cnv_height * this->bar_fraction(active) - 1.0f); + frame_data.add_vertex(Vec2f(l, -1.0f)); + frame_data.add_vertex(Vec2f(l, t)); + frame_data.add_vertex(Vec2f(r, t)); + frame_data.add_vertex(Vec2f(r, -1.0f)); + frame_data.add_line(0, 1); + frame_data.add_line(1, 2); + frame_data.add_line(2, 3); + m_bar_frame.init_from(std::move(frame_data)); + } } #if SLIC3R_OPENGL_ES @@ -713,8 +983,12 @@ void GLCanvas3D::LayersEditing::render_profile(const GLCanvas3D& canvas) #if !SLIC3R_OPENGL_ES } #endif // !SLIC3R_OPENGL_ES - m_profile.baseline.render(); - m_profile.profile.render(); + m_bar_lines.render(); + if (bars > 1 && this->bar_in_focus(canvas)) + m_bar_frame.render(); + for (size_t bar = 0; bar < bars; ++bar) + if (m_bar_models[bar].profile.is_initialized()) + m_bar_models[bar].profile.render(); shader->stop_using(); } } @@ -738,42 +1012,203 @@ void GLCanvas3D::LayersEditing::render_volumes(const GLCanvas3D& canvas, const G generate_layer_height_texture(); // Uniforms were resolved, go ahead using the layer editing shader. - shader->set_uniform("z_to_texture_row", float(m_layers_texture.cells - 1) / (float(m_layers_texture.width) * float(m_object_max_z))); shader->set_uniform("z_texture_row_to_normalized", 1.0f / float(m_layers_texture.height)); - shader->set_uniform("z_cursor", float(m_object_max_z) * float(this->get_cursor_z_relative(canvas))); shader->set_uniform("z_cursor_band_width", float(this->band_width)); + // The band at the height under the mouse goes on the objects the edit will change: all of them + // while they share a profile, or the object shown alone when each has its own. + const float z_cursor = float(m_object_max_z) * float(this->get_cursor_z_relative(canvas)); + shader->set_uniform("projection_matrix", wxGetApp().plater()->get_camera().get_projection_matrix()); - const Camera& camera = wxGetApp().plater()->get_camera(); - shader->set_uniform("projection_matrix", camera.get_projection_matrix()); + // Orca: the other selected objects. Those on the layers of the object shown are drawn with its + // texture, the others with their own. With a profile each, pointing at a bar tones down the + // objects it does not edit. + const float dimming = m_each_separately && this->bar_in_focus(canvas) ? 0.6f : 0.0f; + for (int object_id : this->edited_object_ids()) + if (object_id != this->last_object_id) { + ObjectTexture& other = this->other_object(object_id); + if (this->shares_shown_layers(other)) { + this->bind_shown_texture(); + this->render_object_volumes(volumes, *shader, object_id, m_layers_texture, m_object_max_z, z_cursor, dimming); + } else { + const LayersTexture& texture = this->bind_object_texture(other); + this->render_object_volumes(volumes, *shader, object_id, texture, other.max_z, + this->follows_shown_object(other.slicing_parameters) ? z_cursor : -1000.0f * float(other.max_z), dimming); + } + } + this->bind_shown_texture(); + this->render_object_volumes(volumes, *shader, this->last_object_id, m_layers_texture, m_object_max_z, z_cursor, 0.0f); + // Revert back to the previous shader. + glBindTexture(GL_TEXTURE_2D, 0); +} - // Initialize the layer height texture mapping. - const GLsizei w = (GLsizei)m_layers_texture.width; - const GLsizei h = (GLsizei)m_layers_texture.height; - const GLsizei half_w = w / 2; - const GLsizei half_h = h / 2; - glsafe(::glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); - glsafe(::glBindTexture(GL_TEXTURE_2D, m_z_texture_id)); - glsafe(::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0)); - glsafe(::glTexImage2D(GL_TEXTURE_2D, 1, GL_RGBA, half_w, half_h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0)); - glsafe(::glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, m_layers_texture.data.data())); - glsafe(::glTexSubImage2D(GL_TEXTURE_2D, 1, 0, 0, half_w, half_h, GL_RGBA, GL_UNSIGNED_BYTE, m_layers_texture.data.data() + m_layers_texture.width * m_layers_texture.height * 4)); +void GLCanvas3D::LayersEditing::render_object_volumes(const GLVolumeCollection& volumes, GLShaderProgram& shader, int object_id, const LayersTexture& texture, double object_max_z, float z_cursor, float dimming) +{ + shader.set_uniform("z_to_texture_row", float(texture.cells - 1) / (float(texture.width) * float(object_max_z))); + shader.set_uniform("z_cursor", z_cursor); + shader.set_uniform("dimming", dimming); + + const Transform3d& view_matrix = wxGetApp().plater()->get_camera().get_view_matrix(); for (GLVolume* glvolume : volumes.volumes) { // Render the object using the layer editing shader and texture. - if (!glvolume->is_active || glvolume->composite_id.object_id != this->last_object_id || glvolume->is_modifier) + if (!glvolume->is_active || glvolume->composite_id.object_id != object_id || glvolume->is_modifier) continue; - shader->set_uniform("volume_world_matrix", glvolume->world_matrix()); - shader->set_uniform("object_max_z", 0.0f); - const Transform3d& view_matrix = camera.get_view_matrix(); + shader.set_uniform("volume_world_matrix", glvolume->world_matrix()); + shader.set_uniform("object_max_z", 0.0f); const Transform3d model_matrix = glvolume->world_matrix(); - shader->set_uniform("view_model_matrix", view_matrix * model_matrix); - const Matrix3d view_normal_matrix = view_matrix.matrix().block(0, 0, 3, 3) * model_matrix.matrix().block(0, 0, 3, 3).inverse().transpose(); - shader->set_uniform("view_normal_matrix", view_normal_matrix); + shader.set_uniform("view_model_matrix", view_matrix * model_matrix); + // Orca: the shader also tells the horizontal faces from the normals in world space, which need the inverse transpose + // too: the world matrix itself tilts them under a non-uniform scale. + const Matrix3d world_normal_matrix = model_matrix.matrix().block(0, 0, 3, 3).inverse().transpose(); + shader.set_uniform("volume_world_normal_matrix", world_normal_matrix); + const Matrix3d view_normal_matrix = view_matrix.matrix().block(0, 0, 3, 3) * world_normal_matrix; + shader.set_uniform("view_normal_matrix", view_normal_matrix); glvolume->render(); } - // Revert back to the previous shader. - glBindTexture(GL_TEXTURE_2D, 0); +} + +// Sends the texture to the GPU as texture_id and leaves it bound. +void GLCanvas3D::LayersEditing::load_texture(const LayersTexture& texture, unsigned int texture_id) +{ + // Initialize the layer height texture mapping. + const GLsizei w = (GLsizei)texture.width; + const GLsizei h = (GLsizei)texture.height; + const GLsizei half_w = w / 2; + const GLsizei half_h = h / 2; + glsafe(::glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); + glsafe(::glBindTexture(GL_TEXTURE_2D, texture_id)); + glsafe(::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0)); + glsafe(::glTexImage2D(GL_TEXTURE_2D, 1, GL_RGBA, half_w, half_h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0)); + glsafe(::glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, texture.data.data())); + glsafe(::glTexSubImage2D(GL_TEXTURE_2D, 1, 0, 0, half_w, half_h, GL_RGBA, GL_UNSIGNED_BYTE, texture.data.data() + texture.width * texture.height * 4)); +} + +void GLCanvas3D::LayersEditing::bind_shown_texture() +{ + if (m_layers_texture.uploaded) + glsafe(::glBindTexture(GL_TEXTURE_2D, m_z_texture_id)); + else { + load_texture(m_layers_texture, m_z_texture_id); + m_layers_texture.uploaded = true; + } +} + +// A copy of a GLModel shares the GPU buffers that the original deletes, so the models of the bars +// are not moved when the vector grows: they are all made again when the number of bars changes. +void GLCanvas3D::LayersEditing::reset_bar_models(size_t bars) +{ + if (m_bar_models.size() != bars) { + m_bar_models.clear(); + m_bar_models.resize(bars); + } +} + +bool GLCanvas3D::LayersEditing::is_edited_object(int object_id) const +{ + return object_id == last_object_id || std::find(m_other_object_ids.begin(), m_other_object_ids.end(), object_id) != m_other_object_ids.end(); +} + +// Orca: whether two objects, whatever their heights, are sliced at the same layers by the same profile, +// and have their layer heights drawn in the same colours. +static bool same_layer_parameters(const SlicingParameters& lhs, const SlicingParameters& rhs) +{ + return lhs.layer_height == rhs.layer_height && lhs.min_layer_height == rhs.min_layer_height && + lhs.max_layer_height == rhs.max_layer_height && lhs.first_object_layer_height == rhs.first_object_layer_height && + lhs.first_object_layer_height_fixed() == rhs.first_object_layer_height_fixed() && + lhs.object_print_z_min == rhs.object_print_z_min && lhs.object_shrinkage_compensation_z == rhs.object_shrinkage_compensation_z; +} + +GLCanvas3D::LayersEditing::ObjectTexture& GLCanvas3D::LayersEditing::other_object(int object_id) +{ + const ModelObject& model_object = *m_model->objects[object_id]; + ObjectTexture& object = m_other_textures[model_object.id().id]; + const ObjectWithTimestamp::Timestamp timestamp = model_object.layer_height_profile.timestamp(); + const double max_z = model_object.max_z(); + if (object.config_version != m_config_version || object.model_profile_timestamp != timestamp || object.max_z != max_z) { + object.config_version = m_config_version; + object.model_profile_timestamp = timestamp; + object.max_z = max_z; + const SlicingParameters slicing_parameters = this->slicing_parameters_of(model_object); + std::vector profile; + PrintObject::update_layer_height_profile(model_object, slicing_parameters, profile); + if (profile != object.profile || !same_layer_parameters(slicing_parameters, object.slicing_parameters) || + slicing_parameters.object_print_z_height() != object.slicing_parameters.object_print_z_height()) { + object.profile = std::move(profile); + object.slicing_parameters = slicing_parameters; + object.texture.valid = false; + object.shares_version = size_t(-1); + } + } + return object; +} + +const GLCanvas3D::LayersEditing::LayersTexture& GLCanvas3D::LayersEditing::bind_object_texture(ObjectTexture& object) +{ + LayersTexture& texture = object.texture; + if (!texture.valid) { + if (texture.data.empty()) { + texture.width = 1024; + texture.height = 1024; + texture.levels = 2; + texture.data.assign(texture.width * texture.height * 5, 0); + } + texture.cells = Slic3r::generate_layer_height_texture( + object.slicing_parameters, + Slic3r::generate_object_layers(object.slicing_parameters, object.profile, false), + texture.data.data(), texture.height, texture.width, true); + texture.valid = true; + texture.uploaded = false; + } + if (object.texture_id == 0) + object.texture_id = create_texture(); + if (texture.uploaded) + glsafe(::glBindTexture(GL_TEXTURE_2D, object.texture_id)); + else { + load_texture(texture, object.texture_id); + texture.uploaded = true; + // The GPU keeps the texture; the 5 MB here are only needed to make it again. + std::vector().swap(texture.data); + } + return texture; +} + +bool GLCanvas3D::LayersEditing::follows_shown_object(const SlicingParameters& slicing_parameters) const +{ + // The first entries of a shared profile are those of the object shown, and + // PrintObject::update_layer_height_profile() drops a profile whose first layer is not the object's own. + return !m_each_separately && m_slicing_parameters != nullptr && + std::abs(slicing_parameters.first_object_layer_height - m_slicing_parameters->first_object_layer_height) < EPSILON && + slicing_parameters.first_object_layer_height_fixed() == m_slicing_parameters->first_object_layer_height_fixed() && + std::abs(slicing_parameters.object_print_z_min - m_slicing_parameters->object_print_z_min) < EPSILON; +} + +bool GLCanvas3D::LayersEditing::shares_shown_layers(ObjectTexture& object) const +{ + if (!this->follows_shown_object(object.slicing_parameters)) + return false; + // While a profile is painted, the others take it when the stroke ends (accept_changes()), so they show it already. + if (state == Editing) + return true; + if (object.shares_version != m_layers_texture_version) { + object.shares_version = m_layers_texture_version; + object.shares = m_slicing_parameters != nullptr && m_layer_height_profile.size() >= 4 && object.max_z > EPSILON && + same_layer_parameters(object.slicing_parameters, *m_slicing_parameters); + if (object.shares) { + const std::vector fitted = layer_height_profile_fit_to_height(m_layer_height_profile, object.max_z); + object.shares = fitted.size() == object.profile.size() && + std::equal(fitted.begin(), fitted.end(), object.profile.begin(), [](double lhs, double rhs) { return std::abs(lhs - rhs) < EPSILON; }); + } + } + return object.shares; +} + +void GLCanvas3D::LayersEditing::release_object_texture(ObjectTexture& object) +{ + if (object.texture_id != 0) { + glsafe(::glDeleteTextures(1, &object.texture_id)); + object.texture_id = 0; + } } void GLCanvas3D::LayersEditing::adjust_layer_height_profile() @@ -784,33 +1219,88 @@ void GLCanvas3D::LayersEditing::adjust_layer_height_profile() m_layers_texture.valid = false; } +std::vector GLCanvas3D::LayersEditing::edited_object_ids() const +{ + std::vector object_ids{ last_object_id }; + for (int object_id : m_other_object_ids) + if (object_id >= 0 && object_id < int(m_model->objects.size()) && object_id != last_object_id) + object_ids.emplace_back(object_id); + return object_ids; +} + +SlicingParameters GLCanvas3D::LayersEditing::slicing_parameters_of(const ModelObject& model_object) const +{ + return PrintObject::slicing_parameters(*m_config, model_object, float(model_object.max_z()), m_shrinkage_compensation); +} + +// profiles[0] is the profile of the object shown. +void GLCanvas3D::LayersEditing::set_profiles(GLCanvas3D& canvas, const std::vector& object_ids, const std::vector>& profiles) +{ + for (size_t i = 0; i < object_ids.size(); ++i) { + m_model->objects[object_ids[i]]->layer_height_profile.set(profiles[i]); + wxGetApp().obj_list()->update_info_items(object_ids[i]); + } + m_layer_height_profile = profiles.front(); + m_layers_texture.valid = false; + canvas.post_event(SimpleEvent(EVT_GLCANVAS_SCHEDULE_BACKGROUND_PROCESS)); +} + void GLCanvas3D::LayersEditing::reset_layer_height_profile(GLCanvas3D & canvas) { - const_cast(m_model_object)->layer_height_profile.clear(); + for (int object_id : this->edited_object_ids()) { + m_model->objects[object_id]->layer_height_profile.clear(); + wxGetApp().obj_list()->update_info_items(object_id); + } m_layer_height_profile.clear(); m_layers_texture.valid = false; canvas.post_event(SimpleEvent(EVT_GLCANVAS_SCHEDULE_BACKGROUND_PROCESS)); - wxGetApp().obj_list()->update_info_items(last_object_id); } void GLCanvas3D::LayersEditing::adaptive_layer_height_profile(GLCanvas3D & canvas, float quality_factor) { this->update_slicing_parameters(); - m_layer_height_profile = layer_height_profile_adaptive(*m_slicing_parameters, *m_model_object, quality_factor); - const_cast(m_model_object)->layer_height_profile.set(m_layer_height_profile); - m_layers_texture.valid = false; - canvas.post_event(SimpleEvent(EVT_GLCANVAS_SCHEDULE_BACKGROUND_PROCESS)); - wxGetApp().obj_list()->update_info_items(last_object_id); + const std::vector object_ids = this->edited_object_ids(); + std::vector> profiles; + // The objects that share one profile: all of them by default, but an object that starts its layers + // elsewhere (a raft of its own, say) keeps its own adaptive profile, as does one too thin for a profile. + std::vector sharing; + for (size_t i = 0; i < object_ids.size(); ++i) { + const ModelObject& model_object = *m_model->objects[object_ids[i]]; + const SlicingParameters slicing_parameters = this->slicing_parameters_of(model_object); + profiles.emplace_back(layer_height_profile_adaptive(slicing_parameters, model_object, quality_factor)); + if (profiles.back().size() >= 4 && (i == 0 || this->follows_shown_object(slicing_parameters))) + sharing.emplace_back(i); + } + if (sharing.size() > 1 && sharing.front() == 0 && !m_each_separately) { + // One profile for them: the finest layer height any of them asks for at each Z. + std::vector> shared; + for (size_t i : sharing) + shared.emplace_back(profiles[i]); + const std::vector merged = layer_height_profile_merge_finest(shared); + for (size_t i : sharing) + profiles[i] = layer_height_profile_fit_to_height(merged, m_model->objects[object_ids[i]]->max_z()); + } + this->set_profiles(canvas, object_ids, profiles); } void GLCanvas3D::LayersEditing::smooth_layer_height_profile(GLCanvas3D & canvas, const HeightProfileSmoothingParams & smoothing_params) { this->update_slicing_parameters(); - m_layer_height_profile = smooth_height_profile(m_layer_height_profile, *m_slicing_parameters, smoothing_params); - const_cast(m_model_object)->layer_height_profile.set(m_layer_height_profile); - m_layers_texture.valid = false; - canvas.post_event(SimpleEvent(EVT_GLCANVAS_SCHEDULE_BACKGROUND_PROCESS)); - wxGetApp().obj_list()->update_info_items(last_object_id); + const std::vector object_ids = this->edited_object_ids(); + // The object shown is the tallest one, so its profile covers the others when they share one. + std::vector> profiles{ smooth_height_profile(m_layer_height_profile, *m_slicing_parameters, smoothing_params) }; + for (size_t i = 1; i < object_ids.size(); ++i) { + const ModelObject& model_object = *m_model->objects[object_ids[i]]; + const SlicingParameters slicing_parameters = this->slicing_parameters_of(model_object); + if (this->follows_shown_object(slicing_parameters)) + profiles.emplace_back(layer_height_profile_fit_to_height(profiles.front(), model_object.max_z())); + else { + std::vector profile; + PrintObject::update_layer_height_profile(model_object, slicing_parameters, profile); + profiles.emplace_back(smooth_height_profile(profile, slicing_parameters, smoothing_params)); + } + } + this->set_profiles(canvas, object_ids, profiles); } void GLCanvas3D::LayersEditing::generate_layer_height_texture() @@ -840,6 +1330,9 @@ void GLCanvas3D::LayersEditing::generate_layer_height_texture() Slic3r::generate_object_layers(*m_slicing_parameters, m_layer_height_profile, false), m_layers_texture.data.data(), m_layers_texture.height, m_layers_texture.width, level_of_detail_2nd_level); m_layers_texture.valid = true; + // Orca: sent to the GPU when next drawn, and the other objects check whether they still share it. + m_layers_texture.uploaded = false; + ++m_layers_texture_version; } void GLCanvas3D::LayersEditing::accept_changes(GLCanvas3D & canvas) @@ -847,6 +1340,15 @@ void GLCanvas3D::LayersEditing::accept_changes(GLCanvas3D & canvas) if (last_object_id >= 0) { wxGetApp().plater()->take_snapshot("Variable layer height - Manual edit"); const_cast(m_model_object)->layer_height_profile.set(m_layer_height_profile); + // The other selected objects share the profile that was just edited, if they can. + for (int object_id : this->edited_object_ids()) + if (object_id != last_object_id) { + ModelObject& model_object = *m_model->objects[object_id]; + if (this->follows_shown_object(this->slicing_parameters_of(model_object))) { + model_object.layer_height_profile.set(layer_height_profile_fit_to_height(m_layer_height_profile, model_object.max_z())); + wxGetApp().obj_list()->update_info_items(object_id); + } + } canvas.post_event(SimpleEvent(EVT_GLCANVAS_SCHEDULE_BACKGROUND_PROCESS)); wxGetApp().obj_list()->update_info_items(last_object_id); } @@ -2347,6 +2849,21 @@ void GLCanvas3D::smooth_layer_height_profile(const HeightProfileSmoothingParams& m_dirty = true; } +std::vector GLCanvas3D::get_layers_editing_object_idxs() const +{ + std::vector object_idxs; + if (m_model == nullptr) + return object_idxs; + for (const auto& [object_idx, instance_idxs] : m_selection.get_content()) + // Orca: an object needs some height above the bed to have layers to edit. + if (object_idx >= 0 && object_idx < int(m_model->objects.size()) && m_model->objects[object_idx]->max_z() > EPSILON) + object_idxs.emplace_back(object_idx); + std::stable_sort(object_idxs.begin(), object_idxs.end(), [this](int lhs, int rhs) { + return m_model->objects[lhs]->max_z() > m_model->objects[rhs]->max_z(); + }); + return object_idxs; +} + void GLCanvas3D::enable_layers_editing(bool enable) { m_layers_editing.set_enabled(enable); @@ -4282,8 +4799,10 @@ bool GLCanvas3D::handle_shortcut(const KeyChord& chord) }; switch (shortcut) { + // Orca: the variable layer height tool works on several objects, so selecting all the plate's stays + // available in it, though not while a profile is painted. All the plates' would mix their layers. case Shortcut::SelectAll: - if (!painting && !m_layers_editing.is_enabled()) + if (!painting && m_layers_editing.state != LayersEditing::Editing) post_event(SimpleEvent(EVT_GLCANVAS_SELECT_CURR_PLATE_ALL)); break; case Shortcut::SelectAllPlates: @@ -4997,7 +5516,9 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) #endif /* SLIC3R_DEBUG_MOUSE_EVENTS */ } const int selected_object_idx = m_selection.get_object_idx(); - const int layer_editing_object_idx = is_layers_editing_enabled() ? selected_object_idx : -1; + // Orca: with several objects selected, the tool shows the tallest one. + const int layer_editing_object_idx = is_layers_editing_enabled() ? + (selected_object_idx != -1 ? selected_object_idx : m_layers_editing.last_object_id) : -1; const bool mouse_in_layer_editing = layer_editing_object_idx != -1 && m_layers_editing.bar_rect_contains(*this, pos(0), pos(1)); if (!mouse_in_layer_editing && m_main_toolbar.on_mouse(evt, *this)) { @@ -5211,6 +5732,8 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) m_layers_editing.state = LayersEditing::Unknown; if (mouse_in_layer_editing) { // A volume is selected and the mouse is inside the layer thickness bar. + // Orca: edit the object of the bar under the mouse, though no frame was drawn since it got there. + _update_layers_editing_objects(false); // Start editing the layer height. m_layers_editing.state = LayersEditing::Editing; _perform_layer_editing_action(&evt); @@ -9769,8 +10292,8 @@ void GLCanvas3D::_render_objects(GLVolumeCollection::ERenderType type, bool with m_camera_clipping_plane = _get_volumes_clipping_plane(); if (m_picking_enabled) - // Update the layer editing selection to the first object selected, update the current object maximum Z. - m_layers_editing.select_object(*m_model, this->is_layers_editing_enabled() ? m_selection.get_object_idx() : -1); + // Update the layer editing selection to the tallest object selected, update the current object maximum Z. + _update_layers_editing_objects(true); if (const BuildVolume &build_volume = m_bed.build_volume(); build_volume.valid()) { switch (build_volume.type()) { @@ -9885,11 +10408,10 @@ void GLCanvas3D::_render_objects(GLVolumeCollection::ERenderType type, bool with if (dynamic_cast(gm.get_current()) == nullptr) { if (m_picking_enabled && m_layers_editing.is_enabled() && (m_layers_editing.last_object_id != -1) && (m_layers_editing.object_max_z() > 0.0f)) { - int object_id = m_layers_editing.last_object_id; const Camera& camera = wxGetApp().plater()->get_camera(); - m_volumes.render(type, false, camera.get_view_matrix(), camera.get_projection_matrix(), [object_id](const GLVolume& volume) { + m_volumes.render(type, false, camera.get_view_matrix(), camera.get_projection_matrix(), [this](const GLVolume& volume) { // Which volume to paint without the layer height profile shader? - return volume.is_active && (volume.is_modifier || volume.composite_id.object_id != object_id); + return volume.is_active && (volume.is_modifier || !m_layers_editing.is_edited_object(volume.composite_id.object_id)); }, true, nullptr, outlined_volumes); m_layers_editing.render_volumes(*this, m_volumes); } @@ -12285,6 +12807,17 @@ void GLCanvas3D::_update_volumes_hover_state() } } +void GLCanvas3D::_update_layers_editing_objects(bool rendering) +{ + std::vector object_idxs = this->is_layers_editing_enabled() ? this->get_layers_editing_object_idxs() : std::vector(); + if (rendering) + m_layers_editing.release_unselected_textures(*m_model, object_idxs); + const int shown = m_layers_editing.choose_shown_object(*this, *m_model, object_idxs); + m_layers_editing.select_object(*m_model, shown); + object_idxs.erase(std::remove(object_idxs.begin(), object_idxs.end(), shown), object_idxs.end()); + m_layers_editing.set_other_objects(std::move(object_idxs)); +} + void GLCanvas3D::_perform_layer_editing_action(wxMouseEvent* evt) { int object_idx_selected = m_layers_editing.last_object_id; diff --git a/src/slic3r/GUI/GLCanvas3D.hpp b/src/slic3r/GUI/GLCanvas3D.hpp index 9728363568..b178d3638f 100644 --- a/src/slic3r/GUI/GLCanvas3D.hpp +++ b/src/slic3r/GUI/GLCanvas3D.hpp @@ -17,6 +17,7 @@ #include "libslic3r/Polygon.hpp" #include "libslic3r/Technologies.hpp" #include "libslic3r/Model.hpp" +#include "libslic3r/ObjectID.hpp" #include "libvgcode/include/Types.hpp" #include "libslic3r/libslic3r.h" #include "libslic3r/Line.hpp" @@ -268,6 +269,11 @@ class GLCanvas3D const DynamicPrintConfig* m_config{ nullptr }; // ModelObject for the currently selected object (Model::objects[last_object_id]). const ModelObject* m_model_object{ nullptr }; + // Orca: the other selected objects, edited along with the one shown. Indices into m_model->objects. + const Model* m_model{ nullptr }; + std::vector m_other_object_ids; + // Orca: whether several selected objects each get a profile of their own, or share one. + bool m_each_separately{ false }; // Maximum z of the currently selected object (Model::objects[last_object_id]). float m_object_max_z{ 0.0f }; // Owned by LayersEditing. @@ -296,8 +302,58 @@ class GLCanvas3D size_t cells{ 0 }; // Does it need to be refreshed? bool valid{ false }; + // Orca: whether the GPU has the data as it is now. + bool uploaded{ false }; }; LayersTexture m_layers_texture; + // Orca: counts the times m_layers_texture was generated, so that the other objects can tell + // whether they still are on the layers it shows. + size_t m_layers_texture_version{ 0 }; + // Orca: counts the calls to set_config(), after which the other objects check their slicing + // parameters and their profiles again. + size_t m_config_version{ 0 }; + // Orca: the layer heights of the other selected objects, keyed by ModelObject ID. The texture is + // generated and sent to the GPU only when the object is drawn with it, and only again when the + // profile or the slicing parameters it shows change. + struct ObjectTexture + { + LayersTexture texture; + unsigned int texture_id{ 0 }; + // What the profile was read from: the object's own profile, its height and the configuration. + ObjectWithTimestamp::Timestamp model_profile_timestamp{ 0 }; + double max_z{ 0. }; + size_t config_version{ size_t(-1) }; + SlicingParameters slicing_parameters; + // The profile the object is sliced with: its own, or the one of its height ranges. + std::vector profile; + // Whether it is on the layers of m_layers_texture, as of shares_version. + bool shares{ false }; + size_t shares_version{ size_t(-1) }; + }; + std::map m_other_textures; + // Orca: the bars and the lines over them are rebuilt only when what they show changes. + struct BarModels + { + GLModel background; + std::vector background_layout; + GLModel profile; + std::vector profile_layout; + std::vector profile_source; + }; + std::vector m_bar_models; + GLModel m_bar_lines; + GLModel m_bar_frame; + std::vector m_bar_lines_layout; + // Orca: the objects that have a bar of their own, the rightmost bar first. With one profile + // shared between the selected objects that is the tallest object alone; with a profile each, + // the tallest ones, up to MAX_BARS. The object shown (last_object_id) is one of them. + static constexpr size_t MAX_BARS = 3; + std::vector m_bar_object_ids; + // Height of each bar as a fraction of the canvas height: the bars share one scale, set by the + // tallest object, so a lower object has a lower bar. + std::vector m_bar_fractions; + // Whether the notice that some selected objects have no bar is up. + bool m_bars_notice_shown{ false }; public: EState state{ Unknown }; @@ -306,15 +362,6 @@ class GLCanvas3D int last_object_id{ -1 }; float last_z{ 0.0f }; LayerHeightEditActionType last_action{ LAYER_HEIGHT_EDIT_ACTION_INCREASE }; - struct Profile - { - GLModel baseline; - GLModel profile; - GLModel background; - float old_canvas_width{ 0.0f }; - std::vector old_layer_height_profile; - }; - Profile m_profile; LayersEditing() = default; ~LayersEditing(); @@ -323,6 +370,14 @@ class GLCanvas3D void set_config(const DynamicPrintConfig* config); void select_object(const Model& model, int object_id); + void set_other_objects(std::vector object_ids) { m_other_object_ids = std::move(object_ids); } + // Orca: lays out the bars for the selected objects (tallest first) and returns the object to + // show and edit: the one whose bar the mouse is on, or else the one shown so far. + int choose_shown_object(const GLCanvas3D& canvas, const Model& model, const std::vector& object_ids); + // Orca: frees the textures of the objects that are no longer selected. Needs the GL context. + void release_unselected_textures(const Model& model, const std::vector& object_ids); + // Orca: whether the tool paints this object with its layer heights. + bool is_edited_object(int object_id) const; bool is_allowed() const; @@ -343,6 +398,8 @@ class GLCanvas3D static bool bar_rect_contains(const GLCanvas3D& canvas, float x, float y); static Rect get_bar_rect_screen(const GLCanvas3D& canvas); static float get_overlay_window_width() { return LayersEditing::s_overlay_window_width; } + // Orca: the width taken by the bars beyond the first one, which notifications have to clear too. + float extra_bars_width() const { return m_enabled && m_bar_object_ids.size() > 1 ? float(m_bar_object_ids.size() - 1) * THICKNESS_BAR_WIDTH : 0.0f; } float object_max_z() const { return m_object_max_z; } @@ -351,9 +408,36 @@ class GLCanvas3D private: bool is_initialized() const; void generate_layer_height_texture(); + // Orca: the layer heights of another selected object, read again when they may have changed. + ObjectTexture& other_object(int object_id); + // Orca: its texture, generated and sent to the GPU if needed, and bound. + const LayersTexture& bind_object_texture(ObjectTexture& object); + // Orca: the texture of the object shown, sent to the GPU if needed, and bound. + void bind_shown_texture(); + // Orca: whether the object is drawn with the texture of the object shown. + bool shares_shown_layers(ObjectTexture& object) const; + // Orca: whether an object with these slicing parameters takes the profile of the object shown when + // they share one. It has to start its layers where that profile does. + bool follows_shown_object(const SlicingParameters& slicing_parameters) const; + static unsigned int create_texture(); + static void load_texture(const LayersTexture& texture, unsigned int texture_id); + void release_object_texture(ObjectTexture& object); + void reset_bar_models(size_t bars); + // Index into m_bar_object_ids of the bar of the object shown. + size_t active_bar() const; + bool bar_in_focus(const GLCanvas3D& canvas) const; + float bar_fraction(size_t bar) const { return bar < m_bar_fractions.size() ? m_bar_fractions[bar] : 1.0f; } + // Index of the bar under the given point, or -1. + static int bar_at(const GLCanvas3D& canvas, float x, float y); + // Draws the object with the texture that is bound. + void render_object_volumes(const GLVolumeCollection& volumes, GLShaderProgram& shader, int object_id, const LayersTexture& texture, double object_max_z, float z_cursor, float dimming); void render_active_object_annotations(const GLCanvas3D& canvas); void render_profile(const GLCanvas3D& canvas); void update_slicing_parameters(); + // Orca: the object shown, followed by the other selected ones. + std::vector edited_object_ids() const; + SlicingParameters slicing_parameters_of(const ModelObject& model_object) const; + void set_profiles(GLCanvas3D& canvas, const std::vector& object_ids, const std::vector>& profiles); static float thickness_bar_width(const GLCanvas3D& canvas); }; @@ -1096,6 +1180,8 @@ public: bool is_layers_editing_enabled() const { return m_layers_editing.is_enabled(); } bool is_layers_editing_allowed() const { return m_layers_editing.is_allowed(); } + // Orca: the selected objects the variable layer height tool edits, tallest first. The tallest is the one it shows. + std::vector get_layers_editing_object_idxs() const; void reset_layer_height_profile(); void adaptive_layer_height_profile(float quality_factor); @@ -1484,6 +1570,9 @@ public: void apply_retina_scale(Vec2d &screen_coordinate) const; void _perform_layer_editing_action(wxMouseEvent* evt = nullptr); + // Orca: hands the variable layer height tool the selected objects and the one to show. While + // rendering, it also frees the textures of the objects no longer selected. + void _update_layers_editing_objects(bool rendering); // Convert the screen space coordinate to an object space coordinate. // If the Z screen space coordinate is not provided, a depth buffer value is substituted. @@ -1690,7 +1779,7 @@ private: bool _deactivate_layersediting_menu(); // BBS FIXME - float get_overlay_window_width() { return 0; /*LayersEditing::get_overlay_window_width();*/ } + float get_overlay_window_width() { return m_layers_editing.extra_bars_width(); /*LayersEditing::get_overlay_window_width();*/ } }; const ModelVolume *get_model_volume(const GLVolume &v, const Model &model); diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 30fdb056c4..595736406c 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -15466,8 +15466,8 @@ bool Plater::priv::layers_height_allowed() const if (printer_technology != ptFFF) return false; - int obj_idx = get_selected_object_idx(); - return 0 <= obj_idx && obj_idx < (int)model.objects.size() && model.objects[obj_idx]->max_z() > SINKING_Z_THRESHOLD && view3D->is_layers_editing_allowed(); + // Orca: one object or several. + return !view3D->get_canvas3d()->get_layers_editing_object_idxs().empty() && view3D->is_layers_editing_allowed(); } bool Plater::priv::can_layers_editing() const diff --git a/tests/fff_print/test_wipe_tower.cpp b/tests/fff_print/test_wipe_tower.cpp index 03f44e851f..5ae4bcac86 100644 --- a/tests/fff_print/test_wipe_tower.cpp +++ b/tests/fff_print/test_wipe_tower.cpp @@ -9,6 +9,7 @@ #include #include #include "libslic3r/Model.hpp" +#include "libslic3r/Layer.hpp" #include "libslic3r/Print.hpp" #include #include @@ -32,6 +33,7 @@ #include "libslic3r/LocalesUtils.hpp" #include "libslic3r/ModelArrange.hpp" #include "libslic3r/PrintConfig.hpp" +#include "libslic3r/Slicing.hpp" #include "libslic3r/Utils.hpp" #include "test_helpers.hpp" @@ -449,6 +451,226 @@ TEST_CASE("The tower is sized for the thinnest layer any object on the plate is CHECK_THAT(print.wipe_tower_data(2).depth, Catch::Matchers::WithinAbs(20., 1e-4)); } +// A 20 mm and a 10 mm tall box sharing one variable layer height profile: 0.2 mm layers up to +// 5 mm, thinning to 0.1 mm at 10 mm and staying there. `fit` says whether the lower box gets the +// profile cut to its own height, or the tall box's profile as it is. Each box prints with its own +// filament, which is what makes the tower real. +static std::string validate_two_heights_with_variable_layers(bool fit, bool precise_z_height = false, + std::vector *warnings = nullptr) +{ + const DynamicPrintConfig config = multifilament_config(2, { + { "enable_prime_tower", "1" }, + { "wipe_tower_x", "50" }, // inside the 200x200 test bed + { "wipe_tower_y", "50" }, // (the default y, 220, is not) + { "layer_change_gcode", "G92 E0\n" }, // validate() wants the relative-E reset + { "layer_height", "0.2" }, + { "initial_layer_print_height", "0.2" }, + { "precise_z_height", precise_z_height ? "1" : "0" }, + { "raft_layers", "0" } }); + const std::vector> overrides{ { { "extruder", "1" } }, { { "extruder", "2" } } }; + const std::vector profile = { 0., 0.2, 5., 0.2, 10., 0.1, 20., 0.1 }; + + Print print; + Model model; + init_print(std::vector{ make_cube(20, 20, 20), make_cube(20, 20, 10) }, print, model, config, &overrides); + model.objects[0]->layer_height_profile.set(profile); + model.objects[1]->layer_height_profile.set(fit ? layer_height_profile_fit_to_height(profile, 10.) : profile); + print.apply(model, config); + REQUIRE(print.has_wipe_tower()); + // Precise Z height would fit the last layers of each box to its own height, so it is left out when it is on. + REQUIRE(print.precise_z_height_overridden() == precise_z_height); + // Leaving it out slices the boxes again, which must not leave them without slicing parameters. + for (const PrintObject *object : print.objects()) + REQUIRE(object->slicing_parameters().valid); + return print.validate(warnings).string; +} + +TEST_CASE("Objects of different heights keep the prime tower when they share a variable layer height profile", "[WipeTower]") +{ + CHECK_THAT(validate_two_heights_with_variable_layers(true), !Catch::Matchers::ContainsSubstring("layer height")); +} + +TEST_CASE("Precise Z height is left out when objects of different heights share their layers under the prime tower", "[WipeTower]") +{ + CHECK_THAT(validate_two_heights_with_variable_layers(true, true), !Catch::Matchers::ContainsSubstring("layer height")); +} + +TEST_CASE("Leaving precise Z height out is reported only when it is on", "[WipeTower]") +{ + const auto reported = [](bool precise_z_height) { + std::vector warnings; + validate_two_heights_with_variable_layers(true, precise_z_height, &warnings); + return std::any_of(warnings.begin(), warnings.end(), [](const StringObjectException &warning) { + return warning.string.find("Precise Z height is not applied") != std::string::npos; + }); + }; + CHECK(reported(true)); + CHECK_FALSE(reported(false)); +} + +TEST_CASE("Precise Z height applies again once the prime tower is turned off", "[WipeTower]") +{ + DynamicPrintConfig config = multifilament_config(2, { + { "enable_prime_tower", "1" }, + { "wipe_tower_x", "50" }, + { "wipe_tower_y", "50" }, + { "layer_change_gcode", "G92 E0\n" }, + { "layer_height", "0.2" }, + { "initial_layer_print_height", "0.2" }, + { "precise_z_height", "1" }, + { "raft_layers", "0" } }); + const std::vector> overrides{ { { "extruder", "1" } }, { { "extruder", "2" } } }; + const std::vector profile = { 0., 0.2, 5., 0.2, 10., 0.1, 20., 0.1 }; + + Print print; + Model model; + init_print(std::vector{ make_cube(20, 20, 20), make_cube(20, 20, 10.05) }, print, model, config, &overrides); + model.objects[0]->layer_height_profile.set(profile); + model.objects[1]->layer_height_profile.set(layer_height_profile_fit_to_height(profile, 10.05)); + print.apply(model, config); + REQUIRE(print.precise_z_height_overridden()); + REQUIRE(print.objects().size() == 2); + CHECK_FALSE(print.get_object(1)->precise_z_height()); + + config.set_deserialize_strict({ { "enable_prime_tower", "0" } }); + print.apply(model, config); + REQUIRE_FALSE(print.has_wipe_tower()); + CHECK_FALSE(print.precise_z_height_overridden()); + REQUIRE(print.objects().size() == 2); + PrintObject &lower = *print.get_object(1); + CHECK(lower.precise_z_height()); + REQUIRE(lower.slicing_parameters().valid); + lower.slice(); + REQUIRE(lower.layer_count() > 50); + CHECK_THAT(lower.get_layer(int(lower.layer_count()) - 1)->print_z, Catch::Matchers::WithinAbs(10.05, 1e-4)); +} + +TEST_CASE("A variable layer height profile that does not end at the object's top is rejected with the prime tower", "[WipeTower]") +{ + // The profile is dropped for the lower box, which is then sliced at a constant 0.2 mm. + CHECK_THAT(validate_two_heights_with_variable_layers(false), Catch::Matchers::ContainsSubstring("same variable layer height")); +} + +// Two boxes of different heights, both with a height range modifier over the same 2 to 5 mm. +// `range_layer_height` is the layer height the modifier asks for on the lower box; the tall one keeps +// the 0.2 mm of the print, so 0.2 leaves every layer where it was. +static std::string validate_two_heights_with_height_ranges(double range_layer_height) +{ + const DynamicPrintConfig config = multifilament_config(2, { + { "enable_prime_tower", "1" }, + { "wipe_tower_x", "50" }, + { "wipe_tower_y", "50" }, + { "layer_change_gcode", "G92 E0\n" }, + { "layer_height", "0.2" }, + { "initial_layer_print_height", "0.2" }, + { "raft_layers", "0" } }); + const std::vector> overrides{ { { "extruder", "1" } }, { { "extruder", "2" } } }; + + Print print; + Model model; + init_print(std::vector{ make_cube(20, 20, 20), make_cube(20, 20, 10) }, print, model, config, &overrides); + for (size_t idx = 0; idx < 2; ++idx) { + DynamicPrintConfig range_config; + // Every layer range carries a layer height, also one that only changes another setting. + range_config.set_key_value("layer_height", new ConfigOptionFloat(idx == 1 ? range_layer_height : 0.2)); + range_config.set_key_value("wall_loops", new ConfigOptionInt(3)); + model.objects[idx]->layer_config_ranges[{ 2., 5. }].assign_config(std::move(range_config)); + } + print.apply(model, config); + REQUIRE(print.has_wipe_tower()); + return print.validate().string; +} + +TEST_CASE("Height range modifiers that leave the layers alone keep the prime tower on objects of different heights", "[WipeTower]") +{ + CHECK_THAT(validate_two_heights_with_height_ranges(0.2), !Catch::Matchers::ContainsSubstring("layer height")); +} + +TEST_CASE("Height range modifiers that put the objects on different layers are rejected with the prime tower", "[WipeTower]") +{ + CHECK_THAT(validate_two_heights_with_height_ranges(0.1), Catch::Matchers::ContainsSubstring("same variable layer height")); +} + +TEST_CASE("Objects of different heights sharing a profile are sliced on the same layers under the prime tower", "[WipeTower]") +{ + // What the prime tower needs is that the objects are sliced at the same Z, which this checks on the + // sliced layers rather than on validate() alone. The lower box is 10.05 mm tall, between two layers + // of the shared profile: with precise Z height on, its last layers would be fitted to end at + // 10.05 mm and leave the tall box's, if only by a micrometre or so. The print leaves precise Z height + // out, so they must not. + const DynamicPrintConfig config = multifilament_config(2, { + { "enable_prime_tower", "1" }, + { "wipe_tower_x", "50" }, + { "wipe_tower_y", "50" }, + { "layer_change_gcode", "G92 E0\n" }, + { "layer_height", "0.2" }, + { "initial_layer_print_height", "0.2" }, + { "precise_z_height", "1" }, + { "raft_layers", "0" } }); + const std::vector> overrides{ { { "extruder", "1" } }, { { "extruder", "2" } } }; + const std::vector profile = { 0., 0.2, 5., 0.2, 10., 0.1, 20., 0.1 }; + + Print print; + Model model; + init_print(std::vector{ make_cube(20, 20, 20), make_cube(20, 20, 10.05) }, print, model, config, &overrides); + model.objects[0]->layer_height_profile.set(profile); + model.objects[1]->layer_height_profile.set(layer_height_profile_fit_to_height(profile, 10.05)); + print.apply(model, config); + REQUIRE(print.has_wipe_tower()); + REQUIRE(print.precise_z_height_overridden()); + REQUIRE(print.validate().string.empty()); + REQUIRE(print.objects().size() == 2); + + // Slicing the objects is where precise Z height would act, so their layers are compared right + // after it, before the tower is generated from them. + PrintObject &tall = *print.get_object(0); + PrintObject &lower = *print.get_object(1); + tall.slice(); + lower.slice(); + REQUIRE(lower.layer_count() > 50); + REQUIRE(lower.layer_count() < tall.layer_count()); + for (size_t idx = 0; idx < lower.layer_count(); ++idx) { + INFO("layer " << idx); + CHECK_THAT(lower.get_layer(int(idx))->print_z, Catch::Matchers::WithinAbs(tall.get_layer(int(idx))->print_z, 1e-6)); + } + + // And the tower is generated from those layers. + print.process(); + CHECK(print.is_step_done(psWipeTower)); +} + +TEST_CASE("Precise Z height still fits objects of different heights when there is no prime tower", "[WipeTower]") +{ + // The same plate as above without the tower: nothing asks the objects to share their layers, so + // precise Z height stays on and fits the last layers of the 10.05 mm box to end at its top, where + // the shared profile alone would stop at about 10.0515 mm. + const DynamicPrintConfig config = multifilament_config(2, { + { "enable_prime_tower", "0" }, + { "layer_change_gcode", "G92 E0\n" }, + { "layer_height", "0.2" }, + { "initial_layer_print_height", "0.2" }, + { "precise_z_height", "1" }, + { "raft_layers", "0" } }); + const std::vector> overrides{ { { "extruder", "1" } }, { { "extruder", "2" } } }; + const std::vector profile = { 0., 0.2, 5., 0.2, 10., 0.1, 20., 0.1 }; + + Print print; + Model model; + init_print(std::vector{ make_cube(20, 20, 20), make_cube(20, 20, 10.05) }, print, model, config, &overrides); + model.objects[0]->layer_height_profile.set(profile); + model.objects[1]->layer_height_profile.set(layer_height_profile_fit_to_height(profile, 10.05)); + print.apply(model, config); + REQUIRE_FALSE(print.has_wipe_tower()); + REQUIRE_FALSE(print.precise_z_height_overridden()); + REQUIRE(print.objects().size() == 2); + + PrintObject &lower = *print.get_object(1); + CHECK(lower.precise_z_height()); + lower.slice(); + REQUIRE(lower.layer_count() > 50); + CHECK_THAT(lower.get_layer(int(lower.layer_count()) - 1)->print_z, Catch::Matchers::WithinAbs(10.05, 1e-4)); +} + TEST_CASE("Validation is given the tower's effective width, not the configured one", "[WipeTower]") { // A rib wall squares the tower, so its width is its depth. Validation reads this rather diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index 6c878026e8..809f74f212 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -83,6 +83,7 @@ add_executable(${_TEST_NAME}_tests test_wipe_tower_estimate.cpp test_wipe_tower.cpp test_wipe_path.cpp + test_slicing.cpp test_optimizers.cpp test_ordering_strategies.cpp test_parameter_utils.cpp diff --git a/tests/libslic3r/test_slicing.cpp b/tests/libslic3r/test_slicing.cpp new file mode 100644 index 0000000000..afa7a3988b --- /dev/null +++ b/tests/libslic3r/test_slicing.cpp @@ -0,0 +1,129 @@ +#include +#include +#include +#include + +#include +#include + +#include "libslic3r/Slicing.hpp" +#include "libslic3r/libslic3r.h" + +using namespace Slic3r; + +// Profiles are flat lists of (z, layer height) pairs. +static void check_profile(const std::vector &profile, const std::vector &expected) +{ + REQUIRE(profile.size() == expected.size()); + for (size_t i = 0; i < expected.size(); ++i) { + INFO("entry " << i); + CHECK_THAT(profile[i], Catch::Matchers::WithinAbs(expected[i], 1e-9)); + } +} + +TEST_CASE("A layer height profile fitted to a lower object is cut at its top", "[Slicing]") +{ + // 0.2 mm up to 5 mm, thinning to 0.1 mm at 10 mm: halfway through the ramp, 7.5 mm, is 0.15 mm. + const std::vector profile = { 0., 0.2, 5., 0.2, 10., 0.1, 20., 0.1 }; + check_profile(layer_height_profile_fit_to_height(profile, 7.5), { 0., 0.2, 5., 0.2, 7.5, 0.15 }); +} + +TEST_CASE("A layer height profile fitted just above one of its entries does not run past it", "[Slicing]") +{ + // The entry at 9.99999 mm lies within EPSILON under the top, so the cut falls between it and the one + // below and must take its layer height, not run on past it to below 0.1 mm. + const std::vector profile = { 0., 0.2, 9.9, 0.2, 9.99999, 0.1, 20., 0.1 }; + const std::vector fitted = layer_height_profile_fit_to_height(profile, 10.); + REQUIRE(fitted.size() == 6); + CHECK_THAT(fitted[4], Catch::Matchers::WithinAbs(10., 1e-12)); + CHECK(fitted[5] >= 0.1); + CHECK(fitted[5] <= 0.2); +} + +TEST_CASE("A layer height profile fitted to a taller object carries its last layer height up", "[Slicing]") +{ + const std::vector profile = { 0., 0.2, 5., 0.2, 10., 0.1 }; + check_profile(layer_height_profile_fit_to_height(profile, 30.), { 0., 0.2, 5., 0.2, 10., 0.1, 30., 0.1 }); +} + +TEST_CASE("A layer height profile fitted to its own height is unchanged", "[Slicing]") +{ + const std::vector profile = { 0., 0.2, 5., 0.2, 10., 0.1 }; + check_profile(layer_height_profile_fit_to_height(profile, 10.), profile); +} + +TEST_CASE("Merged layer height profiles take the finest layer height up to the top of each object", "[Slicing]") +{ + // A 20 mm object at a constant 0.2 mm, and a 10 mm one thinning to 0.1 mm at 5 mm. The 0.3 mm + // entry closing the lower profile is not a layer height the object asks for. + const std::vector tall = { 0., 0.2, 10., 0.2, 20., 0.2 }; + const std::vector lower = { 0., 0.2, 5., 0.1, 10., 0.3 }; + const std::vector merged = layer_height_profile_merge_finest({ tall, lower }); + + REQUIRE(merged.size() >= 4); + REQUIRE(merged.size() % 2 == 0); + CHECK_THAT(merged[0], Catch::Matchers::WithinAbs(0., 1e-9)); + CHECK_THAT(merged[1], Catch::Matchers::WithinAbs(0.2, 1e-9)); + CHECK_THAT(merged[merged.size() - 2], Catch::Matchers::WithinAbs(20., 1e-9)); + for (size_t i = 2; i + 2 < merged.size(); i += 2) { + INFO("entry at z = " << merged[i]); + // One entry per layer: each starts where the layer before it ended. + if (i + 4 < merged.size()) + CHECK_THAT(merged[i + 2], Catch::Matchers::WithinAbs(merged[i] + merged[i + 1], 1e-9)); + if (merged[i] < 5.) + // Thinning with the lower object: 0.2 mm at the bed, 0.1 mm at 5 mm. + CHECK_THAT(merged[i + 1], Catch::Matchers::WithinAbs(0.2 - 0.02 * merged[i], 1e-9)); + else if (merged[i] < 10.) + CHECK_THAT(merged[i + 1], Catch::Matchers::WithinAbs(0.1, 1e-9)); + else { + // Above the lower object the layers grow back to the 0.2 mm of the tall one, by no + // more than the 0.04 mm the adaptive profile allows from one layer to the next. + CHECK(merged[i + 1] <= 0.2 + 1e-9); + CHECK(merged[i + 1] - merged[i - 1] <= 0.04 + 1e-9); + } + if (merged[i] > 11.) + CHECK_THAT(merged[i + 1], Catch::Matchers::WithinAbs(0.2, 1e-9)); + } +} + +TEST_CASE("The layer height texture is filled up to the top of an object whose last layer ends under it", "[Slicing]") +{ + // A 10 mm object with 0.15 mm layers: the last one ends at 9.9 mm, as generate_object_layers() leaves it + // when one more layer would end too far above the top. The top face is drawn with the cells above 9.9 mm. + SlicingParameters params; + params.object_print_z_min = 0.; + params.object_print_z_max = 10.; + params.layer_height = 0.2; + params.min_layer_height = 0.07; + params.max_layer_height = 0.28; + std::vector layers; + for (int i = 0; i < 66; ++i) { + layers.push_back(0.15 * i); + layers.push_back(0.15 * (i + 1)); + } + REQUIRE_THAT(layers.back(), Catch::Matchers::WithinAbs(9.9, 1e-9)); + + // The buffer starts out black and transparent, as the texture of an object is made the first time. + const int rows = 256; + const int cols = 256; + std::vector data(size_t(rows) * size_t(cols) * 5, 0); + const int ncells = generate_layer_height_texture(params, layers, data.data(), rows, cols, true); + REQUIRE(ncells > 0); + // Each cell, up to the last, is written: opaque. + for (int cell = 0; cell < ncells; ++cell) { + const int row = cell / (cols - 1); + const int col = cell - row * (cols - 1); + INFO("cell " << cell << " of " << ncells); + CHECK(int(data[(size_t(row) * cols + col) * 4 + 3]) == 255); + } + // And so in the second level of detail, half as many cells in a texture half as wide. + const unsigned char *data1 = data.data() + size_t(rows) * cols * 4; + const int cols1 = cols / 2; + const int ncells1 = ncells / 2; + for (int cell = 0; cell < ncells1; ++cell) { + const int row = cell / (cols1 - 1); + const int col = cell - row * (cols1 - 1); + INFO("second level cell " << cell << " of " << ncells1); + CHECK(int(data1[(size_t(row) * cols1 + col) * 4 + 3]) == 255); + } +} From 34de2b49dfe8bc3fc1eefebdde9c6a82865a0242 Mon Sep 17 00:00:00 2001 From: Ian Bassi Date: Wed, 11 Nov 2026 19:18:28 -0300 Subject: [PATCH 07/26] Copy per-nozzle settings to every tool of a toolchanger, and choose which unsaved changes to keep (#17461) Co-authored-by: raistlin7447 --- docs/HLSD/per-nozzle-settings.md | 122 ++++ src/libslic3r/ParameterUtils.cpp | 52 ++ src/libslic3r/ParameterUtils.hpp | 4 + src/libslic3r/PrintConfig.cpp | 2 + src/slic3r/GUI/SettingsIndex.cpp | 6 + src/slic3r/GUI/SettingsIndex.hpp | 2 +- src/slic3r/GUI/Tab.cpp | 327 +++++---- src/slic3r/GUI/Tab.hpp | 4 +- src/slic3r/GUI/UnsavedChangesDialog.cpp | 829 +++++++++++++++-------- src/slic3r/GUI/UnsavedChangesDialog.hpp | 78 ++- tests/libslic3r/test_parameter_utils.cpp | 44 ++ 11 files changed, 1042 insertions(+), 428 deletions(-) create mode 100644 docs/HLSD/per-nozzle-settings.md diff --git a/docs/HLSD/per-nozzle-settings.md b/docs/HLSD/per-nozzle-settings.md new file mode 100644 index 0000000000..ad9f208560 --- /dev/null +++ b/docs/HLSD/per-nozzle-settings.md @@ -0,0 +1,122 @@ +# Per-nozzle settings — High Level Design + +## Purpose and scope + +On printers with several extruders, or with extruders that take different +nozzles, some settings must differ per nozzle: speeds and accelerations depend +on the nozzle's flow, retraction on the drive, and a filament's flow ratio or +temperature on both. These settings are stored once per *nozzle variant* instead +of once per preset. This document covers how the variants are stored, how a +value is found for an extruder, how the settings tabs edit them, and how the copy +button moves values between extruders or variants. + +## Variants and columns + +A variant is the pair of an extruder type and a nozzle volume type, written as +one string such as "Direct Drive Standard" or "Direct Drive High Flow". The +printer's `extruder_variant_list` holds, per extruder, the comma-separated +variants that extruder can take. Which one is in use comes from the project's +`nozzle_volume_type`, one entry per extruder, set in the sidebar. A Hybrid +extruder carries both Standard and High Flow nozzles, and each filament's own +volume type picks between them. + +Each per-variant setting is a vector with one value per *column*. Two parallel +vectors describe the columns of a preset: + +| Scope | Settings | Column keys | Values per column | +|----------|---------------------------------------------------|---------------------------------------------------|-------------------| +| Process | `print_options_with_variant` | `print_extruder_id`, `print_extruder_variant` | 1 | +| Printer | `printer_options_with_variant_1` | `printer_extruder_id`, `printer_extruder_variant` | 1 | +| Printer | `printer_options_with_variant_2` (machine limits) | `printer_extruder_id`, `printer_extruder_variant` | 2: normal, silent | +| Filament | `filament_options_with_variant` | `filament_extruder_variant` | 1 | + +A process or printer column belongs to one extruder (the id, 1-based) and one +variant. A filament column belongs only to a variant, and every extruder of that +variant shares it. Printer settings outside these sets that are still vectors, +such as `nozzle_diameter`, `extruder_type` or `extruder_offset`, have one value +per extruder instead. + +`DynamicPrintConfig::get_index_for_extruder` finds the column of an extruder: +the first whose id matches and whose variant string equals the extruder's type +and nozzle volume type, Hybrid counting as Standard. Given a stride, it returns +the position of the column's first value, and -1 when there is no such column. + +## Loading, sizing and slicing + +Profiles may store fewer values than columns, often a single value meant for +every column. `extend_default_config_length` pads every per-variant setting to +its column count with its first value whenever a preset is loaded: system, user, +cloud and project presets alike. User presets start from their parent's padded +vectors and apply their own values per variant. After loading, every column has +a value of its own, so editing one column never changes another. + +The printer's columns follow its extruder count. `set_num_extruders` rebuilds +`printer_extruder_id` and `printer_extruder_variant` from `extruder_variant_list` +and resizes the per-variant and per-extruder printer settings, padding new +entries with the first value. + +A process ships with columns for the tools of its profile. Raising the printer's +extruder count does not give it columns for the new tools, so +`add_process_columns_for_new_tools` adds one per variant of each such tool, +copied from tool 1's column of the same variant (the first column when tool 1 +has no such variant). The settings tabs run it in memory on every copy the +edited process is compared with: the selected preset, its parent, the edited +preset and, when it was clean, the saved baseline. The added columns therefore +never show as changes. A process with a single column is left alone: its one +value applies to every tool, and splitting it would make an edit reach the first +tool only. + +For slicing, `update_values_to_printer_extruders` reduces each per-variant +setting to one value per slot, a slot being an extruder and a nozzle volume type +it prints with. A slot without a column of its own reads the first column. A +process that still has one column is given a column per extruder variant first +(`ensure_process_variant_columns`), all holding that value. + +## Editing in the settings tabs + +The process and printer tabs have an extruder switch, the filament tab a variant +switch. Its tags name the selection as the user sees it: "T2 HF" on the process +tab, "Extruder 2: HF" on the printer tab, "Direct Drive HF" on the filament tab, +and the left and right nozzle names on Bambu dual-nozzle printers. +`switch_excluder` points every per-variant field of the pages at the selected +column. On the printer's Extruder page, the fields of per-extruder settings point +at the selected extruder instead. Groups holding such fields draw the per-nozzle +icon next to them. + +## Copying between extruders and variants + +The copy button next to the switch copies the values modified on the current +page, for the selected extruder or variant, to the others. What a value may be +copied to depends on the page: + +- On the process tab and the printer's Motion ability page, to every extruder + with the same extruder type whose nozzle has the selected nozzle volume type, + or is Hybrid. Values go into that extruder's column of the same variant. +- On the printer's Extruder page, per-extruder settings go to every other + extruder. Per-variant settings follow the rule above, so an extruder with + another nozzle volume type gets only the per-extruder ones. +- On the filament tab, to the filament's other variants. + +Values are never copied across nozzle volume types on the process and printer +tabs: Standard and High Flow values are tuned separately, and a copy would +overwrite one with the other. + +The copy is confirmed in the unsaved changes dialog in a copy mode. It shows one +column per extruder or variant, titled with the switch tags, and one row per +setting. Each setting carries its own position in every column, because one page +can mix per-variant and per-extruder settings. A cell whose value would change +has a checkbox, ticked by default. A cell without a value of that setting stays +empty. Tick-all boxes cover each row, group, category and column, and one covers +everything. Only the ticked values are written. + +## Implementation and verification + +The column handling lives in `PrintConfig.cpp` (`get_index_for_extruder`, +`update_values_to_printer_extruders`, `set_num_extruders`) and `Preset.cpp` +(`extend_default_config_length`). `add_process_columns_for_new_tools` is in +`ParameterUtils.cpp`. The switches, the copy button and the in-memory +completion are in `Tab.cpp`, the dialog in `UnsavedChangesDialog.cpp`. + +`tests/libslic3r/test_parameter_utils.cpp` covers the columns added for new +tools, and `tests/libslic3r/test_config_variant_expansion.cpp` the slicing +expansion. diff --git a/src/libslic3r/ParameterUtils.cpp b/src/libslic3r/ParameterUtils.cpp index 2edaa6b00e..612fbc395a 100644 --- a/src/libslic3r/ParameterUtils.cpp +++ b/src/libslic3r/ParameterUtils.cpp @@ -1,6 +1,12 @@ #include "ParameterUtils.hpp" +#include "Config.hpp" #include "PrintConfig.hpp" +#include +#include +#include +#include #include +#include #include #include #include @@ -88,4 +94,50 @@ int get_index_for_extruder_parameter(const DynamicPrintConfig &config, const std return variant_index; } +bool add_process_columns_for_new_tools(DynamicPrintConfig &process_config, const DynamicPrintConfig &printer_config) +{ + auto *ids = process_config.option("print_extruder_id"); + auto *variants = process_config.option("print_extruder_variant"); + const auto *tools = printer_config.option("extruder_variant_list"); + // A single column is shared by every tool; splitting it would make an edit reach the first tool only. + if (ids == nullptr || variants == nullptr || tools == nullptr || ids->size() < 2 || ids->size() != variants->size()) + return false; + + const size_t columns = ids->size(); + std::vector sources; // the column each added one copies + for (int tool = 1; tool <= int(tools->size()); ++tool) { + if (std::find(ids->values.begin(), ids->values.end(), tool) != ids->values.end()) + continue; + std::vector tool_variants; + boost::split(tool_variants, tools->get_at(tool - 1), boost::is_any_of(","), boost::token_compress_on); + for (std::string &variant : tool_variants) { + boost::trim(variant); + if (variant.empty()) + continue; + // Without a tool 1 column of this variant, the first column, which slicing falls back to. + size_t source = 0; + for (size_t i = 0; i < columns; ++i) + if (ids->values[i] == 1 && variants->values[i] == variant) { + source = i; + break; + } + ids->values.push_back(tool); + variants->values.push_back(variant); + sources.push_back(source); + } + } + if (sources.empty()) + return false; + + for (const std::string &key : print_options_with_variant) { + auto *opt = dynamic_cast(process_config.option(key)); + // An option with fewer values than columns gives the missing ones its first value already. + if (opt == nullptr || opt == ids || opt == variants || opt->size() != columns) + continue; + for (size_t source : sources) + opt->set_at(opt, opt->size(), source); + } + return true; +} + }; // namespace Slic3r diff --git a/src/libslic3r/ParameterUtils.hpp b/src/libslic3r/ParameterUtils.hpp index bf475c16bd..649492879c 100644 --- a/src/libslic3r/ParameterUtils.hpp +++ b/src/libslic3r/ParameterUtils.hpp @@ -13,6 +13,10 @@ std::vector get_other_layers_print_sequence(int sequence_num void get_other_layers_print_sequence(const std::vector &customize_sequences, int &sequence_nums, std::vector &sequence); extern int get_index_for_extruder_parameter(const DynamicPrintConfig &config, const std::string &opt_key, int cur_extruder_id, ExtruderType extruder_type, NozzleVolumeType nozzle_volume_type); + +// Gives a per-tool process a column per variant for each printer tool it has none for, copied from tool 1's column of +// that variant. Returns whether it added any. See docs/HLSD/per-nozzle-settings.md. +bool add_process_columns_for_new_tools(DynamicPrintConfig &process_config, const DynamicPrintConfig &printer_config); } // namespace Slic3r #endif // slic3r_Parameter_Utils_hpp_ diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 60d2fdc03a..dea9b68c6b 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -10109,6 +10109,8 @@ std::set print_options_with_variant = { "inner_wall_speed", "small_perimeter_speed", //coFloatsOrPercents "small_perimeter_threshold", + "small_support_perimeter_speed", //coFloatsOrPercents + "small_support_perimeter_threshold", "sparse_infill_speed", "internal_solid_infill_speed", "top_surface_speed", diff --git a/src/slic3r/GUI/SettingsIndex.cpp b/src/slic3r/GUI/SettingsIndex.cpp index ffd5cdadeb..3ef58b9f5f 100644 --- a/src/slic3r/GUI/SettingsIndex.cpp +++ b/src/slic3r/GUI/SettingsIndex.cpp @@ -233,6 +233,12 @@ Option SettingsIndex::get_option(const std::string &opt_key, const wxString &lab return create_option(opt_key, label, type, gc); } +GroupAndCategory SettingsIndex::get_group_and_category(const std::string &opt_key, Preset::Type type) const +{ + auto it = m_groups_and_categories.find(get_key(opt_key, type)); + return it == m_groups_and_categories.end() ? GroupAndCategory{} : it->second; +} + void SettingsIndex::add_key(const std::string &opt_key, Preset::Type type, const wxString &group, const wxString &category, const wxString &icon) { // Update fields in place so a page rebuild (get_option after set_path) doesn't drop the diff --git a/src/slic3r/GUI/SettingsIndex.hpp b/src/slic3r/GUI/SettingsIndex.hpp index fd29696a08..9f894c0a6b 100644 --- a/src/slic3r/GUI/SettingsIndex.hpp +++ b/src/slic3r/GUI/SettingsIndex.hpp @@ -112,7 +112,7 @@ public: const Option &get_option(const std::string &opt_key, Preset::Type type, int &variant_index) const; Option get_option(const std::string &opt_key, const wxString &label, Preset::Type type) const; - const GroupAndCategory &get_group_and_category(const std::string &opt_key) { return m_groups_and_categories[opt_key]; } + GroupAndCategory get_group_and_category(const std::string &opt_key, Preset::Type type) const; void sort_options_by_key() { diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 081c85a4da..3cddbb97d8 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -557,6 +557,23 @@ void Tab::create_preset_tab() m_main_sizer->Add(m_tabctrl, 0, wxEXPAND | wxALL, 0 ); + // The copy button, in a box whose tooltip shows while the button is disabled. + auto create_extruder_sync = [this, panel]() { + m_extruder_sync_box = new wxPanel(panel, wxID_ANY); + m_extruder_sync_box->SetBackgroundColour(panel->GetBackgroundColour()); + m_extruder_sync_box->SetToolTip(_L("Synchronization of different extruder drives or nozzle volume types is not supported.")); + m_extruder_sync = nullptr; + add_scaled_button(m_extruder_sync_box, &m_extruder_sync, "extruder_sync"); + m_extruder_sync->SetToolTip(_L("Synchronize the modification of parameters to the corresponding parameters of another extruder.")); + m_extruder_sync->Bind(wxEVT_BUTTON, [this](auto &evt) { + evt.Skip(); + sync_excluder(); + }); + auto sync_box_sizer = new wxBoxSizer(wxHORIZONTAL); + sync_box_sizer->Add(m_extruder_sync, 1, wxEXPAND); + m_extruder_sync_box->SetSizer(sync_box_sizer); + }; + if (dynamic_cast(this) || dynamic_cast(this)) { m_extruder_switch = new MultiSwitchButton(panel); m_extruder_switch->SetFont(Label::Body_11); @@ -575,25 +592,12 @@ void Tab::create_preset_tab() switch_excluder(extruder_id); }); - m_extruder_sync_box = new wxPanel(panel, wxID_ANY); - m_extruder_sync_box->SetBackgroundColour(panel->GetBackgroundColour()); - m_extruder_sync_box->SetToolTip(_L("Synchronization of different extruder drives or nozzle volume types is not supported.")); - m_extruder_sync = nullptr; - add_scaled_button(m_extruder_sync_box, &m_extruder_sync, "extruder_sync"); - m_extruder_sync->SetToolTip(_L("Synchronize the modification of parameters to the corresponding parameters of another extruder.")); - m_extruder_sync->Bind(wxEVT_BUTTON, [this](auto &evt) { - evt.Skip(); - sync_excluder(); - }); + create_extruder_sync(); ScalableButton* icon = nullptr; add_scaled_button(panel, &icon, "multi_extruder"); icon->SetToolTip(_L("Parameters with this icon can be configured per nozzle.")); - auto sync_box_sizer = new wxBoxSizer(wxHORIZONTAL); - sync_box_sizer->Add(m_extruder_sync, 1, wxEXPAND); - m_extruder_sync_box->SetSizer(sync_box_sizer); - m_variant_sizer = new wxBoxSizer(wxHORIZONTAL); auto right_sizer = new wxBoxSizer(wxHORIZONTAL); auto left_sizer = new wxBoxSizer(wxHORIZONTAL); @@ -625,10 +629,13 @@ void Tab::create_preset_tab() ScalableButton* icon = nullptr; add_scaled_button(panel, &icon, "multi_extruder"); icon->SetToolTip(_L("Parameters with this icon can be configured per nozzle.")); + create_extruder_sync(); wxBoxSizer *top_sizer = new wxBoxSizer(wxHORIZONTAL); top_sizer->Add(icon, 0, wxALIGN_CENTER_VERTICAL); top_sizer->Add(m_variant_combo, 0, wxALIGN_CENTER_VERTICAL | wxLEFT, FromDIP(2)); + top_sizer->AddStretchSpacer(1); + top_sizer->Add(m_extruder_sync_box, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, m_em_unit); m_variant_sizer = new wxBoxSizer(wxVERTICAL); m_variant_sizer->Add(top_sizer, 0, wxEXPAND | wxLEFT, m_em_unit); @@ -2074,6 +2081,21 @@ static wxString pad_combo_value_for_config(const DynamicPrintConfig &config) return config.opt_bool("pad_enable") ? (config.opt_bool("pad_around_object") ? _("Around object") : _("Below object")) : _("None"); } +// Orca: gives the process columns for tools its profile lacks, e.g. after the extruder count was raised. Every copy the +// edited process is compared with gets the same columns, so they do not show as changes. +static void add_selected_process_columns_for_new_tools(PresetBundle &bundle) +{ + PresetCollection &prints = bundle.prints; + const DynamicPrintConfig &printer = bundle.printers.get_edited_preset().config; + const bool saved = !prints.saved_is_dirty(); + add_process_columns_for_new_tools(prints.get_selected_preset().config, printer); + if (const Preset *parent = prints.get_selected_preset_parent()) + if (Preset *preset = prints.find_preset(parent->name)) + add_process_columns_for_new_tools(preset->config, printer); + if (add_process_columns_for_new_tools(prints.get_edited_preset().config, printer) && saved) + prints.update_saved_preset_from_current_preset(); +} + // Rebuilds the variant switch of every tab that has one, e.g. after the extruder count or a nozzle volume type changed. static void update_all_extruder_variants(int extruder_idx = -1) { @@ -5870,6 +5892,7 @@ void TabPrinter::extruders_count_changed(size_t extruders_count) if (m_extruders_count != extruders_count) { m_extruders_count = extruders_count; m_preset_bundle->on_extruders_count_changed(extruders_count); + add_selected_process_columns_for_new_tools(*m_preset_bundle); is_count_changed = true; wxGetApp().plater()->get_partplate_list().on_extruder_count_changed((int)m_extruders_count); @@ -7252,6 +7275,7 @@ void Tab::load_current_preset() wxGetApp().obj_list()->update_objects_list_filament_column(1); } if (m_type == Preset::TYPE_PRINT) { + add_selected_process_columns_for_new_tools(*m_preset_bundle); if (auto tab = wxGetApp().plate_tab) { tab->m_config->apply(*m_config); tab->update_extruder_variants(); @@ -8758,7 +8782,7 @@ wxSizer* TabPrinter::create_bed_shape_widget(wxWindow* parent) { Search::SettingsIndex& index = wxGetApp().sidebar().settings_index(); - const Search::GroupAndCategory& gc = index.get_group_and_category("printable_area"); + const Search::GroupAndCategory gc = index.get_group_and_category("printable_area", m_type); index.add_key("bed_custom_texture", m_type, gc.group, gc.category, gc.icon); index.add_key("bed_custom_model", m_type, gc.group, gc.category, gc.icon); } @@ -9048,6 +9072,18 @@ static wxString short_nozzle_volume_name(const std::string &volume_name) return from_u8(volume_name); } +// Orca: Bambu dual-nozzle printers name their toolheads (extruder 0 is the left, deputy one); others number their tools. +static bool has_toolhead_names(PresetBundle &bundle) { return bundle.get_printer_extruder_count() == 2 && bundle.is_bbl_vendor(); } + +static wxString extruder_display_name(PresetBundle &bundle, int extruder, ToolHeadNameCase name_case, bool short_name = false) +{ + if (!has_toolhead_names(bundle)) + return wxString::Format("T%d", extruder + 1); + const std::string pt = bundle.printers.get_edited_preset().get_printer_type(&bundle); + return _L(DevPrinterConfigUtil::get_toolhead_display_name(pt, extruder == 0 ? DEPUTY_EXTRUDER_ID : MAIN_EXTRUDER_ID, + ToolHeadComponent::Nozzle, name_case, short_name)); +} + std::vector Tab::generate_extruder_options() { std::vector options; @@ -9103,22 +9139,22 @@ std::vector Tab::generate_extruder_options() // Orca: the printer tab has one tag per extruder, named as its former "Extruder N" pages were. // parse_extruder_selection() counts a hybrid extruder as two tags; that still lines up because - // only the last extruder can be hybrid. + // only the last extruder can be hybrid. When the extruders have nozzle variants, the tag also names + // the one its pages edit, which the sidebar's nozzle volume type selects. if (m_type == Preset::TYPE_PRINTER) { - for (int i = 0; i < extruder_nums; ++i) - options.push_back(translate_category(wxString::Format("Extruder %d", i + 1), m_type)); + for (int i = 0; i < extruder_nums; ++i) { + wxString name = translate_category(wxString::Format("Extruder %d", i + 1), m_type); + const NozzleVolumeType volume_type = NozzleVolumeType(nozzle_volumes->values[i]); + if (m_extruder_switch_variants && volume_type != NozzleVolumeType::nvtHybrid) + // TRN Printer settings extruder tab: the extruder's name, e.g. "Extruder 2", and its nozzle flow tag, e.g. "HF". + name = wxString::Format(_L("%s: %s"), name, short_nozzle_volume_name(get_nozzle_volume_type_string(volume_type))); + options.push_back(name); + } return options; } - std::string pt = m_preset_bundle->printers.get_edited_preset().get_printer_type(m_preset_bundle); - // Orca: the main/deputy toolhead names describe a Bambu dual-nozzle printer, where extruder 0 is - // the left (deputy) and extruder 1 the right (main) nozzle. Other printers number their tools. - const bool toolhead_names = extruder_nums == 2 && m_preset_bundle->is_bbl_vendor(); for (int i = 0; i < extruder_nums; ++i) { - wxString extruder_name = !toolhead_names ? wxString::Format("T%d", i + 1) : - _L(DevPrinterConfigUtil::get_toolhead_display_name( - pt, (i == 0) ? DEPUTY_EXTRUDER_ID : MAIN_EXTRUDER_ID, - ToolHeadComponent::Nozzle, ToolHeadNameCase::TitleCase, true)); + wxString extruder_name = extruder_display_name(*m_preset_bundle, i, ToolHeadNameCase::TitleCase, true); NozzleVolumeType volume_type = NozzleVolumeType(nozzle_volumes->values[i]); if (volume_type == NozzleVolumeType::nvtHybrid) { @@ -9217,60 +9253,33 @@ NozzleVolumeType Tab::get_actual_nozzle_volume_type(int extruder_id) return m_actual_nozzle_volumes[extruder_id]; } -bool Tab::get_extruder_sync_enable_state(int extruder_id) +std::vector Tab::get_extruder_sync_targets(int extruder_id) { - Preset& printer_preset = m_preset_bundle->printers.get_edited_preset(); auto nozzle_volumes = m_preset_bundle->project_config.option("nozzle_volume_type"); - auto extruders = printer_preset.config.option("extruder_type"); - // Orca: every rule below describes the two toolheads of a dual-nozzle printer as left/right. - // A printer with any other extruder count has no single counterpart to copy to, so it gets no - // sync button (a toolchanger would need a target to be chosen). - if (nozzle_volumes->values.size() != 2 || extruders->values.size() != 2) { - return false; + auto extruders = m_preset_bundle->printers.get_edited_preset().config.option("extruder_type"); + const int count = int(std::min(nozzle_volumes->size(), extruders->size())); + std::vector targets; + if (extruder_id < 0 || extruder_id >= count) + return targets; + // A target needs the same drive and a nozzle that has the active nozzle's volume type. + const NozzleVolumeType nozzle = get_actual_nozzle_volume_type(extruder_id); + for (int i = 0; i < count; ++i) { + const auto volume = NozzleVolumeType(nozzle_volumes->values[i]); + if (i != extruder_id && extruders->values[i] == extruders->values[extruder_id] && + (volume == nozzle || volume == NozzleVolumeType::nvtHybrid)) + targets.push_back(i); } + return targets; +} - NozzleVolumeType left_nozzle = NozzleVolumeType(nozzle_volumes->values[0]); - NozzleVolumeType right_nozzle = NozzleVolumeType(nozzle_volumes->values[1]); - ExtruderType left_extruder = ExtruderType(extruders->values[0]); - ExtruderType right_extruder = ExtruderType(extruders->values[1]); - - if (left_extruder != right_extruder) { - return false; - } - - if (left_nozzle == right_nozzle) { - return true; - } - - if (left_nozzle != NozzleVolumeType::nvtHybrid && right_nozzle != NozzleVolumeType::nvtHybrid) { - return false; - } - - if (left_nozzle == NozzleVolumeType::nvtHybrid && right_nozzle == NozzleVolumeType::nvtHybrid) { - return true; - } - - // Hybrid rules - auto current_nozzle = get_actual_nozzle_volume_type(extruder_id); - if (left_nozzle != NozzleVolumeType::nvtHybrid) { - if (extruder_id == 0) { - return true; - } - if (extruder_id == 1 && current_nozzle == left_nozzle) { - return true; - } - return false; - } - if (right_nozzle != NozzleVolumeType::nvtHybrid) { - if (extruder_id == 1) { - return true; - } - if (extruder_id == 0 && current_nozzle == right_nozzle) { - return true; - } - return false; - } - return false; +bool Tab::extruder_sync_enabled() +{ + // Orca: a filament copies between its nozzle variants, and the printer's Extruder page between any extruders. + if (m_variant_combo) + return m_variant_combo->IsThisEnabled(); + if (is_printer_extruder_page(m_active_page)) + return m_preset_bundle->get_printer_extruder_count() >= 2; + return m_extruder_switch_variants && !get_extruder_sync_targets(get_current_active_extruder()).empty(); } bool Tab::variant_switch_active() const @@ -9288,9 +9297,7 @@ void Tab::update_variant_sizer_visibility() m_main_sizer->Show(m_variant_sizer, show); if (m_extruder_sync) { m_extruder_sync->Show(show); - // Orca: copying between extruders is offered only between nozzle variants, and not on the Extruder page. - m_extruder_sync->Enable(m_extruder_switch_variants && !is_printer_extruder_page(m_active_page) && - get_extruder_sync_enable_state(get_current_active_extruder())); + m_extruder_sync->Enable(extruder_sync_enabled()); } GetParent()->Layout(); } @@ -9307,10 +9314,10 @@ void Tab::switch_excluder(int extruder_id, bool reload) extruder_id = get_current_active_extruder(); if (!m_variant_combo && (extruder_id >= (int)nozzle_volumes->size() || extruder_id >= (int)extruders->size())) extruder_id = 0; + if (m_extruder_sync) + m_extruder_sync->Enable(extruder_sync_enabled()); if (m_extruder_switch) { int current_extruder = get_current_active_extruder(); - bool sync_enable = get_extruder_sync_enable_state(current_extruder); - m_extruder_sync->Enable(m_extruder_switch_variants && sync_enable && !is_printer_extruder_page(m_active_page)); m_extruder_sync->Show(); if (m_type != Preset::TYPE_PRINTER) { if (extruder_id == -1) @@ -9355,6 +9362,7 @@ void Tab::switch_excluder(int extruder_id, bool reload) const int idx = printer_options_with_variant_1.count(opt.second.first) > 0 ? page_index : extruder_id; const_cast(opt.second.second) = idx; page->m_opt_id_map.insert({opt.second.first + "#" + std::to_string(idx), opt.first}); + group->draw_multi_extruder = variant_switch_active(); continue; } auto iter = std::find(printer_extruder_options.begin(), printer_extruder_options.end(), opt.second.first); @@ -9383,76 +9391,145 @@ void Tab::switch_excluder(int extruder_id, bool reload) void Tab::sync_excluder() { - Preset & printer_preset = m_preset_bundle->printers.get_edited_preset(); - auto nozzle_volumes = m_preset_bundle->project_config.option("nozzle_volume_type"); - auto extruders = printer_preset.config.option("extruder_type"); + // Orca: copies the modified values of the switch's selection to the extruders that can take them, or, on the + // filament tab, to the filament's other nozzle variants. Each option keeps its values at its own position in every + // column: the variant column of the active nozzle, the extruder for per-extruder options of the printer's Extruder + // page, the variant for a filament. + const bool extruder_page = is_printer_extruder_page(m_active_page); // Motion ability options hold a (normal, silent) pair per variant, so switch_excluder indexes that page with stride 2. - const int stride = m_active_page->title().StartsWith("Motion ability") ? 2 : 1; - auto get_index_for_extruder = - [this, &extruders, stride, variant_keys = extruder_variant_keys[m_type >= Preset::TYPE_COUNT ? Preset::TYPE_PRINT : m_type]](int extruder_id, NozzleVolumeType nozzle_type) { - return m_config->get_index_for_extruder(extruder_id + 1, variant_keys.first, - ExtruderType(extruders->values[extruder_id]), nozzle_type, variant_keys.second, stride); + const int stride = m_active_page->title().StartsWith("Motion ability") ? 2 : 1; + const Preset::Type base_type = m_type >= Preset::TYPE_COUNT ? Preset::TYPE_PRINT : m_type; + const auto *extruders = m_preset_bundle->printers.get_edited_preset().config.option("extruder_type"); + const int source = m_variant_combo ? std::max(0, m_variant_combo->GetSelection()) : get_current_active_extruder(); + const NozzleVolumeType active_nozzle = m_variant_combo ? NozzleVolumeType::nvtStandard : get_actual_nozzle_volume_type(source); + const std::vector targets = m_variant_combo ? std::vector() : get_extruder_sync_targets(source); + auto position = [&](const std::string &key, int column) -> int { + if (m_variant_combo) + return filament_options_with_variant.count(key) > 0 ? column : -1; + if (extruder_page && printer_options_with_variant_1.count(key) == 0) + return column; + // A per-variant option goes only to an extruder with the same drive and the active nozzle's variant. + if (column != source && std::find(targets.begin(), targets.end(), column) == targets.end()) + return -1; + const auto variant_keys = extruder_variant_keys[base_type]; + return m_config->get_index_for_extruder(column + 1, variant_keys.first, ExtruderType(extruders->values[column]), active_nozzle, + variant_keys.second, stride); }; - int active_index = get_current_active_extruder(); - // The button copies to the other toolhead, so it is only offered when that other one exists; - // without this the `1 - active_index` below would index an extruder that is not there. - if (!get_extruder_sync_enable_state(active_index)) - return; - auto active_nozzle = get_actual_nozzle_volume_type(active_index); - int from_index = get_index_for_extruder(active_index, active_nozzle); - int dest_index = get_index_for_extruder(1 - active_index, active_nozzle); - if (from_index < 0 || dest_index < 0) // no variant column for this nozzle on one of the extruders + + // Extruders, or a filament's nozzle variants, in order. + std::vector columns; + if (m_variant_combo) { + const auto *variants = m_config->option("filament_extruder_variant"); + for (int variant = 0; variants != nullptr && variant < int(variants->size()); ++variant) + columns.push_back(variant); + } else if (extruder_page) { + for (int extruder = 0; extruder < m_preset_bundle->get_printer_extruder_count(); ++extruder) + columns.push_back(extruder); + } else { + if (position("", source) < 0) + return; + columns.push_back(source); + for (int extruder : targets) + if (position("", extruder) >= 0) + columns.push_back(extruder); + std::sort(columns.begin(), columns.end()); + } + if (columns.size() < 2) return; + + UnsavedChangesDialog::SyncExtruderParams params{nullptr, {}, 0, {}}; auto dirty_options = m_presets->current_dirty_options(true); - DynamicConfig config_origin, config_to_apply; + DynamicConfig config_origin; for (int i = 0; i < dirty_options.size(); ++i) { auto &opt = dirty_options[i]; auto n= opt.find('#'); if (n == std::string::npos) continue; - auto field = m_active_page->get_field(opt.substr(0, n), from_index + 256); - auto line = m_active_page->get_line(opt.substr(0, n), from_index + 256); - if (field == nullptr || line == nullptr) - continue; + const std::string key = opt.substr(0, n); + const int from = position(key, source); + auto field = from < 0 ? nullptr : m_active_page->get_field(key, from + 256); + auto line = from < 0 ? nullptr : m_active_page->get_line(key, from + 256); ++n; auto is_from_slot = [&](const std::string &dirty_opt) { int slot = std::atoi(dirty_opt.c_str() + n); - return slot >= from_index && slot < from_index + stride; + return slot >= from && slot < from + stride; }; bool dirty = is_from_slot(opt); while (i + 1 < dirty_options.size() && dirty_options[i + 1].compare(0, n, opt, 0, n) == 0) { dirty |= is_from_slot(dirty_options[i + 1]); ++i; } - if (dirty) { - auto key = opt.substr(0, n - 1); - auto option = dynamic_cast(m_config->option(key)); - auto option2 = dynamic_cast(option->clone()); - for (int s = 0; s < stride; ++s) - option2->set_at(option, dest_index + s, from_index + s); - if (*option == *option2) { - delete option2; - continue; - } - config_origin.set_key_value(key, option->clone()); - config_to_apply.set_key_value(key, option2); + if (field == nullptr || line == nullptr || !dirty) + continue; + UnsavedChangesDialog::SyncExtruderParams::Positions positions{stride, {}}; + size_t width = 0; // values the option needs to hold one for every column + for (int column : columns) { + positions.index.push_back(position(key, column)); + if (positions.index.back() >= 0) + width = std::max(width, size_t(positions.index.back() + stride)); + } + std::unique_ptr origin(dynamic_cast(m_config->option(key)->clone())); + // A vector shorter than the columns gives the missing ones its first value; pad it with that, so the + // dialog can read every column. + if (origin->size() < width) + origin->set_at(origin.get(), width - 1, width - 1); + const std::vector values = origin->vserialize(); + bool changes = false; + for (int index : positions.index) + for (int s = 0; index >= 0 && s < stride; ++s) + changes |= values[index + s] != values[from + s]; + if (changes) { + config_origin.set_key_value(key, origin.release()); + params.positions.emplace(key, std::move(positions)); } } - if (config_to_apply.empty()) { + if (config_origin.empty()) { MessageDialog md(wxGetApp().plater(), _L("No modifications need to be copied."), _L("Copy parameters"), wxICON_INFORMATION | wxOK); md.ShowModal(); return; } - std::string pt = m_preset_bundle->printers.get_edited_preset().get_printer_type(m_preset_bundle); - std::string active_nozzle_name = DevPrinterConfigUtil::get_toolhead_display_name(pt, active_index, ToolHeadComponent::Nozzle, ToolHeadNameCase::LowerCase); - std::string other_nozzle_name = DevPrinterConfigUtil::get_toolhead_display_name(pt, 1 - active_index, ToolHeadComponent::Nozzle, ToolHeadNameCase::LowerCase); - wxString title = wxString::Format(_L("Modify parameters of %s"), _L(active_nozzle_name)); - wxString header = wxString::Format(_L("Do you want to modify the following parameters of the %s to that of the %s?"), - _L(active_nozzle_name), _L(other_nozzle_name)); - UnsavedChangesDialog dlg(title, header, &config_origin, from_index, dest_index, active_index == 0, active_nozzle); + // Orca: the columns are named by this tab's switch tags. + const std::vector tags = generate_extruder_options(); + auto tag_name = [&](int column) { + const size_t tag = m_variant_combo ? size_t(column) : size_t(calculate_selection_index_for_extruder(column, active_nozzle)); + return tag < tags.size() ? tags[tag] : wxString::Format("T%d", column + 1); + }; + // A Bambu dual-nozzle printer's message names its nozzles within a sentence; the others use the tags. + const bool toolheads = !m_variant_combo && has_toolhead_names(*m_preset_bundle); + auto message_name = [&](int column) { + return toolheads ? extruder_display_name(*m_preset_bundle, column, ToolHeadNameCase::LowerCase) : tag_name(column); + }; + params.config = &config_origin; + wxString to_names; + for (int column : columns) { + if (column == source) + params.source = int(params.titles.size()); + else + to_names += (to_names.empty() ? "" : ", ") + message_name(column); + params.titles.push_back(tag_name(column)); + } + const wxString from_name = message_name(source); + wxString title = wxString::Format(_L("Modify parameters of %s"), to_names); + wxString header; + if (toolheads) + header = wxString::Format(_L("Do you want to modify the following parameters of the %s to that of the %s?"), to_names, from_name); + else + // TRN %1% is the extruder (or nozzle variant) the values are copied from, %2% the list of those they are copied to, as the switch names them, e.g. "T2 HF, T3 HF". + header = format_wxstr(_L("Do you want to copy the following parameters of %1% to %2%?"), from_name, to_names); + UnsavedChangesDialog dlg(title, header, base_type, params); dlg.ShowModal(); - if (dlg.transfer_changes()) { + DynamicConfig config_to_apply; + if (dlg.transfer_changes()) + for (const auto &[key, index] : dlg.get_sync_selection()) { + const auto &positions = params.positions.at(key); + const int from = positions.index[params.source]; + if (!config_to_apply.has(key)) + config_to_apply.set_key_value(key, m_config->option(key)->clone()); + for (int s = 0; s < positions.stride; ++s) + dynamic_cast(config_to_apply.option(key))->set_at(m_config->option(key), index + s, from + s); + } + if (!config_to_apply.empty()) { m_config->apply(config_to_apply); auto &applying_keys = const_cast(m_config_manipulation.applying_keys()); if (m_type > Preset::TYPE_COUNT) diff --git a/src/slic3r/GUI/Tab.hpp b/src/slic3r/GUI/Tab.hpp index 8df7d6c84c..c698b7dff0 100644 --- a/src/slic3r/GUI/Tab.hpp +++ b/src/slic3r/GUI/Tab.hpp @@ -498,6 +498,7 @@ public: DynamicPrintConfig* get_config() { return m_config; } PresetCollection * get_presets() { return m_presets; } + const std::vector& pages() const { return m_pages; } TabPresetComboBox * get_combo_box() { return m_presets_choice; } virtual void on_value_change(const std::string& opt_key, const boost::any& value); @@ -536,7 +537,8 @@ public: void sync_excluder(); void parse_extruder_selection(int selection, int &extruder_id, NozzleVolumeType &nozzle_type); int calculate_selection_index_for_extruder(int extruder_id, NozzleVolumeType nozzle_type); - bool get_extruder_sync_enable_state(int extruder_id); + std::vector get_extruder_sync_targets(int extruder_id); + bool extruder_sync_enabled(); int get_current_active_extruder(); std::vector generate_extruder_options(); diff --git a/src/slic3r/GUI/UnsavedChangesDialog.cpp b/src/slic3r/GUI/UnsavedChangesDialog.cpp index fb23aff48d..322826ed0b 100644 --- a/src/slic3r/GUI/UnsavedChangesDialog.cpp +++ b/src/slic3r/GUI/UnsavedChangesDialog.cpp @@ -1,11 +1,15 @@ #include "UnsavedChangesDialog.hpp" +#include #include +#include +#include #include #include #include #include #include +#include #include "slic3r/GUI/Event.hpp" #include #include "libslic3r/Preset.hpp" @@ -16,8 +20,6 @@ #include #include "slic3r/GUI/GUI_Utils.hpp" #include "slic3r/GUI/Widgets/Label.hpp" -#include "slic3r/GUI/DeviceCore/DevConfigUtil.h" -#include "slic3r/GUI/DeviceCore/DevDefs.h" #include "slic3r/GUI/Widgets/StateColor.hpp" #include "slic3r/GUI/Widgets/Button.hpp" #include "slic3r/GUI/SettingsIndex.hpp" @@ -47,14 +49,16 @@ #include #include #include +#include +#include -#include "CalibUtils.hpp" #include "libslic3r/PrintConfig.hpp" #include "libslic3r/PresetBundle.hpp" #include "libslic3r/Color.hpp" #include "format.hpp" #include "ConfigValueFormatter.hpp" #include "GUI_App.hpp" +#include "OptionsGroup.hpp" #include "Plater.hpp" #include "Tab.hpp" #include "ExtraRenderers.hpp" @@ -611,6 +615,41 @@ void DiffModel::Clear() } +// Top-down order of the sidebar's preset sections. +static const Preset::Type PRESET_TYPE_ORDER[] = { + Preset::TYPE_PRINTER, Preset::TYPE_FILAMENT, Preset::TYPE_SLA_MATERIAL, Preset::TYPE_PRINT, Preset::TYPE_SLA_PRINT }; + +static int preset_type_rank(Preset::Type type) +{ + return int(std::find(std::begin(PRESET_TYPE_ORDER), std::end(PRESET_TYPE_ORDER), type) - std::begin(PRESET_TYPE_ORDER)); +} + +// opt_key -> its position on the settings pages, with the tabs taken in PRESET_TYPE_ORDER. +static std::map build_tab_order_map() +{ + std::vector tabs = wxGetApp().tabs_list; + std::stable_sort(tabs.begin(), tabs.end(), [](Tab *a, Tab *b) { return preset_type_rank(a->type()) < preset_type_rank(b->type()); }); + + std::map order; + for (Tab *tab : tabs) + for (const PageShp &page : tab->pages()) + for (const auto &optgroup : page->m_optgroups) + for (const Line &line : optgroup->get_lines()) + for (const Option &opt : line.get_options()) + order.emplace(get_pure_opt_key(opt.opt_id), int(order.size())); + return order; +} + +static int order_of(const std::map &tab_order, const std::string &opt_key) +{ + auto it = tab_order.find(get_pure_opt_key(opt_key)); + return it != tab_order.end() ? it->second : INT_MAX; +} + +// Same-named categories on different tabs must stay separate, so the keys carry the preset type. +static wxString preset_item_cat_key(const PresetItem &pi) { return wxString::Format("%d:", int(pi.type)) + pi.category_name; } +static wxString preset_item_grp_key(const PresetItem &pi) { return preset_item_cat_key(pi) + ":" + pi.group_name; } + // ---------------------------------------------------------------------------- // DiffViewCtrl // ---------------------------------------------------------------------------- @@ -809,7 +848,16 @@ static std::string none{"none"}; #define UNSAVE_CHANGE_DIALOG_ACTION_LINE_SIZE wxSize(FromDIP(490), -1) #define UNSAVE_CHANGE_DIALOG_FIRST_VALUE_WIDTH FromDIP(190) #define UNSAVE_CHANGE_DIALOG_VALUE_WIDTH FromDIP(150) +#define UNSAVE_CHANGE_DIALOG_VALUE_TEXT_WIDTH (UNSAVE_CHANGE_DIALOG_VALUE_WIDTH - FromDIP(10)) +#define UNSAVE_CHANGE_DIALOG_CATEGORY_INDENT FromDIP(23) +#define UNSAVE_CHANGE_DIALOG_GROUP_INDENT FromDIP(37) +#define UNSAVE_CHANGE_DIALOG_OPTION_INDENT FromDIP(51) +#define UNSAVE_CHANGE_DIALOG_ICON_WIDTH FromDIP(24) #define UNSAVE_CHANGE_DIALOG_ITEM_HEIGHT FromDIP(24) +#define UNSAVE_CHANGE_DIALOG_SYNC_CELL_PADDING FromDIP(8) +#define UNSAVE_CHANGE_DIALOG_TYPE_INDENT FromDIP(8) +// A row's checkbox and the gap after it +#define UNSAVE_CHANGE_DIALOG_CHECK_WIDTH FromDIP(22) #define UNSAVE_CHANGE_DIALOG_BUTTON_SIZE wxSize(FromDIP(70), FromDIP(24)) #define THUMB_COLOR wxColor(196, 196, 196) @@ -835,7 +883,7 @@ UnsavedChangesDialog::UnsavedChangesDialog(const wxString &caption, const wxStri wxGetApp().UpdateDlgDarkUI(this); } -UnsavedChangesDialog::UnsavedChangesDialog(const wxString &caption, const wxString &header, DynamicConfig *config, int from, int to, bool left_to_right, NozzleVolumeType nozzle) +UnsavedChangesDialog::UnsavedChangesDialog(const wxString &caption, const wxString &header, Preset::Type type, SyncExtruderParams params) : DPIDialog(static_cast(wxGetApp().mainframe), wxID_ANY, caption, @@ -844,8 +892,7 @@ UnsavedChangesDialog::UnsavedChangesDialog(const wxString &caption, const wxStri wxCAPTION | wxCLOSE_BOX) , m_buttons(ActionButtons::SAVE | ActionButtons::DONT_SAVE) { - SyncExtruderParams params { config, from, to, left_to_right, nozzle }; - build(Preset::TYPE_PRINT, reinterpret_cast(¶ms), "SyncExtruderParams", header); + build(type, reinterpret_cast(¶ms), "SyncExtruderParams", header); this->CenterOnScreen(); wxGetApp().UpdateDlgDarkUI(this); } @@ -893,6 +940,61 @@ void UnsavedChangesDialog::build(Preset::Type type, PresetCollection *dependent_ { SetBackgroundColour(*wxWHITE); + SyncExtruderParams *params = nullptr; + if (new_selected_preset == "SyncExtruderParams") { + params = reinterpret_cast(dependent_presets); + dependent_presets = nullptr; + } + + // The rows size the columns, so collect them before building the header. + if (params) + update_tree(type, params->config); + else + update_tree(type, dependent_presets); + + // The sync dialog has a value column per extruder, each fitted to its content once the table is built. + const int value_columns = params ? int(params->titles.size()) : 2; + m_value_width = params ? wxDefaultCoord : UNSAVE_CHANGE_DIALOG_VALUE_WIDTH; + if (params) { + m_sync_columns.assign(value_columns + 1, {}); + m_first_value_width = m_content_width = wxDefaultCoord; + } else { + auto row_width = [this](const wxString &text, const wxFont &font, int indent) { + int w = 0, h = 0; + GetTextExtent(text, &w, &h, nullptr, nullptr, &font); + return indent + w + FromDIP(16); + }; + // Category headers span the row, so they widen the dialog rather than the label column. + m_first_value_width = UNSAVE_CHANGE_DIALOG_FIRST_VALUE_WIDTH; + int category_width = 0; + for (const PresetItem &pi : m_presetitems) { + const int option_w = row_width(pi.option_name, ::Label::Body_13, UNSAVE_CHANGE_DIALOG_OPTION_INDENT) + (pi.has_icon ? UNSAVE_CHANGE_DIALOG_ICON_WIDTH : 0); + m_first_value_width = std::max({m_first_value_width, option_w, row_width(pi.group_name, ::Label::Head_13, UNSAVE_CHANGE_DIALOG_GROUP_INDENT)}); + category_width = std::max(category_width, row_width(pi.category_name, ::Label::Head_13, UNSAVE_CHANGE_DIALOG_CATEGORY_INDENT)); + } + // Every row has its box before the label. + m_first_value_width = std::min(m_first_value_width + UNSAVE_CHANGE_DIALOG_CHECK_WIDTH, FromDIP(420)); + category_width += UNSAVE_CHANGE_DIALOG_CHECK_WIDTH; + m_content_width = std::min(std::max(m_first_value_width + 2 * UNSAVE_CHANGE_DIALOG_VALUE_WIDTH, category_width), FromDIP(760)); + } + + // update_list() gives every category, group and option one ITEM_HEIGHT row, and every type one outside the sync + // dialog, so this is the exact list height. + std::set row_types; + std::set row_cats, row_grps; + for (const PresetItem &pi : m_presetitems) { + row_types.insert(int(pi.type)); + row_cats.insert(preset_item_cat_key(pi)); + row_grps.insert(preset_item_grp_key(pi)); + } + const int row_count = int((params ? 0 : row_types.size()) + row_cats.size() + row_grps.size() + m_presetitems.size()); + const bool needs_scrollbar = row_count * UNSAVE_CHANGE_DIALOG_ITEM_HEIGHT > UNSAVE_CHANGE_DIALOG_SCROLL_WINDOW_SIZE.GetHeight(); + + // Overlay scrollbars report a width of 0 and take no space. + const int scrollbar_w = needs_scrollbar ? std::max(0, wxSystemSettings::GetMetric(wxSYS_VSCROLL_X, this)) : 0; + if (!params) + m_content_width += scrollbar_w; + wxBoxSizer *m_sizer_main = new wxBoxSizer(wxVERTICAL); m_top_line = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxSize(-1, 1), wxTAB_TRAVERSAL); @@ -902,7 +1004,7 @@ void UnsavedChangesDialog::build(Preset::Type type, PresetCollection *dependent_ m_sizer_main->Add(0, 0, 0, wxTOP, 20); - m_action_line = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, UNSAVE_CHANGE_DIALOG_ACTION_LINE_SIZE, 0); + m_action_line = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(m_content_width, UNSAVE_CHANGE_DIALOG_ACTION_LINE_SIZE.y), 0); m_action_line->SetFont(::Label::Body_13); m_action_line->SetForegroundColour(wxColour("#363636")); m_action_line->Wrap(-1); @@ -910,13 +1012,7 @@ void UnsavedChangesDialog::build(Preset::Type type, PresetCollection *dependent_ m_sizer_main->Add(0, 0, 0, wxTOP, 12); - SyncExtruderParams *params = nullptr; - if (new_selected_preset == "SyncExtruderParams") { - params = reinterpret_cast(dependent_presets); - dependent_presets = nullptr; - } - - m_panel_tab = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxSize(UNSAVE_CHANGE_DIALOG_SCROLL_WINDOW_SIZE.x, -1), wxTAB_TRAVERSAL); + m_panel_tab = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxSize(m_content_width, -1), wxTAB_TRAVERSAL); m_panel_tab->SetBackgroundColour(wxColour("#D9D9D9")); wxBoxSizer *m_sizer_tab = new wxBoxSizer(wxVERTICAL); @@ -926,69 +1022,80 @@ void UnsavedChangesDialog::build(Preset::Type type, PresetCollection *dependent_ wxBoxSizer *m_sizer_top = new wxBoxSizer(wxHORIZONTAL); // m_sizer_top->Add(0, 0, 0, wxLEFT, UNSAVE_CHANGE_DIALOG_FIRST_VALUE_WIDTH); - auto m_panel_temp = new wxPanel(m_table_top, wxID_ANY, wxDefaultPosition, wxSize(UNSAVE_CHANGE_DIALOG_FIRST_VALUE_WIDTH, -1), wxTAB_TRAVERSAL); + auto m_panel_temp = new wxPanel(m_table_top, wxID_ANY, wxDefaultPosition, wxSize(m_first_value_width, -1), wxTAB_TRAVERSAL); wxBoxSizer *top_title_temp_v = new wxBoxSizer(wxVERTICAL); - top_title_temp_v->SetMinSize(wxSize(UNSAVE_CHANGE_DIALOG_VALUE_WIDTH, -1)); + if (!params) + top_title_temp_v->SetMinSize(wxSize(UNSAVE_CHANGE_DIALOG_VALUE_WIDTH, -1)); wxBoxSizer *top_title_temp_h = new wxBoxSizer(wxHORIZONTAL); + + // Tick-all boxes of the header: every change or copy (column -1), or in the sync dialog every copy to one column. + std::vector> header_checks; + auto add_header_check = [this, &header_checks](wxPanel *panel, wxBoxSizer *sizer, int column) { + panel->SetBackgroundColour(wxColour("#D9D9D9")); + const size_t k = add_all_check(panel); + header_checks.emplace_back(k, column); + sizer->Add(m_all_checks[k].first, 0, wxALIGN_CENTER | wxRIGHT | wxRESERVE_SPACE_EVEN_IF_HIDDEN, FromDIP(4)); + }; + add_header_check(m_panel_temp, top_title_temp_h, -1); static_temp_title = new wxStaticText(m_panel_temp, wxID_ANY, _L("Settings"), wxDefaultPosition, wxDefaultSize, 0); static_temp_title->SetFont(::Label::Body_13); static_temp_title->Wrap(-1); static_temp_title->SetForegroundColour(wxColour("#363636")); top_title_temp_h->Add(static_temp_title, 0, wxALIGN_CENTER | wxBOTTOM | wxTOP, 5); - top_title_temp_v->Add(top_title_temp_h, 1, wxALIGN_CENTER, 0); + // The corner box sits above the boxes of the outermost rows: the categories in the sync dialog, else the preset types. + top_title_temp_v->Add(top_title_temp_h, 1, wxLEFT, params ? UNSAVE_CHANGE_DIALOG_CATEGORY_INDENT : UNSAVE_CHANGE_DIALOG_TYPE_INDENT); m_panel_temp->SetSizer(top_title_temp_v); m_panel_temp->Layout(); m_sizer_top->Add(m_panel_temp, 1, wxALIGN_CENTER, 0); + if (params) + m_sync_columns[0].push_back(m_panel_temp); - title_block_middle = new wxPanel(m_table_top, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); - title_block_middle->SetBackgroundColour(wxColour(172, 172, 172)); + auto add_title = [this, m_sizer_top, params, &add_header_check](const wxString &label, bool highlight, int column) { + // The first separator keeps its default width, except in the sync dialog, which aligns its header with the rows. + auto separator = new wxPanel(m_table_top, wxID_ANY, wxDefaultPosition, !params && m_sizer_top->GetItemCount() == 1 ? wxDefaultSize : wxSize(1, -1), wxTAB_TRAVERSAL); + separator->SetBackgroundColour(wxColour(172, 172, 172)); + m_sizer_top->Add(separator, 0, wxBOTTOM | wxEXPAND | wxTOP, 2); - m_sizer_top->Add(title_block_middle, 0, wxBOTTOM | wxEXPAND | wxTOP, 2); - auto m_panel_oldv = new wxPanel( m_table_top, wxID_ANY, wxDefaultPosition, wxSize(UNSAVE_CHANGE_DIALOG_VALUE_WIDTH,-1), wxTAB_TRAVERSAL ); - wxBoxSizer *top_title_oldv = new wxBoxSizer(wxVERTICAL); - wxBoxSizer *top_title_oldv_h = new wxBoxSizer(wxHORIZONTAL); + auto panel = new wxPanel(m_table_top, wxID_ANY, wxDefaultPosition, wxSize(m_value_width, -1), wxTAB_TRAVERSAL); + auto sizer_v = new wxBoxSizer(wxVERTICAL); + auto sizer_h = new wxBoxSizer(wxHORIZONTAL); + if (column >= 0) + add_header_check(panel, sizer_h, column); + auto title = new wxStaticText(panel, wxID_ANY, label, wxDefaultPosition, wxDefaultSize, 0); + title->SetFont(::Label::Body_13); + title->Wrap(-1); + title->SetForegroundColour(highlight ? wxGetApp().get_label_clr_modified() : wxColour("#363636")); + sizer_h->Add(title, 0, wxALIGN_CENTER | wxBOTTOM | wxTOP, 5); + sizer_v->Add(sizer_h, 1, params ? wxLEFT : wxALIGN_CENTER, params ? UNSAVE_CHANGE_DIALOG_SYNC_CELL_PADDING : 0); + panel->SetSizer(sizer_v); + panel->Layout(); + m_sizer_top->Add(panel, 0, wxALIGN_CENTER, 0); + return title; + }; + if (params) { + // With a single target its column box would repeat the one ticking every copy. + for (int i = 0; i < value_columns; ++i) + m_sync_columns[i + 1].push_back( + add_title(params->titles[i], i == params->source, value_columns > 2 && i != params->source ? i : -1)->GetParent()); + } else { + static_oldv_title = add_title(_L("Old Value"), false, -1); + static_newv_title = add_title(_L("New Value"), false, -1); + } - std::string ucd_pt = wxGetApp().preset_bundle->printers.get_edited_preset().get_printer_type(wxGetApp().preset_bundle); - static_oldv_title = new wxStaticText(m_panel_oldv, wxID_ANY, params ? _L(DevPrinterConfigUtil::get_toolhead_display_name(ucd_pt, DEPUTY_EXTRUDER_ID, ToolHeadComponent::Nozzle, ToolHeadNameCase::SentenceCase)) + ": " + get_nozzle_volume_type_name(params->nozzle) : _L("Old Value"), wxDefaultPosition, wxDefaultSize, 0); - static_oldv_title->SetFont(::Label::Body_13); - static_oldv_title->Wrap(-1); - static_oldv_title->SetForegroundColour(params && params->left_to_right ? wxGetApp().get_label_clr_modified() : wxColour("#363636")); - top_title_oldv_h->Add(static_oldv_title, 0, wxALIGN_CENTER | wxBOTTOM | wxTOP, 5); - top_title_oldv->Add(top_title_oldv_h, 1, wxALIGN_CENTER, 0); - m_panel_oldv->SetSizer(top_title_oldv); - m_panel_oldv->Layout(); - m_sizer_top->Add(m_panel_oldv, 0, wxALIGN_CENTER, 0); - - title_block_right = new wxPanel(m_table_top, wxID_ANY, wxDefaultPosition, wxSize(1, -1), wxTAB_TRAVERSAL); - title_block_right->SetBackgroundColour(wxColour(172, 172, 172)); - - m_sizer_top->Add(title_block_right, 0, wxBOTTOM | wxEXPAND | wxTOP, 2); - - auto m_panel_newv = new wxPanel( m_table_top, wxID_ANY, wxDefaultPosition, wxSize( UNSAVE_CHANGE_DIALOG_VALUE_WIDTH,-1 ), wxTAB_TRAVERSAL ); - wxBoxSizer *top_title_newv = new wxBoxSizer(wxVERTICAL); - wxBoxSizer *top_title_newv_h = new wxBoxSizer(wxHORIZONTAL); - - static_newv_title = new wxStaticText(m_panel_newv, wxID_ANY, params ? _L(DevPrinterConfigUtil::get_toolhead_display_name(ucd_pt, MAIN_EXTRUDER_ID, ToolHeadComponent::Nozzle, ToolHeadNameCase::SentenceCase)) + ": " + get_nozzle_volume_type_name(params->nozzle) : _L("New Value"), - wxDefaultPosition, wxDefaultSize, 0); - static_newv_title->SetFont(::Label::Body_13); - static_newv_title->Wrap(-1); - static_newv_title->SetForegroundColour(params && !params->left_to_right ? wxGetApp().get_label_clr_modified() : wxColour("#363636")); - - top_title_newv_h->Add(static_newv_title, 0, wxALIGN_CENTER | wxBOTTOM | wxTOP, 5); - - top_title_newv->Add(top_title_newv_h, 1, wxALIGN_CENTER, 0); - - m_panel_newv->SetSizer(top_title_newv); - m_panel_newv->Layout(); - m_sizer_top->Add(m_panel_newv, 0, wxALIGN_CENTER, 0); - //m_sizer_top->Add(top_title_newv, 1, wxALIGN_CENTER, 0); + if (scrollbar_w > 0) { + // Extend the header over the scrollbar so New Value lines up with its rows. + auto title_block_gutter = new wxPanel(m_table_top, wxID_ANY, wxDefaultPosition, wxSize(1, -1), wxTAB_TRAVERSAL); + title_block_gutter->SetBackgroundColour(wxColour(172, 172, 172)); + m_sizer_top->Add(title_block_gutter, 0, wxBOTTOM | wxEXPAND | wxTOP, 2); + m_sizer_top->AddSpacer(scrollbar_w - 1); + } m_table_top->SetSizer(m_sizer_top); m_table_top->Layout(); m_sizer_top->Fit(m_table_top); m_sizer_tab->Add(m_table_top, 1, 0, 0); - m_scrolledWindow = new wxScrolledWindow(m_panel_tab, wxID_ANY, wxDefaultPosition, UNSAVE_CHANGE_DIALOG_SCROLL_WINDOW_SIZE, wxNO_BORDER|wxVSCROLL); + m_scrolledWindow = new wxScrolledWindow(m_panel_tab, wxID_ANY, wxDefaultPosition, wxSize(m_content_width, UNSAVE_CHANGE_DIALOG_SCROLL_WINDOW_SIZE.y), wxNO_BORDER|wxVSCROLL); m_scrolledWindow->SetScrollRate(0, FromDIP(20)); m_scrolledWindow->SetBackgroundColour(GREY200); m_sizer_bottom = new wxBoxSizer(wxVERTICAL); @@ -1070,14 +1177,20 @@ void UnsavedChangesDialog::build(Preset::Type type, PresetCollection *dependent_ add_btn(&m_transfer_btn, m_move_btn_id, "menu_paste", Action::Transfer, _L("Transfer"), true); bool is_copy = new_selected_preset == "SyncExtruderParams"; + // "Save" button; the sync dialog's Yes confirms its question, so it comes first. + auto add_save_btn = [&]() { + if (ActionButtons::SAVE & m_buttons) + add_btn(&m_save_btn, m_save_btn_id, "save", is_copy ? Action::Transfer : Action::Save, is_copy ? _L("Yes") : _L("Save"), is_copy); + }; + if (is_copy) + add_save_btn(); { // "Don't save" / "Discard" button std::string btn_icon = (ActionButtons::DONT_SAVE & m_buttons) ? "" : (dependent_presets || (ActionButtons::KEEP & m_buttons)) ? "blank_16" : "exit"; wxString btn_label = (ActionButtons::DONT_SAVE & m_buttons) ? (is_copy ? _L("No") : _L("Don't save")) : _L("Discard"); add_btn(&m_discard_btn, m_continue_btn_id, btn_icon, Action::Discard, btn_label, false); } - - // "Save" button - if (ActionButtons::SAVE & m_buttons) add_btn(&m_save_btn, m_save_btn_id, "save", is_copy ? Action::Transfer : Action::Save, is_copy ? _L("Yes") : _L("Save"), false); + if (!is_copy) + add_save_btn(); if (dependent_presets != nullptr) { const wxString previous_profile = from_u8(dependent_presets->get_edited_preset().name); @@ -1123,16 +1236,39 @@ void UnsavedChangesDialog::build(Preset::Type type, PresetCollection *dependent_ m_sizer_main->Add(0, 0, 1, wxTOP, 18); if (params) { - if (params->left_to_right) - update_tree(type, params->config, params->from, params->to); - else - update_tree(type, params->config, params->to, params->from); m_action_line->SetLabel(header); - m_action_line->Wrap(UNSAVE_CHANGE_DIALOG_SCROLL_WINDOW_SIZE.x); update_list(params); + // Each column is as wide as its widest cell or title, every extruder's column alike. The header + // windows come first; each sits next to a 1 px separator. + int widths[2] = {0, 0}; // labels, values + for (size_t c = 0; c < m_sync_columns.size(); ++c) + for (size_t r = 0; r < m_sync_columns[c].size(); ++r) + widths[c > 0] = std::max(widths[c > 0], m_sync_columns[c][r]->GetBestSize().x + UNSAVE_CHANGE_DIALOG_SYNC_CELL_PADDING + (r == 0 ? 1 : 0)); + for (size_t c = 0; c < m_sync_columns.size(); ++c) + for (size_t r = 0; r < m_sync_columns[c].size(); ++r) { + m_sync_columns[c][r]->SetMinSize(wxSize(widths[c > 0] - (r == 0 ? 1 : 0), -1)); + m_sync_columns[c][r]->GetParent()->Layout(); + } + m_scrolledWindow->FitInside(); + const int fitted_width = widths[0] + value_columns * widths[1]; + m_scrolledWindow->SetMinSize(wxSize(fitted_width + scrollbar_w, UNSAVE_CHANGE_DIALOG_SCROLL_WINDOW_SIZE.y)); + m_action_line->SetMinSize(wxSize(fitted_width, -1)); + m_action_line->Wrap(fitted_width); } else { update(type, dependent_presets, new_selected_preset, header); } + for (const auto &[k, column] : header_checks) { + for (const auto &[check, opt_key, index, check_column] : m_sync_checks) + if (column < 0 || column == check_column) + m_all_checks[k].second.push_back(check); + if (column < 0) + for (const auto &option : m_option_checks) + m_all_checks[k].second.push_back(std::get<0>(option)); + } + // A box over a single one would only repeat it. + for (const auto &[all, cells] : m_all_checks) + all->Show(cells.size() > 1); + update_all_checks(); //SetSizer(topSizer); //topSizer->SetSizeHints(this); @@ -1388,12 +1524,20 @@ void UnsavedChangesDialog::update(Preset::Type type, PresetCollection* dependent } m_action_line->SetLabel(action_msg); - m_action_line->Wrap(UNSAVE_CHANGE_DIALOG_SCROLL_WINDOW_SIZE.x); + m_action_line->Wrap(m_content_width); - update_tree(type, presets); update_list(); } +bool UnsavedChangesDialog::value_clips(const wxString &value) const +{ + if (value.find('\n') != wxString::npos) + return true; + int w = 0, h = 0; + GetTextExtent(value, &w, &h, nullptr, nullptr, &::Label::Body_13); + return w > UNSAVE_CHANGE_DIALOG_VALUE_TEXT_WIDTH; +} + void UnsavedChangesDialog::update_list(SyncExtruderParams *params) { if (!m_scrolledWindow) { @@ -1402,199 +1546,278 @@ void UnsavedChangesDialog::update_list(SyncExtruderParams *params) return; } - std::map> class_g_list; - std::map> class_c_list; - std::vector category_list; + const std::map tab_order = build_tab_order_map(); + for (PresetItem &pi : m_presetitems) + pi.order = order_of(tab_order, pi.opt_key); - // group - for (auto i = 0; i < m_presetitems.size(); i++) { - auto name = m_presetitems[i].category_name + ":" + m_presetitems[i].group_name; - if (class_g_list.count(name) <= 0) { - std::vector vp; - vp.push_back(m_presetitems[i]); - class_g_list.emplace(name, vp); - } else { - //for (auto iter = class_g_list.begin(); iter != class_g_list.end(); iter++) iter->second.push_back(m_presetitems[i]); - class_g_list[name].push_back(m_presetitems[i]); + // Each option's per-extruder rows share one tab-order slot, so ordering by slot alone would interleave the + // extruders. Anchor each type's extruder block at its first slot, per type so no type moves above its own rows. + std::map ext_anchor; + for (const PresetItem &pi : m_presetitems) + if (pi.extruder_id > 0) { + auto it = ext_anchor.find(pi.type); + if (it == ext_anchor.end()) + ext_anchor.emplace(pi.type, pi.order); + else + it->second = std::min(it->second, pi.order); } - } - // category - for (auto i = 0; i < m_presetitems.size(); i++) { - auto name = m_presetitems[i].category_name + ":" + m_presetitems[i].group_name; - if (class_c_list.count(m_presetitems[i].category_name) <= 0) { - std::vector vp; - vp.push_back(name); - class_c_list.emplace(m_presetitems[i].category_name, vp); - category_list.push_back(m_presetitems[i].category_name); - } else { - /*for (auto iter = class_c_list.begin(); iter != class_c_list.end(); iter++) - iter->second.push_back(m_presetitems[i].group_name);*/ - //class_c_list[m_presetitems[i].category_name].push_back(m_presetitems[i].group_name); - std::vector::iterator it; - it = find(class_c_list[m_presetitems[i].category_name].begin(), class_c_list[m_presetitems[i].category_name].end(), name); - if (it == class_c_list[m_presetitems[i].category_name].end()) { - class_c_list[m_presetitems[i].category_name].push_back(name); - } - } - } + std::stable_sort(m_presetitems.begin(), m_presetitems.end(), + [&ext_anchor](const PresetItem &a, const PresetItem &b) { + const int ra = preset_type_rank(a.type), rb = preset_type_rank(b.type); + if (ra != rb) return ra < rb; + const int sa = a.extruder_id > 0 ? ext_anchor.at(a.type) : a.order; + const int sb = b.extruder_id > 0 ? ext_anchor.at(b.type) : b.order; + if (sa != sb) return sa < sb; + if (a.extruder_id != b.extruder_id) return a.extruder_id < b.extruder_id; + return a.order < b.order; + }); + auto value_tooltip = [](const wxString &full) { + const size_t cap = 500; // a whole g-code block is unreadable in a tooltip + return full.length() <= cap ? full : full.Left(cap) + "...\n\n" + _L("Click the compare button to see the full value."); + }; + + // A width of wxDefaultCoord keeps the label's natural width, which the sync dialog's fitted columns use. + auto make_label = [](wxWindow *parent, const wxString &text, const wxFont &font, int width, const wxColour &colour, + const wxString &tooltip = wxString(), long style = wxST_ELLIPSIZE_END) { + const bool natural = width == wxDefaultCoord; + auto t = new wxStaticText(parent, wxID_ANY, text, wxDefaultPosition, natural ? wxDefaultSize : wxSize(std::max(0, width), -1), style); + t->SetFont(font); + t->SetForegroundColour(colour); + t->SetToolTip(tooltip.IsEmpty() && !natural && t->GetTextExtent(text).GetWidth() > width ? text : tooltip); + return t; + }; + + // A box before a line's label: one change's own, or one ticking every change (or, in the sync dialog, copy) under it. + auto add_check_and_label = [this](wxSizer *sizer, ::CheckBox *check, wxStaticText *text, int indent) { + sizer->Add(check, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRESERVE_SPACE_EVEN_IF_HIDDEN, indent); + sizer->Add(text, 0, wxALIGN_CENTER_VERTICAL | wxLEFT, FromDIP(4)); + }; + auto add_label = [this, &add_check_and_label](wxWindow *parent, wxSizer *sizer, wxStaticText *text, int indent) -> size_t { + const size_t k = add_all_check(parent); + add_check_and_label(sizer, m_all_checks[k].first, text, indent); + return k; + }; + // The label width of a line, or the natural one in the sync dialog. + auto label_width = [params](int width) { return params ? wxDefaultCoord : width; }; + + auto make_value_col = [&](wxWindow *parent, wxString value, bool modified, bool may_clip) { + auto panel = new wxPanel(parent, wxID_ANY, wxDefaultPosition, wxSize(UNSAVE_CHANGE_DIALOG_VALUE_WIDTH, -1), wxTAB_TRAVERSAL); + auto sizer = new wxBoxSizer(wxVERTICAL); + // Before flattening, so g-code newlines survive in the tooltip. + const wxString tooltip = (may_clip && value_clips(value)) ? value_tooltip(value) : wxString(); + value.Replace("\n", " "); + value.Replace("\r", " "); + value.Trim(false); + auto text = make_label(panel, value, ::Label::Body_13, UNSAVE_CHANGE_DIALOG_VALUE_TEXT_WIDTH, + modified ? wxGetApp().get_label_clr_modified() : GREY700, tooltip, + wxST_ELLIPSIZE_END | wxALIGN_CENTRE_HORIZONTAL); + sizer->Add(text, 0, wxALIGN_CENTER | wxLEFT | wxRIGHT, 5); + panel->SetSizer(sizer); + panel->Layout(); + return panel; + }; auto m_listsizer = new wxBoxSizer(wxVERTICAL); - for (auto category : category_list) { - auto iter = class_c_list.find(category); - //category - auto panel_category = new wxPanel(m_scrolledWindow, wxID_ANY, wxDefaultPosition, wxSize(-1, UNSAVE_CHANGE_DIALOG_ITEM_HEIGHT), wxTAB_TRAVERSAL); - panel_category->SetBackgroundColour(GREY300); - wxBoxSizer *sizer_category = new wxBoxSizer(wxHORIZONTAL); - wxBoxSizer *sizer_category_v = new wxBoxSizer(wxHORIZONTAL); + auto finish_row = [&](wxWindow *panel, wxSizer *sizer) { + panel->SetSizer(sizer); + panel->Layout(); + m_listsizer->Add(panel, 0, wxEXPAND, 0); + }; - auto text_category = new wxStaticText(panel_category, wxID_ANY, iter->first, wxDefaultPosition, wxSize(-1, -1), 0); - text_category->SetFont(::Label::Head_13); - text_category->SetForegroundColour(GREY900); - text_category->Wrap(-1); + // Other preset types get no header, and so no box. + static constexpr size_t no_box = size_t(-1); + auto emit_type_header = [&](Preset::Type type) -> size_t { + wxString label; + switch (type) { + case Preset::TYPE_PRINT: label = _L("Process settings"); break; + case Preset::TYPE_FILAMENT: label = _L("Material settings"); break; + case Preset::TYPE_PRINTER: label = _L("Printer settings"); break; + default: return no_box; + } + auto panel = new wxPanel(m_scrolledWindow, wxID_ANY, wxDefaultPosition, wxSize(-1, UNSAVE_CHANGE_DIALOG_ITEM_HEIGHT), wxTAB_TRAVERSAL); + panel->SetBackgroundColour(GREY400); + auto sizer = new wxBoxSizer(wxHORIZONTAL); + const size_t all = add_label(panel, sizer, make_label(panel, label, ::Label::Head_16, + m_content_width - UNSAVE_CHANGE_DIALOG_TYPE_INDENT - FromDIP(8) - UNSAVE_CHANGE_DIALOG_CHECK_WIDTH, GREY900), + UNSAVE_CHANGE_DIALOG_TYPE_INDENT); + finish_row(panel, sizer); + return all; + }; - sizer_category_v->Add(text_category, 0, wxALIGN_CENTER | wxLEFT, 23); + auto emit_category = [&](const wxString &category_name) { + auto panel = new wxPanel(m_scrolledWindow, wxID_ANY, wxDefaultPosition, wxSize(-1, UNSAVE_CHANGE_DIALOG_ITEM_HEIGHT), wxTAB_TRAVERSAL); + panel->SetBackgroundColour(GREY300); + auto sizer = new wxBoxSizer(wxHORIZONTAL); + const size_t all = add_label(panel, sizer, make_label(panel, category_name, ::Label::Head_13, + label_width(m_content_width - UNSAVE_CHANGE_DIALOG_CATEGORY_INDENT - FromDIP(8) - UNSAVE_CHANGE_DIALOG_CHECK_WIDTH), GREY900), + UNSAVE_CHANGE_DIALOG_CATEGORY_INDENT); + finish_row(panel, sizer); + return all; + }; - sizer_category->Add(sizer_category_v, 1, wxEXPAND, 0); + auto emit_group = [&](const wxString &group_name) { + auto panel = new wxWindow(m_scrolledWindow, -1, wxDefaultPosition, wxSize(-1, UNSAVE_CHANGE_DIALOG_ITEM_HEIGHT)); + panel->SetBackgroundColour(GREY200); + auto sizer = new wxBoxSizer(wxHORIZONTAL); + auto panel_left = new wxPanel(panel, wxID_ANY, wxDefaultPosition, wxSize(m_first_value_width, -1), wxTAB_TRAVERSAL); + panel_left->SetBackgroundColour(GREY200); + auto left_sizer = new wxBoxSizer(wxHORIZONTAL); + const size_t all = add_label(panel_left, left_sizer, make_label(panel_left, group_name, ::Label::Head_13, + label_width(m_first_value_width - UNSAVE_CHANGE_DIALOG_GROUP_INDENT - FromDIP(8) - UNSAVE_CHANGE_DIALOG_CHECK_WIDTH), GREY700), + UNSAVE_CHANGE_DIALOG_GROUP_INDENT); + panel_left->SetSizer(left_sizer); + panel_left->Layout(); + sizer->Add(panel_left, 0, wxALIGN_CENTER, 0); + if (params) + m_sync_columns[0].push_back(panel_left); + finish_row(panel, sizer); + return all; + }; - panel_category->SetSizer(sizer_category); - panel_category->Layout(); - m_listsizer->Add(panel_category, 0, wxEXPAND, 0); + auto emit_option = [&](const PresetItem &data, size_t type_all, size_t category_all, size_t group_all) { + auto panel = new wxWindow(m_scrolledWindow, -1, wxDefaultPosition, wxSize(-1, UNSAVE_CHANGE_DIALOG_ITEM_HEIGHT)); + panel->SetBackgroundColour(GREY200); + auto sizer = new wxBoxSizer(wxHORIZONTAL); - /*auto item_line = new wxStaticLine(list, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL); - item_line->SetForegroundColour(wxColour(206, 206, 206)); - item_line->SetBackgroundColour(wxColour(206, 206, 206)); - sizer_list->Add(item_line, 0, wxALL, 0); */ - - // isset group - for (auto i = 0; i < iter->second.size(); i++) { - auto gname = iter->second[i]; - for (auto g = 0; g < class_g_list[gname].size(); g++) { - - //first group - if (g == 0) { - auto panel_item = new wxWindow(m_scrolledWindow, -1, wxDefaultPosition, wxSize(-1, UNSAVE_CHANGE_DIALOG_ITEM_HEIGHT)); - panel_item->SetBackgroundColour(GREY200); - - wxBoxSizer *sizer_item = new wxBoxSizer(wxHORIZONTAL); - - auto panel_left = new wxPanel(panel_item, wxID_ANY, wxDefaultPosition, wxSize(UNSAVE_CHANGE_DIALOG_FIRST_VALUE_WIDTH, -1), wxTAB_TRAVERSAL); - panel_left->SetBackgroundColour(GREY200); - - wxBoxSizer *sizer_left_v = new wxBoxSizer(wxVERTICAL); - - auto text_left = new wxStaticText(panel_left, wxID_ANY, class_g_list[gname][0].group_name, wxDefaultPosition, wxSize(-1, -1), 0); - text_left->SetFont(::Label::Head_13); - text_left->Wrap(-1); - text_left->SetForegroundColour(GREY700); - - sizer_left_v->Add(text_left, 0, wxLEFT, 37); - - panel_left->SetSizer(sizer_left_v); - panel_left->Layout(); - sizer_item->Add(panel_left, 0, wxALIGN_CENTER, 0); - - panel_item->SetSizer(sizer_item); - panel_item->Layout(); - m_listsizer->Add(panel_item, 0, wxEXPAND, 0); - } - - auto data = class_g_list[gname][g]; - - auto panel_item = new wxWindow(m_scrolledWindow, -1, wxDefaultPosition, wxSize(-1, UNSAVE_CHANGE_DIALOG_ITEM_HEIGHT)); - panel_item->SetBackgroundColour(GREY200); - - wxBoxSizer *sizer_item = new wxBoxSizer(wxHORIZONTAL); - - auto panel_left = new wxPanel(panel_item, wxID_ANY, wxDefaultPosition, wxSize(UNSAVE_CHANGE_DIALOG_FIRST_VALUE_WIDTH , -1), wxTAB_TRAVERSAL); - panel_left->SetBackgroundColour(GREY200); - - wxBoxSizer *sizer_left_v = new wxBoxSizer(wxVERTICAL); - - auto text_left = new wxStaticText(panel_left, wxID_ANY, data.option_name, wxDefaultPosition, wxSize(-1, -1), 0); - text_left->SetFont(::Label::Body_13); - text_left->Wrap(-1); - text_left->SetForegroundColour(GREY700); - - sizer_left_v->Add(text_left, 0, wxLEFT, 51 ); - - panel_left->SetSizer(sizer_left_v); - panel_left->Layout(); - sizer_item->Add(panel_left, 0, wxALIGN_CENTER, 0); - - auto panel_oldv = new wxPanel(panel_item, wxID_ANY, wxDefaultPosition, wxSize(UNSAVE_CHANGE_DIALOG_VALUE_WIDTH, -1), wxTAB_TRAVERSAL); - wxBoxSizer *sizer_old_v = new wxBoxSizer(wxVERTICAL); - - - data.old_value = subreplace(data.old_value.ToStdString(), "\n", " "); - auto text_oldv = new wxStaticText(panel_oldv, wxID_ANY, data.old_value, wxDefaultPosition, wxDefaultSize, wxST_ELLIPSIZE_END); - text_oldv->SetFont(::Label::Body_13); - text_oldv->Wrap(-1); - text_oldv->SetForegroundColour(params && params->left_to_right ? wxGetApp().get_label_clr_modified() : GREY700); - sizer_old_v->Add(text_oldv, 0, wxALIGN_CENTER|wxLEFT|wxRIGHT, 5); - - panel_oldv->SetSizer(sizer_old_v); - panel_oldv->Layout(); - sizer_item->Add(panel_oldv, 0, wxALIGN_CENTER, 0); - - auto panel_newv = new wxPanel(panel_item, wxID_ANY, wxDefaultPosition, wxSize(UNSAVE_CHANGE_DIALOG_VALUE_WIDTH, -1), wxTAB_TRAVERSAL); - wxBoxSizer *sizer_new_v = new wxBoxSizer(wxVERTICAL); - - data.new_value = subreplace(data.new_value.ToStdString(), "\n", " "); - auto text_newv = new wxStaticText(panel_newv, wxID_ANY, data.new_value, wxDefaultPosition, wxDefaultSize, wxST_ELLIPSIZE_END); - text_newv->SetFont(::Label::Body_13); - text_newv->Wrap(-1); - text_newv->SetForegroundColour(params && !params->left_to_right ? wxGetApp().get_label_clr_modified() : GREY700); - - sizer_new_v->Add(text_newv, 0, wxALIGN_CENTER|wxLEFT|wxRIGHT, 5); - - panel_newv->SetSizer(sizer_new_v); - panel_newv->Layout(); - sizer_item->Add(panel_newv, 0, wxALIGN_CENTER, 0); - - panel_item->SetSizer(sizer_item); - panel_item->Layout(); - m_listsizer->Add(panel_item, 0, wxEXPAND, 0); - - - - ////if (g == class_g_list[gname].size() - 1) { - // auto item_line = new wxStaticLine(list, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL); - // item_line->SetForegroundColour(wxColour(206, 206, 206)); - // item_line->SetBackgroundColour(wxColour(206, 206, 206)); - // sizer_list->Add(item_line, 0, wxALL, 0); - ////} + auto panel_left = new wxPanel(panel, wxID_ANY, wxDefaultPosition, wxSize(m_first_value_width, -1), wxTAB_TRAVERSAL); + panel_left->SetBackgroundColour(GREY200); + auto left_sizer = new wxBoxSizer(wxHORIZONTAL); + const int text_w = m_first_value_width - UNSAVE_CHANGE_DIALOG_OPTION_INDENT - FromDIP(8) - UNSAVE_CHANGE_DIALOG_CHECK_WIDTH - + (data.has_icon ? UNSAVE_CHANGE_DIALOG_ICON_WIDTH : 0); + auto label = make_label(panel_left, data.option_name, ::Label::Body_13, label_width(text_w), GREY700); + size_t row_all = 0; + if (params) + row_all = add_label(panel_left, left_sizer, label, UNSAVE_CHANGE_DIALOG_OPTION_INDENT); + else { + // The change's own box. Extruder count has none: the per-extruder values follow it. + auto check = new ::CheckBox(panel_left); + add_check_and_label(left_sizer, check, label, UNSAVE_CHANGE_DIALOG_OPTION_INDENT); + if (data.opt_key == "extruders_count") + check->Hide(); + else { + check->SetValue(true); + check->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent &e) { update_all_checks(); e.Skip(); }); + m_option_checks.emplace_back(check, data.type, data.opt_key); + for (size_t k : {type_all, category_all, group_all}) + if (k != no_box) + m_all_checks[k].second.push_back(check); } } + if (data.has_icon) { + auto compare_btn = new Button(panel_left, "", "compare", 0, 16); + compare_btn->SetStyle(ButtonStyle::Regular, ButtonType::Icon); + compare_btn->SetPaddingSize(FromDIP(wxSize(1, 1))); + compare_btn->SetMinSize(FromDIP(wxSize(20, 20))); + compare_btn->SetSize(FromDIP(wxSize(20, 20))); + compare_btn->SetCanFocus(false); + compare_btn->SetToolTip(_L("Compare the full values")); + compare_btn->Bind(wxEVT_BUTTON, [this, data](wxCommandEvent &) { + FullCompareDialog(data.option_name, data.old_value, data.new_value, + static_oldv_title->GetLabel(), static_newv_title->GetLabel()).ShowModal(); + }); + left_sizer->Add(compare_btn, 0, wxLEFT | wxALIGN_CENTER_VERTICAL, FromDIP(4)); + } + panel_left->SetSizer(left_sizer); + panel_left->Layout(); + sizer->Add(panel_left, 0, wxALIGN_CENTER, 0); + + if (params) { + m_sync_columns[0].push_back(panel_left); + // A target whose value differs from the source gets a checkbox for copying it. + DynamicPrintConfig value_config; + value_config.set_key_value(data.opt_key, params->config->option(data.opt_key)->clone()); + const auto values = dynamic_cast(params->config->option(data.opt_key))->vserialize(); + const auto &positions = params->positions.at(data.opt_key); + const int from = positions.index[params->source]; + for (int i = 0; i < int(params->titles.size()); ++i) { + // A column without a value of this option, e.g. an extruder without its nozzle variant, stays empty. + const int index = positions.index[i]; + bool differs = false; + for (int s = 0; index >= 0 && s < positions.stride; ++s) + differs |= values[from + s] != values[index + s]; + + auto cell = new wxPanel(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); + cell->SetBackgroundColour(GREY200); + m_sync_columns[i + 1].push_back(cell); + auto cell_sizer = new wxBoxSizer(wxHORIZONTAL); + cell_sizer->AddSpacer(UNSAVE_CHANGE_DIALOG_SYNC_CELL_PADDING); + if (i != params->source) { + // A target that already has the value keeps the box's space, so its column stays aligned. + auto check = new ::CheckBox(cell); + cell_sizer->Add(check, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxRESERVE_SPACE_EVEN_IF_HIDDEN, FromDIP(4)); + if (differs) { + check->SetValue(true); + check->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent &e) { update_all_checks(); e.Skip(); }); + m_sync_checks.emplace_back(check, data.opt_key, index, i); + for (size_t k : {category_all, group_all, row_all}) + m_all_checks[k].second.push_back(check); + } else + check->Hide(); + } + if (index >= 0) + cell_sizer->Add(make_label(cell, get_string_value(data.opt_key + "#" + std::to_string(index), value_config), ::Label::Body_13, + wxDefaultCoord, i == params->source ? wxGetApp().get_label_clr_modified() : GREY700), + 0, wxALIGN_CENTER_VERTICAL); + cell->SetSizer(cell_sizer); + cell->Layout(); + sizer->Add(cell, 0, wxALIGN_CENTER, 0); + } + } else { + sizer->Add(make_value_col(panel, data.old_value, false, data.has_icon), 0, wxALIGN_CENTER, 0); + sizer->Add(make_value_col(panel, data.new_value, false, data.has_icon), 0, wxALIGN_CENTER, 0); + } + + finish_row(panel, sizer); + }; + + // Group by key, not adjacency: per-variant tags make one category recur at non-adjacent tab slots, so a walk that + // starts a section whenever the name changes would duplicate it. + struct Section { Preset::Type type; wxString name; std::vector group_keys; }; + std::map sections; // cat_key -> section + std::vector section_order; // cat_keys in first-encounter order + std::map> rows_by_group; // grp_key -> its rows, in tab order + for (const PresetItem &pi : m_presetitems) { + const wxString ckey = preset_item_cat_key(pi); + const wxString gkey = preset_item_grp_key(pi); + auto section = sections.try_emplace(ckey); + if (section.second) { + section.first->second = {pi.type, pi.category_name, {}}; + section_order.push_back(ckey); + } + auto group = rows_by_group.try_emplace(gkey); + if (group.second) + section.first->second.group_keys.push_back(gkey); + group.first->second.push_back(pi); + } + + Preset::Type shown_type = Preset::TYPE_INVALID; + size_t type_all = 0; + for (const wxString &ckey : section_order) { + const Section §ion = sections.at(ckey); + // The sync dialog copies within one tab, so it needs no type header. + if (section.type != shown_type && !params) { + shown_type = section.type; + type_all = emit_type_header(section.type); + } + const size_t category_all = emit_category(section.name); + for (const wxString &gkey : section.group_keys) { + const std::vector &rows = rows_by_group.at(gkey); + const size_t group_all = emit_group(rows.front().group_name); + for (const PresetItem &pi : rows) + emit_option(pi, type_all, category_all, group_all); + } } - m_scrolledWindow->SetSizer(m_listsizer); - m_scrolledWindow->Layout(); - /*wxSize text_size = m_action_line->GetTextExtent(m_action_line->GetLabel()); - int width = UNSAVE_CHANGE_DIALOG_ACTION_LINE_SIZE.GetWidth(); - // +2: Ensure that there is at least one line and that the content contains '\n' - int rows = int(text_size.GetWidth() / width) + 2; - int height = rows * text_size.GetHeight(); - m_action_line->SetMinSize(wxSize(width, height)); - m_action_line->Wrap(UNSAVE_CHANGE_DIALOG_ACTION_LINE_SIZE.GetWidth());*/ - Layout(); - Fit(); + m_scrolledWindow->SetSizer(m_listsizer); + m_scrolledWindow->Layout(); + Layout(); + Fit(); } -std::string UnsavedChangesDialog::subreplace(std::string resource_str, std::string sub_str, std::string new_str) -{ - std::string dst_str = resource_str; - std::string::size_type pos = 0; - while ((pos = dst_str.find(sub_str)) != std::string::npos) - { - dst_str.replace(pos, sub_str.length(), new_str); - } - return dst_str; -} - -void UnsavedChangesDialog::update_tree(Preset::Type type, DynamicConfig * config, int from, int to) +void UnsavedChangesDialog::update_tree(Preset::Type type, DynamicConfig *config) { Search::SettingsIndex &index = wxGetApp().sidebar().settings_index(); index.sort_options_by_key(); @@ -1610,12 +1833,57 @@ void UnsavedChangesDialog::update_tree(Preset::Type type, DynamicConfig * config option.category_local = (def && !def->category.empty() ? Tab::translate_category(from_u8(def->category), type) : _L("Others")).ToStdWstring(); } - auto category = option.category_local; - auto opt = dynamic_cast(config->option(opt_key)); - std::string value_from = opt->vserialize()[from]; - std::string value_to = opt->vserialize()[to]; - PresetItem pi = {type, opt_key, category, option.group_local, option.label_local, into_u8(value_from), into_u8(value_to)}; - m_presetitems.push_back(pi); + // update_list() reads the values of every extruder from the config. + m_presetitems.push_back({type, opt_key, option.category_local, option.group_local, option.label_local, {}, {}}); + } + + index.sort_options_by_label(); +} + +std::vector> UnsavedChangesDialog::get_sync_selection() const +{ + std::vector> selection; + for (const auto &[check, opt_key, index, column] : m_sync_checks) + if (check->GetValue()) + selection.emplace_back(opt_key, index); + return selection; +} + +size_t UnsavedChangesDialog::add_all_check(wxWindow *parent) +{ + const size_t k = m_all_checks.size(); + m_all_checks.push_back({new ::CheckBox(parent), {}}); + m_all_checks[k].first->Bind(wxEVT_TOGGLEBUTTON, [this, k](wxCommandEvent &e) { + for (::CheckBox *cell : m_all_checks[k].second) + cell->SetValue(m_all_checks[k].first->GetValue()); + update_all_checks(); + e.Skip(); + }); + return k; +} + +std::vector UnsavedChangesDialog::options_by_selection(const Preset::Type *type, bool selected) const +{ + std::vector options; + for (const PresetItem &item : m_presetitems) { + if (type != nullptr && item.type != *type) + continue; + auto check = std::find_if(m_option_checks.begin(), m_option_checks.end(), [&item](const auto &option) { + return std::get<1>(option) == item.type && std::get<2>(option) == item.opt_key; + }); + if ((check == m_option_checks.end() || std::get<0>(*check)->GetValue()) == selected) + options.push_back(item.opt_key); + } + return options; +} + +void UnsavedChangesDialog::update_all_checks() +{ + for (const auto &[all, cells] : m_all_checks) { + const auto checked = size_t(std::count_if(cells.begin(), cells.end(), [](const ::CheckBox *cell) { return cell->GetValue(); })); + // A partly ticked box holds false, so clicking it ticks everything under it. + all->SetValue(!cells.empty() && checked == cells.size()); + all->SetHalfChecked(checked > 0 && checked < cells.size()); } } @@ -1678,6 +1946,21 @@ void UnsavedChangesDialog::update_tree(Preset::Type type, PresetCollection* pres auto extruder_variant = dynamic_cast(new_config.option(variant_key)); auto extruder_id = dynamic_cast(new_config.option(id_key)); + auto extruder_variant_of = [type](const std::string& pure_key, int index) { + return type == Preset::TYPE_PRINTER && printer_options_with_variant_2.count(pure_key) > 0 ? index / 2 : index; + }; + + std::map dirty_variants_per_option; + std::map, int> dirty_variants_per_extruder; + for (const std::string& opt_key : dirty_options) { + const std::string pure_key = get_pure_opt_key(opt_key); + ++dirty_variants_per_option[pure_key]; + const size_t hash_pos = opt_key.find('#'); + const int variant = hash_pos == std::string::npos ? -1 : extruder_variant_of(pure_key, std::atoi(opt_key.c_str() + hash_pos + 1)); + if (extruder_id && variant >= 0 && variant < extruder_id->size()) + ++dirty_variants_per_extruder[{pure_key, extruder_id->values[variant]}]; + } + for (const std::string& opt_key : dirty_options) { int variant_index = -2; const Search::Option &option = index.get_option(opt_key, type, variant_index); @@ -1689,22 +1972,31 @@ void UnsavedChangesDialog::update_tree(Preset::Type type, PresetCollection* pres } wxString category = option.category_local; wxString label = option.label_local; - if (type == Preset::TYPE_PRINTER && variant_index >= 0 && - printer_options_with_variant_2.count(get_pure_opt_key(opt_key)) > 0) { - variant_index /= 2; - } + // A multi-extruder printer registers its per-extruder options under "Extruder N". + const bool on_extruder_page = option.category.compare(0, 9, L"Extruder ") == 0; + int row_extruder_id = on_extruder_page ? int(std::wcstol(option.category.c_str() + 9, nullptr, 10)) : 0; + if (variant_index >= 0) + variant_index = extruder_variant_of(get_pure_opt_key(opt_key), variant_index); if (variant_index >= 0 && extruder_variant && variant_index < extruder_variant->size()) { // Orca: Match the untranslated category and use the same extruder names as the printer tabs. - if (option.category.compare(0, 9, L"Extruder ") == 0) + if (on_extruder_page) category = _L("Extruder"); - wxString variant_label = L(extruder_variant->values[variant_index]); + const bool ambiguous = dirty_variants_per_option[get_pure_opt_key(opt_key)] > 1; + wxString variant_label = from_u8(extruder_variant->values[variant_index]); // Orca: An extruder name only disambiguates variants on printers with multiple extruders. - if (multiple_extruders && extruder_id && variant_index < extruder_id->size() && extruder_id->values[variant_index] > 0) { - const wxString extruder_name = Tab::translate_category( - wxString::Format("Extruder %d", extruder_id->values[variant_index]), Preset::TYPE_PRINTER); - variant_label = extruder_name + " (" + variant_label + ")"; + const bool named_extruder = multiple_extruders && extruder_id && variant_index < extruder_id->size() && extruder_id->values[variant_index] > 0; + if (named_extruder) { + const int id = extruder_id->values[variant_index]; + const wxString extruder_name = Tab::translate_category(wxString::Format("Extruder %d", id), Preset::TYPE_PRINTER); + const bool several_dirty_on_extruder = dirty_variants_per_extruder[{get_pure_opt_key(opt_key), id}] > 1; + variant_label = several_dirty_on_extruder ? extruder_name + " (" + variant_label + ")" : extruder_name; + if (on_extruder_page) + row_extruder_id = id; } - category = variant_label + ": " + category; + if (on_extruder_page && named_extruder) + category = variant_label; + else if (ambiguous) + category = variant_label + ": " + category; } /*m_tree->Append(opt_key, type, option.category_local, option.group_local, option.label_local, @@ -1714,6 +2006,8 @@ void UnsavedChangesDialog::update_tree(Preset::Type type, PresetCollection* pres //PresetItem pi = {opt_key, type, 1983}; //m_presetitems.push_back() PresetItem pi = {type, opt_key, category, option.group_local, label, get_string_value(opt_key, old_config), get_string_value(opt_key, new_config)}; + pi.has_icon = value_clips(pi.old_value) || value_clips(pi.new_value); + pi.extruder_id = row_extruder_id; m_presetitems.push_back(pi); } @@ -1806,22 +2100,22 @@ FullCompareDialog::FullCompareDialog(const wxString& option_name, const wxString std::set_difference(old_set.begin(), old_set.end(), new_set.begin(), new_set.end(), std::inserter(old_new_diff_set, old_new_diff_set.begin())); std::set_difference(new_set.begin(), new_set.end(), old_set.begin(), old_set.end(), std::inserter(new_old_diff_set, new_old_diff_set.begin())); - auto add_value = [grid_sizer, border, this](wxString label, const std::set& diff_set, bool is_colored = false) { + auto add_value = [grid_sizer, border, this](wxString label, const std::set& diff_set) { wxTextCtrl* text = new wxTextCtrl(this, wxID_ANY, label, wxDefaultPosition, wxSize(400, 400), wxTE_MULTILINE | wxTE_READONLY | wxBORDER_DEFAULT | wxTE_RICH); wxGetApp().UpdateDarkUI(text); - text->SetStyle(0, label.Len(), wxTextAttr(is_colored ? wxColour(orange) : wxNullColour, wxNullColour, this->GetFont())); + text->SetStyle(0, label.Len(), wxTextAttr(wxNullColour, wxNullColour, this->GetFont())); for (const wxString& str : diff_set) { int pos = label.First(str); if (pos == wxNOT_FOUND) continue; - text->SetStyle(pos, pos + (int)str.Len(), wxTextAttr(is_colored ? wxColour(orange) : wxNullColour, wxNullColour, this->GetFont().Bold())); + text->SetStyle(pos, pos + (int)str.Len(), wxTextAttr(wxGetApp().get_label_clr_modified(), wxNullColour, this->GetFont().Bold())); } grid_sizer->Add(text, 1, wxALL | wxEXPAND, border); }; add_value(old_value, old_new_diff_set); - add_value(new_value, new_old_diff_set, true); + add_value(new_value, new_old_diff_set); sizer->Add(grid_sizer, 1, wxEXPAND); @@ -1862,7 +2156,7 @@ void DiffPresetDialog::create_presets_sizer() { m_presets_sizer = new wxBoxSizer(wxVERTICAL); - for (auto new_type : { Preset::TYPE_PRINTER, Preset::TYPE_FILAMENT, Preset::TYPE_SLA_MATERIAL, Preset::TYPE_PRINT, Preset::TYPE_SLA_PRINT }) + for (auto new_type : PRESET_TYPE_ORDER) { const PresetCollection* collection = get_preset_collection(new_type); wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL); @@ -2179,6 +2473,7 @@ void DiffPresetDialog::update_tree() m_tree->Clear(); wxString bottom_info = ""; bool show_tree = false; + const std::map tab_order = build_tab_order_map(); for (auto preset_combos : m_preset_combos) { @@ -2250,6 +2545,10 @@ void DiffPresetDialog::update_tree() get_category_icon("Basic information")); } + std::stable_sort(dirty_options.begin(), dirty_options.end(), [&tab_order](const std::string& a, const std::string& b) { + return order_of(tab_order, a) < order_of(tab_order, b); + }); + for (const std::string& opt_key : dirty_options) { wxString left_val = get_string_value(opt_key, left_config); wxString right_val = get_string_value(opt_key, right_congig); diff --git a/src/slic3r/GUI/UnsavedChangesDialog.hpp b/src/slic3r/GUI/UnsavedChangesDialog.hpp index 9aaf75b6fc..be65c28cfd 100644 --- a/src/slic3r/GUI/UnsavedChangesDialog.hpp +++ b/src/slic3r/GUI/UnsavedChangesDialog.hpp @@ -9,8 +9,11 @@ #include "libslic3r/Config.hpp" #include "libslic3r/PrintConfig.hpp" #include +#include #include +#include #include +#include #include #include #include @@ -29,6 +32,7 @@ class ScalableButton; class wxStaticText; +class CheckBox; namespace Slic3r { namespace GUI{ @@ -276,6 +280,9 @@ struct PresetItem wxString option_name; wxString old_value; wxString new_value; + int order{ INT_MAX }; // position on the settings pages; rows on no page sort last + int extruder_id{ 0 }; // extruder of a per-extruder page row, else 0 + bool has_icon{ false }; // a value is too long to show, so the row has a compare button }; @@ -285,12 +292,11 @@ protected: wxPanel * m_top_line; wxPanel * m_panel_tab; wxPanel * m_table_top; - wxPanel * title_block_middle; - wxPanel * title_block_right; wxStaticText *static_temp_title; - wxStaticText *static_oldv_title; - wxStaticText *static_newv_title; + wxStaticText *static_oldv_title { nullptr }; + wxStaticText *static_newv_title { nullptr }; wxBoxSizer * m_sizer_bottom; + int m_value_width { 0 }; //DiffViewCtrl* m_tree { nullptr }; Button* m_save_btn { nullptr }; @@ -301,6 +307,9 @@ protected: wxStaticText* m_info_line { nullptr }; wxScrolledWindow* m_scrolledWindow{ nullptr }; + int m_first_value_width { 0 }; + int m_content_width { 0 }; + bool m_has_long_strings { false }; int m_save_btn_id { wxID_ANY }; int m_move_btn_id { wxID_ANY }; @@ -333,6 +342,15 @@ public: private: std::vector m_presetitems; + std::vector> m_sync_checks; // checkbox, option, value position and column of each copy + std::vector> m_option_checks; // checkbox, preset type and option of each change + std::vector>> m_all_checks; // a box ticking several changes or copies, and those + std::vector> m_sync_columns; // the label column, then one per extruder; the header window first + size_t add_all_check(wxWindow *parent); + void update_all_checks(); + // The options of the changed rows of the type (any type for nullptr) whose box is ticked, or not. A row without + // a box is always selected. + std::vector options_by_selection(const Preset::Type *type, bool selected) const; // preset names which are modified in SavePresetDialog and related types std::vector names_and_types; //std::vector> names_and_types; @@ -354,18 +372,23 @@ public: struct SyncExtruderParams { - DynamicConfig *config; - int from; - int to; - bool left_to_right; - NozzleVolumeType nozzle; + // Where an option's values are in each column, -1 for a column without one, and how many each holds. + struct Positions + { + int stride; + std::vector index; + }; + DynamicConfig *config; // the options to copy, with their values before the copy + std::vector titles; // the source and targets, in extruder (or nozzle variant) order + int source; // the source's column + std::map positions; // per option }; // show unsaved changes when preset is switching UnsavedChangesDialog(Preset::Type type, PresetCollection* dependent_presets, const std::string& new_selected_preset, bool no_transfer = false); // show unsaved changes for all another cases UnsavedChangesDialog(const wxString& caption, const wxString& header, const std::string& app_config_key, int act_buttons); - UnsavedChangesDialog(const wxString &caption, const wxString &header, DynamicConfig *config, int from, int to, bool left_to_right, NozzleVolumeType nozzle); + UnsavedChangesDialog(const wxString &caption, const wxString &header, Preset::Type type, SyncExtruderParams params); ~UnsavedChangesDialog() override = default; int ShowModal() override; @@ -373,15 +396,18 @@ public: void build(Preset::Type type, PresetCollection *dependent_presets, const std::string &new_selected_preset, const wxString &header = ""); void update(Preset::Type type, PresetCollection* dependent_presets, const std::string& new_selected_preset, const wxString& header); void update_list(SyncExtruderParams *params = nullptr); - std::string subreplace(std::string resource_str, std::string sub_str, std::string new_str); + bool value_clips(const wxString &value) const; void update_tree(Preset::Type type, PresetCollection *presets); - void update_tree(Preset::Type type, DynamicConfig *config, int from, int to); + void update_tree(Preset::Type type, DynamicConfig *config); void show_info_line(Action action, std::string preset_name = ""); void update_config(Action action); void close(Action action); // save information about saved presets and their types to names_and_types and show SavePresetDialog to set the names for new presets bool save(PresetCollection* dependent_presets, bool show_save_preset_dialog = true); + // Option and variant column of each ticked copy in the extruder sync dialog. + std::vector> get_sync_selection() const; + bool save_preset() const { return m_exit_action == Action::Save; } bool transfer_changes() const { return m_exit_action == Action::Transfer; } bool discard() const { return m_exit_action == Action::Discard; } @@ -394,30 +420,10 @@ public: // short version of the previous function, for the case, when just one preset is modified std::string get_preset_name() { return names_and_types[0].name; } - std::vector get_unselected_options(Preset::Type type) { /* return m_tree->options(type, false);*/return std::vector();} - std::vector get_selected_options (Preset::Type type) { - //return m_tree->options(type, true); - std::vector tmp; - for (int i = 0; i < m_presetitems.size(); i++) { - if (m_presetitems[i].type == type) { - tmp.push_back(m_presetitems[i].opt_key); - } - } - - return tmp; - } - std::vector get_selected_options() { - //return m_tree->selected_options(); - - std::vector tmp; - for (int i = 0; i < m_presetitems.size(); i++) - { - tmp.push_back(m_presetitems[i].opt_key); - } - - return tmp; - } - bool has_unselected_options() { /*return m_tree->has_unselected_options();*/return false;} + std::vector get_unselected_options(Preset::Type type) { return options_by_selection(&type, false); } + std::vector get_selected_options (Preset::Type type) { return options_by_selection(&type, true); } + std::vector get_selected_options() { return options_by_selection(nullptr, true); } + bool has_unselected_options() { return !options_by_selection(nullptr, false).empty(); } protected: void on_dpi_changed(const wxRect& suggested_rect) override; diff --git a/tests/libslic3r/test_parameter_utils.cpp b/tests/libslic3r/test_parameter_utils.cpp index a1a436eb83..e247200345 100644 --- a/tests/libslic3r/test_parameter_utils.cpp +++ b/tests/libslic3r/test_parameter_utils.cpp @@ -1,8 +1,11 @@ #include +#include #include +#include "libslic3r/Config.hpp" #include "libslic3r/ParameterUtils.hpp" +#include "libslic3r/PrintConfig.hpp" using namespace Slic3r; @@ -47,3 +50,44 @@ TEST_CASE("A sequence count without matching values gives no custom sequence", " CHECK(get_other_layers_print_sequence(-1, std::vector{1, 5, 2}).empty()); CHECK(get_other_layers_print_sequence(1, {}).empty()); } + +TEST_CASE("A process gets columns for tools added to the printer, copied from tool 1", "[ParameterUtils]") +{ + const std::string standard = "Direct Drive Standard", high_flow = "Direct Drive High Flow"; + // Two tools with a Standard and a High Flow column each, as a toolchanger profile ships them. + DynamicPrintConfig process; + process.option("print_extruder_id", true)->values = {1, 1, 2, 2}; + process.option("print_extruder_variant", true)->values = {standard, high_flow, standard, high_flow}; + process.option("outer_wall_speed", true)->values = {100., 200., 110., 210.}; + process.option("inner_wall_speed", true)->values = {50.}; + // The printer's extruder count raised to three. + DynamicPrintConfig printer; + printer.option("extruder_variant_list", true)->values = {standard + "," + high_flow, standard + "," + high_flow, + standard + "," + high_flow}; + + REQUIRE(add_process_columns_for_new_tools(process, printer)); + CHECK(process.option("print_extruder_id")->values == std::vector{1, 1, 2, 2, 3, 3}); + CHECK(process.option("print_extruder_variant")->values == + std::vector{standard, high_flow, standard, high_flow, standard, high_flow}); + // Each new column copies tool 1's column of its variant. + CHECK(process.option("outer_wall_speed")->values == std::vector{100., 200., 110., 210., 100., 200.}); + // A single value already serves every column. + CHECK(process.option("inner_wall_speed")->values == std::vector{50.}); + // Every tool has its columns now. + CHECK_FALSE(add_process_columns_for_new_tools(process, printer)); + CHECK(process.option("print_extruder_id")->values.size() == 6); +} + +TEST_CASE("A process with one column keeps it shared by every tool", "[ParameterUtils]") +{ + DynamicPrintConfig process; + process.option("print_extruder_id", true)->values = {1}; + process.option("print_extruder_variant", true)->values = {"Direct Drive Standard"}; + process.option("outer_wall_speed", true)->values = {30.}; + DynamicPrintConfig printer; + printer.option("extruder_variant_list", true)->values = {"Direct Drive Standard", "Direct Drive Standard"}; + + CHECK_FALSE(add_process_columns_for_new_tools(process, printer)); + CHECK(process.option("print_extruder_id")->values == std::vector{1}); + CHECK(process.option("outer_wall_speed")->values == std::vector{30.}); +} From ec1b800e23b531aa8c4cd6f25d6e29b507b794d1 Mon Sep 17 00:00:00 2001 From: Rodrigo Faselli <162915171+RF47@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:32:14 -0300 Subject: [PATCH 08/26] Round the corners of input boxes and dropdowns (#17393) Co-authored-by: Ian Bassi <12130714+ianalexis@users.noreply.github.com> --- .../references/painting-custom-widgets.md | 6 +++++ src/slic3r/GUI/Widgets/SpinInput.cpp | 23 +++++++++---------- src/slic3r/GUI/Widgets/SpinInput.hpp | 2 -- src/slic3r/GUI/Widgets/StaticBox.cpp | 7 ++++++ src/slic3r/GUI/Widgets/StaticBox.hpp | 8 +++++++ src/slic3r/GUI/Widgets/TempInput.cpp | 4 +++- src/slic3r/GUI/Widgets/TextInput.cpp | 10 +++----- src/slic3r/GUI/Widgets/TextInput.hpp | 2 -- 8 files changed, 38 insertions(+), 24 deletions(-) diff --git a/.claude/skills/orca-wxwidgets/references/painting-custom-widgets.md b/.claude/skills/orca-wxwidgets/references/painting-custom-widgets.md index 4f047042c3..7563d8db94 100644 --- a/.claude/skills/orca-wxwidgets/references/painting-custom-widgets.md +++ b/.claude/skills/orca-wxwidgets/references/painting-custom-widgets.md @@ -739,6 +739,12 @@ plain window. static `GetParentBackgroundColor(wxWindow*)`. Protected members: `radius`, `border_width`, `top_margin`, `border_style`, `state_handler`, `border_color`, `background_color`, `background_color2`, `badge`. +- **Input corner radius:** the boxed inputs (`TextInput` and so `ComboBox`, `SpinInput`, `TempInput`) + share `StaticBox::InputCornerRadius` (DIP). Their constructor sets the protected `input_corner_radius` + flag, and `Create()` and `Rescale()` call `apply_input_corner_radius()`, which re-applies + `FromDIP(InputCornerRadius)` at the current DPI. `SetCornerRadius()` clears the flag, so an explicit + radius (`0` for square cells in tables and grids) survives a DPI change. A new boxed input follows + the same three steps. - **`SetBackgroundColor` ≠ wx `SetBackgroundColour`.** The former sets the `StateColor` fill that `doRender` paints; the latter is the wx window colour that the erase pass uses outside the rounded rect. They are different things on purpose. diff --git a/src/slic3r/GUI/Widgets/SpinInput.cpp b/src/slic3r/GUI/Widgets/SpinInput.cpp index 89c1132f7e..fc7239fa75 100644 --- a/src/slic3r/GUI/Widgets/SpinInput.cpp +++ b/src/slic3r/GUI/Widgets/SpinInput.cpp @@ -4,6 +4,7 @@ #include "TextCtrl.h" #include "slic3r/GUI/Widgets/StaticBox.hpp" +#include #include #include "slic3r/GUI/Widgets/StateHandler.hpp" #include @@ -44,7 +45,7 @@ SpinInput::SpinInput() : label_color(std::make_pair(0x6B6B6B, (int) StateColor::Disabled), std::make_pair(0x6B6B6B, (int) StateColor::Normal)) , text_color(std::make_pair(0x6B6B6B, (int) StateColor::Disabled), std::make_pair(0x262E30, (int) StateColor::Normal)) { - radius = 0; + input_corner_radius = true; border_width = 1; border_color = StateColor(std::make_pair(0xDBDBDB, (int) StateColor::Disabled), std::make_pair(0x009688, (int) StateColor::Hovered), std::make_pair(0xDBDBDB, (int) StateColor::Normal)); @@ -73,6 +74,7 @@ void SpinInput::Create(wxWindow *parent, int min, int max, int initial, int step) { StaticBox::Create(parent, wxID_ANY, pos, size); + apply_input_corner_radius(); SetFont(Label::Body_12); wxWindow::SetLabel(label); state_handler.attach({&label_color, &text_color}); @@ -106,12 +108,6 @@ void SpinInput::Create(wxWindow *parent, messureSize(); } -void SpinInput::SetCornerRadius(double radius) -{ - this->radius = radius; - Refresh(); -} - void SpinInput::SetLabel(const wxString &label) { wxWindow::SetLabel(label); @@ -173,6 +169,7 @@ void SpinInput::Rescale() { button_inc->Rescale(); button_dec->Rescale(); + apply_input_corner_radius(); messureSize(); } @@ -236,17 +233,19 @@ void SpinInput::messureSize() minSize.x = GetMinWidth(); StaticBox::SetSize(size); SetMinSize(size); - wxSize btnSize = {14, (size.y - 4) / 2}; + // Keep the buttons inside the border and clear of the rounded corners: they paint over whatever is under them + const int btn_x = std::max(3, int(radius)); + wxSize btnSize = {14, (size.y - 6) / 2}; btnSize.x = btnSize.x * btnSize.y / 10; wxClientDC dc(this); labelSize = dc.GetMultiLineTextExtent(GetLabel()); - textSize.x = size.x - labelSize.x - btnSize.x - 16; + textSize.x = size.x - labelSize.x - btnSize.x - btn_x - 13; text_ctrl->SetSize(textSize); - text_ctrl->SetPosition({6 + btnSize.x, (size.y - textSize.y) / 2}); + text_ctrl->SetPosition({btn_x + 3 + btnSize.x, (size.y - textSize.y) / 2}); button_inc->SetSize(btnSize); button_dec->SetSize(btnSize); - button_inc->SetPosition({3, size.y / 2 - btnSize.y - 1}); - button_dec->SetPosition({3, size.y / 2 + 1}); + button_inc->SetPosition({btn_x, size.y / 2 - btnSize.y - 1}); + button_dec->SetPosition({btn_x, size.y / 2 + 1}); } Button *SpinInput::createButton(bool inc) diff --git a/src/slic3r/GUI/Widgets/SpinInput.hpp b/src/slic3r/GUI/Widgets/SpinInput.hpp index 0a26392bc4..eef822eef6 100644 --- a/src/slic3r/GUI/Widgets/SpinInput.hpp +++ b/src/slic3r/GUI/Widgets/SpinInput.hpp @@ -64,8 +64,6 @@ public: int initial = 0, int step = 1); - void SetCornerRadius(double radius); - void SetLabel(const wxString &label) wxOVERRIDE; void SetLabelColor(StateColor const &color); diff --git a/src/slic3r/GUI/Widgets/StaticBox.cpp b/src/slic3r/GUI/Widgets/StaticBox.cpp index 593ee6b525..3c38beeb0e 100644 --- a/src/slic3r/GUI/Widgets/StaticBox.cpp +++ b/src/slic3r/GUI/Widgets/StaticBox.cpp @@ -62,9 +62,16 @@ bool StaticBox::Create(wxWindow* parent, wxWindowID id, const wxPoint& pos, cons void StaticBox::SetCornerRadius(double radius) { this->radius = radius; + input_corner_radius = false; Refresh(); } +void StaticBox::apply_input_corner_radius() +{ + if (input_corner_radius) + radius = FromDIP(InputCornerRadius); +} + // ORCA use when adding widgets to top to show it like LabeledStaticBox void StaticBox::SetTopMargin(int margin) { diff --git a/src/slic3r/GUI/Widgets/StaticBox.hpp b/src/slic3r/GUI/Widgets/StaticBox.hpp index 7c8d7c50ee..4df10e756d 100644 --- a/src/slic3r/GUI/Widgets/StaticBox.hpp +++ b/src/slic3r/GUI/Widgets/StaticBox.hpp @@ -16,6 +16,9 @@ class StaticBox : public wxWindow { public: + // Corner radius, in DIP, of the boxed input widgets (TextInput, ComboBox, SpinInput, TempInput) + static constexpr int InputCornerRadius = 6; + StaticBox(); StaticBox(wxWindow* parent, @@ -63,8 +66,13 @@ protected: virtual void doRender(wxDC& dc); + // While input_corner_radius is set, sets the radius to InputCornerRadius at the current DPI. Input widgets + // set the flag in their constructor and call this from Create() and Rescale(); SetCornerRadius() clears it. + void apply_input_corner_radius(); + protected: double radius; + bool input_corner_radius = false; int border_width = 1; int top_margin = 0; wxPenStyle border_style = wxPENSTYLE_SOLID; diff --git a/src/slic3r/GUI/Widgets/TempInput.cpp b/src/slic3r/GUI/Widgets/TempInput.cpp index d75d8cecd7..eda14404c2 100644 --- a/src/slic3r/GUI/Widgets/TempInput.cpp +++ b/src/slic3r/GUI/Widgets/TempInput.cpp @@ -38,7 +38,7 @@ TempInput::TempInput() , text_color(std::make_pair(wxColour(0xAC,0xAC,0xAC), (int) StateColor::Disabled), std::make_pair(0x6B6B6B, (int) StateColor::Normal)) { hover = false; - radius = 0; + input_corner_radius = true; border_color = StateColor(std::make_pair(*wxWHITE, (int) StateColor::Disabled), std::make_pair(0x009688, (int) StateColor::Focused), std::make_pair(0x009688, (int) StateColor::Hovered), std::make_pair(*wxWHITE, (int) StateColor::Normal)); background_color = StateColor(std::make_pair(*wxWHITE, (int) StateColor::Disabled), std::make_pair(*wxWHITE, (int) StateColor::Normal)); @@ -96,6 +96,7 @@ bool TempInput::CheckIsValidVal(bool show_warning) void TempInput::Create(wxWindow *parent, wxString text, wxString label, wxString normal_icon, wxString actice_icon, const wxPoint &pos, const wxSize &size, long style) { StaticBox::Create(parent, wxID_ANY, pos, size, style); + apply_input_corner_radius(); wxWindow::SetLabel(label); style &= ~wxALIGN_CENTER_HORIZONTAL; state_handler.attach({&label_color, &text_color}); @@ -346,6 +347,7 @@ void TempInput::Rescale() if (this->actice_icon.bmp().IsOk()) this->actice_icon.msw_rescale(); if (this->degree_icon.bmp().IsOk()) this->degree_icon.msw_rescale(); if (this->round_scale_hint_icon.bmp().IsOk()) this->round_scale_hint_icon.msw_rescale(); + apply_input_corner_radius(); messureSize(); } diff --git a/src/slic3r/GUI/Widgets/TextInput.cpp b/src/slic3r/GUI/Widgets/TextInput.cpp index 356ce626a5..fe53f43f87 100644 --- a/src/slic3r/GUI/Widgets/TextInput.cpp +++ b/src/slic3r/GUI/Widgets/TextInput.cpp @@ -40,7 +40,7 @@ TextInput::TextInput() , text_color(std::make_pair(0x6B6B6B, (int) StateColor::Disabled), std::make_pair(0x262E30, (int) StateColor::Normal)) { - radius = 0; + input_corner_radius = true; border_width = 1; border_color = StateColor(std::make_pair(0xDBDBDB, (int) StateColor::Disabled), std::make_pair(0x009688, (int) StateColor::Hovered), std::make_pair(0xDBDBDB, (int) StateColor::Normal)); @@ -70,6 +70,7 @@ void TextInput::Create(wxWindow * parent, { text_ctrl = nullptr; StaticBox::Create(parent, wxID_ANY, pos, size, style); + apply_input_corner_radius(); wxWindow::SetLabel(label); assert((style & wxRIGHT) == 0); style &= ~wxALIGN_MASK; @@ -104,12 +105,6 @@ void TextInput::Create(wxWindow * parent, messureSize(); } -void TextInput::SetCornerRadius(double radius) -{ - this->radius = radius; - Refresh(); -} - void TextInput::SetLabel(const wxString& label) { wxWindow::SetLabel(label); @@ -178,6 +173,7 @@ void TextInput::Rescale() this->icon.msw_rescale(); if (!this->icon_1.name().empty()) this->icon_1.msw_rescale(); + apply_input_corner_radius(); messureSize(); Refresh(); } diff --git a/src/slic3r/GUI/Widgets/TextInput.hpp b/src/slic3r/GUI/Widgets/TextInput.hpp index 0e7d722961..c0404cde98 100644 --- a/src/slic3r/GUI/Widgets/TextInput.hpp +++ b/src/slic3r/GUI/Widgets/TextInput.hpp @@ -48,8 +48,6 @@ public: const wxSize & size = wxDefaultSize, long style = 0); - void SetCornerRadius(double radius); - // Only meant to be used by inspector, not public API int GetCornerRadius() const { return static_cast(radius); } From 029139513220f66398733017421ddee3e2004938 Mon Sep 17 00:00:00 2001 From: Rodrigo Faselli <162915171+RF47@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:32:58 -0300 Subject: [PATCH 09/26] Place Separate Objects Side by Side in the Assembly View (#17386) --- src/libslic3r/Model.cpp | 31 +++++++++++++++++ src/libslic3r/Model.hpp | 8 +++++ src/slic3r/GUI/GUI_ObjectList.cpp | 12 ++++--- src/slic3r/GUI/Plater.cpp | 5 ++- src/slic3r/GUI/Selection.cpp | 2 ++ tests/libslic3r/test_model.cpp | 57 +++++++++++++++++++++++++++++++ 6 files changed, 109 insertions(+), 6 deletions(-) diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index ba03c9bc71..4d0577a536 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -815,6 +815,26 @@ bool Model::add_default_instances() return true; } +void Model::set_assembly_pos(ModelObject *model_object, const std::vector &ignore) +{ + for (ModelInstance *instance : model_object->instances) + if (!instance->is_assemble_initialized()) + instance->set_assemble_transformation(instance->get_transformation()); + + const BoundingBoxf3 box = model_object->bounding_box_in_assembly_view(); + if (!box.defined) + return; + BoundingBoxf3 others; + for (const ModelObject *o : this->objects) + if (o != model_object && std::find(ignore.begin(), ignore.end(), o) == ignore.end()) + others.merge(o->bounding_box_in_assembly_view()); + + const Vec2d target = others.defined ? Vec2d(others.max.x() + 10. + 0.5 * box.size().x(), others.center().y()) : Vec2d::Zero(); + const Vec3d shift(target.x() - box.center().x(), target.y() - box.center().y(), 0.); + for (ModelInstance *instance : model_object->instances) + instance->set_assemble_offset(instance->get_assemble_offset() + shift); +} + // this returns the bounding box of the *transformed* instances BoundingBoxf3 Model::bounding_box_approx() const { @@ -1874,6 +1894,17 @@ BoundingBoxf3 ModelObject::instance_bounding_box(const ModelInstance &instance, return bb; } +BoundingBoxf3 ModelObject::bounding_box_in_assembly_view() const +{ + // The cached raw box keeps this cheap: placing an object measures every other object in the model. + BoundingBoxf3 bb; + const BoundingBoxf3 &raw_bbox = this->raw_mesh_bounding_box(); + if (raw_bbox.defined) + for (const ModelInstance *instance : this->instances) + bb.merge(raw_bbox.transformed(instance->get_assemble_transformation().get_matrix())); + return bb; +} + //BBS: add convex bounding box BoundingBoxf3 ModelObject::instance_convex_hull_bounding_box(size_t instance_idx, bool dont_translate) const diff --git a/src/libslic3r/Model.hpp b/src/libslic3r/Model.hpp index c59ec6db75..562c7aa900 100644 --- a/src/libslic3r/Model.hpp +++ b/src/libslic3r/Model.hpp @@ -508,6 +508,9 @@ public: // A snug bounding box around the transformed non-modifier object volumes. BoundingBoxf3 instance_bounding_box(size_t instance_idx, bool dont_translate = false) const; BoundingBoxf3 instance_bounding_box(const ModelInstance& instance, bool dont_translate = false) const; + // A bounding box around the non-modifier object volumes of all instances, as placed in the assembly view. + // It encloses the corners of the raw mesh box, so it is loose for rotated instances. + BoundingBoxf3 bounding_box_in_assembly_view() const; // A snug bounding box of non-transformed (non-rotated, non-scaled, non-translated) sum of non-modifier object volumes. const BoundingBoxf3& raw_mesh_bounding_box() const; @@ -1836,6 +1839,11 @@ public: void clear_materials(); // Make sure all objects have at least one instance bool add_default_instances(); + // Moves model_object in the assembly view 10 mm to the right of the other objects (except those in ignore), + // centred on them in Y, or onto the origin when there are none, so that an object added on its own does not + // overlap the others there. Keeps its height and the layout of its instances. Instances that have no + // assembly pose yet start from their pose on the plate. + void set_assembly_pos(ModelObject *model_object, const std::vector &ignore = {}); // Returns approximate axis aligned bounding box of this model. BoundingBoxf3 bounding_box_approx() const; // Returns exact axis aligned bounding box of this model. diff --git a/src/slic3r/GUI/GUI_ObjectList.cpp b/src/slic3r/GUI/GUI_ObjectList.cpp index 58718073c4..bc3e95bed1 100644 --- a/src/slic3r/GUI/GUI_ObjectList.cpp +++ b/src/slic3r/GUI/GUI_ObjectList.cpp @@ -2832,9 +2832,8 @@ void ObjectList::load_mesh_object(const std::vectorensure_on_bed(); - //BBS init assmeble transformation - Geometry::Transformation t = new_object->instances[0]->get_transformation(); - new_object->instances[0]->set_assemble_transformation(t); + // Its pose on the plate would put it far from the other objects in the assembly view. + model.set_assembly_pos(new_object); object_idxs.push_back(model.objects.size() - 1); #ifdef _DEBUG @@ -3389,9 +3388,12 @@ void ObjectList::merge(bool to_multipart_object) new_object->center_around_origin(); new_object->translate_instances(-new_object->origin_translation); new_object->origin_translation = Vec3d::Zero(); - //BBS init asssmble transformation Geometry::Transformation new_object_trsf = new_object->instances[0]->get_transformation(); - new_object->instances[0]->set_assemble_transformation(new_object_trsf); + // Place it beside the objects that remain in the assembly view; the merged ones are removed below. + std::vector merged_objects; + for (int obj_idx : obj_idxs) + merged_objects.push_back((*m_objects)[obj_idx]); + model->set_assembly_pos(new_object, merged_objects); const Transform3d& new_object_inverse_matrix = new_object_trsf.get_matrix().inverse(); for (auto& p : new_object->brim_points) { diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 595736406c..c625c42bcd 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -10680,7 +10680,10 @@ std::vector Plater::priv::load_model_objects(const ModelObjectPtrs& mode model_object->instances[i]->set_assemble_transformation(model_object->instances[i]->get_transformation()); } } - } + } + // An object that came without a position would otherwise sit at the origin of the assembly view, on top of the others. + if (model_object->instances.empty()) + model.set_assembly_pos(object); } } diff --git a/src/slic3r/GUI/Selection.cpp b/src/slic3r/GUI/Selection.cpp index 57c40059ce..1a27227456 100644 --- a/src/slic3r/GUI/Selection.cpp +++ b/src/slic3r/GUI/Selection.cpp @@ -3351,6 +3351,8 @@ void Selection::paste_objects_from_clipboard() Geometry::Transformation t = inst->get_transformation(); inst->set_assemble_transformation(t); } + // Its pose on the plate would put it far from the other objects in the assembly view. + m_model->set_assembly_pos(dst_object); object_idxs.push_back(m_model->objects.size() - 1); #ifdef _DEBUG diff --git a/tests/libslic3r/test_model.cpp b/tests/libslic3r/test_model.cpp index 0c79bd83ed..9c3b9f0f35 100644 --- a/tests/libslic3r/test_model.cpp +++ b/tests/libslic3r/test_model.cpp @@ -202,6 +202,63 @@ TEST_CASE("Repairing a part replaces its mesh only when the repair changes it", CHECK(valid->id() == valid_id); } +// A cube whose raw mesh spans [0, size] on every axis, with one instance at plate_offset on the plate. +static ModelObject *add_cube(Model &model, double size, const Vec3d &plate_offset) +{ + ModelObject *object = model.add_object(); + object->add_volume(make_cube(size, size, size), ModelVolumeType::MODEL_PART, false); + object->add_instance()->set_offset(plate_offset); + return object; +} + +TEST_CASE("An object placed in the assembly view goes 10 mm to the right of the others", "[Model]") +{ + Model model; + ModelObject *placed = add_cube(model, 20., Vec3d::Zero()); + placed->instances.front()->set_assemble_transformation(placed->instances.front()->get_transformation()); + const Vec3d plate_offset(128., 128., 5.); + ModelObject *added = add_cube(model, 10., plate_offset); + + model.set_assembly_pos(added); + + const BoundingBoxf3 placed_box = placed->bounding_box_in_assembly_view(); + const BoundingBoxf3 added_box = added->bounding_box_in_assembly_view(); + CHECK(added->instances.front()->is_assemble_initialized()); + CHECK_THAT(added_box.min.x(), Catch::Matchers::WithinAbs(placed_box.max.x() + 10., 1e-6)); + CHECK_THAT(added_box.center().y(), Catch::Matchers::WithinAbs(placed_box.center().y(), 1e-6)); + // The height comes from the plate, and the plate itself is left alone. + CHECK_THAT(added_box.min.z(), Catch::Matchers::WithinAbs(plate_offset.z(), 1e-6)); + CHECK_THAT((added->instances.front()->get_offset() - plate_offset).norm(), Catch::Matchers::WithinAbs(0., 1e-6)); +} + +TEST_CASE("An object alone in the assembly view is centred on the origin and keeps its instance layout", "[Model]") +{ + Model model; + ModelObject *object = add_cube(model, 10., {100., 100., 0.}); + object->add_instance()->set_offset({130., 100., 0.}); + + model.set_assembly_pos(object); + + const BoundingBoxf3 box = object->bounding_box_in_assembly_view(); + CHECK_THAT(box.center().x(), Catch::Matchers::WithinAbs(0., 1e-6)); + CHECK_THAT(box.center().y(), Catch::Matchers::WithinAbs(0., 1e-6)); + const Vec3d spacing = object->instances[1]->get_assemble_offset() - object->instances[0]->get_assemble_offset(); + CHECK_THAT((spacing - Vec3d(30., 0., 0.)).norm(), Catch::Matchers::WithinAbs(0., 1e-6)); +} + +TEST_CASE("Ignored objects do not push an object aside in the assembly view", "[Model]") +{ + Model model; + ModelObject *ignored = add_cube(model, 20., Vec3d::Zero()); + ignored->instances.front()->set_assemble_transformation(ignored->instances.front()->get_transformation()); + ModelObject *object = add_cube(model, 10., {128., 128., 0.}); + + model.set_assembly_pos(object, {ignored}); + + const BoundingBoxf3 box = object->bounding_box_in_assembly_view(); + CHECK_THAT(box.center().x(), Catch::Matchers::WithinAbs(0., 1e-6)); + CHECK_THAT(box.center().y(), Catch::Matchers::WithinAbs(0., 1e-6)); +} namespace { // A box of the given size whose lowest corner is at `corner` in the file's coordinates. The mesh keeps them, unless From 18ac48ed966adbb311b81cc5c440ce1f8ee59668 Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:59:49 +0800 Subject: [PATCH 10/26] Skip the Clipper2 Intersection Sort When No Edges Crossed (#17384) BuildIntersectList() merge-sorts the active edges by their new x to find crossings. Most scanbeams have no crossing, so AdjustCurrXAndCopyToSEL() now reports whether the edges stayed in order and the sort is skipped when they did. --- .../Clipper2Lib/include/clipper2/clipper.engine.h | 2 +- deps_src/clipper2/Clipper2Lib/src/clipper.engine.cpp | 12 ++++++++++-- docs/HLSD/polygon-clipping.md | 5 +++-- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/deps_src/clipper2/Clipper2Lib/include/clipper2/clipper.engine.h b/deps_src/clipper2/Clipper2Lib/include/clipper2/clipper.engine.h index 5151e53c7b..e4201974ab 100644 --- a/deps_src/clipper2/Clipper2Lib/include/clipper2/clipper.engine.h +++ b/deps_src/clipper2/Clipper2Lib/include/clipper2/clipper.engine.h @@ -242,7 +242,7 @@ namespace Clipper2Lib { inline void UpdateEdgeIntoAEL(Active *e); void IntersectEdges(Active &e1, Active &e2, const Point64& pt); inline void DeleteFromAEL(Active &e); - inline void AdjustCurrXAndCopyToSEL(const int64_t top_y); + inline bool AdjustCurrXAndCopyToSEL(const int64_t top_y); void DoIntersections(const int64_t top_y); void AddNewIntersectNode(Active &e1, Active &e2, const int64_t top_y); bool BuildIntersectList(const int64_t top_y); diff --git a/deps_src/clipper2/Clipper2Lib/src/clipper.engine.cpp b/deps_src/clipper2/Clipper2Lib/src/clipper.engine.cpp index 2948565ff4..a3a5c7ca1b 100644 --- a/deps_src/clipper2/Clipper2Lib/src/clipper.engine.cpp +++ b/deps_src/clipper2/Clipper2Lib/src/clipper.engine.cpp @@ -9,6 +9,7 @@ #include "clipper2/clipper.engine.h" #include "clipper2/clipper.h" +#include #include #include #include @@ -2136,10 +2137,12 @@ namespace Clipper2Lib { } - inline void ClipperBase::AdjustCurrXAndCopyToSEL(const int64_t top_y) + inline bool ClipperBase::AdjustCurrXAndCopyToSEL(const int64_t top_y) { Active* e = actives_; sel_ = e; + bool sorted = true; + int64_t prev_x = std::numeric_limits::min(); while (e) { e->prev_in_sel = e->prev_in_ael; @@ -2148,8 +2151,11 @@ namespace Clipper2Lib { // it is safe to ignore 'joined' edges here because // if necessary they will be split in IntersectEdges() e->curr_x = TopX(*e, top_y); + sorted = sorted && e->curr_x >= prev_x; + prev_x = e->curr_x; e = e->next_in_ael; } + return sorted; } bool ClipperBase::ExecuteInternal(ClipType ct, FillRule fillrule, bool use_polytrees) @@ -2419,7 +2425,9 @@ namespace Clipper2Lib { //Calculate edge positions at the top of the current scanbeam, and from this //we will determine the intersections required to reach these new positions. - AdjustCurrXAndCopyToSEL(top_y); + // Orca: edges still in order have not crossed, which holds for most scanbeams, and the + // merge sort below would only confirm that in log2(n) passes over every edge. + if (AdjustCurrXAndCopyToSEL(top_y)) return false; //Find all edge intersections in the current scanbeam using a stable merge //sort that ensures only adjacent edges are intersecting. Intersect info is //stored in FIntersectList ready to be processed in ProcessIntersectList. diff --git a/docs/HLSD/polygon-clipping.md b/docs/HLSD/polygon-clipping.md index 00a1e2863b..afbc53aad7 100644 --- a/docs/HLSD/polygon-clipping.md +++ b/docs/HLSD/polygon-clipping.md @@ -29,10 +29,10 @@ as for predictable geometry. ## Vendored Clipper2 -`deps_src/clipper2` builds the static target `Clipper2`. It carries four +`deps_src/clipper2` builds the static target `Clipper2`. It carries five changes to the upstream sources that must be carried over when Clipper2 is updated. The namespace switch sits at the top of every header and source, the -other three are marked with `Orca:` comments. +other four are marked with `Orca:` comments. | Change | Files | Why | | --- | --- | --- | @@ -40,6 +40,7 @@ other three are marked with `Orca:` comments. | Engine nodes from tbbmalloc | `clipper.engine.h`, `clipper.engine.cpp` | Vertices, active edges, output points and records, local minima and `PolyTree` nodes are allocated one by one. `CLIPPER2_NODE_ALLOCATOR` routes them through `scalable_malloc`, because the default heap does not scale when all slicing threads clip at once. | | Concave joins at the edge crossing | `clipper.offset.cpp` | For closed paths, a concave corner is joined at the crossing of the two offset edges when that point lies within half of both adjacent edges. The upstream 3-point loop makes inward offsets of dense curves very slow to union. | | Rounded arc steps | `clipper.offset.cpp` | Round joins use the rounded number of steps, not the ceiling, which keeps the vertex count of round offsets that the rest of the code is tuned for. | +| No intersection sort for edges in order | `clipper.engine.h`, `clipper.engine.cpp` | `AdjustCurrXAndCopyToSEL()` reports whether the active edges kept their order at the top of the scanbeam, and `BuildIntersectList()` returns before its merge sort when they did. Most scanbeams have no crossing, and the sort was a large part of every boolean on dense support layers. | ## ClipperUtils semantics From 2d7b0e1c6dfbcb680a63a5e7680413ded643f399 Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:19:20 +0800 Subject: [PATCH 11/26] Slice Each Final Configuration Once in the Surface Centering Test (#17481) The test compared every one of its 216 combinations against a fresh slice of the final settings, but those settings take only 72 distinct values. Keep each fresh slice and reuse it, which cuts the test's slices from 648 to 504 with the same checks. --- tests/fff_print/test_printobject.cpp | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/tests/fff_print/test_printobject.cpp b/tests/fff_print/test_printobject.cpp index 80de36c608..8d0ac0e6e7 100644 --- a/tests/fff_print/test_printobject.cpp +++ b/tests/fff_print/test_printobject.cpp @@ -35,6 +35,7 @@ #include #include #include +#include #include #include #include "libslic3r/ExPolygon.hpp" @@ -462,11 +463,20 @@ TEST_CASE("Surface centering survives changes to separated infill settings", "[P print.process(); const auto resliced = surface_fills(print); - Print fresh_print; - Model fresh_model; - init_print({mesh}, fresh_print, fresh_model, config, nullptr, false); - fresh_print.process(); - const auto fresh = surface_fills(fresh_print); + // The fresh slice depends only on the final settings, which several combinations share, + // so slice each set once. The resliced paths must match it exactly, so slicing is deterministic. + using FreshKey = std::tuple; + static std::map fresh_slices; + const FreshKey fresh_key{pattern, final_center, separated, top_order, density}; + auto fresh_it = fresh_slices.find(fresh_key); + if (fresh_it == fresh_slices.end()) { + Print fresh_print; + Model fresh_model; + init_print({mesh}, fresh_print, fresh_model, config, nullptr, false); + fresh_print.process(); + fresh_it = fresh_slices.emplace(fresh_key, surface_fills(fresh_print)).first; + } + const auto &fresh = fresh_it->second; REQUIRE_FALSE(fresh.empty()); REQUIRE(resliced.size() == fresh.size()); std::set roles; From a4de8cb891158c8c29ba969cb399cad037f580da Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:29:26 +0800 Subject: [PATCH 12/26] Build the Flatpak, macOS x86_64 and Windows arm64 for Pull Requests on Request (#17202) * Move the Flatpak Jobs Into a Reusable Workflow build_flatpak.yml holds the Flatpak build and its two sandbox unit-test jobs, moved verbatim, so a second workflow can call them. Build all calls it for every event it built the Flatpak for before. * Build the Flatpak, macOS x86_64 and Windows arm64 for Pull Requests on Request Build all no longer builds them for a pull request: the Flatpak is the slowest Linux leg, a macOS x86_64 build holds one of the few hosted macOS runners for an hour, and Windows arm64 doubles the Windows legs. Pushes, the nightly and dispatches still build everything, and a pull request's macOS arm64 build ships as its own DMG in place of the universal one. The new build_optional.yml builds them on a label (build-flatpak, build-macos-x86_64, build-windows-arm64), from when it is added and on every later push, and builds the Flatpak and Windows arm64 without a label when the pull request changes anything outside the sources, tests, profiles, translations and docs, which is where what breaks only those legs lives. Each build keeps its own concurrency group, which cancel_closed_pr_builds.yml joins. The macOS admission script now counts the macOS jobs of both workflows, and build_check_cache.yml names the workflows in its env instead of deriving one from the caller. The label bot lets a contributor ask for the Flatpak. * Run the Windows Build Script Tests Only When a Pull Request Changes Them The three suites build their own fixtures and read nothing else from the tree, so on a pull request a short Linux job looks for a change to the scripts or the suites first, and the Windows builds accept the skipped job. Pushes and the nightly still run them every time. * Read WORKFLOW Through a Checked Expansion Shellcheck's SC2153 takes a bare uppercase reference next to the lowercase variable for a misspelling. * Let the Pull Request Author Ask for Any Optional Build Through the Bot GitHub starts no workflow from an event the job's own token causes, so the label bot mints a GitHub App installation token when the app's secrets exist and adds the build-* labels with it; without them the build starts with the next push. The run a label starts is an ordinary pull_request run, so a first pull request's waits for a maintainer's approval as Build all does. * Build Everything the Labels Ask for in Every Optional Builds Run Each label added starts a run of its own, and the pull request's checks show the newest run only, so a run that built its own label's leg alone left the others looking skipped. Every run now builds everything the labels and the changed files ask for; the concurrency group of each build cancels the one an earlier run of the commit started, so the newest run ends with them all. * Filter Optional Builds Like Build All and Add a build-all Label The workflow takes Build all's pull_request paths plus the Flatpak packaging, so a pull request Build all skips, one that only changes an unrelated workflow or script, gets no optional build and starts none on a label. The build-all label asks for every optional build at once. * Keep the Flatpak on Every Pull Request flatpak-builder compiles with the GNOME SDK's default flags, which include -D_GLIBCXX_ASSERTIONS, so the Flatpak's unit tests are the only pull request check that aborts on an out-of-range vector access where the other legs' Release builds read garbage and pass. Since August that caught four bugs that changed only src/, tests/ or resources/, which the infra rule would not have built, and the leg runs on hosted Linux runners, so gating it freed no macOS runner. Build all calls build_flatpak.yml on pull requests again; the optional builds are the macOS x86_64 and Windows arm64 ones, and build-all means those two. * Revert "Keep the Flatpak on Every Pull Request" This reverts commit 998e31a99b668a288f50d54c296df39a737178d9. The Flatpak stays behind the build-flatpak label and the infra rule, as the maintainers prefer. * Build the Linux Legs With libstdc++'s Assertions flatpak-builder compiles with the GNOME SDK's default flags, which include -D_GLIBCXX_ASSERTIONS, so the Flatpak's unit tests were the only pull request check that aborts on an out-of-range vector access where the other legs' Release builds read garbage and pass. Pull requests build the Flatpak on request only now. SLIC3R_GLIBCXX_ASSERTIONS defines the macro for the OrcaSlicer build, and the Linux legs turn it on, so every pull request keeps those checks on a leg that always runs. The checks are libstdc++'s lightweight subset: no class changes layout, so the prebuilt deps link as they are. --- .github/workflows/build_all.yml | 318 +++--------------- .github/workflows/build_check_cache.yml | 7 +- .github/workflows/build_flatpak.yml | 261 ++++++++++++++ .github/workflows/build_optional.yml | 186 ++++++++++ .github/workflows/build_orca.yml | 34 +- .github/workflows/cancel_closed_pr_builds.yml | 14 + .github/workflows/pr-label-bot.yml | 62 +++- CMakeLists.txt | 9 + CONTRIBUTING.md | 1 + scripts/ci_deps_cache.sh | 8 +- scripts/ci_macos_admission.py | 34 +- scripts/tests/test_ci_macos_admission.py | 62 ++-- 12 files changed, 687 insertions(+), 309 deletions(-) create mode 100644 .github/workflows/build_flatpak.yml create mode 100644 .github/workflows/build_optional.yml diff --git a/.github/workflows/build_all.yml b/.github/workflows/build_all.yml index 1aa14d9810..3fb204ef42 100644 --- a/.github/workflows/build_all.yml +++ b/.github/workflows/build_all.yml @@ -34,6 +34,7 @@ on: branches: - main - release/* + # build_optional.yml keeps the same list, plus scripts/flatpak/**. paths: - 'deps/**' - 'deps_src/**' @@ -52,7 +53,6 @@ on: - 'scripts/build_preset_cache.*' - 'scripts/prune_cached_presets.ps1' - 'scripts/test_prune_cached_presets.ps1' - - 'scripts/flatpak/**' - 'scripts/msix/**' - 'scripts/sign_windows.ps1' - 'tests/**' @@ -78,9 +78,40 @@ concurrency: jobs: - # build_win.bat ships a test suite. Run it before the Windows builds. + # build_win.bat and two of the scripts it runs ship test suites. They run + # before the Windows builds, on a pull request only when it changes one of + # the scripts or the suites: the suites build their own fixtures and read + # nothing else from the tree. Pushes and the nightly always run them. + build_script_changes: + name: Look for build script changes + if: ${{ github.event_name == 'pull_request' }} + runs-on: ubuntu-24.04 + outputs: + changed: ${{ steps.changes.outputs.changed }} + steps: + - name: Checkout + uses: actions/checkout@v7 + with: + lfs: 'false' + # The merge commit plus its first parent, the base it is diffed against. + fetch-depth: 2 + sparse-checkout: .github/workflows + - name: Look for changed files + id: changes + run: | + if git diff --quiet HEAD^1 HEAD -- build_win.bat .github/workflows/build_all.yml \ + scripts/check_exception_throw_info.ps1 scripts/prune_cached_presets.ps1 \ + scripts/test_build_win.ps1 scripts/test_check_exception_throw_info.ps1 scripts/test_prune_cached_presets.ps1; then + echo "No build script changes." + else + echo "changed=true" >> "$GITHUB_OUTPUT" + fi check_build_script: name: Windows build script tests + needs: build_script_changes + # Runs unless the lookup ran and found nothing: skipped off pull requests, + # and failed lookups run the suites rather than skip them. + if: ${{ !cancelled() && (needs.build_script_changes.result != 'success' || needs.build_script_changes.outputs.changed == 'true') }} runs-on: windows-latest steps: - name: Checkout @@ -125,10 +156,14 @@ jobs: strategy: fail-fast: false # SELF_HOSTED skips arm64 (the self-hosted Windows server is x64-only). + # So does a pull request; build_optional.yml builds arm64 on the + # build-windows-arm64 label or a change outside the sources. matrix: include: ${{ fromJSON(vars.SELF_HOSTED && '[{"arch":"x64","os":"orca-win-server","compiler":"clang"}]' - || '[{"arch":"x64","os":"windows-latest","compiler":"clang"},{"arch":"arm64","os":"windows-11-vs2026-arm","compiler":"clang"}]') }} + || (github.event_name == 'pull_request' + && '[{"arch":"x64","os":"windows-latest","compiler":"clang"}]' + || '[{"arch":"x64","os":"windows-latest","compiler":"clang"},{"arch":"arm64","os":"windows-11-vs2026-arm","compiler":"clang"}]')) }} needs: check_build_script # id-token lets release builds sign through Google Cloud Workload Identity Federation (see # "Configure code signing" in build_orca.yml); the rest is what the build already used. @@ -137,7 +172,7 @@ jobs: contents: write id-token: write # Don't run scheduled builds on forks: - if: ${{ !cancelled() && needs.check_build_script.result == 'success' && (github.event_name != 'schedule' || github.repository == 'OrcaSlicer/OrcaSlicer') }} + if: ${{ !cancelled() && contains(fromJSON('["success", "skipped"]'), needs.check_build_script.result) && (github.event_name != 'schedule' || github.repository == 'OrcaSlicer/OrcaSlicer') }} uses: ./.github/workflows/build_check_cache.yml with: os: ${{ matrix.os }} @@ -149,10 +184,11 @@ jobs: build_macos_arch: strategy: fail-fast: false + # Hosted macOS runners are scarce, so a pull request builds arm64 only and + # ships it as its own DMG; build_optional.yml builds x86_64 on the + # build-macos-x86_64 label. Pushes build both and combine them below. matrix: - arch: - - arm64 - - x86_64 + arch: ${{ fromJSON(github.event_name == 'pull_request' && '["arm64"]' || '["arm64", "x86_64"]') }} # Don't run scheduled builds on forks: if: ${{ !cancelled() && (github.event_name != 'schedule' || github.repository == 'OrcaSlicer/OrcaSlicer') }} uses: ./.github/workflows/build_check_cache.yml @@ -165,7 +201,7 @@ jobs: build_macos_universal: name: Build macOS Universal needs: build_macos_arch - if: ${{ !cancelled() && needs.build_macos_arch.result == 'success' && !inputs.build-deps-only && (github.event_name != 'schedule' || github.repository == 'OrcaSlicer/OrcaSlicer') }} + if: ${{ !cancelled() && needs.build_macos_arch.result == 'success' && !inputs.build-deps-only && github.event_name != 'pull_request' && (github.event_name != 'schedule' || github.repository == 'OrcaSlicer/OrcaSlicer') }} uses: ./.github/workflows/build_orca.yml with: os: ${{ vars.SELF_HOSTED && 'orca-macos-arm64' || 'macos-15' }} @@ -189,10 +225,11 @@ jobs: with: os: ubuntu-24.04-arm artifact: ${{ github.sha }}-tests-linux-aarch64 + # The explicit result, as the script tests ahead of the build may be skipped. unit_tests_windows_x64: name: Windows x64 needs: build_windows - if: ${{ !cancelled() && success() }} + if: ${{ !cancelled() && needs.build_windows.result == 'success' }} uses: ./.github/workflows/unit_tests.yml with: os: ${{ vars.SELF_HOSTED && 'orca-win-server' || 'windows-latest' }} @@ -200,7 +237,7 @@ jobs: unit_tests_windows_arm64: name: Windows arm64 needs: build_windows - if: ${{ !cancelled() && success() && !vars.SELF_HOSTED }} + if: ${{ !cancelled() && needs.build_windows.result == 'success' && !vars.SELF_HOSTED && github.event_name != 'pull_request' }} uses: ./.github/workflows/unit_tests.yml with: os: windows-11-vs2026-arm @@ -243,7 +280,7 @@ jobs: ./validator-bin/OrcaSlicer_profile_validator -p "${{ github.workspace }}/resources/profiles" -s -l 2 publish_test_results: name: Publish Test Results - needs: [unit_tests_linux_x86_64, unit_tests_linux_aarch64, unit_tests_windows_x64, unit_tests_windows_arm64, unit_tests_macos_arm64, unit_tests_flatpak_x86_64, unit_tests_flatpak_aarch64] + needs: [unit_tests_linux_x86_64, unit_tests_linux_aarch64, unit_tests_windows_x64, unit_tests_windows_arm64, unit_tests_macos_arm64, flatpak] if: ${{ !cancelled() }} runs-on: ubuntu-latest steps: @@ -265,259 +302,10 @@ jobs: with: name: test-results-* failOnError: false + # Pull requests build it on the build-flatpak label, from build_optional.yml. flatpak: - name: "Flatpak" - container: - image: ghcr.io/flathub-infra/flatpak-github-actions:gnome-50 - options: --privileged - volumes: - - /usr/local/lib/android:/usr/local/lib/android - - /usr/share/dotnet:/usr/share/dotnet - - /opt/ghc:/opt/ghc1 - - /usr/local/share/boost:/usr/local/share/boost1 - - /opt/hostedtoolcache:/opt/hostedtoolcache1 - # Updating a runtime renames its old deployment, which fails with - # "Invalid cross-device link" on hosts whose Docker overlay cannot - # rename directories from an image layer. A volume is not overlay. - - /var/lib/flatpak - strategy: - fail-fast: false - matrix: - variant: - - arch: x86_64 - runner: ubuntu-24.04 - - arch: aarch64 - runner: ubuntu-24.04-arm + name: Flatpak # Don't run scheduled builds on forks; skip entirely on self-hosted runners - if: ${{ !cancelled() && !vars.SELF_HOSTED && (github.event_name != 'schedule' || github.repository == 'OrcaSlicer/OrcaSlicer') }} - - runs-on: ${{ matrix.variant.runner }} - env: - date: - ver: - ver_pure: - steps: - - name: "Remove unneeded stuff to free disk space" - run: - rm -rf /usr/local/lib/android/* /usr/share/dotnet/* /opt/ghc1/* "/usr/local/share/boost1/*" /opt/hostedtoolcache1/* - - uses: actions/checkout@v7 - - name: Get the version and date - run: | - ver_pure=$(grep 'set(SoftFever_VERSION' version.inc | cut -d '"' -f2) - if [[ "${{ github.event_name }}" == "pull_request" ]]; then - ver="PR-${{ github.event.number }}" - git_commit_hash="${{ github.event.pull_request.head.sha }}" - else - ver=V$ver_pure - git_commit_hash="${{ github.sha }}" - fi - echo "ver=$ver" >> $GITHUB_ENV - echo "ver_pure=$ver_pure" >> $GITHUB_ENV - echo "date=$(date +'%Y%m%d')" >> $GITHUB_ENV - echo "git_commit_hash=$git_commit_hash" >> $GITHUB_ENV - shell: bash - - name: Compute the flatpak-builder cache key - id: fp_cache_key - run: echo "key=flatpak-builder-${{ matrix.variant.arch }}-${{ hashFiles('deps/**', 'scripts/flatpak/com.orcaslicer.OrcaSlicer.yml', 'scripts/flatpak/make_deps_tar.sh') }}" >> "$GITHUB_OUTPUT" - shell: bash - # Manage flatpak-builder cache externally so PRs restore but never upload. - # The compiler cache under it is keyed per run below, so it is left out. - - name: Restore flatpak-builder cache - if: github.event_name == 'pull_request' - uses: actions/cache/restore@v6 - with: - path: | - .flatpak-builder/* - !.flatpak-builder/ccache - key: ${{ steps.fp_cache_key.outputs.key }} - restore-keys: flatpak-builder-${{ matrix.variant.arch }}- - - name: Save/restore flatpak-builder cache - if: github.event_name != 'pull_request' - uses: actions/cache@v6 - with: - path: | - .flatpak-builder/* - !.flatpak-builder/ccache - key: ${{ steps.fp_cache_key.outputs.key }} - restore-keys: flatpak-builder-${{ matrix.variant.arch }}- - # Compiler cache for the OrcaSlicer module, as in build_orca.yml. Pull - # requests only restore it; every other run (main, release branches, the - # nightly, a dispatch) saves it. orca_deps stays on the state cache above. - - name: Name the compiler cache leg - run: | - leg="Flatpak-${{ matrix.variant.arch }}" - echo "CCACHE_LEG=$leg" >> "$GITHUB_ENV" - echo "CCACHE_ENTRY=ccache-$leg-${{ github.run_id }}-${{ github.run_attempt }}" >> "$GITHUB_ENV" - shell: bash - - name: Restore compiler cache - id: ccache_restore - uses: actions/cache/restore@v6 - with: - path: .flatpak-builder/ccache - key: ${{ env.CCACHE_ENTRY }} - restore-keys: ccache-${{ env.CCACHE_LEG }}- - - name: Disable debug info for faster CI builds - run: | - sed -i '/^build-options:/a\ no-debuginfo: true\n strip: true' \ - scripts/flatpak/com.orcaslicer.OrcaSlicer.yml - shell: bash - # flatpak-builder reuses a module from its cache when the definition and - # sources are unchanged, so a re-run of the same commit would skip the - # OrcaSlicer module and ship no test asset. A per-run value in that module's - # env keeps it rebuilding; orca_deps stays cached, and the compiler cache - # still serves the rebuild. run-tests on the same module builds the test - # binaries. - - name: Inject commit hash, run-tests and cache buster into Flatpak manifest - env: - flatpak_builder_cache_buster: ${{ github.run_id }}-${{ github.run_attempt }} - run: | - sed -i "/name: OrcaSlicer/{n;s|buildsystem: simple|buildsystem: simple\n run-tests: true\n build-options:\n env:\n flatpak_builder_cache_buster: \"$flatpak_builder_cache_buster\"\n git_commit_hash: \"$git_commit_hash\"|}" \ - scripts/flatpak/com.orcaslicer.OrcaSlicer.yml - shell: bash - # flatpak-builder's --ccache only wraps cc and gcc, and the manifest builds - # with clang, so CMake's launcher runs ccache instead; --ccache is still what - # mounts the cache directory into the sandbox. The settings go into that - # directory's own config file, which the sandbox reads too. - - name: Enable compiler cache - run: | - printf ' %s\n' \ - 'CMAKE_C_COMPILER_LAUNCHER: ccache' \ - 'CMAKE_CXX_COMPILER_LAUNCHER: ccache' > "$RUNNER_TEMP/ccache-env.yml" - sed -i "/^ git_commit_hash: /r $RUNNER_TEMP/ccache-env.yml" \ - scripts/flatpak/com.orcaslicer.OrcaSlicer.yml - grep -q '^ CMAKE_CXX_COMPILER_LAUNCHER: ccache$' scripts/flatpak/com.orcaslicer.OrcaSlicer.yml - mkdir -p .flatpak-builder/ccache - export CCACHE_DIR=$PWD/.flatpak-builder/ccache - ccache --set-config=max_size=3G - # The compiler is reinstalled every run, so its mtime means nothing. - ccache --set-config=compiler_check=content - # Headers a fresh checkout has just written, the few files that use - # __DATE__ or __TIME__, and the precompiled header, whose macros ccache - # cannot see. - ccache --set-config=sloppiness=pch_defines,time_macros,include_file_mtime,include_file_ctime - # Hash the includes the compiler reports instead of preprocessing every - # miss before compiling it. - ccache --set-config=depend_mode=true - # The restored directory carries the previous run's counters. - ccache -z - shell: bash - - name: Check the manifest keeps orca_deps cacheable - run: ./scripts/flatpak/check_manifest_cacheable.sh - shell: bash - - name: Pack deps/ for the Flatpak manifest - run: ./scripts/flatpak/make_deps_tar.sh - shell: bash - - uses: flatpak/flatpak-github-actions/flatpak-builder@master - with: - bundle: OrcaSlicer-Linux-flatpak_${{ env.ver }}_${{ matrix.variant.arch }}.flatpak - manifest-path: scripts/flatpak/com.orcaslicer.OrcaSlicer.yml - # cache only turns on flatpak-builder --ccache; the caching itself is above. - cache: true - restore-cache: false - save-cache: false - arch: ${{ matrix.variant.arch }} - upload-artifact: false - keep-build-dirs: true - # The build has just touched everything it can use, so an object untouched - # for a week is dead, usually orphaned by a flag change. - - name: Compiler cache statistics - if: always() - run: | - export CCACHE_DIR=$PWD/.flatpak-builder/ccache - ccache --evict-older-than 7d - ccache -s -v || ccache -s - shell: bash - # Save the new entry first, then drop the older ones for this leg on this - # ref, so a failed save leaves the previous entry in place. A cancelled or - # failed build saves too, since what it compiled is still valid; a restore - # that did not finish does not, since the directory may be a truncated copy. - - name: Save compiler cache - id: ccache_save - if: ${{ always() && steps.ccache_restore.outcome == 'success' && github.event_name != 'pull_request' }} - uses: actions/cache/save@v6 - with: - path: .flatpak-builder/ccache - key: ${{ env.CCACHE_ENTRY }} - - name: Drop older compiler cache entries - if: ${{ always() && steps.ccache_save.outcome == 'success' }} - # The container has no gh, so this is the list and delete over the REST API. - # Older means a lower run id, so two runs finishing close together keep - # the newer entry whichever of them cleans up last. - continue-on-error: true - env: - GH_TOKEN: ${{ github.token }} - run: | - api="$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/actions/caches" - # The save step reports success even when its tar failed, so keep - # the older entries unless the new one is listed. - if ! curl -sSf -H "Authorization: Bearer $GH_TOKEN" \ - "$api?ref=$GITHUB_REF&key=$CCACHE_ENTRY" \ - | jq -e --arg entry "$CCACHE_ENTRY" 'any(.actions_caches[]; .key == $entry)' > /dev/null; then - echo "$CCACHE_ENTRY was not saved; keeping the older entries." - exit 0 - fi - curl -sSf -H "Authorization: Bearer $GH_TOKEN" \ - "$api?ref=$GITHUB_REF&key=ccache-$CCACHE_LEG-&per_page=100" \ - | jq -r --arg prefix "ccache-$CCACHE_LEG-" --argjson run "$GITHUB_RUN_ID" \ - '.actions_caches[] | select((.key | ltrimstr($prefix) | split("-")[0] | tonumber?) < $run) | .id' \ - | while read -r id; do - curl -sSf -X DELETE -H "Authorization: Bearer $GH_TOKEN" "$api/$id" - done - shell: bash - - name: Upload artifacts Flatpak - uses: actions/upload-artifact@v7 - with: - name: OrcaSlicer-Linux-flatpak_${{ env.ver }}_${{ matrix.variant.arch }}.flatpak - path: '/__w/OrcaSlicer/OrcaSlicer/OrcaSlicer-Linux-flatpak_${{ env.ver }}_${{ matrix.variant.arch }}.flatpak' - - name: Deploy Flatpak to nightly release - if: github.repository == 'OrcaSlicer/OrcaSlicer' && github.ref == 'refs/heads/main' - uses: ./.github/actions/deploy-nightly - with: - asset_path: /__w/OrcaSlicer/OrcaSlicer/OrcaSlicer-Linux-flatpak_${{ env.ver }}_${{ matrix.variant.arch }}.flatpak - asset_name: OrcaSlicer-Linux-flatpak_nightly_${{ matrix.variant.arch }}.flatpak - # The asset is /app (the exes link it at runtime) plus the build tree - # slimmed to what ctest needs. - - name: Package flatpak test asset - shell: bash - run: | - d=$(ls -d .flatpak-builder/build/OrcaSlicer-* | tail -1) - find "$d/build_flatpak" -mindepth 1 -maxdepth 1 ! -name tests -exec rm -rf {} + - # Strip debug info (the SDK builds with -g, only the app gets stripped); - # the bounds checks are compiled in, so a stripped exe still catches them. - find "$d/build_flatpak/tests" -type f -perm -u+x -exec strip --strip-unneeded {} + 2>/dev/null || true - # At runtime the tests read tests/ (TEST_DATA_DIR), scripts/, and under - # resources/ the shipped profiles (PROFILES_DIR), the printers/ maps, and - # the icon SVGs (NativeCommands icon names are checked against them). - find "$d" -mindepth 1 -maxdepth 1 -type d \ - ! -name tests ! -name build_flatpak ! -name scripts ! -name resources -exec rm -rf {} + - find "$d/resources" -mindepth 1 -maxdepth 1 ! -name profiles ! -name printers ! -name images -exec rm -rf {} + - # Only the SVGs are read; the png/ico/icns/gif assets are ~35MB of dead weight. - find "$d/resources/images" -mindepth 1 -maxdepth 1 ! -name '*.svg' -exec rm -rf {} + 2>/dev/null || true - tar -cf flatpak-test-asset.tar flatpak_app "$d" - - name: Upload flatpak test asset - uses: actions/upload-artifact@v7 - with: - name: ${{ github.sha }}-flatpak-tests-${{ matrix.variant.arch }} - path: flatpak-test-asset.tar - retention-days: 1 - # keep-build-dirs would otherwise land in the flatpak-builder cache saved post-job. - - name: Drop the kept build dirs before the flatpak-builder cache saves - if: always() - shell: bash - run: rm -rf .flatpak-builder/build - unit_tests_flatpak_x86_64: - name: Flatpak x86_64 - needs: flatpak - if: ${{ !cancelled() && success() }} - uses: ./.github/workflows/unit_tests_flatpak.yml - with: - os: ubuntu-24.04 - artifact: ${{ github.sha }}-flatpak-tests-x86_64 - unit_tests_flatpak_aarch64: - name: Flatpak aarch64 - needs: flatpak - if: ${{ !cancelled() && success() }} - uses: ./.github/workflows/unit_tests_flatpak.yml - with: - os: ubuntu-24.04-arm - artifact: ${{ github.sha }}-flatpak-tests-aarch64 + if: ${{ !cancelled() && !vars.SELF_HOSTED && github.event_name != 'pull_request' && (github.event_name != 'schedule' || github.repository == 'OrcaSlicer/OrcaSlicer') }} + uses: ./.github/workflows/build_flatpak.yml + secrets: inherit diff --git a/.github/workflows/build_check_cache.yml b/.github/workflows/build_check_cache.yml index 0da6c2b7b4..b7fdbcdc3d 100644 --- a/.github/workflows/build_check_cache.yml +++ b/.github/workflows/build_check_cache.yml @@ -20,10 +20,13 @@ on: required: false type: boolean -# Read by scripts/ci_deps_cache.sh. +# Read by scripts/ci_deps_cache.sh and scripts/ci_macos_admission.py. env: REPO: ${{ github.repository }} - WORKFLOW_REF: ${{ github.workflow_ref }} + # The workflow whose push and nightly builds save the deps caches. + WORKFLOW: build_all.yml + # Every workflow with macOS builds, the first of them the one above. + MACOS_WORKFLOWS: build_all.yml build_optional.yml BASE_REF: ${{ github.base_ref }} jobs: diff --git a/.github/workflows/build_flatpak.yml b/.github/workflows/build_flatpak.yml new file mode 100644 index 0000000000..88f39a8be6 --- /dev/null +++ b/.github/workflows/build_flatpak.yml @@ -0,0 +1,261 @@ +# The Flatpak build and its unit tests, for build_all.yml and for a pull request +# that asks for it (build_optional.yml). +name: Build Flatpak + +on: + workflow_call: + +jobs: + flatpak: + name: Build Flatpak + container: + image: ghcr.io/flathub-infra/flatpak-github-actions:gnome-50 + options: --privileged + volumes: + - /usr/local/lib/android:/usr/local/lib/android + - /usr/share/dotnet:/usr/share/dotnet + - /opt/ghc:/opt/ghc1 + - /usr/local/share/boost:/usr/local/share/boost1 + - /opt/hostedtoolcache:/opt/hostedtoolcache1 + # Updating a runtime renames its old deployment, which fails with + # "Invalid cross-device link" on hosts whose Docker overlay cannot + # rename directories from an image layer. A volume is not overlay. + - /var/lib/flatpak + strategy: + fail-fast: false + matrix: + variant: + - arch: x86_64 + runner: ubuntu-24.04 + - arch: aarch64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.variant.runner }} + env: + date: + ver: + ver_pure: + steps: + - name: "Remove unneeded stuff to free disk space" + run: + rm -rf /usr/local/lib/android/* /usr/share/dotnet/* /opt/ghc1/* "/usr/local/share/boost1/*" /opt/hostedtoolcache1/* + - uses: actions/checkout@v7 + - name: Get the version and date + run: | + ver_pure=$(grep 'set(SoftFever_VERSION' version.inc | cut -d '"' -f2) + if [[ "${{ github.event_name }}" == "pull_request" ]]; then + ver="PR-${{ github.event.number }}" + git_commit_hash="${{ github.event.pull_request.head.sha }}" + else + ver=V$ver_pure + git_commit_hash="${{ github.sha }}" + fi + echo "ver=$ver" >> $GITHUB_ENV + echo "ver_pure=$ver_pure" >> $GITHUB_ENV + echo "date=$(date +'%Y%m%d')" >> $GITHUB_ENV + echo "git_commit_hash=$git_commit_hash" >> $GITHUB_ENV + shell: bash + - name: Compute the flatpak-builder cache key + id: fp_cache_key + run: echo "key=flatpak-builder-${{ matrix.variant.arch }}-${{ hashFiles('deps/**', 'scripts/flatpak/com.orcaslicer.OrcaSlicer.yml', 'scripts/flatpak/make_deps_tar.sh') }}" >> "$GITHUB_OUTPUT" + shell: bash + # Manage flatpak-builder cache externally so PRs restore but never upload. + # The compiler cache under it is keyed per run below, so it is left out. + - name: Restore flatpak-builder cache + if: github.event_name == 'pull_request' + uses: actions/cache/restore@v6 + with: + path: | + .flatpak-builder/* + !.flatpak-builder/ccache + key: ${{ steps.fp_cache_key.outputs.key }} + restore-keys: flatpak-builder-${{ matrix.variant.arch }}- + - name: Save/restore flatpak-builder cache + if: github.event_name != 'pull_request' + uses: actions/cache@v6 + with: + path: | + .flatpak-builder/* + !.flatpak-builder/ccache + key: ${{ steps.fp_cache_key.outputs.key }} + restore-keys: flatpak-builder-${{ matrix.variant.arch }}- + # Compiler cache for the OrcaSlicer module, as in build_orca.yml. Pull + # requests only restore it; every other run (main, release branches, the + # nightly, a dispatch) saves it. orca_deps stays on the state cache above. + - name: Name the compiler cache leg + run: | + leg="Flatpak-${{ matrix.variant.arch }}" + echo "CCACHE_LEG=$leg" >> "$GITHUB_ENV" + echo "CCACHE_ENTRY=ccache-$leg-${{ github.run_id }}-${{ github.run_attempt }}" >> "$GITHUB_ENV" + shell: bash + - name: Restore compiler cache + id: ccache_restore + uses: actions/cache/restore@v6 + with: + path: .flatpak-builder/ccache + key: ${{ env.CCACHE_ENTRY }} + restore-keys: ccache-${{ env.CCACHE_LEG }}- + - name: Disable debug info for faster CI builds + run: | + sed -i '/^build-options:/a\ no-debuginfo: true\n strip: true' \ + scripts/flatpak/com.orcaslicer.OrcaSlicer.yml + shell: bash + # flatpak-builder reuses a module from its cache when the definition and + # sources are unchanged, so a re-run of the same commit would skip the + # OrcaSlicer module and ship no test asset. A per-run value in that module's + # env keeps it rebuilding; orca_deps stays cached, and the compiler cache + # still serves the rebuild. run-tests on the same module builds the test + # binaries. + - name: Inject commit hash, run-tests and cache buster into Flatpak manifest + env: + flatpak_builder_cache_buster: ${{ github.run_id }}-${{ github.run_attempt }} + run: | + sed -i "/name: OrcaSlicer/{n;s|buildsystem: simple|buildsystem: simple\n run-tests: true\n build-options:\n env:\n flatpak_builder_cache_buster: \"$flatpak_builder_cache_buster\"\n git_commit_hash: \"$git_commit_hash\"|}" \ + scripts/flatpak/com.orcaslicer.OrcaSlicer.yml + shell: bash + # flatpak-builder's --ccache only wraps cc and gcc, and the manifest builds + # with clang, so CMake's launcher runs ccache instead; --ccache is still what + # mounts the cache directory into the sandbox. The settings go into that + # directory's own config file, which the sandbox reads too. + - name: Enable compiler cache + run: | + printf ' %s\n' \ + 'CMAKE_C_COMPILER_LAUNCHER: ccache' \ + 'CMAKE_CXX_COMPILER_LAUNCHER: ccache' > "$RUNNER_TEMP/ccache-env.yml" + sed -i "/^ git_commit_hash: /r $RUNNER_TEMP/ccache-env.yml" \ + scripts/flatpak/com.orcaslicer.OrcaSlicer.yml + grep -q '^ CMAKE_CXX_COMPILER_LAUNCHER: ccache$' scripts/flatpak/com.orcaslicer.OrcaSlicer.yml + mkdir -p .flatpak-builder/ccache + export CCACHE_DIR=$PWD/.flatpak-builder/ccache + ccache --set-config=max_size=3G + # The compiler is reinstalled every run, so its mtime means nothing. + ccache --set-config=compiler_check=content + # Headers a fresh checkout has just written, the few files that use + # __DATE__ or __TIME__, and the precompiled header, whose macros ccache + # cannot see. + ccache --set-config=sloppiness=pch_defines,time_macros,include_file_mtime,include_file_ctime + # Hash the includes the compiler reports instead of preprocessing every + # miss before compiling it. + ccache --set-config=depend_mode=true + # The restored directory carries the previous run's counters. + ccache -z + shell: bash + - name: Check the manifest keeps orca_deps cacheable + run: ./scripts/flatpak/check_manifest_cacheable.sh + shell: bash + - name: Pack deps/ for the Flatpak manifest + run: ./scripts/flatpak/make_deps_tar.sh + shell: bash + - uses: flatpak/flatpak-github-actions/flatpak-builder@master + with: + bundle: OrcaSlicer-Linux-flatpak_${{ env.ver }}_${{ matrix.variant.arch }}.flatpak + manifest-path: scripts/flatpak/com.orcaslicer.OrcaSlicer.yml + # cache only turns on flatpak-builder --ccache; the caching itself is above. + cache: true + restore-cache: false + save-cache: false + arch: ${{ matrix.variant.arch }} + upload-artifact: false + keep-build-dirs: true + # The build has just touched everything it can use, so an object untouched + # for a week is dead, usually orphaned by a flag change. + - name: Compiler cache statistics + if: always() + run: | + export CCACHE_DIR=$PWD/.flatpak-builder/ccache + ccache --evict-older-than 7d + ccache -s -v || ccache -s + shell: bash + # Save the new entry first, then drop the older ones for this leg on this + # ref, so a failed save leaves the previous entry in place. A cancelled or + # failed build saves too, since what it compiled is still valid; a restore + # that did not finish does not, since the directory may be a truncated copy. + - name: Save compiler cache + id: ccache_save + if: ${{ always() && steps.ccache_restore.outcome == 'success' && github.event_name != 'pull_request' }} + uses: actions/cache/save@v6 + with: + path: .flatpak-builder/ccache + key: ${{ env.CCACHE_ENTRY }} + - name: Drop older compiler cache entries + if: ${{ always() && steps.ccache_save.outcome == 'success' }} + # The container has no gh, so this is the list and delete over the REST API. + # Older means a lower run id, so two runs finishing close together keep + # the newer entry whichever of them cleans up last. + continue-on-error: true + env: + GH_TOKEN: ${{ github.token }} + run: | + api="$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/actions/caches" + # The save step reports success even when its tar failed, so keep + # the older entries unless the new one is listed. + if ! curl -sSf -H "Authorization: Bearer $GH_TOKEN" \ + "$api?ref=$GITHUB_REF&key=$CCACHE_ENTRY" \ + | jq -e --arg entry "$CCACHE_ENTRY" 'any(.actions_caches[]; .key == $entry)' > /dev/null; then + echo "$CCACHE_ENTRY was not saved; keeping the older entries." + exit 0 + fi + curl -sSf -H "Authorization: Bearer $GH_TOKEN" \ + "$api?ref=$GITHUB_REF&key=ccache-$CCACHE_LEG-&per_page=100" \ + | jq -r --arg prefix "ccache-$CCACHE_LEG-" --argjson run "$GITHUB_RUN_ID" \ + '.actions_caches[] | select((.key | ltrimstr($prefix) | split("-")[0] | tonumber?) < $run) | .id' \ + | while read -r id; do + curl -sSf -X DELETE -H "Authorization: Bearer $GH_TOKEN" "$api/$id" + done + shell: bash + - name: Upload artifacts Flatpak + uses: actions/upload-artifact@v7 + with: + name: OrcaSlicer-Linux-flatpak_${{ env.ver }}_${{ matrix.variant.arch }}.flatpak + path: '/__w/OrcaSlicer/OrcaSlicer/OrcaSlicer-Linux-flatpak_${{ env.ver }}_${{ matrix.variant.arch }}.flatpak' + - name: Deploy Flatpak to nightly release + if: github.repository == 'OrcaSlicer/OrcaSlicer' && github.ref == 'refs/heads/main' + uses: ./.github/actions/deploy-nightly + with: + asset_path: /__w/OrcaSlicer/OrcaSlicer/OrcaSlicer-Linux-flatpak_${{ env.ver }}_${{ matrix.variant.arch }}.flatpak + asset_name: OrcaSlicer-Linux-flatpak_nightly_${{ matrix.variant.arch }}.flatpak + # The asset is /app (the exes link it at runtime) plus the build tree + # slimmed to what ctest needs. + - name: Package flatpak test asset + shell: bash + run: | + d=$(ls -d .flatpak-builder/build/OrcaSlicer-* | tail -1) + find "$d/build_flatpak" -mindepth 1 -maxdepth 1 ! -name tests -exec rm -rf {} + + # Strip debug info (the SDK builds with -g, only the app gets stripped); + # the bounds checks are compiled in, so a stripped exe still catches them. + find "$d/build_flatpak/tests" -type f -perm -u+x -exec strip --strip-unneeded {} + 2>/dev/null || true + # At runtime the tests read tests/ (TEST_DATA_DIR), scripts/, and under + # resources/ the shipped profiles (PROFILES_DIR), the printers/ maps, and + # the icon SVGs (NativeCommands icon names are checked against them). + find "$d" -mindepth 1 -maxdepth 1 -type d \ + ! -name tests ! -name build_flatpak ! -name scripts ! -name resources -exec rm -rf {} + + find "$d/resources" -mindepth 1 -maxdepth 1 ! -name profiles ! -name printers ! -name images -exec rm -rf {} + + # Only the SVGs are read; the png/ico/icns/gif assets are ~35MB of dead weight. + find "$d/resources/images" -mindepth 1 -maxdepth 1 ! -name '*.svg' -exec rm -rf {} + 2>/dev/null || true + tar -cf flatpak-test-asset.tar flatpak_app "$d" + - name: Upload flatpak test asset + uses: actions/upload-artifact@v7 + with: + name: ${{ github.sha }}-flatpak-tests-${{ matrix.variant.arch }} + path: flatpak-test-asset.tar + retention-days: 1 + # keep-build-dirs would otherwise land in the flatpak-builder cache saved post-job. + - name: Drop the kept build dirs before the flatpak-builder cache saves + if: always() + shell: bash + run: rm -rf .flatpak-builder/build + unit_tests_flatpak_x86_64: + name: Flatpak x86_64 + needs: flatpak + if: ${{ !cancelled() && success() }} + uses: ./.github/workflows/unit_tests_flatpak.yml + with: + os: ubuntu-24.04 + artifact: ${{ github.sha }}-flatpak-tests-x86_64 + unit_tests_flatpak_aarch64: + name: Flatpak aarch64 + needs: flatpak + if: ${{ !cancelled() && success() }} + uses: ./.github/workflows/unit_tests_flatpak.yml + with: + os: ubuntu-24.04-arm + artifact: ${{ github.sha }}-flatpak-tests-aarch64 diff --git a/.github/workflows/build_optional.yml b/.github/workflows/build_optional.yml new file mode 100644 index 0000000000..abe28b5a32 --- /dev/null +++ b/.github/workflows/build_optional.yml @@ -0,0 +1,186 @@ +# The builds a pull request gets only when asked for. build_all.yml leaves them +# out of pull requests and builds them on every push to main: the Flatpak is +# the slowest Linux leg, a macOS x86_64 build holds one of the few hosted macOS +# runners for an hour, and Windows arm64 doubles the Windows legs. +# +# A label asks for one, from the moment it is added and on every later push to +# the pull request: build-flatpak, build-macos-x86_64, build-windows-arm64, or +# build-all for every one of them. Removing and adding a label again rebuilds +# the same commit. +# +# A pull request that changes anything but sources, tests, profiles, +# translations and docs builds the Flatpak and Windows arm64 without a label: +# what breaks only those legs lives in deps/, cmake/, the build scripts and the +# workflows, and a list of those places would go stale, so the safe places are +# listed instead. The macOS build never starts on its own. +# +# Each label added starts a run of its own, and the pull request's checks show +# the newest run only, so every run builds everything the labels and the +# changed files ask for. Each build keeps its own concurrency group: the newest +# run's build cancels the one an earlier run of the commit started, and a push +# cancels the builds of the commit it replaces. cancel_closed_pr_builds.yml +# joins the groups by name, so update that file with any change here. +name: Optional builds + +on: + pull_request: + branches: + - main + - release/* + # Build all's pull_request paths, plus the Flatpak packaging: a pull request + # that Build all skips has nothing for these builds to check either, and + # the filter applies to labeled too. Keep the two lists in step. + paths: + - 'deps/**' + - 'deps_src/**' + - 'cmake/**' + - 'src/**' + - '**/CMakeLists.txt' + - 'version.inc' + - ".github/workflows/build_*.yml" + - ".github/workflows/unit_tests*.yml" + - 'build_linux.sh' + - 'build_win.bat' + - 'scripts/test_build_win.ps1' + - 'scripts/check_exception_throw_info.ps1' + - 'scripts/test_check_exception_throw_info.ps1' + - 'build_release_macos.sh' + - 'scripts/build_preset_cache.*' + - 'scripts/prune_cached_presets.ps1' + - 'scripts/test_prune_cached_presets.ps1' + - 'scripts/flatpak/**' + - 'scripts/msix/**' + - 'tests/**' + # labeled, so adding a label starts the build it asks for. + types: [opened, reopened, synchronize, labeled] + +jobs: + select: + name: Select builds + runs-on: ubuntu-24.04 + outputs: + flatpak: ${{ steps.select.outputs.flatpak }} + macos-x86_64: ${{ steps.select.outputs.macos-x86_64 }} + windows-arm64: ${{ steps.select.outputs.windows-arm64 }} + steps: + - name: Checkout + uses: actions/checkout@v7 + with: + lfs: 'false' + # The merge commit plus its first parent, the base it is diffed against. + fetch-depth: 2 + sparse-checkout: .github/workflows + - name: Select the builds the labels and the changed files ask for + id: select + env: + LABELS: ${{ join(github.event.pull_request.labels.*.name, ' ') }} + run: | + has_label() { [[ " $LABELS " == *" $1 "* ]]; } + infra=false + changed=$(git diff --name-only HEAD^1 HEAD \ + | grep -vE '^(src|tests|resources|localization|docs)/' | grep -vE '\.md$' || true) + if [ -n "$changed" ]; then + echo "This pull request changes files outside the sources, tests, profiles, translations and docs:" + echo "$changed" | head -20 + infra=true + fi + pick() { + local build=$1 label=$2 auto=$3 on=false + if has_label "$label" || has_label build-all || { [ "$auto" = true ] && [ "$infra" = true ]; }; then + on=true + fi + echo "$build=$on" >> "$GITHUB_OUTPUT" + echo "$build: $on" + } + pick flatpak build-flatpak true + pick macos-x86_64 build-macos-x86_64 false + pick windows-arm64 build-windows-arm64 true + + flatpak: + name: Flatpak + needs: select + # Skipped on self-hosted runners, as in build_all.yml. + if: ${{ needs.select.outputs.flatpak == 'true' && !vars.SELF_HOSTED }} + concurrency: + group: build-optional-flatpak-${{ github.event.pull_request.number }} + cancel-in-progress: true + uses: ./.github/workflows/build_flatpak.yml + secrets: inherit + + # Named like build_all.yml's job, so scripts/ci_macos_admission.py and + # scripts/ci_deps_cache.sh find its jobs, and the pull request waits in the + # macOS line like any other. + build_macos_arch: + needs: select + if: ${{ needs.select.outputs.macos-x86_64 == 'true' }} + strategy: + matrix: + arch: + - x86_64 + concurrency: + group: build-optional-macos-${{ matrix.arch }}-${{ github.event.pull_request.number }} + cancel-in-progress: true + uses: ./.github/workflows/build_check_cache.yml + with: + os: ${{ vars.SELF_HOSTED && 'orca-macos-arm64' || 'macos-15' }} + arch: ${{ matrix.arch }} + secrets: inherit + + # build_all.yml has already run the build script's test suite for this + # commit, before its Windows x64 build. Skipped on self-hosted runners, as + # there (the self-hosted Windows server is x64-only). + build_windows_arm64: + name: Build Windows arm64 + needs: select + if: ${{ needs.select.outputs.windows-arm64 == 'true' && !vars.SELF_HOSTED }} + concurrency: + group: build-optional-windows-arm64-${{ github.event.pull_request.number }} + cancel-in-progress: true + uses: ./.github/workflows/build_check_cache.yml + with: + os: windows-11-vs2026-arm + arch: arm64 + compiler: clang + secrets: inherit + unit_tests_windows_arm64: + name: Windows arm64 + needs: build_windows_arm64 + if: ${{ !cancelled() && success() }} + # The build's group, free once the build finished, so a newer build of this + # pull request cancels these tests too. + concurrency: + group: build-optional-windows-arm64-${{ github.event.pull_request.number }} + cancel-in-progress: true + uses: ./.github/workflows/unit_tests.yml + with: + os: windows-11-vs2026-arm + artifact: ${{ github.sha }}-tests-windows-arm64 + test-dir: build-arm64/tests + + publish_test_results: + name: Publish Test Results + needs: [flatpak, unit_tests_windows_arm64] + if: ${{ !cancelled() && (needs.flatpak.result != 'skipped' || needs.unit_tests_windows_arm64.result != 'skipped') }} + runs-on: ubuntu-latest + steps: + - name: Download Test Results + uses: actions/download-artifact@v8 + with: + pattern: test-results-* + path: test-results + # Best-effort, as in build_all.yml: a read-only token (e.g. fork PRs) + # can't write the check. The test jobs gate correctness. + - name: Publish Test Results + continue-on-error: true + uses: EnricoMi/publish-unit-test-result-action@v2 + with: + # Its own check, next to the one build_all.yml publishes for the + # same commit. + check_name: Optional Test Results + files: "test-results/**/*.xml" + - name: Delete Test Results + if: success() + uses: geekyeggo/delete-artifact@v6 + with: + name: test-results-* + failOnError: false diff --git a/.github/workflows/build_orca.yml b/.github/workflows/build_orca.yml index 15293ff970..6fb4b09b08 100644 --- a/.github/workflows/build_orca.yml +++ b/.github/workflows/build_orca.yml @@ -219,14 +219,38 @@ jobs: # installed into it here; the source tree keeps its JSONs for later jobs. run: ./scripts/build_preset_cache.sh -b build/${{ inputs.arch }} build/${{ inputs.arch }}/OrcaSlicer/OrcaSlicer.app/Contents/Resources/profiles + # A pull request builds no universal app (build_all.yml), so each arch it + # builds ships as its own DMG; every other run packs the bundle for the + # universal job below. + - name: Create DMG ${{ inputs.arch }} without notary + if: runner.os == 'macOS' && !inputs.macos-combine-only && github.event_name == 'pull_request' + working-directory: ${{ github.workspace }} + run: | + # Load the `retry` and `create_dmg` helpers. + source ${{ github.workspace }}/scripts/retry.sh + source ${{ github.workspace }}/scripts/create_dmg.sh + dmg_dir=${{ github.workspace }}/build/${{ inputs.arch }}/OrcaSlicer_dmg + mkdir -p "$dmg_dir" + rm -rf "$dmg_dir"/* + cp -R ${{ github.workspace }}/build/${{ inputs.arch }}/OrcaSlicer/OrcaSlicer.app "$dmg_dir/" + ln -sfn /Applications "$dmg_dir/Applications" + create_dmg "OrcaSlicer" "$dmg_dir" OrcaSlicer_Mac_${{ inputs.arch }}_${{ env.ver }}.dmg + + - name: Upload DMG ${{ inputs.arch }} + if: runner.os == 'macOS' && !inputs.macos-combine-only && github.event_name == 'pull_request' + uses: actions/upload-artifact@v7 + with: + name: OrcaSlicer_Mac_${{ inputs.arch }}_${{ env.ver }} + path: ${{ github.workspace }}/OrcaSlicer_Mac_${{ inputs.arch }}_${{ env.ver }}.dmg + - name: Pack macOS app bundle ${{ inputs.arch }} - if: runner.os == 'macOS' && !inputs.macos-combine-only + if: runner.os == 'macOS' && !inputs.macos-combine-only && github.event_name != 'pull_request' working-directory: ${{ github.workspace }} run: | tar -czvf OrcaSlicer_Mac_bundle_${{ inputs.arch }}_${{ github.sha }}.tar.gz -C build/${{ inputs.arch }} OrcaSlicer - name: Upload macOS app bundle ${{ inputs.arch }} - if: runner.os == 'macOS' && !inputs.macos-combine-only + if: runner.os == 'macOS' && !inputs.macos-combine-only && github.event_name != 'pull_request' uses: actions/upload-artifact@v7 with: name: OrcaSlicer_Mac_bundle_${{ inputs.arch }}_${{ github.sha }} @@ -707,6 +731,12 @@ jobs: - name: Build slicer and tests if: runner.os == 'Linux' shell: bash + env: + # libstdc++'s checks, so the unit tests abort on an out-of-range + # access here too. The Flatpak gets them from its SDK's default + # flags and was the only leg catching those on pull requests, which + # build it only on request. + ORCA_EXTRA_BUILD_ARGS: -DSLIC3R_GLIBCXX_ASSERTIONS=ON run: | # Build + tar the unit tests (-t) on both Linux legs so each arch # (x86_64 + aarch64) gets tested by its own unit_tests_linux_* job. diff --git a/.github/workflows/cancel_closed_pr_builds.yml b/.github/workflows/cancel_closed_pr_builds.yml index c0c9c52fee..84fe9a2e59 100644 --- a/.github/workflows/cancel_closed_pr_builds.yml +++ b/.github/workflows/cancel_closed_pr_builds.yml @@ -19,3 +19,17 @@ jobs: runs-on: ubuntu-latest steps: - run: echo "Joined concurrency group build-all-pull_request-${{ github.event.pull_request.number }}." + cancel_optional: + # The same for the builds of build_optional.yml, which keep a group each. + strategy: + matrix: + build: + - flatpak + - macos-x86_64 + - windows-arm64 + concurrency: + group: build-optional-${{ matrix.build }}-${{ github.event.pull_request.number }} + cancel-in-progress: true + runs-on: ubuntu-latest + steps: + - run: echo "Joined concurrency group build-optional-${{ matrix.build }}-${{ github.event.pull_request.number }}." diff --git a/.github/workflows/pr-label-bot.yml b/.github/workflows/pr-label-bot.yml index 25abd94e27..1a450ff205 100644 --- a/.github/workflows/pr-label-bot.yml +++ b/.github/workflows/pr-label-bot.yml @@ -47,7 +47,12 @@ jobs: 'build', 'test', 'dependencies', - 'documentation' + 'documentation', + // optional builds (build_optional.yml) + 'build-flatpak', + 'build-macos-x86_64', + 'build-windows-arm64', + 'build-all' ]; const pr = context.payload.pull_request; // First-time contributors also get a link to the contributing guide @@ -80,6 +85,8 @@ jobs: body: `${greeting} manage the labels for this PR by \`/bot add-label\` and \`/bot remove-label\`.\n\n` + `Allowed labels are:\n${labelsList}\n\n` + + `The \`build-\` labels start the builds a PR does not get by default: the Flatpak, ` + + `the Intel Mac app and Windows arm64. A maintainer may first have to approve the run.\n\n` + `Examples:\n${examplesText}` }); } catch (error) { @@ -192,10 +199,34 @@ jobs: pull-requests: write issues: write runs-on: ubuntu-latest + # GitHub starts no workflow from an event the job's own token causes, so a + # build-* label added with it would not start the build it asks for. An + # installation token of a GitHub App does, and the run it starts still waits + # for a maintainer's approval when the pull request's runs need one. The app + # needs issues and pull requests write access to this repository. Without + # the secrets, labels are still applied and the build starts with the pull + # request's next push. + env: + LABEL_BOT_APP_ID: ${{ secrets.LABEL_BOT_APP_ID }} steps: + - name: Mint a token that starts workflows + id: token + if: ${{ env.LABEL_BOT_APP_ID != '' }} + # An app that is not installed here, or a rotated key, costs the early + # start, not the labels. + continue-on-error: true + uses: actions/create-github-app-token@v3 + with: + app-id: ${{ secrets.LABEL_BOT_APP_ID }} + private-key: ${{ secrets.LABEL_BOT_APP_PRIVATE_KEY }} + permission-issues: write + permission-pull-requests: write - name: Apply label command from PR author uses: actions/github-script@v9 + env: + STARTS_WORKFLOWS: ${{ steps.token.outcome == 'success' }} with: + github-token: ${{ steps.token.outputs.token || github.token }} script: | function isPermissionDenied(error) { return error && error.status === 403 && /Resource not accessible by integration/i.test(error.message || ''); @@ -217,7 +248,12 @@ jobs: 'build', 'test', 'dependencies', - 'documentation' + 'documentation', + // optional builds (build_optional.yml) + 'build-flatpak', + 'build-macos-x86_64', + 'build-windows-arm64', + 'build-all' ]; const issue = context.payload.issue; @@ -314,6 +350,28 @@ jobs: } core.info(`Added labels: ${uniqueRequestedLabels.join(', ')}`); + + const buildLabels = uniqueRequestedLabels.filter((label) => label.startsWith('build-')); + if (buildLabels.length) { + const buildText = buildLabels.map((label) => `\`${label}\``).join(', '); + const when = process.env.STARTS_WORKFLOWS === 'true' + ? 'starts now under "Optional builds" in the Checks tab; a maintainer may first have to approve the workflow run' + : 'starts with the next push to this PR, under "Optional builds" in the Checks tab'; + try { + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issue.number, + body: `@${commenter} the build for ${buildText} ${when}.` + }); + } catch (error) { + if (isPermissionDenied(error)) { + core.warning('Cannot post the build label reply because token cannot write comments.'); + } else { + throw error; + } + } + } } if (action === 'remove' && uniqueRequestedLabels.length) { diff --git a/CMakeLists.txt b/CMakeLists.txt index ae29f2fd5c..dd6ed55818 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -120,6 +120,7 @@ option(SLIC3R_MSVC_COMPILE_PARALLEL "Compile on Visual Studio in parallel" 1) option(SLIC3R_MSVC_PDB "Generate PDB files on MSVC in Release mode" 1) option(SLIC3R_RELATIVE_DEBUG_PATHS "Record a relative compilation directory in debug info (clang-cl)" 0) option(SLIC3R_ASAN "Enable ASan on Clang and GCC" 0) +option(SLIC3R_GLIBCXX_ASSERTIONS "Enable libstdc++'s lightweight checks (_GLIBCXX_ASSERTIONS)" 0) # Python stubgen module option(ORCA_BUILD_PYTHON_STUBGEN_MODULE "Build importable Python module for pybind11-stubgen" ON) @@ -660,6 +661,14 @@ if ((NOT MSVC OR IS_CLANG_CL) AND ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR endif() +if (SLIC3R_GLIBCXX_ASSERTIONS) + # libstdc++'s lightweight checks: operator[] past the end, front() or + # back() on an empty container and the like abort with a message instead + # of reading out of range. No class changes layout, so prebuilt deps link + # as they are. A no-op with libc++ and the MSVC STL. + add_compile_definitions(_GLIBCXX_ASSERTIONS) +endif () + if (SLIC3R_ASAN) # ASAN should be available on MSVC starting with Visual Studio 2019 16.9 # https://devblogs.microsoft.com/cppblog/address-sanitizer-for-msvc-now-generally-available/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7639ce8f3e..7843a07f14 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -82,6 +82,7 @@ If you are an AI agent working for a contributor, please follow these steps: ## After you open the PR - **Add labels.** A bot will comment with instructions. Reply with the labels from the table above, for example `/bot add-label bug-fix, UI/UX`. +- **Need a Flatpak, Intel Mac or Windows arm64 build to test?** PR builds leave those out. `/bot add-label build-flatpak`, `build-macos-x86_64` or `build-windows-arm64` asks for one, `build-all` for all of them; for a first PR a maintainer approves the run first. A PR that changes anything outside `src/`, `tests/`, `resources/`, `localization/` and `docs/` gets the Flatpak and Windows arm64 builds without a label. See [How to Download Pull Requests Artifacts](https://www.orcaslicer.com/wiki/how_to_download_pr_artifacts#builds-on-request). - **Leave "Allow edits by maintainers" turned on**, so a reviewer can push small fixes directly. - **Mark the PR ready for review when it's finished.** Draft PRs are not merged. - **Push new commits to the same PR.** Please don't open a new PR for the same change. diff --git a/scripts/ci_deps_cache.sh b/scripts/ci_deps_cache.sh index 0c3ae85415..136033cbb1 100644 --- a/scripts/ci_deps_cache.sh +++ b/scripts/ci_deps_cache.sh @@ -7,16 +7,14 @@ # request changes deps/. `wait` waits until that build saves KEY under CACHE_REF, # or its deps job fails. actions/cache then confirms the entry can be restored. # -# Environment: GH_TOKEN, REPO, WORKFLOW_REF (or WORKFLOW, the build workflow's -# file name) and BASE_REF, plus HEAD_SHA for `own`, and KEY_INPUTS, WAIT_FOR, +# Environment: GH_TOKEN, REPO, WORKFLOW (the build workflow's file name) and +# BASE_REF, plus HEAD_SHA for `own`, and KEY_INPUTS, WAIT_FOR, # WAIT_SINCE, WAIT_MINUTES, KEY, CACHE_REF (default the base branch) and ARCH # (or JOB, the matrix job's name) for `wait`. # Writes key-inputs, wait-for and wait-since to $GITHUB_OUTPUT. set -uo pipefail -workflow=${WORKFLOW_REF:-} -workflow=${workflow%%@*} -workflow=${WORKFLOW:-${workflow##*/}} +workflow=${WORKFLOW:?} # Must match the job names in build_all.yml, build_check_cache.yml and build_deps.yml. job=${JOB:-build_macos_arch (${ARCH:-})} diff --git a/scripts/ci_macos_admission.py b/scripts/ci_macos_admission.py index 0b5089ac2b..e53f4e29b4 100644 --- a/scripts/ci_macos_admission.py +++ b/scripts/ci_macos_admission.py @@ -3,8 +3,10 @@ Runs from a Linux job in build_check_cache.yml, once per macOS arch, in a single repo-wide line (a concurrency group with queue: max), so only the job at the -front of the line polls. It lets its arch in when the runners every active Build -all run holds or still needs, plus one for this arch, fit in MACOS_RUNNER_LIMIT: +front of the line polls. It lets its arch in when the runners every active run +of the workflows with macOS builds (build_all.yml, and build_optional.yml for a +pull request's x86_64 build) holds or still needs, plus one for this arch, fit +in MACOS_RUNNER_LIMIT: - A push, nightly or manual run holds RESERVE runners until its macOS work is done. The jobs API lists only the jobs a run has reached, so what it still @@ -15,9 +17,8 @@ all run holds or still needs, plus one for this arch, fit in MACOS_RUNNER_LIMIT: pull request that waits for that runner. - A run holds at least the macOS jobs it has queued or running. -A pull request's universal build and tests skip the line and are not held for -in advance. They take minutes, and holding two runners for them through the -slower arch's build left runners idle while other builds waited. +A pull request's macOS tests skip the line and are not held for in advance: +they take minutes. - In the minutes around the nightly's cron time, RESERVE runners are held for it until its run appears. @@ -28,8 +29,10 @@ waiting as holding a runner, so the next free runners go to it. Any API error repeated FAILURES_BEFORE_ADMIT times, and the WAIT_MINUTES limit, let the arch in, so a fault here never blocks pull requests. -Environment: GH_TOKEN, REPO, WORKFLOW_REF, GITHUB_RUN_ID, and optionally PRIORITY, -MACOS_RUNNER_LIMIT, WAIT_MINUTES, POLL_SECONDS and GITHUB_API_URL. +Environment: GH_TOKEN, REPO, MACOS_WORKFLOWS (the workflow files with macOS +builds, the first of them the one that runs the pushes and the nightly), +GITHUB_RUN_ID, and optionally PRIORITY, MACOS_RUNNER_LIMIT, WAIT_MINUTES, +POLL_SECONDS and GITHUB_API_URL. """ import datetime @@ -178,9 +181,10 @@ def latest_run(api, repo, workflow, **params): return runs[0] if runs else None -def measure(api, repo, workflow, run_id, now, priority=False): +def measure(api, repo, workflows, run_id, now, priority=False): """Total macOS runners held or needed, and one line per run that holds any. - The priority line does not count the priority runs waiting behind it.""" + The priority line does not count the priority runs waiting behind it. The + first of the workflows runs the pushes and the nightly.""" total, lines = 0, [] # A run is listed as queued whenever one of its jobs waits for a runner, and # as pending whenever one waits in a concurrency group, so runs in any of these @@ -189,9 +193,11 @@ def measure(api, repo, workflow, run_id, now, priority=False): # runs created recently are listed by creation time as well, and this run is # read directly. since = (now - RECENT).strftime("%Y-%m-%dT%H:%M:%SZ") - runs = {run["id"]: run for status in ("in_progress", "queued", "pending", "waiting") + runs = {run["id"]: run for workflow in workflows + for status in ("in_progress", "queued", "pending", "waiting") for run in list_runs(api, repo, workflow, status=status)} - runs.update((run["id"], run) for run in list_runs(api, repo, workflow, created=f">={since}") + runs.update((run["id"], run) for workflow in workflows + for run in list_runs(api, repo, workflow, created=f">={since}") if run["status"] != "completed") runs[run_id] = api.get(f"repos/{repo}/actions/runs/{run_id}") for run in runs.values(): @@ -207,7 +213,7 @@ def measure(api, repo, workflow, run_id, now, priority=False): # build_all.yml runs the nightly only in the main repository. start, end = nightly_window(now) if repo == NIGHTLY_REPO and start <= now < end: - last = latest_run(api, repo, workflow, event="schedule") + last = latest_run(api, repo, workflows[0], event="schedule") if not last or parse_time(last["created_at"]) < start: total += RESERVE lines.append(f" {RESERVE} the nightly, due at {NIGHTLY_UTC:%H:%M} UTC") @@ -241,7 +247,7 @@ def wait(measure_now, limit, wait_minutes, poll_seconds, def main(): repo = os.environ["REPO"] - workflow = os.environ["WORKFLOW_REF"].split("@")[0].rsplit("/", 1)[-1] + workflows = os.environ["MACOS_WORKFLOWS"].split() api = Api(os.environ["GH_TOKEN"], os.environ.get("GITHUB_API_URL", "https://api.github.com")) run_id = int(os.environ["GITHUB_RUN_ID"]) limit = int(os.environ.get("MACOS_RUNNER_LIMIT") or 5) @@ -249,7 +255,7 @@ def main(): def measure_now(): calls_before = api.calls try: - total, lines = measure(api, repo, workflow, run_id, datetime.datetime.now(datetime.timezone.utc), + total, lines = measure(api, repo, workflows, run_id, datetime.datetime.now(datetime.timezone.utc), priority=os.environ.get("PRIORITY") == "true") except Exception: print(api.usage(calls_before).strip()) diff --git a/scripts/tests/test_ci_macos_admission.py b/scripts/tests/test_ci_macos_admission.py index b872545d3f..0cba1ed167 100644 --- a/scripts/tests/test_ci_macos_admission.py +++ b/scripts/tests/test_ci_macos_admission.py @@ -37,6 +37,7 @@ def build(arch, status="in_progress"): CHECK_CACHE = job("build_macos_arch (arm64) / Check Cache", labels=("ubuntu-24.04",)) UNIVERSAL_DONE = job("Build macOS Universal / Build OrcaSlicer") TESTS_DONE = job("macOS arm64 / Unit Tests") +WORKFLOWS = ["build_all.yml", "build_optional.yml"] PUSH = {"id": 1, "event": "push", "head_branch": "main", "status": "in_progress"} PR = {"id": 2, "event": "pull_request", "head_branch": "topic", "status": "in_progress"} @@ -145,15 +146,15 @@ class PriorityTest(unittest.TestCase): def test_measure_from_each_line(self): api = FakeApi({("runs", "pending"): [dict(PR, status="pending")], jobs_path(2): self.WAITING}) - total, lines = admission.measure(api, "o/r", "build_all.yml", 99, NOON) + total, lines = admission.measure(api, "o/r", ["build_all.yml"], 99, NOON) self.assertEqual(total, admission.RESERVE) self.assertIn("priority, waiting", lines[0]) - total, _ = admission.measure(api, "o/r", "build_all.yml", 99, NOON, priority=True) + total, _ = admission.measure(api, "o/r", ["build_all.yml"], 99, NOON, priority=True) self.assertEqual(total, 0) def test_own_waiting_run_is_not_counted(self): api = FakeApi({("runs", "pending"): [dict(PR, status="pending")], jobs_path(2): self.WAITING}) - total, _ = admission.measure(api, "o/r", "build_all.yml", 2, NOON) + total, _ = admission.measure(api, "o/r", ["build_all.yml"], 2, NOON) self.assertEqual(total, 0) @@ -167,7 +168,12 @@ class FakeApi: def get(self, path, **params): self.calls.append((path, params)) if path.endswith("/runs") and ("status" in params or "created" in params): - runs = self.responses.get(("runs", params.get("status", "recent")), []) + # Runs keyed by status alone are build_all.yml's. + workflow = path.split("/workflows/")[1].split("/")[0] + key = ("runs", params.get("status", "recent")) + if workflow != "build_all.yml": + key = ("runs", workflow, params.get("status", "recent")) + runs = self.responses.get(key, []) start = (params["page"] - 1) * params["per_page"] return {"total_count": len(runs), "workflow_runs": runs[start:start + params["per_page"]]} if path.endswith("/runs"): @@ -192,7 +198,7 @@ class MeasureTest(unittest.TestCase): jobs_path(2): [gate("arm64"), build("arm64")], jobs_path(3): [gate("arm64"), gate("x86_64"), build("arm64", "queued")], }) - total, lines = admission.measure(api, "o/r", "build_all.yml", 99, NOON) + total, lines = admission.measure(api, "o/r", ["build_all.yml"], 99, NOON) self.assertEqual(total, admission.RESERVE + 1 + admission.RESERVE) self.assertEqual(len(lines), 3) @@ -200,26 +206,26 @@ class MeasureTest(unittest.TestCase): # One of its jobs waits in a concurrency group while its macOS builds run. pending_pr = dict(PR, status="pending") api = FakeApi({("runs", "pending"): [pending_pr], jobs_path(2): [gate("arm64"), build("arm64")]}) - total, _ = admission.measure(api, "o/r", "build_all.yml", 99, NOON) + total, _ = admission.measure(api, "o/r", ["build_all.yml"], 99, NOON) self.assertEqual(total, 1) def test_a_push_waiting_behind_another_holds_nothing(self): api = FakeApi({("runs", "pending"): [dict(PUSH, status="pending")], jobs_path(1): []}) - total, _ = admission.measure(api, "o/r", "build_all.yml", 99, NOON) + total, _ = admission.measure(api, "o/r", ["build_all.yml"], 99, NOON) self.assertEqual(total, 0) def test_reads_every_page_of_runs(self): runs = [dict(PR, id=i) for i in range(150)] responses = {("runs", "in_progress"): runs} responses.update({jobs_path(i): [gate("arm64")] for i in range(150)}) - total, _ = admission.measure(FakeApi(responses), "o/r", "build_all.yml", 999, NOON) + total, _ = admission.measure(FakeApi(responses), "o/r", ["build_all.yml"], 999, NOON) self.assertEqual(total, 150) def test_reserves_for_the_nightly_until_its_run_appears(self): due = datetime.datetime(2026, 10, 10, 2, 10, tzinfo=UTC) yesterday = {"created_at": "2026-10-09T02:20:00Z"} total, lines = admission.measure( - FakeApi({("runs", "schedule"): [yesterday]}), "OrcaSlicer/OrcaSlicer", "build_all.yml", 99, due) + FakeApi({("runs", "schedule"): [yesterday]}), "OrcaSlicer/OrcaSlicer", ["build_all.yml"], 99, due) self.assertEqual(total, admission.RESERVE) self.assertIn("nightly", lines[0]) @@ -227,12 +233,30 @@ class MeasureTest(unittest.TestCase): due = datetime.datetime(2026, 10, 10, 2, 30, tzinfo=UTC) today = {"created_at": "2026-10-10T02:21:00Z"} total, _ = admission.measure( - FakeApi({("runs", "schedule"): [today]}), "OrcaSlicer/OrcaSlicer", "build_all.yml", 99, due) + FakeApi({("runs", "schedule"): [today]}), "OrcaSlicer/OrcaSlicer", ["build_all.yml"], 99, due) self.assertEqual(total, 0) + def test_counts_the_runs_of_every_workflow(self): + # build_optional.yml builds a pull request's x86_64 app in its own run. + optional = dict(PR, id=3) + api = FakeApi({("runs", "in_progress"): [PR], + ("runs", "build_optional.yml", "in_progress"): [optional], + jobs_path(2): [gate("arm64"), build("arm64")], + jobs_path(3): [gate("x86_64"), build("x86_64")]}) + total, lines = admission.measure(api, "o/r", WORKFLOWS, 99, NOON) + self.assertEqual(total, 2) + self.assertEqual(len(lines), 2) + + def test_the_nightly_is_looked_up_in_the_first_workflow(self): + due = datetime.datetime(2026, 10, 10, 2, 10, tzinfo=UTC) + api = FakeApi({}) + admission.measure(api, "OrcaSlicer/OrcaSlicer", WORKFLOWS, 99, due) + schedule = [path for path, params in api.calls if params.get("event") == "schedule"] + self.assertEqual(schedule, ["repos/OrcaSlicer/OrcaSlicer/actions/workflows/build_all.yml/runs"]) + def test_no_nightly_reserve_in_a_fork(self): due = datetime.datetime(2026, 10, 10, 2, 10, tzinfo=UTC) - total, _ = admission.measure(FakeApi({}), "fork/OrcaSlicer", "build_all.yml", 99, due) + total, _ = admission.measure(FakeApi({}), "fork/OrcaSlicer", ["build_all.yml"], 99, due) self.assertEqual(total, 0) def test_counts_a_run_in_both_lists_once(self): @@ -241,13 +265,13 @@ class MeasureTest(unittest.TestCase): ("runs", "queued"): [dict(PUSH, status="queued")], jobs_path(1): [], }) - total, _ = admission.measure(api, "o/r", "build_all.yml", 99, NOON) + total, _ = admission.measure(api, "o/r", ["build_all.yml"], 99, NOON) self.assertEqual(total, admission.RESERVE) def test_counts_its_own_run(self): jobs = [gate("arm64"), build("arm64"), gate("x86_64", "in_progress", None)] api = FakeApi({("runs", "in_progress"): [PR], jobs_path(2): jobs}) - self.assertEqual(admission.measure(api, "o/r", "build_all.yml", 2, NOON)[0], 1) + self.assertEqual(admission.measure(api, "o/r", ["build_all.yml"], 2, NOON)[0], 1) def test_a_run_whose_other_arch_waits_behind_this_one_does_not_block_it(self): # The line is A-arm64, B-arm64, A-x86_64. A's arm64 is built and its @@ -258,7 +282,7 @@ class MeasureTest(unittest.TestCase): jobs_path(1): [gate("arm64"), build("arm64", "completed"), gate("x86_64", "pending", None)], jobs_path(2): [gate("arm64", "in_progress", None)], }) - total, _ = admission.measure(api, "o/r", "build_all.yml", 2, NOON) + total, _ = admission.measure(api, "o/r", ["build_all.yml"], 2, NOON) self.assertEqual(total, 0) def test_counts_its_own_run_when_no_status_list_has_it(self): @@ -266,27 +290,27 @@ class MeasureTest(unittest.TestCase): # line, and is in neither list while that gate checks. jobs = [gate("x86_64"), build("x86_64", "queued"), gate("arm64", "in_progress", None)] api = FakeApi({jobs_path(2): jobs}) - self.assertEqual(admission.measure(api, "o/r", "build_all.yml", 2, NOON)[0], 1) + self.assertEqual(admission.measure(api, "o/r", ["build_all.yml"], 2, NOON)[0], 1) def test_counts_a_recent_run_that_no_status_list_has(self): api = FakeApi({("runs", "recent"): [PR], jobs_path(2): [gate("arm64"), build("arm64")]}) - self.assertEqual(admission.measure(api, "o/r", "build_all.yml", 99, NOON)[0], 1) + self.assertEqual(admission.measure(api, "o/r", ["build_all.yml"], 99, NOON)[0], 1) def test_lists_recent_runs_from_a_day_before(self): api = FakeApi({}) - admission.measure(api, "o/r", "build_all.yml", 99, NOON) + admission.measure(api, "o/r", ["build_all.yml"], 99, NOON) self.assertIn(">=2026-10-09T12:00:00Z", [params.get("created") for _, params in api.calls]) def test_finished_recent_runs_are_not_read(self): done = dict(PUSH, status="completed") api = FakeApi({("runs", "recent"): [done]}) - total, _ = admission.measure(api, "o/r", "build_all.yml", 99, NOON) + total, _ = admission.measure(api, "o/r", ["build_all.yml"], 99, NOON) self.assertEqual(total, 0) self.assertNotIn(jobs_path(1), [path for path, _ in api.calls]) def test_no_nightly_lookup_outside_its_window(self): api = FakeApi({}) - admission.measure(api, "o/r", "build_all.yml", 99, NOON) + admission.measure(api, "o/r", ["build_all.yml"], 99, NOON) self.assertFalse(any("event" in params for _, params in api.calls)) From f8a2e3d89609ddf60a2671aff9b1e547353cbed3 Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:29:26 +0800 Subject: [PATCH 13/26] Build Windows x64 With cl.exe on the build-windows-msvc Label (#17205) * Build Windows x64 With cl.exe on the build-windows-msvc Label CI compiles Windows with clang-cl, so an error only cl.exe reports, such as a class template's virtual members instantiated with the class where clang defers, reaches main unseen. The build-windows-msvc label gives a pull request a cl build of x64 that only compiles: build_orca.yml's Windows packaging, uploads and deploys belong to the clang build, the one that ships, and the compiler cache is left out, as the Visual Studio generator takes no launcher. No push build saves a cl deps cache, so a pull request's first such build builds the deps too. * Upload the cl.exe Build's Portable Build, Installer and PDB Under _msvc names, through the arch suffix build_orca.yml already puts in the artifact names, so a tester can tell them from the clang build's. The clang build stays the one tested, checked for throw info, packaged for the Store and deployed. * Leave the MSVC Build Out of build-all build-all stands for the three builds every pull request once got. The MSVC build is another compiler's, never one a pull request got, and the first one builds the deps too, so a pull request asking for an Intel Mac DMG with build-all should not wait on it. pick takes a fourth argument that says whether build-all covers the build; the three existing lines leave it at the default. --- .github/workflows/build_optional.yml | 38 ++++++++++++++++--- .github/workflows/build_orca.yml | 32 +++++++++------- .github/workflows/cancel_closed_pr_builds.yml | 1 + .github/workflows/pr-label-bot.yml | 4 +- CONTRIBUTING.md | 2 +- 5 files changed, 56 insertions(+), 21 deletions(-) diff --git a/.github/workflows/build_optional.yml b/.github/workflows/build_optional.yml index abe28b5a32..fa2f356999 100644 --- a/.github/workflows/build_optional.yml +++ b/.github/workflows/build_optional.yml @@ -4,15 +4,18 @@ # runners for an hour, and Windows arm64 doubles the Windows legs. # # A label asks for one, from the moment it is added and on every later push to -# the pull request: build-flatpak, build-macos-x86_64, build-windows-arm64, or -# build-all for every one of them. Removing and adding a label again rebuilds -# the same commit. +# the pull request: build-flatpak, build-macos-x86_64, build-windows-arm64, +# build-windows-msvc. build-all asks for the first three, the builds every pull +# request once got; the MSVC build is another compiler's, never a build a pull +# request got, and the first one builds the deps too, so it stays label-only. +# Removing and adding a label again rebuilds the same commit. # # A pull request that changes anything but sources, tests, profiles, # translations and docs builds the Flatpak and Windows arm64 without a label: # what breaks only those legs lives in deps/, cmake/, the build scripts and the # workflows, and a list of those places would go stale, so the safe places are -# listed instead. The macOS build never starts on its own. +# listed instead. The macOS and the cl.exe builds never start on their own: +# what breaks only cl comes from source changes, which no path rule can see. # # Each label added starts a run of its own, and the pull request's checks show # the newest run only, so every run builds everything the labels and the @@ -62,6 +65,7 @@ jobs: flatpak: ${{ steps.select.outputs.flatpak }} macos-x86_64: ${{ steps.select.outputs.macos-x86_64 }} windows-arm64: ${{ steps.select.outputs.windows-arm64 }} + windows-msvc: ${{ steps.select.outputs.windows-msvc }} steps: - name: Checkout uses: actions/checkout@v7 @@ -84,9 +88,11 @@ jobs: echo "$changed" | head -20 infra=true fi + # pick