This commit is contained in:
Lam Wei Lun
2026-09-21 17:01:46 +08:00
3240 changed files with 299310 additions and 103072 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
View File
@@ -9,6 +9,7 @@ add_executable(${_TEST_NAME}_tests
test_fill.cpp
test_flow.cpp
test_gcode_timing.cpp
test_gcodeprocessor.cpp
test_gcodewriter.cpp
test_model.cpp
test_multifilament.cpp
+79
View File
@@ -0,0 +1,79 @@
#include <catch2/catch_all.hpp>
#include "libslic3r/libslic3r.h"
#include "libslic3r/GCode/GCodeProcessor.hpp"
#include <string>
#include <vector>
using namespace Slic3r;
// Bambu firmware uses the " FEATURE: " style reserved tags, everything else the Slic3r-compatible
// "TYPE:" style, so which list applies depends on the printer kind passed in.
TEST_CASE("Reserved keyword detection follows the printer kind it is given", "[GCodeProcessor]")
{
struct Case
{
const char* name;
std::string gcode;
bool reserved_on_bbl;
bool reserved_on_non_bbl;
};
const auto test_case = GENERATE(values<Case>({
{"compatible feature tag", ";TYPE:Prime tower", false, true},
{"compatible layer tag", ";LAYER_CHANGE", false, true},
{"bbl feature tag", "; FEATURE: Outer wall", true, false},
{"tag shared by both lists", ";_GP_FIRST_LINE_M73_PLACEHOLDER", true, true},
{"bbl spells this one with a leading space", ";COLOR_CHANGE", false, true},
{"ordinary comment", "; heat the bed", false, false},
{"not a comment at all", "G1 X10 Y10 F3000", false, false},
// A tag counts only as the whole comment's prefix, so neither a tag mentioned mid-comment
// nor one trailing a real command is a reserved use.
{"tag text later in the comment", "; the TYPE:Prime tower marker", false, false},
{"tag trailing a command", "G1 X10 ;TYPE:Prime tower", false, false},
}));
DYNAMIC_SECTION(test_case.name)
{
std::vector<std::string> tags;
REQUIRE(GCodeProcessor::contains_reserved_tags(test_case.gcode, 5, tags, true) == test_case.reserved_on_bbl);
tags.clear();
REQUIRE(GCodeProcessor::contains_reserved_tags(test_case.gcode, 5, tags, false) == test_case.reserved_on_non_bbl);
}
}
TEST_CASE("Reserved keyword detection reports every offending line", "[GCodeProcessor]")
{
const std::string gcode = ";TYPE:Prime tower\nG1 X10\n;LAYER_CHANGE\n";
std::vector<std::string> tags;
REQUIRE(GCodeProcessor::contains_reserved_tags(gcode, 5, tags, false));
REQUIRE(tags.size() == 2);
// Reported in the order they appear, which is what makes the max_count cut-off meaningful.
CHECK(tags[0] == "TYPE:Prime tower");
CHECK(tags[1] == "LAYER_CHANGE");
SECTION("the reported count is capped at max_count")
{
tags.clear();
REQUIRE(GCodeProcessor::contains_reserved_tags(gcode, 1, tags, false));
CHECK(tags.size() == 1);
CHECK(tags[0] == "TYPE:Prime tower");
}
SECTION("a max_count of zero still reports the first tag")
{
tags.clear();
REQUIRE(GCodeProcessor::contains_reserved_tags(gcode, 0, tags, false));
CHECK(tags.size() == 1);
}
SECTION("g-code with nothing reserved in it reports nothing")
{
tags.clear();
CHECK_FALSE(GCodeProcessor::contains_reserved_tags("G28\n; home all axes\n", 5, tags, false));
CHECK(tags.empty());
}
}
+375
View File
@@ -4,9 +4,14 @@
#include "libslic3r/ExtrusionEntityCollection.hpp"
#include "libslic3r/Layer.hpp"
#include "libslic3r/Print.hpp"
#include "libslic3r/GCodeReader.hpp"
#include "libslic3r/Model.hpp"
#include "libslic3r/TriangleMesh.hpp"
#include <algorithm>
#include <cmath>
#include <limits>
#include <string>
#include <vector>
#include "test_helpers.hpp"
@@ -255,3 +260,373 @@ TEST_CASE("Only one wall on the first layer needs a bottom shell", "[Perimeters]
// No bottom shell: the option is inert, down to the same walls an unchecked box gives.
CHECK_THAT(one_wall_no_shell, Catch::Matchers::WithinAbs(plain_no_shell, 1.0));
}
namespace {
// The layer that closes the cavity of box_over_cavity(), the first one printed over air.
const double cavity_ceiling_z = 6.2;
// A cone standing on its tip, flaring by 5mm of radius per mm of height: at a layer height of 0.2 every
// wall of a layer lands a full millimetre outside the one below, entirely off the layer below but right
// alongside the walls printed with it.
TriangleMesh flared_cone()
{
TriangleMesh cone = make_cone(20., 4.);
cone.mirror(Z);
cone.translate(0., 0., 4.);
return cone;
}
// A 30mm box holding a 20mm cavity from z=2 to z=6, with a 4mm hole punched down through the ceiling
// of that cavity. The layer at cavity_ceiling_z bridges the cavity, and the walls of the hole sit in
// the middle of that bridge, 15mm clear of anything the layer below supports.
Print &box_over_cavity(Print &print, Model &model, const DynamicPrintConfig &config)
{
ModelObject *object = model.add_object();
object->name = "box_over_cavity.stl";
object->add_volume(make_cube(30., 30., 8.), ModelVolumeType::MODEL_PART, false);
TriangleMesh cavity = make_cube(20., 20., 4.);
cavity.translate(5.f, 5.f, 2.f);
object->add_volume(std::move(cavity), ModelVolumeType::NEGATIVE_VOLUME, false);
TriangleMesh hole = make_cube(4., 4., 6.);
hole.translate(13.f, 13.f, 5.f);
object->add_volume(std::move(hole), ModelVolumeType::NEGATIVE_VOLUME, false);
object->add_instance();
object->ensure_on_bed();
print.auto_assign_extruders(object);
print.apply(model, config);
print.validate();
print.set_status_silent();
return print;
}
// Every setting the assertions below depend on, so none of them rests on a default.
DynamicPrintConfig unsupported_walls_config(const char *wall_generator, bool unsupported_wall_last)
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "wall_generator", wall_generator },
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "wall_loops", 3 },
{ "detect_overhang_wall", true },
// Outer wall first, so an unsupported loop only ends up last if the feature puts it there.
{ "wall_sequence", "outer wall/inner wall" },
{ "is_infill_first", false },
{ "sparse_infill_density", "15%" },
{ "unsupported_wall_last", unsupported_wall_last },
{ "gcode_comments", true },
});
return config;
}
// A loop extruded entirely in mid air: every one of its paths is an overhang.
bool unsupported_loop(const ExtrusionEntity *entity)
{
if (! entity->is_loop())
return false;
const ExtrusionPaths &paths = static_cast<const ExtrusionLoop *>(entity)->paths;
return ! paths.empty() && std::all_of(paths.begin(), paths.end(),
[](const ExtrusionPath &path) { return path.role() == erOverhangPerimeter; });
}
// The loops of every wall island of the print, island by island, in extrusion order.
std::vector<std::vector<const ExtrusionLoop*>> wall_islands(const Print &print)
{
std::vector<std::vector<const ExtrusionLoop*>> islands;
for (const Layer *layer : print.objects().front()->layers())
for (const LayerRegion *region : layer->regions())
for (const ExtrusionEntity *island : region->perimeters.entities) {
std::vector<const ExtrusionLoop*> loops;
for (const ExtrusionEntity *entity : static_cast<const ExtrusionEntityCollection*>(island)->entities)
if (entity->is_loop())
loops.push_back(static_cast<const ExtrusionLoop*>(entity));
islands.push_back(std::move(loops));
}
return islands;
}
// Islands where a loop that is anchored is extruded after one that is not.
int islands_with_a_supported_loop_last(const Print &print)
{
int count = 0;
for (const std::vector<const ExtrusionLoop*> &loops : wall_islands(print)) {
bool seen_unsupported = false;
for (const ExtrusionLoop *loop : loops) {
if (unsupported_loop(loop))
seen_unsupported = true;
else if (seen_unsupported) {
++ count;
break;
}
}
}
return count;
}
// The unsupported loops of the print, and those of them held back for the infill.
std::vector<const ExtrusionLoop*> unsupported_loops(const Print &print, double print_z = -1.)
{
std::vector<const ExtrusionLoop*> loops;
for (const Layer *layer : print.objects().front()->layers()) {
if (print_z >= 0. && std::abs(layer->print_z - print_z) > EPSILON)
continue;
for (const LayerRegion *region : layer->regions())
for (const ExtrusionEntity *island : region->perimeters.entities)
for (const ExtrusionEntity *entity : static_cast<const ExtrusionEntityCollection*>(island)->entities)
if (unsupported_loop(entity))
loops.push_back(static_cast<const ExtrusionLoop*>(entity));
}
return loops;
}
int loops_held_back_for_infill(const std::vector<const ExtrusionLoop*> &loops)
{
return int(std::count_if(loops.begin(), loops.end(), [](const ExtrusionLoop *loop) { return loop->print_after_infill; }));
}
// The G-code emitted at `print_z`, so the order of one layer can be read on its own.
std::string layer_gcode(const std::string &gcode, double print_z)
{
std::string out;
GCodeReader reader;
reader.parse_buffer(gcode, [&out, print_z](GCodeReader &self, const GCodeReader::GCodeLine &line) {
if (std::abs(self.z() - print_z) < EPSILON)
out += line.raw() + "\n";
});
return out;
}
} // namespace
// Whatever the wall order asks for, a loop with nothing under it cannot be extruded before the loops it
// leans on. The flared cone gives every layer an outer wall that lands completely off the one below, and
// the outer wall first sequence would otherwise put it down before any of them.
TEST_CASE("Unsupported wall loops are extruded after the walls that anchor them", "[Perimeters]")
{
const char *wall_generator = GENERATE("classic", "arachne");
CAPTURE(wall_generator);
auto slice_cone = [wall_generator](bool unsupported_wall_last, Print &print) {
init_and_process_print({ flared_cone() }, print, unsupported_walls_config(wall_generator, unsupported_wall_last));
REQUIRE_FALSE(print.objects().empty());
};
Print on;
slice_cone(true, on);
// Without unsupported loops to reorder the rest of the test would pass on an empty print.
REQUIRE(unsupported_loops(on).size() > 0);
CHECK(islands_with_a_supported_loop_last(on) == 0);
SECTION("the held back loops run innermost first") {
for (const std::vector<const ExtrusionLoop*> &loops : wall_islands(on)) {
int previous_inset = std::numeric_limits<int>::max();
for (const ExtrusionLoop *loop : loops)
if (unsupported_loop(loop)) {
CHECK(loop->inset_idx <= previous_inset);
previous_inset = loop->inset_idx;
}
}
}
SECTION("switched off, the configured wall order is left alone") {
Print off;
slice_cone(false, off);
REQUIRE(unsupported_loops(off).size() == unsupported_loops(on).size());
// Outer wall first puts the unsupported outer wall ahead of the walls behind it.
CHECK(islands_with_a_supported_loop_last(off) > 0);
}
}
// A loop the walls cannot reach is a different case: only the bridges of its own layer will ever hold it,
// so it has to wait for them - while a loop that runs alongside a wall keeps its place, because the
// bridges anchor on it instead.
TEST_CASE("A wall loop out of reach of the layer below waits for the infill", "[Perimeters]")
{
const char *wall_generator = GENERATE("classic", "arachne");
CAPTURE(wall_generator);
Print print;
Model model;
box_over_cavity(print, model, unsupported_walls_config(wall_generator, true));
print.process();
const std::vector<const ExtrusionLoop*> hole_loops = unsupported_loops(print, cavity_ceiling_z);
REQUIRE(hole_loops.size() > 0);
CHECK(loops_held_back_for_infill(hole_loops) == int(hole_loops.size()));
SECTION("a loop alongside a supported wall is not held back") {
Print cone;
init_and_process_print({ flared_cone() }, cone, unsupported_walls_config(wall_generator, true));
const std::vector<const ExtrusionLoop*> loops = unsupported_loops(cone);
REQUIRE(loops.size() > 0);
CHECK(loops_held_back_for_infill(loops) == 0);
}
SECTION("switched off, no loop is held back") {
Print off;
Model off_model;
box_over_cavity(off, off_model, unsupported_walls_config(wall_generator, false));
off.process();
const std::vector<const ExtrusionLoop*> loops = unsupported_loops(off, cavity_ceiling_z);
REQUIRE(loops.size() == hole_loops.size());
CHECK(loops_held_back_for_infill(loops) == 0);
}
}
// The held back loops reach the G-code in a second pass, after the infill of their layer: on the layer
// that closes the cavity the walls of the hole are extruded once the bridge is down, so the layer emits
// perimeters, then infill, then the perimeters that were waiting for it.
TEST_CASE("Loops waiting for the infill are extruded after it", "[Perimeters]")
{
const char *wall_generator = GENERATE("classic", "arachne");
CAPTURE(wall_generator);
auto ceiling_roles = [wall_generator](bool unsupported_wall_last) {
Print print;
Model model;
box_over_cavity(print, model, unsupported_walls_config(wall_generator, unsupported_wall_last));
const std::string layer = layer_gcode(gcode(print), cavity_ceiling_z);
REQUIRE_FALSE(layer.empty());
return role_sequence(layer, { "perimeter", "infill" });
};
CHECK(ceiling_roles(true) == std::vector<std::string>{ "perimeter", "infill", "perimeter" });
CHECK(ceiling_roles(false) == std::vector<std::string>{ "perimeter", "infill" });
}
namespace {
// The rib spans z=[0,5] and the slab z=[5,6], so this is the slab's first layer - the only one whose
// support comes from the rib rather than from the slab below it.
const double slab_first_layer_z = 5.2;
// Rib widths either side of what the wall generators can print. At a 0.4mm nozzle the classic generator
// builds nothing thinner than nozzle/3 = 0.133mm and Arachne drops anything below min_feature_size, 25%
// of the nozzle = 0.1mm. 0.08mm is under both thresholds, 0.3mm over both.
const double unprintable_rib = 0.08;
const double printable_rib = 0.3;
// A 4x5mm anchor tower carrying a 20x5mm slab at z=[5,6], with a rib `rib_width` wide running the whole
// length of the slab beneath its y=0 edge; a `rib_width` of 0 leaves the rib out. Nothing else is under
// that edge, so whether the wall along it is an overhang rests entirely on the rib. Overhang detection
// grows the lower slices by half the nozzle diameter before it asks, which carries either rib past the
// 0.21mm from the slab edge to that wall - the unprintable one only fails to reach it once it is filtered
// out for being unprintable.
Print &slab_over_rib(Print &print, Model &model, double rib_width, const DynamicPrintConfig &config)
{
ModelObject *object = model.add_object();
object->name = "slab_over_rib.stl";
object->add_volume(make_cube(4., 5., 6.), ModelVolumeType::MODEL_PART, false);
if (rib_width > 0.) {
TriangleMesh rib = make_cube(20., rib_width, 5.);
rib.translate(4.f, 0.f, 0.f);
object->add_volume(std::move(rib), ModelVolumeType::MODEL_PART, false);
}
TriangleMesh slab = make_cube(20., 5., 1.);
slab.translate(4.f, 0.f, 5.f);
object->add_volume(std::move(slab), ModelVolumeType::MODEL_PART, false);
object->add_instance();
object->ensure_on_bed();
print.auto_assign_extruders(object);
print.apply(model, config);
print.validate();
print.set_status_silent();
return print;
}
// Every setting the assertions below depend on, so none of them rests on a default. The wall line widths
// are pinned because the rib widths above are chosen against the distance from the slab edge to its outer
// wall, and min_feature_size because it is one of the two thresholds under test.
DynamicPrintConfig printable_rib_config(const char *wall_generator, bool detect_thin_wall)
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "wall_generator", wall_generator },
{ "layer_height", 0.2 }, // puts a layer boundary exactly on the top of the rib
{ "initial_layer_print_height", 0.2 },
{ "nozzle_diameter", "0.4" },
{ "outer_wall_line_width", 0.42 },
{ "inner_wall_line_width", 0.45 },
{ "wall_loops", 2 },
{ "detect_overhang_wall", true },
{ "detect_thin_wall", detect_thin_wall },
{ "min_feature_size", "25%" },
{ "raft_layers", 0 },
// Anything that adds, drops or reorders walls would move length between the roles being counted.
{ "extra_perimeters_on_overhangs", false },
{ "overhang_reverse", false },
{ "only_one_wall_top", false },
{ "only_one_wall_first_layer", false },
{ "unsupported_wall_last", false },
{ "sparse_infill_density", "15%" },
});
return config;
}
// Length of every overhang perimeter path on the layer at `print_z`, loops and open extrusions alike.
double overhang_length_at(const Print &print, double print_z)
{
double len = 0.;
const auto add_entity = [&len](const ExtrusionEntity *entity, auto &&self) -> void {
const auto add_paths = [&len](const ExtrusionPaths &paths) {
for (const ExtrusionPath &path : paths)
if (path.role() == erOverhangPerimeter)
len += path.length();
};
if (const auto *coll = dynamic_cast<const ExtrusionEntityCollection*>(entity)) {
for (const ExtrusionEntity *child : coll->entities)
self(child, self);
} else if (const auto *loop = dynamic_cast<const ExtrusionLoop*>(entity)) {
add_paths(loop->paths);
} else if (const auto *multi = dynamic_cast<const ExtrusionMultiPath*>(entity)) {
add_paths(multi->paths);
} else if (const auto *path = dynamic_cast<const ExtrusionPath*>(entity)) {
if (path->role() == erOverhangPerimeter)
len += path->length();
}
};
for (const Layer *layer : print.objects().front()->layers()) {
if (std::abs(layer->print_z - print_z) > EPSILON)
continue;
for (const LayerRegion *region : layer->regions())
add_entity(&region->perimeters, add_entity);
}
return len;
}
} // namespace
// A sliver the wall generator prints nothing for holds nothing up, so it cannot be what decides that the
// wall above it is not an overhang. The rib under the slab is the only thing that edge of the slab could
// rest on: below the threshold of the active generator the slab has to come out exactly as it does with
// no rib at all, and the last check is the control - a rib the generator does print anchors that wall,
// without which the first check would hold for want of any sensitivity to the rib.
TEST_CASE("A lower layer sliver too thin to print does not support the wall above it", "[Perimeters]")
{
const char *wall_generator = GENERATE("classic", "arachne");
const bool detect_thin_wall = GENERATE(true, false);
CAPTURE(wall_generator, detect_thin_wall);
auto overhang_for = [wall_generator, detect_thin_wall](double rib_width) {
Print print;
Model model;
slab_over_rib(print, model, rib_width, printable_rib_config(wall_generator, detect_thin_wall));
print.process();
REQUIRE_FALSE(print.objects().empty());
return overhang_length_at(print, slab_first_layer_z);
};
const double no_rib = overhang_for(0.);
const double unprintable = overhang_for(unprintable_rib);
const double printable = overhang_for(printable_rib);
// Only where the slab meets the tower is it held up from below, so both of its 20mm walls overhang.
REQUIRE(no_rib > scale_(30.));
CHECK_THAT(unprintable, Catch::Matchers::WithinAbs(no_rib, scale_(1.)));
// A rib that does get printed takes the 20mm outer wall running along it out of the overhangs.
CHECK(printable < no_rib - scale_(15.));
}
+49
View File
@@ -22,10 +22,59 @@
#include <algorithm>
#include <fstream>
#include <iterator>
#include <string_view>
using namespace Slic3r;
using namespace Slic3r::Test;
TEST_CASE("Timelapse g-code is emitted once per layer for Bambu and non-Bambu printers", "[Print][Regression]")
{
struct PrinterCase {
std::string name;
std::string structure;
bool is_bbl;
};
const PrinterCase printer = GENERATE(from_range(std::vector<PrinterCase>{
{ "non-BBL undefined", "undefine", false },
{ "non-BBL CoreXY", "corexy", false },
{ "non-BBL i3", "i3", false },
{ "non-BBL H-Bot", "hbot", false },
{ "non-BBL Delta", "delta", false },
{ "Bambu CoreXY", "corexy", true },
{ "Bambu i3", "i3", true },
}));
INFO("printer: " << printer.name);
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "initial_layer_print_height", 0.2 },
{ "layer_change_gcode", ";TEST_LAYER_CHANGE" },
{ "layer_height", 0.2 },
{ "printer_structure", printer.structure },
{ "spiral_mode", false },
{ "time_lapse_gcode", "TIMELAPSE_TAKE_FRAME" },
});
Print print;
print.is_BBL_printer() = printer.is_bbl;
Model model;
init_print({ cube(20) }, print, model, config);
const std::string gcode = Slic3r::Test::gcode(print);
const auto count = [&gcode](std::string_view token) {
size_t occurrences = 0;
size_t pos = 0;
while ((pos = gcode.find(token, pos)) != std::string::npos) {
++occurrences;
pos += token.size();
}
return occurrences;
};
const size_t layer_changes = count("\n;TEST_LAYER_CHANGE\n");
REQUIRE(layer_changes > 0);
CHECK(count("\nTIMELAPSE_TAKE_FRAME\n") == layer_changes);
}
SCENARIO("Changing the number of solid shell layers does not make all surfaces internal", "[Print]") {
GIVEN("sliced 20mm cube and config with top_shell_layers = 2 and bottom_shell_layers = 1") {
Slic3r::DynamicPrintConfig config = Slic3r::DynamicPrintConfig::full_print_config();
+11
View File
@@ -52,6 +52,17 @@ add_executable(${_TEST_NAME}_tests
../libnest2d/printer_parts.cpp
)
if (SLIC3R_CAD)
target_sources(${_TEST_NAME}_tests PRIVATE
test_caddocument.cpp
test_sketchconstraints.cpp
test_sketchedit.cpp
test_sketchprofile.cpp
test_sketchimport.cpp
test_sketchinference.cpp
test_slvs_constraints.cpp)
endif ()
if (TARGET OpenVDB::openvdb)
target_sources(${_TEST_NAME}_tests PRIVATE test_hollowing.cpp)
endif()
+234
View File
@@ -3,6 +3,8 @@
#include "libslic3r/Format/3mf.hpp"
#include "libslic3r/Format/bbs_3mf.hpp"
#include "libslic3r/Format/STL.hpp"
#include "libslic3r/miniz_extension.hpp"
#include "libslic3r/Zipper.hpp"
#include "libslic3r/PrintConfig.hpp"
#include "libslic3r/Semver.hpp"
#include "libslic3r/Preset.hpp"
@@ -15,6 +17,8 @@
#include <nlohmann/json.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <algorithm>
#include <catch2/catch_tostring.hpp>
#include <Eigen/Core>
@@ -143,6 +147,236 @@ SCENARIO("Export+Import geometry to/from 3mf file cycle", "[3mf]") {
}
}
// The recipe is an opaque binary blob (CadDocument::serialize_recipe()), so the 3mf backend has
// to carry it byte-for-byte — no XML/text mangling, embedded NULs intact.
static std::string make_cad_recipe()
{
// Built from an explicit length, not append(const char*), which would stop at the first
// embedded NUL — the one thing this blob exists to prove survives the archive.
static const char blob[] = "\x01" "RECIPE" "\0" "\xff\xfe\x00\x10" "cad-features-blob";
return std::string(blob, sizeof(blob) - 1);
}
static const std::string CAD_RECIPE_ENTRY = "Metadata/orca_cad.bin";
static const std::string LEGACY_CAD_RECIPE_ENTRY = "Metadata/SnapOrca_cad.bin";
// Pulls one named entry out of a 3mf archive; false when it is absent.
static bool read_cad_recipe_entry(const std::string& path, std::string& out,
const std::string& entry = CAD_RECIPE_ENTRY)
{
mz_zip_archive zip;
mz_zip_zero_struct(&zip);
REQUIRE(open_zip_reader(&zip, path));
bool found = false;
mz_uint n = mz_zip_reader_get_num_files(&zip);
for (mz_uint i = 0; i < n; ++i) {
mz_zip_archive_file_stat st;
if (!mz_zip_reader_file_stat(&zip, i, &st)) continue;
std::string name(st.m_filename);
std::replace(name.begin(), name.end(), '\\', '/');
if (boost::algorithm::iequals(name, entry)) {
out.resize(st.m_uncomp_size);
found = mz_zip_reader_extract_to_mem(&zip, i, out.data(), out.size(), 0) != 0;
break;
}
}
close_zip_reader(&zip);
return found;
}
// Rewrites the archive at `path` with the recipe entry back under the name it had before the
// rename, which is what every project saved by an earlier build looks like on disk. Generated
// rather than checked in because a whole project archive is not frozen evidence the way a bare
// recipe blob is -- it has to be whatever today's exporter writes, with only the name aged.
// miniz cannot rename in place and open_zip_writer truncates, so the entries are held across
// the switch.
static void rename_cad_recipe_entry_to_legacy(const std::string& path)
{
std::vector<std::pair<std::string, std::string>> entries;
bool renamed = false;
{
mz_zip_archive zip;
mz_zip_zero_struct(&zip);
REQUIRE(open_zip_reader(&zip, path));
mz_uint n = mz_zip_reader_get_num_files(&zip);
for (mz_uint i = 0; i < n; ++i) {
mz_zip_archive_file_stat st;
REQUIRE(mz_zip_reader_file_stat(&zip, i, &st));
if (st.m_is_directory) continue;
std::string name(st.m_filename);
std::replace(name.begin(), name.end(), '\\', '/');
std::string data((size_t) st.m_uncomp_size, '\0');
if (st.m_uncomp_size > 0)
REQUIRE(mz_zip_reader_extract_to_mem(&zip, i, data.data(), data.size(), 0));
if (boost::algorithm::iequals(name, CAD_RECIPE_ENTRY)) {
name = LEGACY_CAD_RECIPE_ENTRY;
renamed = true;
}
entries.emplace_back(std::move(name), std::move(data));
}
close_zip_reader(&zip);
}
// Without this the scenario would degrade silently into re-testing the new name if the
// exporter's constant ever moved again: every load below would still pass.
REQUIRE(renamed);
Zipper out(path);
for (const auto& e : entries)
out.add_entry(e.first, e.second.data(), e.second.size());
out.finalize();
}
// The recipe lives only in the BBS-native backend, because that is the only one that runs:
// store_bbs_3mf is the sole exporter the app calls, and 3mf.cpp's load_3mf is reached only for
// files fingerprinted as PrusaSlicer's, which never carry a recipe. This locks in both halves:
// the archive entry is at the exact path the importer looks for, and the recipe comes back
// through the real importer.
SCENARIO("CAD recipe is embedded in the BBS 3mf archive", "[3mf][CAD]") {
GIVEN("a model carrying a binary cad_recipe") {
Model model;
std::string src = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
REQUIRE(load_stl(src.c_str(), &model));
model.add_default_instances();
// store_bbs_3mf stages its metadata through the model's backup path; point it at a
// writable temp dir, as the sibling BBS scenarios do. The process-global
// set_temporary_dir() would leak into every test that ran afterwards.
ScopedTemporaryDir backup_dir("orca_cad");
model.set_backup_path(backup_dir.string());
const std::string recipe = make_cad_recipe();
model.cad_recipe = recipe;
WHEN("saved through the BBS backend (the format the GUI uses)") {
ScopedTemporaryFile temp(".3mf");
const std::string test_file = temp.string();
DynamicPrintConfig cfg;
StoreParams sp;
sp.path = test_file.c_str();
sp.model = &model;
sp.config = &cfg;
sp.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
REQUIRE(store_bbs_3mf(sp));
THEN("the archive entry is present byte-for-byte") {
std::string got;
REQUIRE(read_cad_recipe_entry(test_file, got));
REQUIRE(got.size() == recipe.size());
REQUIRE(got == recipe);
}
THEN("the importer restores it onto the loaded model") {
Model dst_model;
ScopedTemporaryDir dst_backup_dir("orca_cad_dst");
dst_model.set_backup_path(dst_backup_dir.string());
DynamicPrintConfig dst_config;
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
PlateDataPtrs dst_plates;
std::vector<Preset*> project_presets;
bool is_bbl_3mf = false, is_orca_3mf = false;
Semver file_version;
REQUIRE(load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
LoadStrategy::LoadModel | LoadStrategy::LoadConfig));
REQUIRE(dst_model.cad_recipe.size() == recipe.size());
REQUIRE(dst_model.cad_recipe == recipe);
release_PlateData_list(dst_plates);
}
}
WHEN("the same model is saved with no recipe") {
model.cad_recipe.clear();
ScopedTemporaryFile temp(".3mf");
const std::string test_file = temp.string();
DynamicPrintConfig cfg;
StoreParams sp;
sp.path = test_file.c_str();
sp.model = &model;
sp.config = &cfg;
sp.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
REQUIRE(store_bbs_3mf(sp));
THEN("no entry is written at all") {
std::string got;
REQUIRE_FALSE(read_cad_recipe_entry(test_file, got));
}
}
}
}
// The recipe entry was renamed from Metadata/SnapOrca_cad.bin to Metadata/orca_cad.bin. Nothing
// in the blob marks that move, so a reader that knows only the new name loads a project written
// before it with an empty cad_recipe and no error at all — a feature tree gone with no symptom
// but an empty Design tab. The importer must still accept the old name; the exporter may never
// write it.
SCENARIO("a project saved under the pre-rename recipe name still loads", "[3mf][CAD]") {
GIVEN("a project whose recipe entry carries the old name") {
Model model;
std::string src = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
REQUIRE(load_stl(src.c_str(), &model));
model.add_default_instances();
const std::string recipe = make_cad_recipe();
model.cad_recipe = recipe;
WHEN("it was written by the BBS backend") {
ScopedTemporaryDir backup_dir("orca_cad_legacy");
model.set_backup_path(backup_dir.string());
ScopedTemporaryFile temp(".3mf");
const std::string test_file = temp.string();
DynamicPrintConfig cfg;
StoreParams sp;
sp.path = test_file.c_str();
sp.model = &model;
sp.config = &cfg;
sp.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
REQUIRE(store_bbs_3mf(sp));
rename_cad_recipe_entry_to_legacy(test_file);
// Catch2 replays the enclosing sections per THEN, so one load here serves both.
Model dst_model;
ScopedTemporaryDir dst_backup_dir("orca_cad_legacy_dst");
dst_model.set_backup_path(dst_backup_dir.string());
DynamicPrintConfig dst_config;
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
PlateDataPtrs dst_plates;
std::vector<Preset*> project_presets;
bool is_bbl_3mf = false, is_orca_3mf = false;
Semver file_version;
REQUIRE(load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
LoadStrategy::LoadModel | LoadStrategy::LoadConfig));
release_PlateData_list(dst_plates);
THEN("the recipe still comes back byte-for-byte") {
REQUIRE(dst_model.cad_recipe == recipe);
}
THEN("re-saving migrates it to the new name and leaves the old one behind") {
ScopedTemporaryFile again(".3mf");
const std::string resaved = again.string();
DynamicPrintConfig cfg2;
StoreParams sp2;
sp2.path = resaved.c_str();
sp2.model = &dst_model;
sp2.config = &cfg2;
sp2.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
REQUIRE(store_bbs_3mf(sp2));
std::string got;
REQUIRE(read_cad_recipe_entry(resaved, got));
REQUIRE(got == recipe);
REQUIRE_FALSE(read_cad_recipe_entry(resaved, got, LEGACY_CAD_RECIPE_ENTRY));
}
}
}
}
// .3mf multi-nozzle round-trip.
// Locks the load/save handling for the H2C multi-nozzle plate metadata:
// * filament_volume_maps -> plate config "filament_volume_map" (with the >1 -> 0 clamp)
+38
View File
@@ -43,3 +43,41 @@ TEST_CASE("AppConfig network version helpers", "[AppConfig]") {
REQUIRE(config.is_network_version_skipped("02.01.01.52"));
}
}
TEST_CASE("AppConfig Speed Dial recent count defaults, clamps and parses", "[AppConfig]") {
AppConfig config;
SECTION("unset falls back to the default") {
REQUIRE(config.get_speed_dial_recent_count() == SPEED_DIAL_RECENT_COUNT_DEFAULT);
}
SECTION("zero disables recents") {
config.set(SETTING_SPEED_DIAL_RECENT_COUNT, "0");
REQUIRE(config.get_speed_dial_recent_count() == 0);
}
SECTION("a value in range is returned as-is") {
config.set(SETTING_SPEED_DIAL_RECENT_COUNT, "7");
REQUIRE(config.get_speed_dial_recent_count() == 7);
}
SECTION("the maximum is kept") {
config.set(SETTING_SPEED_DIAL_RECENT_COUNT, "10");
REQUIRE(config.get_speed_dial_recent_count() == SPEED_DIAL_RECENT_COUNT_MAX);
}
SECTION("values above the maximum clamp down") {
config.set(SETTING_SPEED_DIAL_RECENT_COUNT, "42");
REQUIRE(config.get_speed_dial_recent_count() == SPEED_DIAL_RECENT_COUNT_MAX);
}
SECTION("negative values clamp up to 0") {
config.set(SETTING_SPEED_DIAL_RECENT_COUNT, "-3");
REQUIRE(config.get_speed_dial_recent_count() == 0);
}
SECTION("garbage falls back to the default") {
config.set(SETTING_SPEED_DIAL_RECENT_COUNT, "abc");
REQUIRE(config.get_speed_dial_recent_count() == SPEED_DIAL_RECENT_COUNT_DEFAULT);
}
}
File diff suppressed because it is too large Load Diff
@@ -594,3 +594,47 @@ TEST_CASE("update_values_from_multi_to_multi_2 sizes the destination row to the
CHECK(object_config.update_values_from_multi_to_multi_2(src_variants, {}, dst, keys) == -1);
}
}
TEST_CASE("get_index_for_extruder returns -1 when no variant column matches the extruder", "[Config]")
{
DynamicPrintConfig config;
config.option<ConfigOptionInts>("print_extruder_id", true)->values = {1};
config.option<ConfigOptionStrings>("print_extruder_variant", true)->values = {"Direct Drive Standard"};
SECTION("the extruder that owns the column resolves to its slot") {
REQUIRE(config.get_index_for_extruder(1, "print_extruder_id", etDirectDrive, nvtStandard, "print_extruder_variant") == 0);
}
SECTION("an extruder with no matching column resolves to -1") {
REQUIRE(config.get_index_for_extruder(2, "print_extruder_id", etDirectDrive, nvtStandard, "print_extruder_variant") == -1);
}
}
// stride scales the returned slot so callers can address stride-2 options (machine_max_*, a
// Normal/Silent pair per column) by their pair's base slot. The printer Tab's extruder sync
// relies on this to copy the right slots on the Motion ability page.
TEST_CASE("get_index_for_extruder scales the variant column by the requested stride", "[Config]")
{
DynamicPrintConfig config;
config.option<ConfigOptionInts>("printer_extruder_id", true)->values = {1, 2};
config.option<ConfigOptionStrings>("printer_extruder_variant", true)->values = {"Direct Drive Standard",
"Direct Drive High Flow"};
// extruder 1 resolves to column 0, extruder 2 to column 1
const int col0_stride1 = config.get_index_for_extruder(1, "printer_extruder_id", etDirectDrive, nvtStandard,
"printer_extruder_variant", 1);
const int col1_stride1 = config.get_index_for_extruder(2, "printer_extruder_id", etDirectDrive, nvtHighFlow,
"printer_extruder_variant", 1);
REQUIRE(col0_stride1 == 0);
REQUIRE(col1_stride1 == 1);
// stride 2 returns exactly twice the stride-1 index (the pair's base slot)
const int col0_stride2 = config.get_index_for_extruder(1, "printer_extruder_id", etDirectDrive, nvtStandard,
"printer_extruder_variant", 2);
const int col1_stride2 = config.get_index_for_extruder(2, "printer_extruder_id", etDirectDrive, nvtHighFlow,
"printer_extruder_variant", 2);
REQUIRE(col0_stride2 == col0_stride1 * 2);
REQUIRE(col1_stride2 == col1_stride1 * 2);
REQUIRE(col0_stride2 == 0);
REQUIRE(col1_stride2 == 2);
}
@@ -553,6 +553,107 @@ TEST_CASE("Profile validator flags dangling and renamed preset references", "[Pr
}
}
TEST_CASE("Every printer variant has a compatible default material", "[Preset][Validate][DefaultMaterials]")
{
PresetBundle bundle;
auto &vendor = bundle.vendors["Acme"];
vendor.id = vendor.name = "Acme";
vendor.models.emplace_back();
auto &model = vendor.models.back();
model.id = model.name = "Acme Printer";
model.default_materials = {"Acme PLA @0.4", "Acme PLA @0.6"};
for (const std::string variant : {"0.4", "0.6"}) {
model.variants.emplace_back(variant);
const std::string printer_name = "Acme Printer " + variant;
Preset &printer = add_inmemory_preset(bundle.printers, printer_name);
printer.is_system = true;
printer.is_visible = false; // Validation covers uninstalled variants too.
printer.vendor = &vendor;
printer.config.option<ConfigOptionString>("printer_model")->value = model.id;
printer.config.option<ConfigOptionString>("printer_variant")->value = variant;
printer.config.option<ConfigOptionFloats>("nozzle_diameter")->values = {std::stod(variant)};
Preset &filament = add_inmemory_preset(bundle.filaments, "Acme PLA @" + variant);
filament.is_system = true;
filament.vendor = &vendor;
filament.alias = "Acme PLA";
filament.config.option<ConfigOptionStrings>("compatible_printers")->values = {printer_name};
}
// A second system filament, compatible with a user printer this model does not have, so a
// section can list a known-but-incompatible name without tripping the existence check.
Preset &other_printer = add_inmemory_preset(bundle.printers, "Acme Printer 0.2");
other_printer.vendor = &vendor;
Preset &other_filament = add_inmemory_preset(bundle.filaments, "Acme PLA @0.2");
other_filament.is_system = true;
other_filament.vendor = &vendor;
other_filament.alias = "Acme PLA";
other_filament.config.option<ConfigOptionStrings>("compatible_printers")->values = {"Acme Printer 0.2"};
CHECK_FALSE(bundle.has_errors());
bool expected_errors = true;
SECTION("A model default for one nozzle does not cover another nozzle") {
model.default_materials = {"Acme PLA @0.4"};
}
SECTION("An empty default list leaves every variant uncovered") {
model.default_materials.clear();
}
SECTION("An unknown filament cannot be a default") {
model.default_materials = {"Missing PLA"};
}
SECTION("An unknown name is an error even when a compatible default covers the variant") {
model.default_materials.insert(model.default_materials.begin(), "Missing PLA");
}
SECTION("An unknown default_filament_profile name is an error") {
bundle.printers.find_preset("Acme Printer 0.6", false, true)
->config.option<ConfigOptionStrings>("default_filament_profile", true)->values = {"Missing PLA"};
}
SECTION("A known default_filament_profile name is not an error") {
bundle.printers.find_preset("Acme Printer 0.6", false, true)
->config.option<ConfigOptionStrings>("default_filament_profile", true)->values = {"Acme PLA @0.6"};
expected_errors = false;
}
SECTION("A short alias does not resolve as an installed default") {
model.default_materials = {"Acme PLA"};
}
SECTION("A user filament cannot satisfy a shipped default") {
bundle.filaments.find_preset("Acme PLA @0.6", false, true)->is_system = false;
}
SECTION("One compatible default per variant is sufficient") {
model.default_materials.insert(model.default_materials.begin(), "Acme PLA @0.2");
expected_errors = false;
}
SECTION("Compatibility conditions apply to each nozzle") {
model.default_materials = {"Acme PLA @0.4"};
Preset *filament = bundle.filaments.find_preset("Acme PLA @0.4", false, true);
auto &library = bundle.vendors[PresetBundle::ORCA_FILAMENT_LIBRARY];
library.id = library.name = PresetBundle::ORCA_FILAMENT_LIBRARY;
filament->vendor = &library;
filament->config.option<ConfigOptionStrings>("compatible_printers")->values.clear();
filament->config.option<ConfigOptionString>("compatible_printers_condition")->value = "nozzle_diameter[0] == 0.4";
}
SECTION("Library defaults respect printer exclusions") {
model.default_materials = {"Acme PLA @0.4"};
Preset *filament = bundle.filaments.find_preset("Acme PLA @0.4", false, true);
auto &library = bundle.vendors[PresetBundle::ORCA_FILAMENT_LIBRARY];
library.id = library.name = PresetBundle::ORCA_FILAMENT_LIBRARY;
filament->vendor = &library;
filament->config.option<ConfigOptionStrings>("compatible_printers")->values.clear();
CHECK_FALSE(bundle.check_printer_default_materials());
filament->m_excluded_from.insert("Acme Printer 0.6");
}
SECTION("User printers do not need model defaults") {
model.default_materials = {"Acme PLA @0.4"};
bundle.printers.find_preset("Acme Printer 0.6", false, true)->is_system = false;
expected_errors = false;
}
CHECK(bundle.check_printer_default_materials() == expected_errors);
CHECK(bundle.has_errors() == expected_errors);
}
// Under a shared override key, the last preset merged into the full config overwrote the others', so an
// edited slicing-pipeline override never reached Print::apply's diff and re-configuring a plugin never
// re-sliced. Per-type keys make that collision impossible; guard the scoping here.
+17
View File
@@ -33,3 +33,20 @@ TEST_CASE("deep_diff flags new vector entries that duplicate values[0]", "[Prese
// specific to new indices rather than flagging the whole vector.
REQUIRE(std::find(diff.begin(), diff.end(), "nozzle_diameter#0") == diff.end());
}
TEST_CASE("deep_diff distinguishes absolute and percentage speeds for each variant", "[PresetDiff][Config]")
{
const size_t changed_index = GENERATE(size_t(0), size_t(1));
Preset reference(Preset::TYPE_PRINT, "ref");
reference.config.set_key_value("small_perimeter_speed", new ConfigOptionFloatsOrPercents{{50., false}, {50., false}});
Preset edited = reference;
edited.config.option<ConfigOptionFloatsOrPercents>("small_perimeter_speed")->values[changed_index].percent = true;
const auto diff = PresetCollection::dirty_options(&edited, &reference, /*deep_compare=*/true);
REQUIRE(diff == std::vector<std::string>{"small_perimeter_speed#" + std::to_string(changed_index)});
DynamicPrintConfig transferred = reference.config;
transferred.apply_only(edited.config, diff);
REQUIRE(*transferred.option("small_perimeter_speed") == *edited.config.option("small_perimeter_speed"));
}
+396
View File
@@ -0,0 +1,396 @@
#include <catch2/catch_all.hpp> // mainline OrcaSlicer ships Catch2 v3 (v2 was catch2/catch.hpp)
#include "libslic3r/CAD/SketchConstraints.hpp"
#include "libslic3r/CAD/SketchEngine.hpp"
using namespace Slic3r;
namespace {
SketchEntity mk_line(double x0, double y0, double x1, double y1)
{
SketchEntity e; e.type = SketchEntity::Type::Line;
e.p0 = Vec2d(x0, y0); e.p1 = Vec2d(x1, y1); return e;
}
SketchEntity mk_point(double x, double y)
{
SketchEntity e; e.type = SketchEntity::Type::Point; e.p0 = Vec2d(x, y); return e;
}
SketchEntity mk_circle(double cx, double cy, double r)
{
SketchEntity e; e.type = SketchEntity::Type::Circle;
e.center = Vec2d(cx, cy); e.radius = r; return e;
}
}
TEST_CASE("Coincident with anchor", "[SketchConstraints]")
{
SketchConstraints sc;
int a = sc.add_point(0, 0);
int b = sc.add_point(5, 5);
sc.fix_point(a);
sc.coincident(a, b);
REQUIRE(sc.solve());
Vec2d pb = sc.get_point(b);
REQUIRE_THAT(pb.x(), Catch::Matchers::WithinAbs(0.0, 1e-4));
REQUIRE_THAT(pb.y(), Catch::Matchers::WithinAbs(0.0, 1e-4));
}
TEST_CASE("Horizontal + distance", "[SketchConstraints]")
{
SketchConstraints sc;
int a = sc.add_point(0, 0);
int b = sc.add_point(5, 3);
sc.fix_point(a);
sc.horizontal(a, b);
sc.distance(a, b, 10);
REQUIRE(sc.solve());
Vec2d pb = sc.get_point(b);
REQUIRE_THAT(pb.y(), Catch::Matchers::WithinAbs(0.0, 1e-3));
REQUIRE_THAT(std::abs(pb.x()), Catch::Matchers::WithinAbs(10.0, 1e-3));
}
TEST_CASE("Rectangle", "[SketchConstraints]")
{
SketchConstraints sc;
int p0 = sc.add_point(0, 0);
int p1 = sc.add_point(8, 1);
int p2 = sc.add_point(9, 5);
int p3 = sc.add_point(-1, 4);
sc.fix_point(p0);
sc.lock_x(p0, 0);
sc.lock_y(p0, 0);
sc.horizontal(p0, p1);
sc.vertical(p1, p2);
sc.horizontal(p2, p3);
sc.vertical(p3, p0);
sc.distance(p0, p1, 10);
sc.distance(p1, p2, 6);
REQUIRE(sc.solve());
Vec2d pp1 = sc.get_point(p1);
Vec2d pp2 = sc.get_point(p2);
Vec2d pp3 = sc.get_point(p3);
REQUIRE_THAT(pp1.x(), Catch::Matchers::WithinAbs(10.0, 1e-3));
REQUIRE_THAT(pp1.y(), Catch::Matchers::WithinAbs(0.0, 1e-3));
REQUIRE_THAT(pp2.x(), Catch::Matchers::WithinAbs(10.0, 1e-3));
REQUIRE_THAT(pp2.y(), Catch::Matchers::WithinAbs(6.0, 1e-3));
REQUIRE_THAT(pp3.x(), Catch::Matchers::WithinAbs(0.0, 1e-3));
REQUIRE_THAT(pp3.y(), Catch::Matchers::WithinAbs(6.0, 1e-3));
}
TEST_CASE("residual_norm after each solve", "[SketchConstraints]")
{
SECTION("coincident case")
{
SketchConstraints sc;
int a = sc.add_point(0, 0);
int b = sc.add_point(5, 5);
sc.fix_point(a);
sc.coincident(a, b);
REQUIRE(sc.solve());
REQUIRE(sc.residual_norm() < 1e-5);
}
SECTION("horizontal+distance case")
{
SketchConstraints sc;
int a = sc.add_point(0, 0);
int b = sc.add_point(5, 3);
sc.fix_point(a);
sc.horizontal(a, b);
sc.distance(a, b, 10);
REQUIRE(sc.solve());
REQUIRE(sc.residual_norm() < 1e-5);
}
SECTION("rectangle case")
{
SketchConstraints sc;
int p0 = sc.add_point(0, 0);
int p1 = sc.add_point(8, 1);
int p2 = sc.add_point(9, 5);
int p3 = sc.add_point(-1, 4);
sc.fix_point(p0);
sc.lock_x(p0, 0);
sc.lock_y(p0, 0);
sc.horizontal(p0, p1);
sc.vertical(p1, p2);
sc.horizontal(p2, p3);
sc.vertical(p3, p0);
sc.distance(p0, p1, 10);
sc.distance(p1, p2, 6);
REQUIRE(sc.solve());
REQUIRE(sc.residual_norm() < 1e-5);
}
}
TEST_CASE("midpoint", "[SketchConstraints]")
{
SketchConstraints sc;
int a = sc.add_point(0, 0);
int b = sc.add_point(10, 0);
int m = sc.add_point(3, 7);
sc.fix_point(a);
sc.fix_point(b);
sc.midpoint(m, a, b);
REQUIRE(sc.solve());
Vec2d pm = sc.get_point(m);
REQUIRE_THAT(pm.x(), Catch::Matchers::WithinAbs(5.0, 1e-3));
REQUIRE_THAT(pm.y(), Catch::Matchers::WithinAbs(0.0, 1e-3));
}
TEST_CASE("symmetric across Y axis", "[SketchConstraints]")
{
SketchConstraints sc;
int a = sc.add_point(2, 3);
int b = sc.add_point(-1, 1);
int c = sc.add_point(0, 0);
int d = sc.add_point(0, 1);
sc.fix_point(a);
sc.fix_point(c);
sc.fix_point(d);
sc.symmetric(a, b, c, d);
REQUIRE(sc.solve());
Vec2d pb = sc.get_point(b);
REQUIRE_THAT(pb.x(), Catch::Matchers::WithinAbs(-2.0, 1e-3));
REQUIRE_THAT(pb.y(), Catch::Matchers::WithinAbs(3.0, 1e-3));
}
TEST_CASE("angle 90 degrees", "[SketchConstraints]")
{
SketchConstraints sc;
int a = sc.add_point(0, 0);
int b = sc.add_point(1, 0);
int c = sc.add_point(0, 0);
int d = sc.add_point(1, 1);
sc.fix_point(a);
sc.fix_point(b);
sc.fix_point(c);
sc.angle(a, b, c, d, M_PI / 2);
REQUIRE(sc.solve());
Vec2d pd = sc.get_point(d);
Vec2d pc = sc.get_point(c);
REQUIRE_THAT(pd.x() - pc.x(), Catch::Matchers::WithinAbs(0.0, 1e-3));
REQUIRE(pd.y() > pc.y());
}
TEST_CASE("point-line distance", "[SketchConstraints]")
{
SketchConstraints sc;
int a = sc.add_point(0, 0);
int b = sc.add_point(10, 0);
int p = sc.add_point(3, 1);
sc.fix_point(a);
sc.fix_point(b);
sc.lock_x(p, 3.0);
sc.point_line_distance(p, a, b, 5.0);
REQUIRE(sc.solve());
Vec2d pp = sc.get_point(p);
REQUIRE_THAT(std::abs(pp.y()), Catch::Matchers::WithinAbs(5.0, 1e-3));
REQUIRE_THAT(pp.x(), Catch::Matchers::WithinAbs(3.0, 1e-3));
}
// ---- entity-constraint planner (kernel port of DesignPanel::apply_entity_constraint) ----
TEST_CASE("sketch_entity_ends exposes real roles only", "[SketchConstraints]")
{
std::pair<SketchPointRole, Vec2d> out[2];
REQUIRE(sketch_entity_ends(mk_point(3, 4), out) == 1);
REQUIRE(out[0].first == SketchPointRole::P0);
REQUIRE(sketch_entity_ends(mk_circle(1, 2, 5), out) == 1);
REQUIRE(out[0].first == SketchPointRole::Center);
REQUIRE_THAT(out[0].second.x(), Catch::Matchers::WithinAbs(1.0, 1e-9));
REQUIRE_THAT(out[0].second.y(), Catch::Matchers::WithinAbs(2.0, 1e-9));
REQUIRE(sketch_entity_ends(mk_line(0, 0, 10, 0), out) == 2);
REQUIRE(out[0].first == SketchPointRole::P0);
REQUIRE(out[1].first == SketchPointRole::P1);
}
TEST_CASE("Coincident on two Points binds P0/P0, not phantom p1", "[SketchConstraints]")
{
std::vector<SketchEntity> ents = { mk_point(0, 0), mk_point(5, 5) };
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, -1, SketchConstraintType::Coincident);
REQUIRE(p.kind == ConstraintPlan::Kind::Apply);
REQUIRE(p.defs.size() == 1);
REQUIRE(p.defs[0].type == SketchConstraintType::Coincident);
REQUIRE(p.defs[0].ea == 0);
REQUIRE(p.defs[0].ra == SketchPointRole::P0);
REQUIRE(p.defs[0].eb == 1);
REQUIRE(p.defs[0].rb == SketchPointRole::P0);
}
TEST_CASE("DistanceX on two Points binds real roles with non-negative prefill", "[SketchConstraints]")
{
// e0 is right of e1, so the raw projected delta is negative: the plan must swap the
// refs so accepting the shown (positive) value is a no-op, not a sign flip.
std::vector<SketchEntity> ents = { mk_point(5, 1), mk_point(2, 3) };
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, -1, SketchConstraintType::DistanceX);
REQUIRE(p.kind == ConstraintPlan::Kind::AskValue);
REQUIRE(p.defs.size() == 1);
REQUIRE(p.defs[0].type == SketchConstraintType::DistanceX);
REQUIRE(p.defs[0].ra == SketchPointRole::P0);
REQUIRE(p.defs[0].rb == SketchPointRole::P0);
REQUIRE(p.prefill >= 0.0);
REQUIRE(p.defs[0].ea == 1);
REQUIRE(p.defs[0].eb == 0);
}
TEST_CASE("Horizontal on a Point rejects with NeedALine", "[SketchConstraints]")
{
std::vector<SketchEntity> ents = { mk_point(1, 2) };
ConstraintPlan p = plan_entity_constraint(ents, 0, -1, -1, SketchConstraintType::Horizontal);
REQUIRE(p.kind == ConstraintPlan::Kind::Reject);
REQUIRE(p.reason == ConstraintReject::NeedALine);
}
TEST_CASE("Angle on two Circles rejects with NeedTwoLines", "[SketchConstraints]")
{
std::vector<SketchEntity> ents = { mk_circle(0, 0, 1), mk_circle(5, 0, 1) };
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, -1, SketchConstraintType::Angle);
REQUIRE(p.kind == ConstraintPlan::Kind::Reject);
REQUIRE(p.reason == ConstraintReject::NeedTwoLines);
}
TEST_CASE("Parallel on a Line + Circle rejects with NeedTwoLines (new guard)", "[SketchConstraints]")
{
std::vector<SketchEntity> ents = { mk_line(0, 0, 1, 0), mk_circle(5, 0, 1) };
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, -1, SketchConstraintType::Parallel);
REQUIRE(p.kind == ConstraintPlan::Kind::Reject);
REQUIRE(p.reason == ConstraintReject::NeedTwoLines);
}
TEST_CASE("Equal on two Circles promotes to EqualRadius", "[SketchConstraints]")
{
std::vector<SketchEntity> ents = { mk_circle(0, 0, 1), mk_circle(5, 0, 2) };
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, -1, SketchConstraintType::EqualLength);
REQUIRE(p.kind == ConstraintPlan::Kind::Apply);
REQUIRE(p.defs.size() == 1);
REQUIRE(p.defs[0].type == SketchConstraintType::EqualRadius);
REQUIRE(p.defs[0].ea == 0);
REQUIRE(p.defs[0].eb == 1);
}
TEST_CASE("Symmetric on two Lines returns two defs with ec set to the axis", "[SketchConstraints]")
{
std::vector<SketchEntity> ents = { mk_line(0, 1, 5, 1), mk_line(0, -1, 5, -1), mk_line(0, 0, 0, 1) };
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, 2, SketchConstraintType::Symmetric);
REQUIRE(p.kind == ConstraintPlan::Kind::Apply);
REQUIRE(p.defs.size() == 2);
for (const auto& d : p.defs) {
REQUIRE(d.type == SketchConstraintType::Symmetric);
REQUIRE(d.ea == 0);
REQUIRE(d.eb == 1);
REQUIRE(d.ec == 2);
}
REQUIRE(p.defs[0].ra == SketchPointRole::P0);
REQUIRE(p.defs[0].rb == SketchPointRole::P0);
REQUIRE(p.defs[1].ra == SketchPointRole::P1);
REQUIRE(p.defs[1].rb == SketchPointRole::P1);
}
TEST_CASE("Symmetric with no axis rejects with NeedAxisLine", "[SketchConstraints]")
{
std::vector<SketchEntity> ents = { mk_point(0, 0), mk_point(5, 0) };
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, -1, SketchConstraintType::Symmetric);
REQUIRE(p.kind == ConstraintPlan::Kind::Reject);
REQUIRE(p.reason == ConstraintReject::NeedAxisLine);
}
TEST_CASE("SymmetricAboutY on two Points returns one def with ec == kSketchRefAxisY", "[SketchConstraints]")
{
std::vector<SketchEntity> ents = { mk_point(1, 0), mk_point(-2, 0) };
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, -1, SketchConstraintType::SymmetricAboutY);
REQUIRE(p.kind == ConstraintPlan::Kind::Apply);
REQUIRE(p.defs.size() == 1);
REQUIRE(p.defs[0].type == SketchConstraintType::SymmetricAboutY);
REQUIRE(p.defs[0].ec == kSketchRefAxisY);
REQUIRE(p.defs[0].ea == 0);
REQUIRE(p.defs[0].eb == 1);
}
TEST_CASE("constraint planner apply/askvalue matrix", "[SketchConstraints]")
{
struct C {
const char* name; SketchConstraintType type; std::vector<SketchEntity> ents;
int e0, e1, e2; ConstraintPlan::Kind kind;
};
const std::vector<C> cases = {
{ "Fix", SketchConstraintType::Fix, { mk_point(1, 2) }, 0, -1, -1, ConstraintPlan::Kind::Apply },
{ "Coincident", SketchConstraintType::Coincident, { mk_point(0, 0), mk_point(5, 5) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
{ "Horizontal", SketchConstraintType::Horizontal, { mk_line(0, 0, 5, 0) }, 0, -1, -1, ConstraintPlan::Kind::Apply },
{ "Vertical", SketchConstraintType::Vertical, { mk_line(0, 0, 0, 5) }, 0, -1, -1, ConstraintPlan::Kind::Apply },
{ "Parallel", SketchConstraintType::Parallel, { mk_line(0, 0, 1, 0), mk_line(0, 1, 1, 1) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
{ "Perpendicular", SketchConstraintType::Perpendicular, { mk_line(0, 0, 1, 0), mk_line(0, 0, 0, 1) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
{ "EqualLength", SketchConstraintType::EqualLength, { mk_line(0, 0, 1, 0), mk_line(0, 1, 2, 1) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
{ "Concentric", SketchConstraintType::Concentric, { mk_circle(0, 0, 1), mk_circle(5, 0, 1) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
{ "Tangent", SketchConstraintType::Tangent, { mk_line(0, 0, 1, 0), mk_circle(0, 1, 1) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
{ "Midpoint", SketchConstraintType::Midpoint, { mk_point(2, 0), mk_line(0, 0, 5, 0) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
{ "Symmetric", SketchConstraintType::Symmetric, { mk_point(0, 0), mk_point(5, 0), mk_line(0, -1, 0, 1) }, 0, 1, 2, ConstraintPlan::Kind::Apply },
{ "SymmetricAboutY", SketchConstraintType::SymmetricAboutY, { mk_point(1, 0), mk_point(-2, 0) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
{ "SymmetricAboutX", SketchConstraintType::SymmetricAboutX, { mk_point(0, 1), mk_point(0, -2) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
{ "EqualRadius", SketchConstraintType::EqualRadius, { mk_circle(0, 0, 1), mk_circle(5, 0, 2) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
{ "Collinear", SketchConstraintType::Collinear, { mk_line(0, 0, 1, 0), mk_line(2, 0, 3, 0) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
{ "Angle", SketchConstraintType::Angle, { mk_line(0, 0, 1, 0), mk_line(0, 0, 0, 1) }, 0, 1, -1, ConstraintPlan::Kind::AskValue },
{ "Radius", SketchConstraintType::Radius, { mk_circle(0, 0, 2.5) }, 0, -1, -1, ConstraintPlan::Kind::AskValue },
{ "Diameter", SketchConstraintType::Diameter, { mk_circle(0, 0, 2.5) }, 0, -1, -1, ConstraintPlan::Kind::AskValue },
{ "DistanceX", SketchConstraintType::DistanceX, { mk_point(0, 0), mk_point(5, 3) }, 0, 1, -1, ConstraintPlan::Kind::AskValue },
{ "DistanceY", SketchConstraintType::DistanceY, { mk_point(0, 0), mk_point(5, 3) }, 0, 1, -1, ConstraintPlan::Kind::AskValue },
};
for (const C& c : cases) {
DYNAMIC_SECTION("apply " << c.name) {
ConstraintPlan p = plan_entity_constraint(c.ents, c.e0, c.e1, c.e2, c.type);
REQUIRE(p.kind == c.kind);
REQUIRE(p.defs.size() >= 1);
for (const auto& d : p.defs) REQUIRE(d.type == c.type);
}
}
}
TEST_CASE("constraint planner reject matrix", "[SketchConstraints]")
{
struct C {
const char* name; SketchConstraintType type; std::vector<SketchEntity> ents;
int e0, e1, e2; ConstraintReject reason;
};
const std::vector<C> cases = {
{ "Fix", SketchConstraintType::Fix, {}, 0, -1, -1, ConstraintReject::NeedOneEntity },
{ "Coincident", SketchConstraintType::Coincident, { mk_point(0, 0) }, 0, -1, -1, ConstraintReject::NeedTwoEntities },
{ "Horizontal", SketchConstraintType::Horizontal, { mk_point(1, 2) }, 0, -1, -1, ConstraintReject::NeedALine },
{ "Vertical", SketchConstraintType::Vertical, { mk_circle(0, 0, 1) }, 0, -1, -1, ConstraintReject::NeedALine },
{ "Parallel", SketchConstraintType::Parallel, { mk_line(0, 0, 1, 0), mk_circle(5, 0, 1) }, 0, 1, -1, ConstraintReject::NeedTwoLines },
{ "Perpendicular", SketchConstraintType::Perpendicular, { mk_circle(0, 0, 1), mk_line(0, 0, 1, 0) }, 0, 1, -1, ConstraintReject::NeedTwoLines },
{ "EqualLength", SketchConstraintType::EqualLength, { mk_line(0, 0, 1, 0), mk_circle(5, 0, 1) }, 0, 1, -1, ConstraintReject::NeedTwoLines },
{ "Concentric", SketchConstraintType::Concentric, { mk_line(0, 0, 1, 0), mk_circle(5, 0, 1) }, 0, 1, -1, ConstraintReject::NeedTwoRounds },
{ "Tangent", SketchConstraintType::Tangent, { mk_line(0, 0, 1, 0), mk_line(0, 1, 1, 1) }, 0, 1, -1, ConstraintReject::NeedTangentPair },
{ "Midpoint", SketchConstraintType::Midpoint, { mk_line(0, 0, 1, 0), mk_line(0, 1, 1, 1) }, 0, 1, -1, ConstraintReject::NeedPointAndLine },
{ "Symmetric", SketchConstraintType::Symmetric, { mk_line(0, 0, 1, 0), mk_point(1, 1), mk_line(0, -1, 0, 1) }, 0, 1, 2, ConstraintReject::NeedTwoPointsOrLines },
{ "SymmetricAboutY", SketchConstraintType::SymmetricAboutY, { mk_line(0, 0, 1, 0), mk_point(1, 1) }, 0, 1, -1, ConstraintReject::NeedTwoPointsOrLines },
{ "SymmetricAboutX", SketchConstraintType::SymmetricAboutX, { mk_point(1, 1), mk_line(0, 0, 1, 0) }, 0, 1, -1, ConstraintReject::NeedTwoPointsOrLines },
{ "EqualRadius", SketchConstraintType::EqualRadius, { mk_line(0, 0, 1, 0), mk_circle(5, 0, 1) }, 0, 1, -1, ConstraintReject::NeedTwoRounds },
{ "Collinear", SketchConstraintType::Collinear, { mk_line(0, 0, 1, 0), mk_circle(5, 0, 1) }, 0, 1, -1, ConstraintReject::NeedTwoLines },
{ "Angle", SketchConstraintType::Angle, { mk_circle(0, 0, 1), mk_circle(5, 0, 1) }, 0, 1, -1, ConstraintReject::NeedTwoLines },
{ "Radius", SketchConstraintType::Radius, { mk_line(0, 0, 1, 0) }, 0, -1, -1, ConstraintReject::NeedRound },
{ "Diameter", SketchConstraintType::Diameter, { mk_point(1, 2) }, 0, -1, -1, ConstraintReject::NeedRound },
{ "DistanceX", SketchConstraintType::DistanceX, { mk_point(0, 0) }, 0, -1, -1, ConstraintReject::NeedTwoEntities },
{ "DistanceY", SketchConstraintType::DistanceY, { mk_point(0, 0) }, 0, -1, -1, ConstraintReject::NeedTwoEntities },
};
for (const C& c : cases) {
DYNAMIC_SECTION("reject " << c.name) {
ConstraintPlan p = plan_entity_constraint(c.ents, c.e0, c.e1, c.e2, c.type);
REQUIRE(p.kind == ConstraintPlan::Kind::Reject);
REQUIRE(p.reason == c.reason);
}
}
}
TEST_CASE("constraint planner rejects types with no entity binding", "[SketchConstraints]")
{
const SketchConstraintType unsupported[] = {
SketchConstraintType::Distance, SketchConstraintType::LockX, SketchConstraintType::LockY,
SketchConstraintType::PointOnLine, SketchConstraintType::PointOnObject,
};
std::vector<SketchEntity> ents = { mk_point(0, 0), mk_point(1, 1) };
for (SketchConstraintType t : unsupported) {
DYNAMIC_SECTION("unsupported " << int(t)) {
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, -1, t);
REQUIRE(p.kind == ConstraintPlan::Kind::Reject);
REQUIRE(p.reason == ConstraintReject::Unsupported);
}
}
}
+730
View File
@@ -0,0 +1,730 @@
#include <catch2/catch_all.hpp> // mainline OrcaSlicer ships Catch2 v3 (v2 was catch2/catch.hpp)
#include "libslic3r/CAD/SketchEngine.hpp"
#include <cmath>
#include <algorithm>
#include <TopExp_Explorer.hxx>
#include <TopAbs.hxx>
using namespace Slic3r;
using Catch::Matchers::WithinAbs;
// CONTRACT: mirror_entities hands the reflected half back REVERSED — the order of the entities
// and the direction of each — because a reflection reverses orientation and the result has to
// CONTINUE the chain it was made from. So a mirrored line's p0 is the reflection of the source's
// p1, not its p0. See [SketchProfile] "a mirrored half continues the original chain".
TEST_CASE("Mirror Line across Y axis (reversed: p0 is the reflection of the source p1)", "[SketchEdit]")
{
SketchEntity e;
e.type = SketchEntity::Type::Line;
e.p0 = Vec2d(3, 2);
e.p1 = Vec2d(5, 4);
Vec2d a(0, -1);
Vec2d b(0, 1);
auto result = SketchEngine::mirror_entities({e}, a, b);
REQUIRE(result.size() == 1);
const auto& m = result[0];
REQUIRE(m.type == SketchEntity::Type::Line);
REQUIRE_THAT(m.p0.x(), WithinAbs(-5.0, 1e-9)); // reflection of the SOURCE p1
REQUIRE_THAT(m.p0.y(), WithinAbs(4.0, 1e-9));
REQUIRE_THAT(m.p1.x(), WithinAbs(-3.0, 1e-9)); // reflection of the SOURCE p0
REQUIRE_THAT(m.p1.y(), WithinAbs(2.0, 1e-9));
}
TEST_CASE("Mirror Circle across Y axis", "[SketchEdit]")
{
SketchEntity e;
e.type = SketchEntity::Type::Circle;
e.center = Vec2d(5, 0);
e.p0 = Vec2d(5, 0);
e.radius = 3;
Vec2d a(0, -1);
Vec2d b(0, 1);
auto result = SketchEngine::mirror_entities({e}, a, b);
REQUIRE(result.size() == 1);
const auto& m = result[0];
REQUIRE(m.type == SketchEntity::Type::Circle);
REQUIRE_THAT(m.center.x(), WithinAbs(-5.0, 1e-9));
REQUIRE_THAT(m.center.y(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(m.radius, WithinAbs(3.0, 1e-9));
REQUIRE_THAT(m.p0.x(), WithinAbs(-5.0, 1e-9));
REQUIRE_THAT(m.p0.y(), WithinAbs(0.0, 1e-9));
}
TEST_CASE("Mirror Arc across X axis", "[SketchEdit]")
{
SketchEntity e;
e.type = SketchEntity::Type::Arc;
e.center = Vec2d(0, 0);
e.radius = 1.0;
e.start_angle = 0.0;
e.end_angle = M_PI / 2.0;
e.p0 = Vec2d(1, 0);
e.p1 = Vec2d(0, 1);
Vec2d a(-1, 0);
Vec2d b(1, 0);
auto result = SketchEngine::mirror_entities({e}, a, b);
REQUIRE(result.size() == 1);
const auto& m = result[0];
REQUIRE(m.type == SketchEntity::Type::Arc);
// Reversed with the rest of the half: the mirrored arc STARTS where the reflection of the
// source's end is, and finishes at the reflection of its start.
REQUIRE_THAT(m.p0.x(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(m.p0.y(), WithinAbs(-1.0, 1e-9));
REQUIRE_THAT(m.p1.x(), WithinAbs(1.0, 1e-9));
REQUIRE_THAT(m.p1.y(), WithinAbs(0.0, 1e-9));
// The reflection alone would negate the sweep; walking the arc the other way negates it
// again, so a mirrored CCW arc is CCW once more and a mirrored CCW loop stays CCW.
double sweep = m.end_angle - m.start_angle;
double orig_sweep = e.end_angle - e.start_angle;
REQUIRE(orig_sweep > 0.0);
REQUIRE(sweep > 0.0);
}
TEST_CASE("Offset Line by positive d", "[SketchEdit]")
{
SketchEntity e;
e.type = SketchEntity::Type::Line;
e.p0 = Vec2d(0, 0);
e.p1 = Vec2d(10, 0);
auto result = SketchEngine::offset_entities({e}, 2.0);
REQUIRE(result.size() == 1);
const auto& o = result[0];
REQUIRE(o.type == SketchEntity::Type::Line);
REQUIRE_THAT(o.p0.x(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(o.p0.y(), WithinAbs(2.0, 1e-9));
REQUIRE_THAT(o.p1.x(), WithinAbs(10.0, 1e-9));
REQUIRE_THAT(o.p1.y(), WithinAbs(2.0, 1e-9));
}
TEST_CASE("Offset Circle: expand and collapse", "[SketchEdit]")
{
SketchEntity e;
e.type = SketchEntity::Type::Circle;
e.center = Vec2d(0, 0);
e.p0 = Vec2d(0, 0);
e.radius = 5;
auto expanded = SketchEngine::offset_entities({e}, 2.0);
REQUIRE(expanded.size() == 1);
REQUIRE_THAT(expanded[0].radius, WithinAbs(7.0, 1e-9));
auto collapsed = SketchEngine::offset_entities({e}, -5.0);
REQUIRE(collapsed.empty());
}
// CONTRACT CHANGED: +d used to mean "radius + d" for every arc regardless of its sweep, while
// for a line it meant "left of the direction of travel". The two disagreed, so a profile made
// of lines AND arcs (any slot outline) offset with its straights going one way and its caps the
// other, and could never come back closed. The arc now follows the line's rule: +d is left of
// travel, which for this CCW quarter-arc is inward -> r = 3. See [SketchProfile].
TEST_CASE("Offset Arc by positive d (left of travel: a CCW arc shrinks)", "[SketchEdit]")
{
SketchEntity e;
e.type = SketchEntity::Type::Arc;
e.center = Vec2d(0, 0);
e.radius = 4.0;
e.start_angle = 0.0;
e.end_angle = M_PI / 2.0;
e.p0 = Vec2d(4, 0);
e.p1 = Vec2d(0, 4);
auto result = SketchEngine::offset_entities({e}, 1.0);
REQUIRE(result.size() == 1);
const auto& o = result[0];
REQUIRE(o.type == SketchEntity::Type::Arc);
REQUIRE_THAT(o.radius, WithinAbs(3.0, 1e-9));
REQUIRE_THAT(o.p0.x(), WithinAbs(3.0, 1e-9));
REQUIRE_THAT(o.p0.y(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(o.p1.x(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(o.p1.y(), WithinAbs(3.0, 1e-9));
}
TEST_CASE("Fillet right-angle corner", "[SketchEdit]")
{
SketchEntity a;
a.type = SketchEntity::Type::Line;
a.p0 = Vec2d(0, 0);
a.p1 = Vec2d(10, 0);
SketchEntity b;
b.type = SketchEntity::Type::Line;
b.p0 = Vec2d(10, 0);
b.p1 = Vec2d(10, 10);
SketchEntity a_out, b_out, arc_out;
bool ok = SketchEngine::fillet_lines(a, b, 2.0, a_out, b_out, arc_out);
REQUIRE(ok);
REQUIRE_THAT(a_out.p0.x(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(a_out.p0.y(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(a_out.p1.x(), WithinAbs(8.0, 1e-9));
REQUIRE_THAT(a_out.p1.y(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(b_out.p0.x(), WithinAbs(10.0, 1e-9));
REQUIRE_THAT(b_out.p0.y(), WithinAbs(2.0, 1e-9));
REQUIRE_THAT(b_out.p1.x(), WithinAbs(10.0, 1e-9));
REQUIRE_THAT(b_out.p1.y(), WithinAbs(10.0, 1e-9));
REQUIRE(arc_out.type == SketchEntity::Type::Arc);
REQUIRE_THAT(arc_out.radius, WithinAbs(2.0, 1e-9));
REQUIRE_THAT(arc_out.center.x(), WithinAbs(8.0, 1e-9));
REQUIRE_THAT(arc_out.center.y(), WithinAbs(2.0, 1e-9));
REQUIRE_THAT((arc_out.p0 - arc_out.center).norm(), WithinAbs(2.0, 1e-9));
REQUIRE_THAT((arc_out.p1 - arc_out.center).norm(), WithinAbs(2.0, 1e-9));
}
TEST_CASE("Fillet parallel lines returns false", "[SketchEdit]")
{
SketchEntity a;
a.type = SketchEntity::Type::Line;
a.p0 = Vec2d(0, 0);
a.p1 = Vec2d(10, 0);
SketchEntity b;
b.type = SketchEntity::Type::Line;
b.p0 = Vec2d(0, 5);
b.p1 = Vec2d(10, 5);
SketchEntity a_out, b_out, arc_out;
REQUIRE_FALSE(SketchEngine::fillet_lines(a, b, 1.0, a_out, b_out, arc_out));
}
TEST_CASE("Fillet arc too big returns false", "[SketchEdit]")
{
SketchEntity a;
a.type = SketchEntity::Type::Line;
a.p0 = Vec2d(0, 0);
a.p1 = Vec2d(1, 0);
SketchEntity b;
b.type = SketchEntity::Type::Line;
b.p0 = Vec2d(1, 0);
b.p1 = Vec2d(1, 1);
SketchEntity a_out, b_out, arc_out;
REQUIRE_FALSE(SketchEngine::fillet_lines(a, b, 5.0, a_out, b_out, arc_out));
}
TEST_CASE("Trim right arm", "[SketchEdit]")
{
SketchEntity e;
e.type = SketchEntity::Type::Line;
e.p0 = Vec2d(-5, 0);
e.p1 = Vec2d(5, 0);
SketchEntity vc;
vc.type = SketchEntity::Type::Line;
vc.p0 = Vec2d(0, -5);
vc.p1 = Vec2d(0, 5);
bool ok = SketchEngine::trim_entity(e, {vc}, Vec2d(3, 0));
REQUIRE(ok);
REQUIRE_THAT(e.p0.x(), WithinAbs(-5.0, 1e-9));
REQUIRE_THAT(e.p0.y(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(e.p1.x(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(e.p1.y(), WithinAbs(0.0, 1e-9));
}
TEST_CASE("Trim left arm", "[SketchEdit]")
{
SketchEntity e;
e.type = SketchEntity::Type::Line;
e.p0 = Vec2d(-5, 0);
e.p1 = Vec2d(5, 0);
SketchEntity vc;
vc.type = SketchEntity::Type::Line;
vc.p0 = Vec2d(0, -5);
vc.p1 = Vec2d(0, 5);
bool ok = SketchEngine::trim_entity(e, {vc}, Vec2d(-3, 0));
REQUIRE(ok);
REQUIRE_THAT(e.p0.x(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(e.p0.y(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(e.p1.x(), WithinAbs(5.0, 1e-9));
REQUIRE_THAT(e.p1.y(), WithinAbs(0.0, 1e-9));
}
TEST_CASE("Trim no cut (u out of range)", "[SketchEdit]")
{
SketchEntity e;
e.type = SketchEntity::Type::Line;
e.p0 = Vec2d(-5, 0);
e.p1 = Vec2d(5, 0);
SketchEntity other;
other.type = SketchEntity::Type::Line;
other.p0 = Vec2d(0, 3);
other.p1 = Vec2d(0, 8);
REQUIRE_FALSE(SketchEngine::trim_entity(e, {other}, Vec2d(3, 0)));
}
TEST_CASE("Extend forward to line", "[SketchEdit]")
{
SketchEntity e;
e.type = SketchEntity::Type::Line;
e.p0 = Vec2d(0, 0);
e.p1 = Vec2d(2, 0);
SketchEntity other;
other.type = SketchEntity::Type::Line;
other.p0 = Vec2d(5, -5);
other.p1 = Vec2d(5, 5);
bool ok = SketchEngine::extend_entity(e, {other}, Vec2d(2, 0));
REQUIRE(ok);
REQUIRE_THAT(e.p0.x(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(e.p0.y(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(e.p1.x(), WithinAbs(5.0, 1e-9));
REQUIRE_THAT(e.p1.y(), WithinAbs(0.0, 1e-9));
}
TEST_CASE("Extend forward to circle", "[SketchEdit]")
{
SketchEntity e;
e.type = SketchEntity::Type::Line;
e.p0 = Vec2d(0, 0);
e.p1 = Vec2d(2, 0);
SketchEntity other;
other.type = SketchEntity::Type::Circle;
other.center = Vec2d(10, 0);
other.p0 = Vec2d(10, 0);
other.radius = 3;
bool ok = SketchEngine::extend_entity(e, {other}, Vec2d(2, 0));
REQUIRE(ok);
REQUIRE_THAT(e.p0.x(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(e.p0.y(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(e.p1.x(), WithinAbs(7.0, 1e-9));
REQUIRE_THAT(e.p1.y(), WithinAbs(0.0, 1e-9));
}
TEST_CASE("Extend backward", "[SketchEdit]")
{
SketchEntity e;
e.type = SketchEntity::Type::Line;
e.p0 = Vec2d(0, 0);
e.p1 = Vec2d(2, 0);
SketchEntity other;
other.type = SketchEntity::Type::Line;
other.p0 = Vec2d(-3, -5);
other.p1 = Vec2d(-3, 5);
bool ok = SketchEngine::extend_entity(e, {other}, Vec2d(0, 0));
REQUIRE(ok);
REQUIRE_THAT(e.p0.x(), WithinAbs(-3.0, 1e-9));
REQUIRE_THAT(e.p0.y(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(e.p1.x(), WithinAbs(2.0, 1e-9));
REQUIRE_THAT(e.p1.y(), WithinAbs(0.0, 1e-9));
}
TEST_CASE("Extend no target", "[SketchEdit]")
{
SketchEntity e;
e.type = SketchEntity::Type::Line;
e.p0 = Vec2d(0, 0);
e.p1 = Vec2d(2, 0);
SketchEntity other;
other.type = SketchEntity::Type::Line;
other.p0 = Vec2d(5, -5);
other.p1 = Vec2d(5, -1);
REQUIRE_FALSE(SketchEngine::extend_entity(e, {other}, Vec2d(2, 0)));
}
// --- Arc/Circle subject trim & extend (Fase 4.5 kernel) -------------------
TEST_CASE("Trim arc drops the picked (start) side", "[SketchEdit]")
{
// Upper semicircle r=5, ccw from (5,0) to (-5,0); cutter = vertical axis.
SketchEntity e;
e.type = SketchEntity::Type::Arc;
e.center = Vec2d(0, 0);
e.radius = 5;
e.start_angle = 0.0;
e.end_angle = M_PI;
SketchEntity cut;
cut.type = SketchEntity::Type::Line;
cut.p0 = Vec2d(0, -10);
cut.p1 = Vec2d(0, 10);
// Pick the right quarter (phi=pi/4) -> it is removed, left quarter kept.
bool ok = SketchEngine::trim_entity(e, {cut}, Vec2d(5 * std::cos(M_PI/4), 5 * std::sin(M_PI/4)));
REQUIRE(ok);
REQUIRE(e.type == SketchEntity::Type::Arc);
REQUIRE_THAT(e.radius, WithinAbs(5.0, 1e-9));
REQUIRE_THAT(e.start_angle, WithinAbs(M_PI / 2.0, 1e-9));
REQUIRE_THAT(e.end_angle, WithinAbs(M_PI, 1e-9));
}
TEST_CASE("Trim arc drops the picked (end) side", "[SketchEdit]")
{
SketchEntity e;
e.type = SketchEntity::Type::Arc;
e.center = Vec2d(0, 0);
e.radius = 5;
e.start_angle = 0.0;
e.end_angle = M_PI;
SketchEntity cut;
cut.type = SketchEntity::Type::Line;
cut.p0 = Vec2d(0, -10);
cut.p1 = Vec2d(0, 10);
// Pick the left quarter (phi=3pi/4) -> removed, right quarter kept.
bool ok = SketchEngine::trim_entity(e, {cut}, Vec2d(5 * std::cos(3*M_PI/4), 5 * std::sin(3*M_PI/4)));
REQUIRE(ok);
REQUIRE(e.type == SketchEntity::Type::Arc);
REQUIRE_THAT(e.start_angle, WithinAbs(0.0, 1e-9));
REQUIRE_THAT(e.end_angle, WithinAbs(M_PI / 2.0, 1e-9));
}
TEST_CASE("Trim circle opens into an arc excluding the pick", "[SketchEdit]")
{
// Full circle r=5; vertical axis cuts it at (0,+-5). Pick the right side
// (5,0): the kept arc is the left half, sweeping pi and centred on (-5,0).
SketchEntity e;
e.type = SketchEntity::Type::Circle;
e.center = Vec2d(0, 0);
e.p0 = Vec2d(5, 0);
e.radius = 5;
SketchEntity cut;
cut.type = SketchEntity::Type::Line;
cut.p0 = Vec2d(0, -10);
cut.p1 = Vec2d(0, 10);
bool ok = SketchEngine::trim_entity(e, {cut}, Vec2d(5, 0));
REQUIRE(ok);
REQUIRE(e.type == SketchEntity::Type::Arc);
REQUIRE_THAT(e.radius, WithinAbs(5.0, 1e-9));
REQUIRE_THAT(e.end_angle - e.start_angle, WithinAbs(M_PI, 1e-9));
// Midpoint of the kept arc must point left (away from the pick).
double mid = 0.5 * (e.start_angle + e.end_angle);
REQUIRE_THAT(5 * std::cos(mid), WithinAbs(-5.0, 1e-9));
REQUIRE_THAT(5 * std::sin(mid), WithinAbs(0.0, 1e-9));
}
TEST_CASE("Extend arc forward (end) to a crossing", "[SketchEdit]")
{
// Quarter arc (5,0)->(0,5); cutter crosses the circle at (-5,0). Picking
// near the end grows the sweep ccw to pi.
SketchEntity e;
e.type = SketchEntity::Type::Arc;
e.center = Vec2d(0, 0);
e.radius = 5;
e.start_angle = 0.0;
e.end_angle = M_PI / 2.0;
SketchEntity cut;
cut.type = SketchEntity::Type::Line;
cut.p0 = Vec2d(-10, 0);
cut.p1 = Vec2d(0, 0);
bool ok = SketchEngine::extend_entity(e, {cut}, Vec2d(0, 5));
REQUIRE(ok);
REQUIRE(e.type == SketchEntity::Type::Arc);
REQUIRE_THAT(e.start_angle, WithinAbs(0.0, 1e-9));
REQUIRE_THAT(e.end_angle, WithinAbs(M_PI, 1e-9));
}
TEST_CASE("Extend arc backward (start) to a crossing", "[SketchEdit]")
{
// Quarter arc (0,5)->(-5,0); cutter crosses at (5,0). Picking near the
// start grows the sweep cw to start_angle 0.
SketchEntity e;
e.type = SketchEntity::Type::Arc;
e.center = Vec2d(0, 0);
e.radius = 5;
e.start_angle = M_PI / 2.0;
e.end_angle = M_PI;
SketchEntity cut;
cut.type = SketchEntity::Type::Line;
cut.p0 = Vec2d(10, 0);
cut.p1 = Vec2d(0, 0);
bool ok = SketchEngine::extend_entity(e, {cut}, Vec2d(0, 5));
REQUIRE(ok);
REQUIRE_THAT(e.start_angle, WithinAbs(0.0, 1e-9));
REQUIRE_THAT(e.end_angle, WithinAbs(M_PI, 1e-9));
}
TEST_CASE("Extend circle returns false (closed)", "[SketchEdit]")
{
SketchEntity e;
e.type = SketchEntity::Type::Circle;
e.center = Vec2d(0, 0);
e.p0 = Vec2d(5, 0);
e.radius = 5;
SketchEntity cut;
cut.type = SketchEntity::Type::Line;
cut.p0 = Vec2d(0, -10);
cut.p1 = Vec2d(0, 10);
REQUIRE_FALSE(SketchEngine::extend_entity(e, {cut}, Vec2d(5, 0)));
}
TEST_CASE("Trim arc with no crossing returns false", "[SketchEdit]")
{
SketchEntity e;
e.type = SketchEntity::Type::Arc;
e.center = Vec2d(0, 0);
e.radius = 5;
e.start_angle = 0.0;
e.end_angle = M_PI / 2.0;
SketchEntity cut; // far away, never reaches the r=5 circle
cut.type = SketchEntity::Type::Line;
cut.p0 = Vec2d(20, -5);
cut.p1 = Vec2d(20, 5);
REQUIRE_FALSE(SketchEngine::trim_entity(e, {cut}, Vec2d(5 * std::cos(M_PI/4), 5 * std::sin(M_PI/4))));
}
// Regression guard: BEFORE the weld fix this test failed with 4 edges instead of 6.
// BRepLib_MakeWire::Add silently DROPS a disconnected edge (BRepLib_DisconnectedWire + NotDone)
// yet every successful Add ends with BRepLib_WireDone + Done(), so IsDone() reported only whether
// the LAST edge connected. This sketch is a real user loop (2 arcs + 4 lines) given in
// creation order, which is NOT traversal order, and its joint between the 3rd and 4th entity
// below is open by 2.28e-5 mm — larger than OCCT's default vertex tolerance.
TEST_CASE("entities_to_wires keeps every edge of a loop drawn out of order", "[SketchEngine]")
{
std::vector<SketchEntity> ents(6);
ents[0].type = SketchEntity::Type::Line;
ents[0].p0 = Vec2d(-0.537697713190522, -0.0009077462579133498);
ents[0].p1 = Vec2d(99.46230228680926, -0.0009141694814321626);
ents[1].type = SketchEntity::Type::Arc;
ents[1].p0 = Vec2d(-0.537697713190522, -0.0009077462579133498);
ents[1].p1 = Vec2d(-100.14602636660666, -0.27673132181233495);
ents[1].center = Vec2d(-50.313868583115394, -10.248112903179617);
ents[1].radius = 50.81999999999999;
ents[1].start_angle = 0.20302922018398933;
ents[1].end_angle = 2.944101582158999;
ents[2].type = SketchEntity::Type::Line;
ents[2].p0 = Vec2d(99.46228668626469, -39.22091416947833);
ents[2].p1 = Vec2d(-0.537864366432629, -39.22420589376945);
ents[3].type = SketchEntity::Type::Arc;
ents[3].p0 = Vec2d(-100.14602636694521, -38.94673132181234);
ents[3].p1 = Vec2d(-0.5378420354900413, -39.22421049164698);
ents[3].center = Vec2d(-50.31377078666179, -28.975499083790503);
ents[3].radius = 50.82006659345552;
ents[3].start_angle = -2.944104841286737;
ents[3].end_angle = -0.20305921095748136;
ents[4].type = SketchEntity::Type::Line;
ents[4].p0 = Vec2d(99.46228668626469, -39.22091416947833);
ents[4].p1 = Vec2d(99.46230228680926, -0.0009141694814321626);
ents[5].type = SketchEntity::Type::Line;
ents[5].p0 = Vec2d(-100.14602636694521, -38.94673132181234);
ents[5].p1 = Vec2d(-100.14602636660666, -0.27673132181233495);
auto wires = SketchEngine::entities_to_wires(ents, SketchPlane::XY());
REQUIRE(wires.size() == 1);
int edge_count = 0;
for (TopExp_Explorer ex(wires[0], TopAbs_EDGE); ex.More(); ex.Next())
++edge_count;
REQUIRE(edge_count == 6);
REQUIRE(wires[0].Closed());
}
// Regression guard: this fails at 1e-4 (the wire builder refuses a joint the viewport had
// already shaded closed) and passes at kSketchJoinTol. A 20x10 quad with one joint left open
// by 9e-4 mm — just inside kSketchJoinTol, exactly the case the viewport shades closed — given
// in an order that is NOT traversal order, so the ordering path is covered too.
TEST_CASE("a loop the viewport shades closed is buildable by the kernel", "[SketchEngine]")
{
std::vector<SketchEntity> ents(4);
// (0,0) -> (20,0) -> (20,10) -> (0,10) -> (0.0009, 0): last endpoint misses (0,0) by 9e-4.
ents[0].type = SketchEntity::Type::Line;
ents[0].p0 = Vec2d(0, 0);
ents[0].p1 = Vec2d(20, 0);
// Index 1 is the FAR side, not the neighbour of index 0: creation order here is
// deliberately not traversal order, so a partial wire would reject it without the
// traversal walk.
ents[1].type = SketchEntity::Type::Line;
ents[1].p0 = Vec2d(20, 10);
ents[1].p1 = Vec2d(0, 10);
ents[2].type = SketchEntity::Type::Line;
ents[2].p0 = Vec2d(20, 0);
ents[2].p1 = Vec2d(20, 10);
ents[3].type = SketchEntity::Type::Line;
ents[3].p0 = Vec2d(0, 10);
ents[3].p1 = Vec2d(0.0009, 0);
auto wires = SketchEngine::entities_to_wires(ents, SketchPlane::XY());
REQUIRE(wires.size() == 1);
int edge_count = 0;
for (TopExp_Explorer ex(wires[0], TopAbs_EDGE); ex.More(); ex.Next())
++edge_count;
REQUIRE(edge_count == 4);
REQUIRE(wires[0].Closed());
}
// Regression guard for the auto-close preference. Same 20x10 quad, one joint open by 9e-4 mm
// and given out of traversal order, as "a loop the viewport shades closed is buildable by the
// kernel". With auto-close ON the gap welds (one closed wire); with auto-close OFF it must not.
TEST_CASE("auto-close off makes the kernel demand an exact joint", "[SketchEngine]")
{
std::vector<SketchEntity> ents(4);
ents[0].type = SketchEntity::Type::Line;
ents[0].p0 = Vec2d(0, 0);
ents[0].p1 = Vec2d(20, 0);
ents[1].type = SketchEntity::Type::Line;
ents[1].p0 = Vec2d(20, 10);
ents[1].p1 = Vec2d(0, 10);
ents[2].type = SketchEntity::Type::Line;
ents[2].p0 = Vec2d(20, 0);
ents[2].p1 = Vec2d(20, 10);
ents[3].type = SketchEntity::Type::Line;
ents[3].p0 = Vec2d(0, 10);
ents[3].p1 = Vec2d(0.0009, 0);
auto edge_count = [](const TopoDS_Wire& w) {
int n = 0;
for (TopExp_Explorer ex(w, TopAbs_EDGE); ex.More(); ex.Next()) ++n;
return n;
};
// ON: the 9e-4 mm gap is inside kSketchJoinTol, so the loop welds into one closed wire.
Slic3r::set_sketch_auto_close(true);
auto wires_on = SketchEngine::entities_to_wires(ents, SketchPlane::XY());
REQUIRE(wires_on.size() == 1);
REQUIRE(edge_count(wires_on[0]) == 4);
REQUIRE(wires_on[0].Closed());
// OFF: the joint is not exact, so the gap is NOT welded. entities_to_wires legitimately
// returns open chains (a sweep path is open), so the observable is an OPEN wire — the
// kernel no longer hands back the closed loop the viewport would have shaded.
Slic3r::set_sketch_auto_close(false);
auto wires_off = SketchEngine::entities_to_wires(ents, SketchPlane::XY());
REQUIRE(wires_off.size() == 1);
REQUIRE(edge_count(wires_off[0]) == 4);
REQUIRE_FALSE(wires_off[0].Closed());
// OFF + an EXACT joint (last endpoint exactly (0,0)): the quad still builds closed,
// proving "off" means exact rather than broken.
ents[3].p1 = Vec2d(0, 0);
auto wires_exact = SketchEngine::entities_to_wires(ents, SketchPlane::XY());
REQUIRE(wires_exact.size() == 1);
REQUIRE(edge_count(wires_exact[0]) == 4);
REQUIRE(wires_exact[0].Closed());
// Restore the default so test order cannot leak OFF into the other cases.
Slic3r::set_sketch_auto_close(true);
}
// A stray open segment touching nothing must not break a closed profile: the viewport
// discards open chains when it shades a region extrudable, so with closed_only the kernel
// must discard them too — otherwise Revolve/Extrude fail on a sketch that looks perfect.
TEST_CASE("a stray open segment does not break a closed profile", "[SketchEngine]")
{
auto line = [](double x0, double y0, double x1, double y1) {
SketchEntity e;
e.type = SketchEntity::Type::Line;
e.p0 = Vec2d(x0, y0);
e.p1 = Vec2d(x1, y1);
return e;
};
std::vector<SketchEntity> ents;
ents.push_back(line(0, 0, 20, 0)); // 20x10 quad
ents.push_back(line(20, 0, 20, 10));
ents.push_back(line(20, 10, 0, 10));
ents.push_back(line(0, 10, 0, 0));
ents.push_back(line(5, 5, 6, 5.2)); // stray, touches nothing
auto edge_count = [](const TopoDS_Wire& w) {
int n = 0;
for (TopExp_Explorer ex(w, TopAbs_EDGE); ex.More(); ex.Next()) ++n;
return n;
};
// Unchanged behaviour: the stray line is its own open wire.
auto wires_all = SketchEngine::entities_to_wires(ents, SketchPlane::XY(), /*closed_only=*/false);
REQUIRE(wires_all.size() == 2);
// closed_only drops the open chain: one closed quad survives.
auto wires_closed = SketchEngine::entities_to_wires(ents, SketchPlane::XY(), /*closed_only=*/true);
REQUIRE(wires_closed.size() == 1);
REQUIRE(edge_count(wires_closed[0]) == 4);
REQUIRE(wires_closed[0].Closed());
// The Revolve path (entities_to_wire) finds the single closed loop.
TopoDS_Wire w = SketchEngine::entities_to_wire(ents, SketchPlane::XY(), /*closed_only=*/true);
REQUIRE_FALSE(w.IsNull());
REQUIRE(edge_count(w) == 4);
}
// sketch_open_ends names the two free endpoints of an open chain, so the "does not form a
// single closed wire" failure can say WHERE the sketch is open.
TEST_CASE("sketch_open_ends names where a chain fails to close", "[SketchEngine]")
{
auto line = [](double x0, double y0, double x1, double y1) {
SketchEntity e;
e.type = SketchEntity::Type::Line;
e.p0 = Vec2d(x0, y0);
e.p1 = Vec2d(x1, y1);
return e;
};
// Open C shape: three lines, free endpoints at (0,0) and (0,10).
std::vector<SketchEntity> ents;
ents.push_back(line(0, 0, 10, 0));
ents.push_back(line(10, 0, 10, 10));
ents.push_back(line(10, 10, 0, 10));
auto got = sketch_open_ends(ents, SketchPlane::XY());
REQUIRE(got.size() == 2);
std::sort(got.begin(), got.end(), [](const Vec2d& a, const Vec2d& b) {
if (a.x() < b.x()) return true;
if (a.x() > b.x()) return false;
return a.y() < b.y();
});
REQUIRE_THAT(got[0].x(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(got[0].y(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(got[1].x(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT(got[1].y(), WithinAbs(10.0, 1e-9));
}
+103
View File
@@ -0,0 +1,103 @@
#include <catch2/catch_all.hpp> // mainline OrcaSlicer ships Catch2 v3 (v2 was catch2/catch.hpp)
#include "libslic3r/CAD/SketchImport.hpp"
#include "libslic3r/Utils.hpp" // resources_dir
#include "test_utils.hpp" // ScopedTemporaryFile
#include <fstream>
#include <string>
using namespace Slic3r;
// A 10x10 mm filled square, on disk because nanosvg reads from a file. The path
// must come from the system temp dir: a hardcoded /tmp is not writable on
// Windows, where the stream fails silently and the parse then sees no file.
static void write_square_svg(const std::string& path)
{
std::ofstream f(path);
f << "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"10mm\" height=\"10mm\" "
"viewBox=\"0 0 10 10\">"
"<path d=\"M0,0 L10,0 L10,10 L0,10 Z\" fill=\"#000000\"/></svg>";
REQUIRE(f.good());
}
TEST_CASE("svg_to_regions parses a filled path into a region", "[SketchImport]")
{
ScopedTemporaryFile square(".svg");
write_square_svg(square.string());
ImportRegions regs = svg_to_regions(square.string(), 1.0);
REQUIRE(regs.size() >= 1);
// Outer contour present with at least a few vertices.
REQUIRE(regs[0].size() >= 1);
REQUIRE(regs[0][0].size() >= 4);
// Centred on the origin: bbox half-extent ~5 mm on each side.
double hi = 0.0;
for (const auto& region : regs)
for (const auto& contour : region)
for (const Vec2d& p : contour)
hi = std::max(hi, std::max(std::abs(p.x()), std::abs(p.y())));
REQUIRE(hi > 3.0); // not collapsed
REQUIRE(hi < 8.0); // ~5 mm half-size after centring
}
TEST_CASE("svg_to_regions rejects bad input gracefully", "[SketchImport]")
{
ScopedTemporaryFile square(".svg");
write_square_svg(square.string());
ScopedTemporaryFile missing(".svg"); // name reserved, never written
REQUIRE(svg_to_regions("", 1.0).empty());
REQUIRE(svg_to_regions(missing.string(), 1.0).empty());
REQUIRE(svg_to_regions(square.string(), 0.0).empty()); // scale<=0
}
TEST_CASE("transform_regions moves and scales independently", "[SketchImport]")
{
ImportRegions r = {{ {Vec2d(-1,-1), Vec2d(1,-1), Vec2d(1,1), Vec2d(-1,1)} }};
ImportRegions t = transform_regions(r, Vec2d(10, 20), 2.0, 3.0);
REQUIRE(t.size() == 1);
REQUIRE(t[0][0].size() == 4);
// (-1,-1) -> (-1*2+10, -1*3+20) = (8, 17)
REQUIRE_THAT(t[0][0][0].x(), Catch::Matchers::WithinAbs(8.0, 1e-9));
REQUIRE_THAT(t[0][0][0].y(), Catch::Matchers::WithinAbs(17.0, 1e-9));
// (1,1) -> (1*2+10, 1*3+20) = (12, 23)
REQUIRE_THAT(t[0][0][2].x(), Catch::Matchers::WithinAbs(12.0, 1e-9));
REQUIRE_THAT(t[0][0][2].y(), Catch::Matchers::WithinAbs(23.0, 1e-9));
// identity is a no-op
ImportRegions id = transform_regions(r, Vec2d(0,0), 1.0, 1.0);
REQUIRE_THAT(id[0][0][1].x(), Catch::Matchers::WithinAbs(1.0, 1e-9));
}
TEST_CASE("text_to_regions vectorizes glyphs with counters", "[SketchImport]")
{
// Locate the bundled font; resources_dir() may be unset under ctest, so
// fall back to a cwd-relative path (tests run from the repo root).
std::string font = resources_dir().empty()
? std::string("resources/fonts/HarmonyOS_Sans_SC_Regular.ttf")
: resources_dir() + "/fonts/HarmonyOS_Sans_SC_Regular.ttf";
{
std::ifstream probe(font);
if (!probe.good()) {
SUCCEED("bundled font not reachable in this environment; covered live on :10");
return;
}
}
// Bad input is rejected without throwing.
REQUIRE(text_to_regions("", 10.0, font).empty());
REQUIRE(text_to_regions("A", 0.0, font).empty());
// 'A' has one triangular counter -> a region with an outer + 1 hole.
ImportRegions a = text_to_regions("A", 12.0, font);
REQUIRE(a.size() >= 1);
bool has_hole = false;
for (const auto& region : a)
if (region.size() >= 2) has_hole = true;
REQUIRE(has_hole);
// Two letters produce more regions than one.
ImportRegions ab = text_to_regions("AB", 12.0, font);
REQUIRE(ab.size() >= a.size());
}
+174
View File
@@ -0,0 +1,174 @@
#include <catch2/catch_all.hpp> // mainline OrcaSlicer ships Catch2 v3 (v2 was catch2/catch.hpp)
using Catch::Approx; // v3 scopes Approx into the Catch namespace; v2 had it at global scope
#include "libslic3r/CAD/SketchInference.hpp"
using namespace Slic3r;
using K = InferenceSnap::Kind;
static SketchEntity line(Vec2d a, Vec2d b)
{
SketchEntity e; e.type = SketchEntity::Type::Line; e.p0 = a; e.p1 = b; return e;
}
static SketchEntity circle(Vec2d c, double r)
{
SketchEntity e; e.type = SketchEntity::Type::Circle; e.center = c; e.p0 = c; e.radius = r; return e;
}
TEST_CASE("inference: cursor near a line endpoint snaps Coincident-able to it", "[inference]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}) };
auto s = infer_point_snap(ents, {10.3, 0.2}, 1.0);
REQUIRE(s.kind == K::Endpoint);
CHECK(s.entity == 0);
CHECK(s.role == SketchPointRole::P1);
CHECK((s.point - Vec2d(10, 0)).norm() == Approx(0.0).margin(1e-9));
}
TEST_CASE("inference: endpoint beats midpoint when both are in range", "[inference]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {2, 0}) };
// Query equidistant-ish but closer to the endpoint: endpoint tier wins regardless.
auto s = infer_point_snap(ents, {1.9, 0.0}, 5.0);
CHECK(s.kind == K::Endpoint);
CHECK(s.role == SketchPointRole::P1);
}
TEST_CASE("inference: midpoint of a line is detected", "[inference]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}) };
auto s = infer_point_snap(ents, {5.1, 0.1}, 0.5, /*include_origin=*/false);
REQUIRE(s.kind == K::Midpoint);
CHECK((s.point - Vec2d(5, 0)).norm() == Approx(0.0).margin(1e-9));
}
TEST_CASE("inference: circle centre and rim", "[inference]")
{
std::vector<SketchEntity> ents = { circle({0, 0}, 5.0) };
auto c = infer_point_snap(ents, {0.2, 0.1}, 1.0, false);
CHECK(c.kind == K::Center);
auto r = infer_point_snap(ents, {5.1, 0.0}, 1.0, false);
REQUIRE(r.kind == K::OnEdge);
CHECK((r.point - Vec2d(5, 0)).norm() == Approx(0.0).margin(1e-9));
}
TEST_CASE("inference: origin snap when nothing else is near", "[inference]")
{
std::vector<SketchEntity> ents = { line({20, 20}, {30, 20}) };
auto s = infer_point_snap(ents, {0.1, 0.1}, 1.0);
REQUIRE(s.kind == K::Origin);
CHECK(s.entity == -1);
CHECK((s.point - Vec2d(0, 0)).norm() == Approx(0.0).margin(1e-9));
}
TEST_CASE("inference: nothing in range returns None and the raw query", "[inference]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}) };
auto s = infer_point_snap(ents, {50, 50}, 1.0, /*include_origin=*/false);
CHECK(s.kind == K::None);
CHECK((s.point - Vec2d(50, 50)).norm() == Approx(0.0).margin(1e-9));
}
TEST_CASE("inference: axis inference flags horizontal / vertical segments", "[inference]")
{
CHECK(infer_axis_constraint({0, 0}, {10, 0.05}).value() == SketchConstraintType::Horizontal);
CHECK(infer_axis_constraint({0, 0}, {0.05, 10}).value() == SketchConstraintType::Vertical);
CHECK_FALSE(infer_axis_constraint({0, 0}, {10, 10}).has_value()); // 45 deg
CHECK_FALSE(infer_axis_constraint({0, 0}, {0, 0}).has_value()); // degenerate
}
TEST_CASE("inference: perpendicular inferred for a connected square corner", "[inference]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({10, 0}, {10, 7}) };
auto r = infer_relations(ents, 1);
REQUIRE(r.size() == 1);
CHECK(r[0].type == SketchConstraintType::Perpendicular);
CHECK(r[0].ea == 0);
CHECK(r[0].eb == 1);
}
TEST_CASE("inference: parallel inferred for connected collinear-ish lines", "[inference]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({10, 0}, {21, 0.1}) };
auto r = infer_relations(ents, 1);
REQUIRE(r.size() == 1);
CHECK(r[0].type == SketchConstraintType::Parallel);
CHECK(r[0].ea == 0);
CHECK(r[0].eb == 1);
}
TEST_CASE("inference: two unconnected parallel lines infer nothing", "[inference]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({0, 5}, {10, 5}) };
auto r = infer_relations(ents, 1);
CHECK(r.empty());
}
TEST_CASE("inference: a corner outside tolerance infers nothing", "[inference]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({10, 0}, {15, 7}) };
auto r = infer_relations(ents, 1);
CHECK(r.empty());
}
TEST_CASE("inference: equal radius inferred for near-equal circles", "[inference]")
{
auto r = infer_relations({ circle({0, 0}, 5.0), circle({30, 0}, 5.02) }, 1);
REQUIRE(r.size() == 1);
CHECK(r[0].type == SketchConstraintType::EqualRadius);
CHECK(r[0].ea == 0);
CHECK(r[0].eb == 1);
auto r2 = infer_relations({ circle({0, 0}, 5.0), circle({30, 0}, 6.0) }, 1);
CHECK(r2.empty());
}
TEST_CASE("inference: tangent inferred for a line meeting a circle tangentially", "[inference]")
{
std::vector<SketchEntity> ents = { circle({0, 0}, 5.0), line({0, 5}, {10, 5}) };
auto r = infer_relations(ents, 1);
REQUIRE(r.size() == 1);
CHECK(r[0].type == SketchConstraintType::Tangent);
CHECK(r[0].ea == 0);
CHECK(r[0].eb == 1);
std::vector<SketchEntity> off = { circle({0, 0}, 5.0), line({0, 5}, {10, 9}) };
CHECK(infer_relations(off, 1).empty());
}
TEST_CASE("inference: nothing inferred against a higher index", "[inference]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({10, 0}, {10, 7}) };
auto r = infer_relations(ents, 0);
CHECK(r.empty());
}
TEST_CASE("inference: degenerate entities are ignored", "[inference]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({10, 0}, {10, 0}) };
auto r = infer_relations(ents, 1);
CHECK(r.empty());
}
// The cap that keeps infer_relations linear rather than quadratic. Without it a drawing with
// many equal holes yields a constraint per PAIR: 200 equal circles produced ~20000 candidates,
// the batch was rejected as over-constrained, and the caller's one-at-a-time fallback then ran
// a solve per constraint -- which pinned the app at 95% of a core with the MCP socket
// unresponsive, and is what the corpus rung caught.
TEST_CASE("inference: at most one relation per rule per new entity", "[inference]")
{
// 40 circles of the same radius; the 41st must not produce 40 EqualRadius constraints.
std::vector<SketchEntity> ents;
for (int i = 0; i < 41; ++i) {
SketchEntity c;
c.type = SketchEntity::Type::Circle;
c.center = Vec2d(i * 20.0, 0.0);
c.p0 = c.center;
c.radius = 5.0;
ents.push_back(c);
}
auto rels = infer_relations(ents, 40);
CHECK(rels.size() == 1);
CHECK(rels[0].type == SketchConstraintType::EqualRadius);
CHECK(rels[0].eb == 40);
}
+209
View File
@@ -0,0 +1,209 @@
// Closed-profile harness for the 2D sketch layer.
//
// The existing [SketchEdit] cases check one entity at a time — offset ONE line, mirror ONE
// arc — and every one of them passes while the feature they belong to is unusable. What a
// user actually does is combine 2D features into a CLOSED PROFILE and extrude it, and the
// property that makes that work is topological, not per-entity: after the operation, do the
// pieces still form a single closed loop?
//
// So these cases assert the loop, not the coordinates. That is the invariant every sketch
// operation has to preserve and the only one that predicts whether the GUI can build a solid
// out of the result.
#include <catch2/catch_all.hpp> // mainline OrcaSlicer ships Catch2 v3 (v2 was catch2/catch.hpp)
#include "libslic3r/CAD/SketchEngine.hpp"
#include <BRepGProp.hxx>
#include <GProp_GProps.hxx>
#include <cmath>
using namespace Slic3r;
using Catch::Matchers::WithinAbs;
namespace {
SketchPlane xy_plane() { return SketchPlane::XY(); }
SketchEntity line(const Vec2d& a, const Vec2d& b)
{
SketchEntity e;
e.type = SketchEntity::Type::Line;
e.p0 = a; e.p1 = b;
return e;
}
// A CCW rectangle as four Line entities sharing endpoints exactly.
std::vector<SketchEntity> rect(double w, double h)
{
return { line({0, 0}, {w, 0}), line({w, 0}, {w, h}),
line({w, h}, {0, h}), line({0, h}, {0, 0}) };
}
// How many of the wires the sketch resolves to are CLOSED.
int closed_wires(const std::vector<SketchEntity>& ents)
{
const auto ws = SketchEngine::entities_to_wires(ents, xy_plane());
int n = 0;
for (const auto& w : ws)
if (!w.IsNull() && w.Closed()) ++n;
return n;
}
// Enclosed area of the single closed loop the sketch resolves to. -1 when it is not one
// closed loop — the failure the whole file exists to catch.
double profile_area(const std::vector<SketchEntity>& ents)
{
const auto ws = SketchEngine::entities_to_wires(ents, xy_plane());
if (ws.size() != 1 || ws[0].IsNull() || !ws[0].Closed()) return -1.0;
const TopoDS_Face f = SketchEngine::wires_to_face(ws, xy_plane());
GProp_GProps props;
BRepGProp::SurfaceProperties(f, props);
return props.Mass();
}
SketchEntity arc(const Vec2d& c, double r, double a0, double a1)
{
SketchEntity e;
e.type = SketchEntity::Type::Arc;
e.center = c;
e.radius = r;
e.start_angle = a0;
e.end_angle = a1;
e.p0 = c + r * Vec2d(std::cos(a0), std::sin(a0));
e.p1 = c + r * Vec2d(std::cos(a1), std::sin(a1));
return e;
}
} // namespace
TEST_CASE("profile baseline: a hand-built rectangle is one closed loop", "[SketchProfile]")
{
REQUIRE(closed_wires(rect(40, 20)) == 1);
}
TEST_CASE("profile: mirroring a closed rectangle keeps it closed", "[SketchProfile]")
{
const auto m = SketchEngine::mirror_entities(rect(40, 20), Vec2d(-10, 0), Vec2d(-10, 1));
REQUIRE(m.size() == 4);
REQUIRE(closed_wires(m) == 1);
}
TEST_CASE("profile: mirroring an open half-profile closes it against the axis", "[SketchProfile]")
{
// Half a rectangle, open along x=0 — the classic "draw half, mirror it" gesture.
const std::vector<SketchEntity> half = {
line({0, 0}, {20, 0}), line({20, 0}, {20, 10}), line({20, 10}, {0, 10}) };
auto all = half;
for (const auto& e : SketchEngine::mirror_entities(half, Vec2d(0, 0), Vec2d(0, 1)))
all.push_back(e);
REQUIRE(all.size() == 6);
REQUIRE(closed_wires(all) == 1);
}
TEST_CASE("profile: offsetting a closed rectangle keeps it closed", "[SketchProfile]")
{
const auto out = SketchEngine::offset_entities(rect(40, 20), 5.0);
REQUIRE(out.size() == 4);
REQUIRE(closed_wires(out) == 1);
}
TEST_CASE("profile: offset outward grows the enclosed area by the right amount", "[SketchProfile]")
{
// A rectangle offset outward by d is (w+2d) x (h+2d) with the corners rounded at r=d,
// so its area is w*h + 2d(w+h) + pi*d^2 whichever way the corners are healed... except
// for a sharp-corner offset, which is exactly (w+2d)*(h+2d). Either healing is defensible;
// a set of four disconnected segments is not, and that is what this measures.
const double w = 40, h = 20, d = 5;
const auto out = SketchEngine::offset_entities(rect(w, h), d);
const auto ws = SketchEngine::entities_to_wires(out, xy_plane());
REQUIRE(ws.size() == 1);
REQUIRE(ws[0].Closed());
}
TEST_CASE("profile: offset sign is left-of-travel, so +d shrinks a CCW rectangle", "[SketchProfile]")
{
// The convention has to be pinned by a test, because it is the one thing a caller cannot
// read off the geometry: +d = left of the direction of travel = inward for a CCW loop.
// Miter join on a rectangle keeps the corners sharp, so the result is exact.
const double w = 40, h = 20, d = 5;
REQUIRE_THAT(profile_area(SketchEngine::offset_entities(rect(w, h), d)),
WithinAbs((w - 2 * d) * (h - 2 * d), 1e-6));
REQUIRE_THAT(profile_area(SketchEngine::offset_entities(rect(w, h), -d)),
WithinAbs((w + 2 * d) * (h + 2 * d), 1e-6));
}
TEST_CASE("profile: offsetting a stadium (two lines + two arcs) stays closed", "[SketchProfile]")
{
// A slot outline: straight top and bottom joined by half-circle caps. This is the case the
// per-entity offset could never repair, because both seams are line-to-arc.
const double L = 30, r = 8, d = 3;
const std::vector<SketchEntity> slot = {
line({0, -r}, {L, -r}),
arc({L, 0}, r, -M_PI / 2, M_PI / 2),
line({L, r}, {0, r}),
arc({0, 0}, r, M_PI / 2, 3 * M_PI / 2),
};
REQUIRE(closed_wires(slot) == 1);
const auto out = SketchEngine::offset_entities(slot, -d); // -d = outward for this CCW loop
REQUIRE(closed_wires(out) == 1);
// Offsetting a stadium outward by d gives the stadium with radius r+d: L*2(r+d) + pi(r+d)^2.
// Lines and caps must move the SAME way — that is the assertion this case exists for.
const double rr = r + d;
REQUIRE_THAT(profile_area(out), WithinAbs(L * 2 * rr + M_PI * rr * rr, 1e-6));
}
TEST_CASE("profile: an open chain offsets without being forced closed", "[SketchProfile]")
{
// A sweep path is legitimately open; the repair must join its interior seams and leave
// the two free ends alone.
const std::vector<SketchEntity> open_chain = {
line({0, 0}, {20, 0}), line({20, 0}, {20, 10}) };
const auto out = SketchEngine::offset_entities(open_chain, 4.0);
REQUIRE(out.size() == 2);
REQUIRE(closed_wires(out) == 0);
// The interior seam is repaired: the two offset segments still meet.
REQUIRE_THAT((out[0].p1 - out[1].p0).norm(), WithinAbs(0.0, 1e-9));
}
TEST_CASE("profile: a mirrored half offsets as one loop, not two", "[SketchProfile]")
{
// The classic "draw half, mirror it" gesture on a stadium. mirror_entities emits a half
// that travels the opposite way round, so the concatenation must still chain as ONE closed
// loop and its mirrored cap must offset outward like the original, not inward.
const double L = 30, R = 15, d = 4;
const std::vector<SketchEntity> half = {
line({0, -R}, {L, -R}),
arc({L, 0}, R, -M_PI / 2, M_PI / 2),
line({L, R}, {0, R}),
};
std::vector<SketchEntity> all = half;
for (const auto& e : SketchEngine::mirror_entities(half, Vec2d(0, 0), Vec2d(0, 1)))
all.push_back(e);
REQUIRE(closed_wires(all) == 1);
const auto out = SketchEngine::offset_entities(all, -d); // -d = outward for this loop
REQUIRE(closed_wires(out) == 1);
for (const auto& o : out)
if (o.type == SketchEntity::Type::Arc)
REQUIRE_THAT(o.radius, WithinAbs(R + d, 1e-9));
}
TEST_CASE("profile: a mirrored half continues the original chain", "[SketchProfile]")
{
// The point of emitting the reflected half reversed: appending it to the source must give a
// chain you can WALK, head-to-tail, with no consumer having to notice that half of it came
// from a mirror. The end of the last source entity must be the start of the first mirrored
// one, and the end of the last mirrored one must close back to the very first start.
const std::vector<SketchEntity> half = {
line({0, -15}, {50, -15}), line({50, -15}, {50, 15}), line({50, 15}, {0, 15}) };
const auto m = SketchEngine::mirror_entities(half, Vec2d(0, 0), Vec2d(0, 1));
REQUIRE(m.size() == 3);
REQUIRE_THAT((half.back().p1 - m.front().p0).norm(), WithinAbs(0.0, 1e-9));
REQUIRE_THAT((m.back().p1 - half.front().p0).norm(), WithinAbs(0.0, 1e-9));
for (size_t i = 0; i + 1 < m.size(); ++i)
REQUIRE_THAT((m[i].p1 - m[i + 1].p0).norm(), WithinAbs(0.0, 1e-9));
auto all = half;
for (const auto& e : m) all.push_back(e);
REQUIRE(closed_wires(all) == 1);
}
+401
View File
@@ -0,0 +1,401 @@
#include <catch2/catch_all.hpp> // mainline OrcaSlicer ships Catch2 v3 (v2 was catch2/catch.hpp)
using Catch::Approx; // v3 scopes Approx into the Catch namespace; v2 had it at global scope
#include "libslic3r/CAD/SketchSolver.hpp"
#include "libslic3r/CAD/SketchEngine.hpp"
using namespace Slic3r;
using CT = SketchConstraintType;
using R = SketchPointRole;
static SketchEntity line(Vec2d a, Vec2d b)
{
SketchEntity e; e.type = SketchEntity::Type::Line; e.p0 = a; e.p1 = b; return e;
}
static SketchEntity circle(Vec2d c, double r)
{
SketchEntity e; e.type = SketchEntity::Type::Circle; e.center = c; e.p0 = c; e.radius = r; return e;
}
static SketchEntityConstraintDef con(CT t, int ea, R ra, int eb, R rb, double v = 0.0)
{
SketchEntityConstraintDef c; c.type = t; c.ea = ea; c.ra = ra; c.eb = eb; c.rb = rb; c.value = v; return c;
}
TEST_CASE("slvs: distance + horizontal + fix solves a line length", "[slvs]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {5, 1}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::Fix, 0, R::P0, 0, R::P0),
con(CT::Horizontal, 0, R::P0, 0, R::P1),
con(CT::Distance, 0, R::P0, 0, R::P1, 10.0),
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK((ents[0].p1 - ents[0].p0).norm() == Approx(10.0).margin(1e-6));
CHECK(ents[0].p0.x() == Approx(0.0).margin(1e-6));
CHECK(ents[0].p0.y() == Approx(0.0).margin(1e-6));
CHECK(ents[0].p1.y() == Approx(0.0).margin(1e-6)); // horizontal
}
TEST_CASE("slvs: coincident joins two line endpoints (loop closes)", "[slvs]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({10.3, 0.2}, {10, 10}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::Coincident, 0, R::P1, 1, R::P0),
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK((ents[0].p1 - ents[1].p0).norm() == Approx(0.0).margin(1e-6));
}
TEST_CASE("slvs: parallel + perpendicular on lines", "[slvs]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {10, 1}), line({0, 5}, {10, 5.5}), line({0, 0}, {0.5, 10}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::Fix, 0, R::P0, 0, R::P0),
con(CT::Horizontal, 0, R::P0, 0, R::P1),
con(CT::Parallel, 0, R::P0, 1, R::P0), // line1 parallel to line0
con(CT::Perpendicular, 0, R::P0, 2, R::P0), // line2 perpendicular to line0
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK(ents[1].p1.y() - ents[1].p0.y() == Approx(0.0).margin(1e-6)); // line1 horizontal
CHECK(ents[2].p1.x() - ents[2].p0.x() == Approx(0.0).margin(1e-6)); // line2 vertical
}
TEST_CASE("slvs: circle radius constraint", "[slvs]")
{
std::vector<SketchEntity> ents = { circle({2, 2}, 3.0) };
std::vector<SketchEntityConstraintDef> cons = { con(CT::Radius, 0, R::P0, -1, R::P0, 7.0) };
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK(ents[0].radius == Approx(7.0).margin(1e-6));
}
TEST_CASE("slvs: degrees of freedom reported", "[slvs]")
{
// One free line with only a Fix on the start: 4 DoF total minus 2 (fix) = 2 remaining.
std::vector<SketchEntity> ents = { line({0, 0}, {3, 4}) };
std::vector<SketchEntityConstraintDef> cons = { con(CT::Fix, 0, R::P0, 0, R::P0) };
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK(res.dof == 2);
}
TEST_CASE("slvs: drag pulls a point while constraints hold", "[slvs]")
{
// A vertical line of fixed length 10, P0 pinned at the origin. Dragging P1 toward
// (10,0) must keep the length (Distance constraint) but rotate the line so the end
// follows the cursor into positive x — the dragged param wins the under-constrained DoF.
std::vector<SketchEntity> ents = { line({0, 0}, {0, 10}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::Fix, 0, R::P0, 0, R::P0),
con(CT::Distance, 0, R::P0, 0, R::P1, 10.0),
};
ents[0].p1 = Vec2d(10, 0); // user dropped the endpoint here
auto res = sketch_solve_drag(ents, cons, 0, R::P1);
REQUIRE(res.ok);
CHECK((ents[0].p1 - ents[0].p0).norm() == Approx(10.0).margin(1e-6)); // length held
CHECK(ents[0].p0.x() == Approx(0.0).margin(1e-6)); // P0 still pinned
CHECK(ents[0].p0.y() == Approx(0.0).margin(1e-6));
CHECK(ents[0].p1.x() > 1.0); // end followed the drag toward +x (not stuck vertical)
}
TEST_CASE("slvs: over-constrained / inconsistent is detected", "[slvs]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {5, 0}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::Fix, 0, R::P0, 0, R::P0),
con(CT::Fix, 0, R::P1, 0, R::P1),
con(CT::Distance, 0, R::P0, 0, R::P1, 99.0), // contradicts the pinned endpoints
};
auto res = sketch_solve(ents, cons);
CHECK_FALSE(res.ok); // SLVS_RESULT_INCONSISTENT
}
// yww4. libslvs sizes its System with a compile-time `MAX_UNKNOWNS = 1024`, and the
// solver is handed every entity in the sketch at 2 params per point — so a sketch of about 480
// lines is the last one that fits and the next comes back TOO_MANY_UNKNOWNS. Because
// try_add_constraints rolls a failed batch back, that turned into: every auto-inferred constraint
// on a large sketch silently dropped, and from then on no dimension could ever be applied to it.
// Constraints only couple entities that share a point, so the sketch is solved component by
// component when the whole system does not fit.
TEST_CASE("slvs: a sketch past the solver's unknown limit still solves", "[slvs]")
{
// 300 disjoint squares: 1200 lines, 4800 unknowns whole, 8 per component.
const int N = 300;
std::vector<SketchEntity> ents;
std::vector<SketchEntityConstraintDef> cons;
for (int i = 0; i < N; ++i) {
const double x = (i % 30) * 10.0, y = (i / 30) * 10.0;
const int b = int(ents.size());
ents.push_back(line({x, y}, {x + 4.0, y}));
ents.push_back(line({x + 4.0, y}, {x + 4.0, y + 4.0}));
ents.push_back(line({x + 4.0, y + 4.0}, {x, y + 4.0}));
ents.push_back(line({x, y + 4.0}, {x, y}));
for (int k = 0; k < 4; ++k)
cons.push_back(con(CT::Coincident, b + k, R::P1, b + (k + 1) % 4, R::P0));
}
REQUIRE(ents.size() == size_t(4 * N));
std::vector<SketchEntity> before = ents;
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
for (size_t i = 0; i < ents.size(); ++i) { // already satisfied: nothing may move
CHECK(ents[i].p0.x() == Approx(before[i].p0.x()).margin(1e-9));
CHECK(ents[i].p0.y() == Approx(before[i].p0.y()).margin(1e-9));
CHECK(ents[i].p1.x() == Approx(before[i].p1.x()).margin(1e-9));
CHECK(ents[i].p1.y() == Approx(before[i].p1.y()).margin(1e-9));
}
// And a dimension typed onto one of them lands exactly, which is what stopped working.
cons.push_back(con(CT::Distance, 0, R::P0, 0, R::P1, 7.0));
auto res2 = sketch_solve(ents, cons);
REQUIRE(res2.ok);
CHECK((ents[0].p1 - ents[0].p0).norm() == Approx(7.0).margin(1e-9));
// A conflict inside ONE component must still be caught, not swallowed by the split.
cons.push_back(con(CT::Distance, 0, R::P0, 0, R::P1, 99.0));
auto res3 = sketch_solve(ents, cons);
CHECK_FALSE(res3.ok);
}
TEST_CASE("slvs: equal radius drives two circles to one radius", "[slvs][CadDocument]")
{
std::vector<SketchEntity> ents = { circle({0, 0}, 5.0), circle({10, 0}, 12.0) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::EqualRadius, 0, R::P0, 1, R::P0),
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK(ents[0].radius == Approx(ents[1].radius).margin(1e-9));
CHECK(ents[0].radius > 1e-6); // equal-at-zero would satisfy the line above trivially
}
TEST_CASE("slvs: equal radius plus a radius dimension pins both", "[slvs][CadDocument]")
{
std::vector<SketchEntity> ents = { circle({0, 0}, 5.0), circle({10, 0}, 12.0) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::EqualRadius, 0, R::P0, 1, R::P0),
con(CT::Radius, 0, R::P0, -1, R::P0, 8.0),
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK(ents[0].radius == Approx(8.0).margin(1e-9));
CHECK(ents[1].radius == Approx(8.0).margin(1e-9));
}
TEST_CASE("slvs: collinear makes two offset lines share one line", "[slvs][CadDocument]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({0, 4}, {10, 4}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::Collinear, 0, R::P0, 1, R::P0),
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
const Vec2d& a0 = ents[0].p0;
const Vec2d ad = ents[0].p1 - ents[0].p0;
for (int k = 0; k <= 1; ++k) {
const Vec2d& pk = (k == 0) ? ents[1].p0 : ents[1].p1;
const double cross = ad.x() * (pk.y() - a0.y()) - ad.y() * (pk.x() - a0.x());
CHECK(cross == Approx(0.0).margin(1e-9));
}
// A line collapsed to a point is trivially collinear with anything, so the cross
// products above would pass on a degenerate solve. Both lines must survive intact.
CHECK(ad.norm() == Approx(10.0).margin(1e-9));
CHECK((ents[1].p1 - ents[1].p0).norm() == Approx(10.0).margin(1e-9));
}
TEST_CASE("slvs: collinear on already-collinear lines moves nothing", "[slvs][CadDocument]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({20, 0}, {30, 0}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::Collinear, 0, R::P0, 1, R::P0),
};
std::vector<SketchEntity> before = ents;
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
for (size_t i = 0; i < ents.size(); ++i) { // already satisfied: nothing may move
CHECK(ents[i].p0.x() == Approx(before[i].p0.x()).margin(1e-9));
CHECK(ents[i].p0.y() == Approx(before[i].p0.y()).margin(1e-9));
CHECK(ents[i].p1.x() == Approx(before[i].p1.x()).margin(1e-9));
CHECK(ents[i].p1.y() == Approx(before[i].p1.y()).margin(1e-9));
}
}
TEST_CASE("slvs: distance-x drives the horizontal gap and leaves Y alone", "[slvs][CadDocument]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {3, 7}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::Fix, 0, R::P0, 0, R::P0),
con(CT::DistanceX, 0, R::P0, 0, R::P1, 10.0),
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
// SIGNED, not abs. PROJ_PT_DISTANCE constrains (pB - pA).dot(unit(dir)), and a
// LINE_SEGMENT's direction is point[0] - point[1] (slvs entity.cpp), so the reference
// line is built head-first to mean +X. Assert on abs and a flipped reference passes
// while every dimension lands the point on the wrong side of its anchor.
CHECK(ents[0].p1.x() - ents[0].p0.x() == Approx(10.0).margin(1e-9));
CHECK(ents[0].p1.y() == Approx(7.0).margin(1e-9)); // Y must not be disturbed
}
TEST_CASE("slvs: distance-y drives the vertical gap and leaves X alone", "[slvs][CadDocument]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {3, 7}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::Fix, 0, R::P0, 0, R::P0),
con(CT::DistanceY, 0, R::P0, 0, R::P1, 10.0),
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK(ents[0].p1.y() - ents[0].p0.y() == Approx(10.0).margin(1e-9)); // signed: see above
CHECK(ents[0].p1.x() == Approx(3.0).margin(1e-9)); // X must not be disturbed
}
TEST_CASE("slvs: distance-x is not the straight-line distance", "[slvs][CadDocument]")
{
// B is at straight-line distance 10 from A; DistanceX = 6 is already satisfied, so a
// correct projection leaves B untouched. This is the case that fails if the constraint
// were wired to SLVS_C_PT_PT_DISTANCE, which would drag B onto the radius-6 circle.
std::vector<SketchEntity> ents = { line({0, 0}, {6, 8}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::Fix, 0, R::P0, 0, R::P0),
con(CT::DistanceX, 0, R::P0, 0, R::P1, 6.0),
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK(ents[0].p1.x() == Approx(6.0).margin(1e-9));
CHECK(ents[0].p1.y() == Approx(8.0).margin(1e-9));
}
TEST_CASE("slvs: distance-x plus distance-y fully locates a point", "[slvs][CadDocument]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {1, 1}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::Fix, 0, R::P0, 0, R::P0),
con(CT::DistanceX, 0, R::P0, 0, R::P1, 4.0),
con(CT::DistanceY, 0, R::P0, 0, R::P1, 3.0),
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK(ents[0].p1.x() - ents[0].p0.x() == Approx(4.0).margin(1e-9)); // signed: see above
CHECK(ents[0].p1.y() - ents[0].p0.y() == Approx(3.0).margin(1e-9));
}
// The property the GUI's ref-ordering exists to preserve: DistanceX is SIGNED, so applying
// the CURRENT projected delta as the target must not move anything. If the refs are ordered
// so the shown value is positive while the actual signed delta is negative, accepting the
// value a dimension opens with teleports the point to the other side of its anchor.
TEST_CASE("slvs: applying a point's own distance-x is a no-op", "[slvs][CadDocument]")
{
// p1 sits to the LEFT of p0, so the signed delta p1 - p0 is negative.
std::vector<SketchEntity> ents = { line({0, 0}, {-4, 7}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::Fix, 0, R::P0, 0, R::P0),
con(CT::DistanceX, 0, R::P0, 0, R::P1, -4.0), // the CURRENT signed delta
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK(ents[0].p1.x() == Approx(-4.0).margin(1e-9)); // stayed left, did not flip to +4
CHECK(ents[0].p1.y() == Approx(7.0).margin(1e-9));
}
static SketchEntity point(Vec2d p)
{
SketchEntity e; e.type = SketchEntity::Type::Point; e.p0 = p; return e;
}
TEST_CASE("slvs: coincident onto the origin sentinel pins a point", "[slvs][CadDocument]")
{
std::vector<SketchEntity> ents = { point({5, 5}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::Coincident, 0, R::P0, kSketchRefOrigin, R::P0),
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK(ents[0].p0.x() == Approx(0.0).margin(1e-9));
CHECK(ents[0].p0.y() == Approx(0.0).margin(1e-9));
}
// NOTE on why these pin the free direction instead of asserting "the other coordinate is
// left alone". sys.dragged[] is populated only while a drag is in progress, so a plain
// sketch_solve of an UNDER-constrained system is free to move any parameter -- solvespace
// runs a Newton iteration, it does not minimise movement. PointOnLine alone is one equation
// in two unknowns, and the point measurably slides along the axis (from (7,4) to (4,0)).
// That is legal, not a defect, so the well-posed test states both coordinates.
TEST_CASE("slvs: point-on-line onto the X axis, located along it from the origin", "[slvs][CadDocument]")
{
std::vector<SketchEntity> ents = { point({7, 4}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::PointOnLine, 0, R::P0, kSketchRefAxisX, R::P0),
con(CT::DistanceX, kSketchRefOrigin, R::P0, 0, R::P0, 7.0), // both sentinels at once
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK(ents[0].p0.y() == Approx(0.0).margin(1e-9)); // driven onto the X axis
CHECK(ents[0].p0.x() == Approx(7.0).margin(1e-9)); // and located along it
}
TEST_CASE("slvs: point-on-line onto the Y axis, located along it from the origin", "[slvs][CadDocument]")
{
std::vector<SketchEntity> ents = { point({4, 7}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::PointOnLine, 0, R::P0, kSketchRefAxisY, R::P0),
con(CT::DistanceY, kSketchRefOrigin, R::P0, 0, R::P0, 7.0),
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK(ents[0].p0.x() == Approx(0.0).margin(1e-9)); // driven onto the Y axis
CHECK(ents[0].p0.y() == Approx(7.0).margin(1e-9)); // and located along it
}
TEST_CASE("slvs: parallel to the X axis levels a line without collapsing it", "[slvs][CadDocument]")
{
std::vector<SketchEntity> ents = { line({0, 0}, {10, 3}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::Fix, 0, R::P0, 0, R::P0),
con(CT::Parallel, 0, R::P0, kSketchRefAxisX, R::P0),
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK(ents[0].p1.y() == Approx(0.0).margin(1e-9)); // leveled onto y = 0
// A bare Parallel leaves length free; the solver preserves the endpoint's free
// x-coordinate, so the line lands at (10,0) — length 10, not the original sqrt(109).
// Assert that free coordinate rather than abs(): a flipped/collapsed line would not
// land exactly here.
CHECK(ents[0].p1.x() == Approx(10.0).margin(1e-9));
CHECK((ents[0].p1 - ents[0].p0).norm() == Approx(10.0).margin(1e-6)); // did not collapse
}
TEST_CASE("slvs: symmetric-about-Y mirrors two points across x = 0", "[slvs][CadDocument]")
{
std::vector<SketchEntity> ents = { point({3, 5}), point({9, 5}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::SymmetricAboutY, 0, R::P0, 1, R::P0),
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK(ents[0].p0.x() == Approx(-ents[1].p0.x()).margin(1e-9)); // mirror across x = 0
// Neither x may be 0: a both-collapsed-to-the-axis solution also satisfies the mirror
// trivially. Squared, not abs(), so a near-zero x still fails cleanly.
CHECK(ents[0].p0.x() * ents[0].p0.x() > 1e-12);
CHECK(ents[1].p0.x() * ents[1].p0.x() > 1e-12);
CHECK(ents[0].p0.y() == Approx(5.0).margin(1e-9)); // Y values untouched
CHECK(ents[1].p0.y() == Approx(5.0).margin(1e-9));
}
TEST_CASE("slvs: reference-based constraint adds no degrees of freedom", "[slvs][CadDocument]")
{
// A free line with Fix on P0 and Parallel to the X axis: 4 DoF - 2 (fix) - 1 (angle)
// = 1 (length still free). If the G_FIXED reference entities leaked unknowns into the
// solved group, this figure would be wrong.
std::vector<SketchEntity> ents = { line({0, 0}, {3, 4}) };
std::vector<SketchEntityConstraintDef> cons = {
con(CT::Fix, 0, R::P0, 0, R::P0),
con(CT::Parallel, 0, R::P0, kSketchRefAxisX, R::P0),
};
auto res = sketch_solve(ents, cons);
REQUIRE(res.ok);
CHECK(res.dof == 1);
}
@@ -1025,3 +1025,41 @@ TEST_CASE("Selector slicing keeps the result valid across re-apply", "[Print][H2
REQUIRE(status != PrintBase::APPLY_STATUS_INVALIDATED);
REQUIRE(print.is_step_done(psSlicingFinished));
}
TEST_CASE("parse_cyclic_order parses user cyclic toolchange sequences", "[ToolOrdering][Cyclic]")
{
// Filament numbers are 1-based in the UI; the parser returns 0-based indices.
SECTION("well-formed sequence") {
REQUIRE(parse_cyclic_order("3,2,1,4", 4) == std::vector<unsigned int>({2, 1, 0, 3}));
}
SECTION("surrounding whitespace is tolerated") {
REQUIRE(parse_cyclic_order(" 3 , 2 ,1, 4 ", 4) == std::vector<unsigned int>({2, 1, 0, 3}));
}
SECTION("out-of-range and non-positive entries are dropped") {
// 0 is below the 1-based range, 5 is above it for a 4-filament setup, -1 is invalid.
REQUIRE(parse_cyclic_order("0,5,-1,2", 4) == std::vector<unsigned int>({1}));
}
SECTION("duplicates keep only the first occurrence") {
REQUIRE(parse_cyclic_order("2,2,1,2", 4) == std::vector<unsigned int>({1, 0}));
}
SECTION("garbage tokens are ignored") {
REQUIRE(parse_cyclic_order("3,abc,,2,x1", 4) == std::vector<unsigned int>({2, 1}));
}
SECTION("tokens that only start with a number are ignored") {
// "2x" must be dropped rather than parsed as filament 2.
REQUIRE(parse_cyclic_order("3,2x,1", 4) == std::vector<unsigned int>({2, 0}));
}
SECTION("empty string yields an empty order") {
REQUIRE(parse_cyclic_order("", 4).empty());
}
SECTION("a partial sequence only names the filaments it lists") {
REQUIRE(parse_cyclic_order("3,1", 4) == std::vector<unsigned int>({2, 0}));
}
}
+196
View File
@@ -6,6 +6,8 @@
#include "libslic3r/ClipperUtils.hpp"
#include "libslic3r/GCode/WipeTower.hpp"
#include "libslic3r/GCode/WipeTower2.hpp"
#include "libslic3r/Print.hpp"
#include "libslic3r/PrintConfig.hpp"
using namespace Slic3r;
using Catch::Matchers::WithinAbs;
@@ -91,3 +93,197 @@ TEST_CASE("Brim width estimate matches each generator's loop quantization", "[Wi
CHECK_THAT(WipeTower::estimate_brim_real_width(3.f, 0.4f, 0.2f, false), WithinAbs(7.5f * spacing, 1e-4f));
CHECK_THAT(WipeTower::estimate_brim_real_width(0.f, 0.4f, 0.2f, true), WithinAbs(0.f, 1e-6f));
}
// ---------------------------------------------------------------------------------------------
// "No sparse layers": the compaction rule and the clearance it demands of the plate.
// ---------------------------------------------------------------------------------------------
// A square of side mm centred on (cx, cy), in bed coordinates.
static Polygon centered_square(double cx, double cy, double side)
{
const double h = 0.5 * side;
Polygon poly;
poly.points = {Point::new_scale(cx - h, cy - h), Point::new_scale(cx + h, cy - h),
Point::new_scale(cx + h, cy + h), Point::new_scale(cx - h, cy + h)};
return poly;
}
static WipeTower::ToolChangeResult make_tcr(int initial_tool, int new_tool, float layer_height)
{
WipeTower::ToolChangeResult tcr{};
tcr.initial_tool = initial_tool;
tcr.new_tool = new_tool;
tcr.layer_height = layer_height;
return tcr;
}
// A 20 mm square tower at the bed origin, no spiral z-hop, so the keep-out zone is the bare
// footprint and every distance below is one the test sets.
static PrintConfig clearance_config()
{
PrintConfig cfg;
cfg.extruder_clearance_radius.value = 40.;
cfg.extruder_clearance_dist_to_rod.value = 20.;
cfg.extruder_clearance_height_to_rod.value = 25.;
cfg.extruder_clearance_height_to_lid.value = 120.;
cfg.nozzle_height.value = 5.;
cfg.nozzle_diameter.values = {0.4};
cfg.z_hop.values = {0.};
cfg.travel_slope.values = {3.};
return cfg;
}
TEST_CASE("Sparse layers are skipped only when nothing else needs a tower on every layer", "[WipeTower][NoSparseLayers]") {
PrintConfig cfg;
cfg.timelapse_type.value = TimelapseType::tlTraditional;
cfg.enable_wrapping_detection.value = false;
cfg.wipe_tower_no_sparse_layers.value = false;
CHECK_FALSE(wipe_tower_sparse_layers_skipped(cfg));
cfg.wipe_tower_no_sparse_layers.value = true;
CHECK(wipe_tower_sparse_layers_skipped(cfg));
// Both park the nozzle on the tower every layer, so no layer is ever dropped and the option
// must read as off everywhere rather than compact in one place and not another.
cfg.timelapse_type.value = TimelapseType::tlSmooth;
CHECK_FALSE(wipe_tower_sparse_layers_skipped(cfg));
cfg.timelapse_type.value = TimelapseType::tlTraditional;
cfg.enable_wrapping_detection.value = true;
CHECK_FALSE(wipe_tower_sparse_layers_skipped(cfg));
}
TEST_CASE("A planned layer is sparse only when its single tool change keeps the filament", "[WipeTower][NoSparseLayers]") {
CHECK(wipe_tower_layer_is_sparse({make_tcr(1, 1, 0.2f)}));
CHECK_FALSE(wipe_tower_layer_is_sparse({make_tcr(0, 1, 0.2f)}));
// A second entry means the layer carries real work whatever the tools are.
CHECK_FALSE(wipe_tower_layer_is_sparse({make_tcr(1, 1, 0.2f), make_tcr(1, 1, 0.2f)}));
CHECK_FALSE(wipe_tower_layer_is_sparse({}));
}
TEST_CASE("The compacted tower falls one layer height behind the object per sparse layer", "[WipeTower][NoSparseLayers]") {
// Five 0.2 mm layers off a 0.1 mm z offset, the middle two sparse. The object reaches
// 0.1 + 5 * 0.2 = 1.1; the tower only grows on the three printed layers, so it ends at
// 0.1 + 3 * 0.2 = 0.7 and a sparse layer carries the previous value rather than its own.
const std::vector<std::vector<WipeTower::ToolChangeResult>> tool_changes{
{make_tcr(0, 1, 0.2f)}, {make_tcr(1, 1, 0.2f)}, {make_tcr(1, 1, 0.2f)},
{make_tcr(1, 0, 0.2f)}, {make_tcr(0, 1, 0.2f)}};
const std::vector<float> tower_z = compute_compacted_wipe_tower_z(tool_changes, 0.1f);
REQUIRE(tower_z.size() == tool_changes.size());
CHECK_THAT(tower_z[0], WithinAbs(0.3f, 1e-5f));
CHECK_THAT(tower_z[1], WithinAbs(0.3f, 1e-5f));
CHECK_THAT(tower_z[2], WithinAbs(0.3f, 1e-5f));
CHECK_THAT(tower_z[3], WithinAbs(0.5f, 1e-5f));
CHECK_THAT(tower_z[4], WithinAbs(0.7f, 1e-5f));
CHECK_THAT(1.1f - tower_z.back(), WithinAbs(2 * 0.2f, 1e-5f));
// Without a base the tower starts at the bed, and an empty layer carries over like a sparse one.
const std::vector<float> no_offset = compute_compacted_wipe_tower_z({{make_tcr(0, 1, 0.2f)}, {}}, 0.f);
CHECK_THAT(no_offset[0], WithinAbs(0.2f, 1e-5f));
CHECK_THAT(no_offset[1], WithinAbs(0.2f, 1e-5f));
}
TEST_CASE("The tower keep-out zone grows by the spiral z-hop envelope", "[WipeTower][NoSparseLayers]") {
PrintConfig cfg = clearance_config();
const Polygon footprint = centered_square(0., 0., 20.);
// No lift, no envelope: the zone works on the bare footprint.
CHECK_THAT(unscaled(compacted_wipe_tower_zone(cfg, footprint).hull.bounding_box().max.x()), WithinAbs(10., 1e-6));
// A spiral lift leaves the outline at low z, so it counts as tower. The circle reaches
// 2 * lift / (2*pi*atan(slope)) past the outline, matching GCodeWriter: 2*2/(2*pi*atan(3)) = 0.51 mm.
cfg.z_hop.values = {2.};
const CompactedTowerZone lifted = compacted_wipe_tower_zone(cfg, footprint);
CHECK_THAT(unscaled(lifted.hull.bounding_box().max.x()), WithinAbs(10.51, 0.02));
CHECK_THAT(unscaled(lifted.hull.bounding_box().min.y()), WithinAbs(-10.51, 0.02));
CHECK(diff(Polygons{footprint}, Polygons{lifted.hull}).empty());
// z_hop is capped at 5 mm by the option, so a taller lift cannot widen the zone further.
cfg.z_hop.values = {10.};
const double capped = unscaled(compacted_wipe_tower_zone(cfg, footprint).hull.bounding_box().max.x());
CHECK_THAT(capped, WithinAbs(10. + 2. * 5. / (2. * M_PI * std::atan(3.)), 0.02));
// The rod sweeps the whole X axis, so its band is the tower's y span plus half the rod offset.
CHECK_THAT(unscaled(lifted.bbox_rod.max.y()), WithinAbs(10.51 + 10., 0.02));
}
TEST_CASE("An object beside a compacted tower is limited by the nearest part of the toolhead", "[WipeTower][NoSparseLayers]") {
const PrintConfig cfg = clearance_config();
const CompactedTowerZone zone = compacted_wipe_tower_zone(cfg, centered_square(0., 0., 20.));
// Each side carries half its clearance less 0.1 mm slack, so the two outlines meet when the
// objects are a full clearance apart: 2 * (4 - 0.2) / 2 = 3.8 mm for the bare nozzle cone,
// 2 * (40 - 0.2) / 2 = 39.8 mm for the head body. A 10 mm object at x leaves a gap of x - 15.
const double tall = 50., shortish = 3.;
// Gap 1 mm, inside the nozzle cone: the object may not rise above the tower at all.
const CompactedTowerClearance touching = compacted_wipe_tower_clearance(cfg, zone, centered_square(16., 0., 10.), tall);
CHECK_THAT(touching.allowed_rise, WithinAbs(0., 1e-9));
// Gap 10 mm: clear of the cone but inside the head body, which starts at nozzle_height.
const CompactedTowerClearance near_body = compacted_wipe_tower_clearance(cfg, zone, centered_square(25., 0., 10.), tall);
CHECK(near_body.near_body);
CHECK_THAT(near_body.allowed_rise, WithinAbs(5., 1e-9));
CHECK_THAT(near_body.body_clearance, WithinAbs(40., 1e-9));
// The same spot, but an object that never rises past the cone. The body sits above the cone, so
// it cannot reach this object however close it stands, and only the narrow tier applies.
const CompactedTowerClearance low = compacted_wipe_tower_clearance(cfg, zone, centered_square(25., 0., 10.), shortish);
CHECK_FALSE(low.near_body);
CHECK_THAT(low.body_clearance, WithinAbs(4., 1e-9));
CHECK_THAT(low.allowed_rise, WithinAbs(25., 1e-9));
// Gap 55 mm, clear of the head entirely: the rod is the obstacle, since the object shares the
// tower's y band and the rod spans the whole x axis however far apart the two stand.
const CompactedTowerClearance far_in_band = compacted_wipe_tower_clearance(cfg, zone, centered_square(70., 0., 10.), tall);
CHECK_FALSE(far_in_band.near_body);
CHECK_THAT(far_in_band.far_clearance, WithinAbs(25., 1e-9));
CHECK_THAT(far_in_band.allowed_rise, WithinAbs(25., 1e-9));
// Out of the band the rod passes over it and only the lid is left.
const CompactedTowerClearance out_of_band = compacted_wipe_tower_clearance(cfg, zone, centered_square(70., 60., 10.), tall);
CHECK_THAT(out_of_band.allowed_rise, WithinAbs(120., 1e-9));
}
TEST_CASE("The ring drawn around the tower meets the outline drawn around an offender", "[WipeTower][NoSparseLayers]") {
const PrintConfig cfg = clearance_config();
const CompactedTowerZone zone = compacted_wipe_tower_zone(cfg, centered_square(0., 0., 20.));
// What the plater draws has to be what the check tested, otherwise a user moves an object until
// the outlines part and slicing still refuses the plate. Both halves of the 3.8 mm nozzle
// clearance: at a 3 mm gap the rings overlap and the rise limit is zero, at 5 mm neither holds.
for (const auto &c : {std::make_pair(18., true), std::make_pair(20., false)}) {
DYNAMIC_SECTION("object at x = " << c.first) {
const Polygon hull = centered_square(c.first, 0., 10.);
const CompactedTowerClearance clearance = compacted_wipe_tower_clearance(cfg, zone, hull, 3.);
const Polygons rings = compacted_wipe_tower_rings(zone, compacted_tower_body_tier(clearance));
const Polygon outline = compacted_wipe_tower_offender_outline(hull, clearance.body_clearance);
const bool outlines_meet = ! intersection(rings, Polygons{outline}).empty();
const bool rise_denied = clearance.allowed_rise < EPSILON;
CHECK(outlines_meet == c.second);
CHECK(rise_denied == c.second);
}
}
}
TEST_CASE("Only the keep-out ring an object is measured against is drawn", "[WipeTower][NoSparseLayers]") {
const PrintConfig cfg = clearance_config();
const CompactedTowerZone zone = compacted_wipe_tower_zone(cfg, centered_square(0., 0., 20.));
// Drawing the wide ring when no object is judged on it would show a keep-out zone the check can
// never trip, so it is added only once some object reaches past the nozzle cone.
CHECK(compacted_wipe_tower_rings(zone, false).size() == zone.grown_nozzle.size());
CHECK(compacted_wipe_tower_rings(zone, true).size() == zone.grown_nozzle.size() + zone.grown_body.size());
CHECK_THAT(unscaled(get_extents(zone.grown_nozzle).max.x()), WithinAbs(10. + 0.5 * (4. - 0.2), 0.02));
CHECK_THAT(unscaled(get_extents(zone.grown_body).max.x()), WithinAbs(10. + 0.5 * (40. - 0.2), 0.02));
}
TEST_CASE("Footprint padding covers the brim and the extrusion half width on each side", "[WipeTower][NoSparseLayers]") {
// A nominal outline hulls extrusion centre lines and is re-centred once the real wall is known,
// so a line width per side on top of the brim is what keeps an estimate enclosing the real tower.
const PrintConfig cfg = clearance_config();
CHECK_THAT(compacted_tower_footprint_padding(cfg, 2.), WithinAbs(2. + 2. * 0.4, 1e-9));
CHECK_THAT(compacted_tower_footprint_padding(cfg, 0.), WithinAbs(2. * 0.4, 1e-9));
// Callers whose outline already carries the brim pass zero, and a negative one cannot shrink it.
CHECK_THAT(compacted_tower_footprint_padding(cfg, -5.), WithinAbs(2. * 0.4, 1e-9));
}
@@ -335,6 +335,10 @@ TEST_CASE("The shipped defaults size the tower from the flush matrix", "[WipeTow
const double flush_volume = WipeTower2::estimate_semm_flush_volume(config, 2);
const double expected = std::max(double(WipeTower::get_limit_depth_by_height(5.f)), flush_volume / (0.2 * 50.));
CHECK_THAT(estimate(config, 2, 0.2, 5.).depth, WithinAbs(expected, 1e-6));
// The flush volume is nonzero for one slot, but a lone filament makes no tool change.
REQUIRE(WipeTower2::estimate_semm_flush_volume(config, 1) > 0.);
CHECK_THAT(estimate(config, 1, 0.2, 5.).depth, WithinAbs(0., 1e-9));
}
TEST_CASE("A config missing a tower key falls back to that key's default", "[WipeTowerEstimate]") {
+290 -5
View File
@@ -1,10 +1,16 @@
#include <catch2/catch_test_macros.hpp>
#include "slic3r/GUI/ActionRegistry.hpp"
#include "slic3r/GUI/NativeCommands.hpp"
#include "slic3r/GUI/SettingsIndex.hpp"
#include <boost/filesystem.hpp>
#include <memory>
#include <set>
#include <string>
#include <type_traits>
#include <vector>
using Slic3r::GUI::AppAction;
using Slic3r::GUI::AppActionRunResult;
@@ -19,21 +25,21 @@ class TestAppAction final : public AppAction
public:
TestAppAction() : AppAction("test", "Action title", "src-key", "Action source") {}
AppActionRunResult run() const override { return {}; }
AppActionRunResult run(const std::string& param = {}) const override { return {}; }
};
} // namespace
TEST_CASE("AppAction composes a stable id from prefix:title:source_key", "[speeddial][actions]")
TEST_CASE("AppAction composes a stable id from prefix:title:source_key", "[ActionSource][SpeedDial]")
{
CHECK(AppAction::compose_id("test", "Action title", "src-key") == "test:Action title:src-key");
// source_key (not the display name) carries identity, so it is the third field.
CHECK(AppAction::compose_id("script", "Do Thing", "pack.py") == "script:Do Thing:pack.py");
}
TEST_CASE("AppAction definitions are immutable after construction", "[speeddial][actions]")
TEST_CASE("AppAction definitions are immutable after construction", "[ActionSource][SpeedDial]")
{
using StringAccessor = const std::string& (AppAction::*)() const;
using StringAccessor = const std::string& (AppAction::*) () const;
STATIC_CHECK(std::is_same_v<decltype(&AppAction::id), StringAccessor>);
STATIC_CHECK(std::is_same_v<decltype(&AppAction::title), StringAccessor>);
@@ -47,9 +53,288 @@ TEST_CASE("AppAction definitions are immutable after construction", "[speeddial]
CHECK(action.source_name() == "Action source");
}
TEST_CASE("ActionRegistry takes exclusive ownership of published actions", "[speeddial][actions]")
TEST_CASE("ActionRegistry takes exclusive ownership of published actions", "[ActionSource][SpeedDial]")
{
using ExpectedUpsert = void (ActionRegistry::*)(std::unique_ptr<AppAction>);
STATIC_CHECK(std::is_same_v<decltype(&ActionRegistry::upsert), ExpectedUpsert>);
}
// A dynamic "Go to Plate N" action is keyed by plate index (not the display title), so renaming
// a plate never re-keys it - the same contract as a setting action.
TEST_CASE("Go-to-plate actions are keyed by index, not title", "[ActionSource][SpeedDial]")
{
CHECK(AppAction::compose_id("orca_plate_goto", "0", "orca") == "orca_plate_goto:0:orca");
CHECK(AppAction::compose_id("orca_plate_goto", "2", "orca") == "orca_plate_goto:2:orca");
}
// A dynamic "Open recent project" action is keyed by file path (not the display name), so renaming
// a project or reordering the recents list never re-keys it - the same contract as a setting action.
TEST_CASE("Recent-project actions are keyed by path, not title", "[ActionSource][SpeedDial]")
{
CHECK(AppAction::compose_id("orca_recent_project", "/a/b/project.3mf", "orca") ==
"orca_recent_project:/a/b/project.3mf:orca");
CHECK(AppAction::compose_id("orca_recent_project", "C:/Data/cube.3mf", "orca") ==
"orca_recent_project:C:/Data/cube.3mf:orca");
}
// A built-in command is keyed by its stable catalog key (not the localized display title), so a
// rename or a UI-language switch never re-keys the action and its persisted favourite/stats survive.
TEST_CASE("Command actions are keyed by catalog key, not display title", "[ActionSource][SpeedDial]")
{
CHECK(AppAction::compose_id("orca_command", "save_project", "orca") == "orca_command:save_project:orca");
// The second field is the stable key, so distinct commands never collide.
CHECK(AppAction::compose_id("orca_command", "save_project", "orca") !=
AppAction::compose_id("orca_command", "load_project", "orca"));
}
// The real catalog -> action mapping keys by the stable catalog key and copies presentation from the
// catalog, so a rename or a UI-language switch never re-keys the action.
TEST_CASE("Command action construction keys by catalog key", "[ActionSource][SpeedDial]")
{
const std::vector<Slic3r::GUI::NativeCommand>& commands = Slic3r::GUI::NativeCommands::catalog();
REQUIRE_FALSE(commands.empty());
const Slic3r::GUI::NativeCommand& c = commands.front();
std::unique_ptr<AppAction> action = Slic3r::GUI::NativeCommands::make_action(c);
REQUIRE(action != nullptr);
CHECK(action->id() == AppAction::compose_id("orca_command", c.key, "orca"));
CHECK(action->id() != AppAction::compose_id("orca_command", c.title, "orca"));
CHECK(action->title() == c.title);
CHECK(action->group == c.group);
CHECK(action->input == c.input);
CHECK(action->icon == c.icon);
}
// The footer description/wiki link is settings-only: built-in commands leave both fields empty, so
// the palette's detail strip depends on list-level visibility for them.
TEST_CASE("Actions default to no description or wiki link", "[ActionSource][SpeedDial]")
{
const TestAppAction action;
CHECK(action.tooltip.empty());
CHECK(action.help_url.empty());
REQUIRE_FALSE(Slic3r::GUI::NativeCommands::catalog().empty());
std::unique_ptr<AppAction> command = Slic3r::GUI::NativeCommands::make_action(Slic3r::GUI::NativeCommands::catalog().front());
REQUIRE(command != nullptr);
CHECK(command->tooltip.empty());
CHECK(command->help_url.empty());
}
// Two-phase commands declare the input the palette must collect before they can run.
TEST_CASE("Two-phase commands declare their input phase", "[ActionSource][SpeedDial]")
{
auto input_of = [](const std::string& key) -> std::string {
for (const auto& c : Slic3r::GUI::NativeCommands::catalog())
if (c.key == key)
return c.input;
return {};
};
CHECK(input_of("go_to_layer") == "percent");
CHECK(input_of("go_to_tab") == "tab");
}
// The input token vocabulary is a JS<->C++ contract (speeddial.js dispatches "percent"/"tab").
// A typo here would leave a command that never enters its second phase, so pin the allowed set.
TEST_CASE("Command input tokens stay in the known vocabulary", "[ActionSource][SpeedDial]")
{
for (const auto& c : Slic3r::GUI::NativeCommands::catalog()) {
INFO(c.key << " input=" << c.input);
CHECK((c.input.empty() || c.input == "percent" || c.input == "tab"));
}
}
// The quick-launch cap must stay 10 to match the numbered Alt/Option+1..9,0 keys. The web palette
// mirrors it as K_FAV_LIMIT (asserted in speeddial.test.js); the C++ side pins it here.
static_assert(Slic3r::GUI::ActionRegistry::kFavLimit == 10, "kFavLimit must stay 10");
TEST_CASE("Favourite lists are capped and deduped preserving order", "[ActionSource][SpeedDial]")
{
using Slic3r::GUI::cap_favourites;
CHECK(cap_favourites({}, 10) == std::vector<std::string>{});
CHECK(cap_favourites({"a", "b", "a"}, 10) == std::vector<std::string>{"a", "b"});
CHECK(cap_favourites({"c", "a", "b", "c"}, 3) == std::vector<std::string>{"c", "a", "b"});
CHECK(cap_favourites({"a", "b"}, 0) == std::vector<std::string>{});
}
TEST_CASE("Native command catalog has unique keys and present titles", "[ActionSource][SpeedDial]")
{
const std::vector<Slic3r::GUI::NativeCommand>& commands = Slic3r::GUI::NativeCommands::catalog();
CHECK_FALSE(commands.empty());
std::set<std::string> seen;
for (const auto& c : commands) {
CHECK_FALSE(c.key.empty());
CHECK_FALSE(c.title.empty());
// A duplicated key would silently shadow the earlier command in the palette.
CHECK(seen.insert(c.key).second);
}
}
// Every command's tile pictogram is a theme-neutral SVG (the matching GUI control's icon, or the
// equivalent settings-group icon); an absent icon gets the page's generic placeholder. Guard
// representative names and that every non-empty value resolves to a shipped file, so a rename/typo
// cannot leave broken images in the palette.
TEST_CASE("Native command icons resolve to shipped SVGs", "[ActionSource][SpeedDial]")
{
const std::vector<Slic3r::GUI::NativeCommand>& commands = Slic3r::GUI::NativeCommands::catalog();
auto icon_of = [&commands](const std::string& key) -> const std::string* {
for (const auto& c : commands)
if (c.key == key)
return &c.icon;
return nullptr;
};
struct Expected
{
const char* key;
const char* icon;
};
for (const Expected& e : {Expected{"load_project", "menu_open"},
Expected{"save_project", "menu_save"},
Expected{"sync_ams", "ams_fila_sync"},
Expected{"mode_simple", "advanced"},
Expected{"calib_temperature", "param_temperature"},
Expected{"calib_cornering", "param_precision"},
Expected{"plate_add", "toolbar_add_plate"},
Expected{"add_primitive_cube", "menu_obj_cube"},
// These previously pointed at blank placeholder SVGs or theme-broken ones.
Expected{"obj_delete", "delete"},
Expected{"export_gcode", "custom-gcode_gcode"},
Expected{"import_file", "menu_open"},
Expected{"help_open_config_folder", "open_project"},
Expected{"help_check_updates", "refresh"},
Expected{"help_about", "OrcaSlicer_gradient_circle"},
Expected{"go_to_tab", ""}}) {
const std::string* icon = icon_of(e.key);
INFO(e.key);
REQUIRE(icon != nullptr);
CHECK(*icon == e.icon);
}
const boost::filesystem::path images = boost::filesystem::path(PROFILES_DIR).parent_path() / "images";
for (const auto& c : commands) {
if (c.icon.empty())
continue;
INFO(c.key << " -> " << c.icon);
CHECK(boost::filesystem::exists(images / (c.icon + ".svg")));
}
}
// The Help-menu commands, wiki/YouTube links and the developer-mode toggle are part of the palette.
// Guard their presence and that they stay grouped with their peers, so a catalog edit cannot drop
// or scatter them. Groups are compared to the peer's own group to stay independent of translation.
TEST_CASE("Native command catalog includes the Help and developer-mode commands", "[ActionSource][SpeedDial]")
{
const std::vector<Slic3r::GUI::NativeCommand>& commands = Slic3r::GUI::NativeCommands::catalog();
auto find = [&commands](const std::string& key) -> const Slic3r::GUI::NativeCommand* {
for (const auto& c : commands)
if (c.key == key)
return &c;
return nullptr;
};
const Slic3r::GUI::NativeCommand* first = find("help_keyboard_shortcuts");
REQUIRE(first != nullptr);
for (const char* key : {"help_setup_wizard", "help_open_config_folder", "help_troubleshoot", "help_network_test",
"help_tip_of_the_day", "help_check_updates", "help_about", "open_wiki", "open_youtube"}) {
const Slic3r::GUI::NativeCommand* c = find(key);
REQUIRE(c != nullptr);
CHECK(c->group == first->group);
}
const Slic3r::GUI::NativeCommand* mode_simple = find("mode_simple");
const Slic3r::GUI::NativeCommand* dev_mode = find("toggle_developer_mode");
REQUIRE(mode_simple != nullptr);
REQUIRE(dev_mode != nullptr);
CHECK(dev_mode->group == mode_simple->group);
}
// Every "Add Primitive" item and shipped handy model has a palette command, grouped as in the Add
// menu. Groups are compared to a peer's own group to stay independent of translation.
TEST_CASE("Native command catalog covers the Add menus", "[ActionSource][SpeedDial]")
{
const std::vector<Slic3r::GUI::NativeCommand>& commands = Slic3r::GUI::NativeCommands::catalog();
auto group_of = [&commands](const std::string& key) -> const std::string* {
for (const auto& c : commands)
if (c.key == key)
return &c.group;
return nullptr;
};
const std::string* primitive_group = group_of("add_primitive_cube");
REQUIRE(primitive_group != nullptr);
for (const char* key : {"add_primitive_cylinder", "add_primitive_sphere", "add_primitive_cone", "add_primitive_disc",
"add_primitive_torus", "add_primitive_text", "add_primitive_svg"}) {
const std::string* group = group_of(key);
INFO(key);
REQUIRE(group != nullptr);
CHECK(*group == *primitive_group);
}
const std::string* handy_group = group_of("add_handy_orca_cube");
REQUIRE(handy_group != nullptr);
for (const char* key : {"add_handy_orcasliced_combo", "add_handy_orca_badge", "add_handy_orca_tolerance_test",
"add_handy_3dbenchy", "add_handy_cali_cat", "add_handy_autodesk_fdm_test", "add_handy_voron_cube",
"add_handy_stanford_bunny", "add_handy_orca_string_hell"}) {
const std::string* group = group_of(key);
INFO(key);
REQUIRE(group != nullptr);
CHECK(*group == *handy_group);
}
}
// A setting action is named like its settings row, not the ConfigOptionDef label: the row's
// Line::label, plus the field leaf when the row packs several options.
TEST_CASE("Setting display labels mirror the settings row", "[ActionSource][SpeedDial]")
{
using Slic3r::Search::compose_display_label;
// Single-option row: the row label is the whole title.
CHECK(compose_display_label(L"Reverse on even", L"Reverse on even", false) == L"Reverse on even");
// No recorded row label falls back to the field leaf.
CHECK(compose_display_label(L"", L"Outer wall", false) == L"Outer wall");
// Multi-option row: qualify with the leaf so the plate-temperature fields are distinct.
CHECK(compose_display_label(L"Cool Plate", L"First layer", true) == wxString(L"Cool Plate \u2013 First layer"));
CHECK(compose_display_label(L"Cool Plate", L"Other layers", true) == wxString(L"Cool Plate \u2013 Other layers"));
// A leaf equal to the row label is not repeated.
CHECK(compose_display_label(L"Skirt loops", L"Skirt loops", true) == L"Skirt loops");
using Slic3r::Search::resolve_setting_title;
// A single-option row's live label wins, so a runtime rename is reflected.
CHECK(resolve_setting_title(L"Brim width", L"Brim ear radius", false) == L"Brim ear radius");
// Multi-option rows keep their precomposed "row – field" label (the leaf disambiguates them).
CHECK(resolve_setting_title(L"Cool Plate \u2013 First layer", L"Cool Plate", true) ==
wxString(L"Cool Plate \u2013 First layer"));
// No live row label (option not on a built page) keeps the precomposed label.
CHECK(resolve_setting_title(L"Reverse on even", L"", false) == L"Reverse on even");
// Neither present: empty, so the caller falls back to the descriptive label.
CHECK(resolve_setting_title(L"", L"", false).IsEmpty());
}
// A setting whose mode is above the user's current mode must be prompted before it can be edited.
// Developer settings (comDevelop) are above every non-developer mode, so they always prompt then.
TEST_CASE("Settings above the current mode require a switch", "[ActionSource][SpeedDial]")
{
using Slic3r::GUI::requires_mode_switch;
using Slic3r::comAdvanced;
using Slic3r::comDevelop;
using Slic3r::comExpert;
using Slic3r::comSimple;
CHECK(requires_mode_switch(comAdvanced, comSimple));
CHECK(requires_mode_switch(comExpert, comSimple));
CHECK(requires_mode_switch(comExpert, comAdvanced));
CHECK(requires_mode_switch(comDevelop, comSimple));
CHECK(requires_mode_switch(comDevelop, comAdvanced));
CHECK(requires_mode_switch(comDevelop, comExpert));
CHECK_FALSE(requires_mode_switch(comSimple, comSimple));
CHECK_FALSE(requires_mode_switch(comSimple, comAdvanced));
CHECK_FALSE(requires_mode_switch(comAdvanced, comAdvanced));
CHECK_FALSE(requires_mode_switch(comAdvanced, comExpert));
CHECK_FALSE(requires_mode_switch(comExpert, comExpert));
CHECK_FALSE(requires_mode_switch(comDevelop, comDevelop));
}
+7 -1
View File
@@ -358,7 +358,12 @@ TEST_CASE("integration: orca.printer_agent binding surface", "[integration][Pyth
REQUIRE(py::hasattr(pa, "PrinterAgentBase"));
py::object base = pa.attr("PrinterAgentBase");
for (const char* method : { "get_agent_info", "connect_printer", "disconnect_printer",
"send_message", "start_discovery", "bind_detect",
"send_message", "send_message_to_printer",
"command_ams_refresh_rfid", "command_ams_calibrate",
"command_ams_select_tray", "command_start_camera",
"command_xyz_abs", "command_auto_leveling", "command_go_home",
"command_set_bed", "command_set_nozzle", "command_axis_control",
"start_discovery", "bind_detect",
"start_print", "get_filament_sync_mode" }) {
CAPTURE(method);
CHECK(py::hasattr(base, method));
@@ -380,6 +385,7 @@ TEST_CASE("integration: orca.printer_agent binding surface", "[integration][Pyth
REQUIRE(py::hasattr(pa, "CameraStreamMode"));
py::object camera_mode = pa.attr("CameraStreamMode");
CHECK(py::hasattr(camera_mode, "HTTPS"));
CHECK_FALSE(py::hasattr(camera_mode, "WebRTC"));
// Plugin-type enum exposed at module root (host reads it without the GIL).
CHECK(py::hasattr(orca, "PluginType"));