Files
OrcaSlicer/tests/fff_print/test_print.cpp
T

3954 lines
183 KiB
C++

#ifdef WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <Windows.h>
#endif
#include <catch2/catch_test_macros.hpp>
#include <initializer_list>
#include <string>
#include <catch2/generators/catch_generators.hpp>
#include <catch2/generators/catch_generators_range.hpp>
#include <catch2/catch_message.hpp>
#include "libslic3r/PrintConfig.hpp"
#include "libslic3r/libslic3r.h"
#include <cstddef>
#include "libslic3r/Surface.hpp"
#include "libslic3r/Config.hpp"
#include "libslic3r/PrintBase.hpp"
#include "libslic3r/TriangleMesh.hpp"
#include <catch2/matchers/catch_matchers.hpp>
#include <catch2/matchers/catch_matchers_floating_point.hpp>
#include <catch2/matchers/catch_matchers_string.hpp>
#include <catch2/catch_all.hpp>
#include "libslic3r/Print.hpp"
#include "libslic3r/Slicing.hpp"
#include "libslic3r/Layer.hpp"
#include "libslic3r/BuildVolume.hpp"
#include "libslic3r/Support/TreeModelVolumes.hpp"
#include "libslic3r/Support/TreeSupportCommon.hpp"
#include "libslic3r/Support/BeltFloorContext.hpp"
#include "libslic3r/ClipperUtils.hpp"
#include "libslic3r/ExtrusionEntity.hpp"
#include "libslic3r/ExtrusionEntityCollection.hpp"
#include "libslic3r/Point.hpp"
#include "libslic3r/Polyline.hpp"
#include <limits>
#include <cmath>
#include <map>
#include "libslic3r/Polygon.hpp"
#include "libslic3r/Model.hpp"
#include "libslic3r/GCode.hpp"
#include "libslic3r/GCodeReader.hpp"
#include "libslic3r/GCode/GCodeProcessor.hpp"
#include "libslic3r/Exception.hpp"
#include "libslic3r/LifecycleEvents.hpp"
#include "libslic3r/Utils.hpp"
#include "test_helpers.hpp"
#include "test_utils.hpp"
#include <algorithm>
#include <boost/algorithm/string/predicate.hpp>
#include <cstdlib>
#include <sstream>
#include <atomic>
#include <chrono>
#include <thread>
#include <limits>
#include <fstream>
#include <iterator>
#include <ios>
#include <memory>
#include <optional>
#include <string_view>
#include <utility>
#include <vector>
#include "libslic3r/ObjectID.hpp"
#include "libslic3r/Point.hpp"
#include "libslic3r/SurfaceCollection.hpp"
#include "libslic3r/BoundingBox.hpp"
#include "libslic3r/ExPolygon.hpp"
#include "libslic3r/Geometry.hpp"
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();
config.set_deserialize_strict({
{ "top_shell_layers", 2 },
{ "bottom_shell_layers", 1 },
{ "layer_height", 0.25 }, // get a known number of layers
{ "initial_layer_print_height", 0.25 }
});
Slic3r::Print print;
Slic3r::Model model;
Slic3r::Test::init_print({cube(20)}, print, model, config);
// Precondition: Ensure that the model has 2 solid top layers (79, 78)
// and one solid bottom layer (0).
auto test_is_solid_infill = [&print](size_t obj_id, size_t layer_id) {
const Layer &layer = *(print.objects().at(obj_id)->get_layer((int)layer_id));
// iterate over all of the regions in the layer
for (const LayerRegion *region : layer.regions()) {
// for each region, iterate over the fill surfaces
for (const Surface &surface : region->fill_surfaces.surfaces)
CHECK(surface.is_solid());
}
};
print.process();
test_is_solid_infill(0, 0); // should be solid
test_is_solid_infill(0, 79); // should be solid
test_is_solid_infill(0, 78); // should be solid
WHEN("Model is re-sliced with top_shell_layers == 3") {
config.set("top_shell_layers", 3);
print.apply(model, config);
print.process();
THEN("Print object does not have 0 solid bottom layers.") {
test_is_solid_infill(0, 0);
}
AND_THEN("Print object has 3 top solid layers") {
test_is_solid_infill(0, 79);
test_is_solid_infill(0, 78);
test_is_solid_infill(0, 77);
}
}
}
}
// Two copies of one object share a single slice. When a copy that has sliced itself becomes identical to an
// earlier object, it keeps its own layers while that object slices and only then takes the shared layers over.
TEST_CASE("An object that starts sharing another object's slices keeps its own layers until it takes them over", "[Print][Regression]")
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "raft_layers", 1 }, // each object gets support layers of its own
{ "sparse_infill_density", "20%" }, // object_a's override below differs from this
});
// Activates the slicing-pipeline hook installed for the second slice below.
config.set_key_value("slicing_pipeline_plugin", new ConfigOptionStrings({"probe"}));
Print print;
Model model;
init_print({cube(20)}, print, model, config);
ModelObject *object_a = model.objects.front();
// add_object() gives the copy extruder 1, and objects only share slices when their configs match.
object_a->config.set_key_value("extruder", new ConfigOptionInt(1));
ModelObject *object_b = model.add_object(*object_a); // shares object_a's mesh
for (ModelInstance *instance : object_b->instances)
instance->set_offset(instance->get_offset() + Vec3d(40., 0., 0.));
// A per-object override makes the objects differ, so each slices itself.
object_a->config.set_key_value("sparse_infill_density", new ConfigOptionPercent(40));
print.apply(model, config);
print.process();
REQUIRE(print.objects().size() == 2);
// The non-const accessors hand out the layer vectors themselves, which the checks below compare.
PrintObject *print_b = print.get_object(1);
REQUIRE(print_b->model_object()->id() == object_b->id()); // Print slices its own copy of the model
REQUIRE(print_b->get_shared_object() == nullptr);
const LayerPtrs own_layers = print_b->layers();
const SupportLayerPtrs own_support_layers = print_b->support_layers();
REQUIRE(!own_layers.empty());
REQUIRE(!own_support_layers.empty());
// Without the override the objects are identical again: print_a redoes the steps the setting invalidated,
// and print_b shares it.
object_a->config.erase("sparse_infill_density");
print.apply(model, config);
REQUIRE(print.objects().size() == 2);
PrintObject *print_a = print.get_object(0);
// Erasing the override invalidates print_a's posPrepareInfill and the steps after it. Its hook is the first one
// print_a fires, and it runs after print_b starts sharing but before print_b takes the shared layers over.
bool hook_fired = false;
bool shared_while_a_runs = false;
bool kept_layers = false;
bool kept_support_layers = false;
{
Print::set_slicing_pipeline_hook_fn([&](Print &, const PrintObject *object, SlicingPipelineStepPlugin) {
if (object != print_a || hook_fired)
return;
hook_fired = true;
shared_while_a_runs = print_b->get_shared_object() == print_a;
kept_layers = print_b->layers() == own_layers;
kept_support_layers = print_b->support_layers() == own_support_layers;
});
const ScopeGuard reset_hook([] { Print::set_slicing_pipeline_hook_fn(nullptr); });
print.process();
}
REQUIRE(hook_fired);
CHECK(print.objects()[1] == print_b);
CHECK(shared_while_a_runs);
CHECK(kept_layers);
CHECK(kept_support_layers);
CHECK(print_b->get_shared_object() == print_a);
REQUIRE(!print_a->layers().empty());
CHECK(print_b->layers() == print_a->layers());
CHECK(print_b->support_layers() == print_a->support_layers());
}
// A copy that shares the mesh of another object shares its slices only when its height ranges are the same: a height
// range gives the layers in its range other regions, which the other object's layers do not have.
TEST_CASE("Objects share slices only when their height ranges are the same", "[Print][Regression]")
{
struct HeightRange {
t_layer_height_range range;
double density;
};
struct RangesCase {
std::string name;
std::vector<HeightRange> ranges_a; // on the object that slices first
std::vector<HeightRange> ranges_b; // on its copy
bool shared;
};
// The first two differ in the number of ranges, the next two in the heights or the settings of one range.
const RangesCase ranges_case = GENERATE(from_range(std::vector<RangesCase>{
{ "a range on the first object only", { { { 10., 20. }, 40. } }, {}, false },
{ "a range on the copy only", {}, { { { 10., 20. }, 40. } }, false },
{ "same heights, other settings", { { { 10., 20. }, 40. } }, { { { 10., 20. }, 30. } }, false },
{ "other heights, same settings", { { { 10., 20. }, 40. } }, { { { 12., 20. }, 40. } }, false },
{ "the same range on both", { { { 10., 20. }, 40. } }, { { { 10., 20. }, 40. } }, true },
}));
INFO("height ranges: " << ranges_case.name);
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "sparse_infill_density", "20%" },
});
Print print;
Model model;
init_print({cube(20)}, print, model, config);
ModelObject *object_a = model.objects.front();
// add_object() gives the copy extruder 1, and objects only share slices when their configs match.
object_a->config.set_key_value("extruder", new ConfigOptionInt(1));
ModelObject *object_b = model.add_object(*object_a); // shares object_a's mesh
for (ModelInstance *instance : object_b->instances)
instance->set_offset(instance->get_offset() + Vec3d(40., 0., 0.));
const auto add_ranges = [](ModelObject *object, const std::vector<HeightRange> &ranges) {
for (const HeightRange &height_range : ranges) {
DynamicPrintConfig range_config;
// Every layer range must carry a layer_height (see layer_height_profile_from_ranges).
range_config.set_key_value("layer_height", new ConfigOptionFloat(0.2));
range_config.set_key_value("sparse_infill_density", new ConfigOptionPercent(height_range.density));
object->layer_config_ranges[height_range.range].assign_config(std::move(range_config));
}
};
add_ranges(object_a, ranges_case.ranges_a);
add_ranges(object_b, ranges_case.ranges_b);
print.apply(model, config);
print.process();
REQUIRE(print.objects().size() == 2);
const PrintObject *print_a = print.objects()[0];
const PrintObject *print_b = print.objects()[1];
REQUIRE(print_b->model_object()->id() == object_b->id()); // Print slices its own copy of the model
CHECK(print_a->get_shared_object() == nullptr);
CHECK(print_b->get_shared_object() == (ranges_case.shared ? print_a : nullptr));
// The infill density of each object at a height is the one of its own height range there, or the default without
// one. A height range has regions of its own, so the density is read from the region that has the slices there.
const auto density_at = [](const PrintObject *object, double print_z) {
const Layer *layer = object->get_layer_at_printz(print_z, 0.1);
REQUIRE(layer != nullptr);
std::vector<double> densities;
for (const LayerRegion *region : layer->regions())
if (!region->slices.empty())
densities.push_back(region->region().config().sparse_infill_density.value);
REQUIRE(densities.size() == 1);
return densities.front();
};
const auto expected_density = [](const std::vector<HeightRange> &ranges, double print_z) {
for (const HeightRange &height_range : ranges)
if (height_range.range.first < print_z && print_z <= height_range.range.second)
return height_range.density;
return 20.;
};
// 11 mm is in the ranges that start at 10 mm, and not in the one that starts at 12 mm.
for (const double print_z : { 11., 15. }) {
INFO("at " << print_z << " mm");
CHECK(density_at(print_a, print_z) == expected_density(ranges_case.ranges_a, print_z));
CHECK(density_at(print_b, print_z) == expected_density(ranges_case.ranges_b, print_z));
}
}
TEST_CASE("Objects whose center offsets differ do not share slices", "[Print][Regression]")
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
});
// A triangular prism: the center of its bounding box does not turn with the prism unless it is turned by
// a multiple of 90 degrees.
const std::vector<Vec3f> vertices{{0, 0, 0}, {30, 0, 0}, {0, 10, 0}, {0, 0, 10}, {30, 0, 10}, {0, 10, 10}};
const std::vector<Vec3i32> faces{{0, 2, 1}, {3, 4, 5}, {0, 1, 4}, {0, 4, 3}, {1, 2, 5}, {1, 5, 4}, {2, 0, 3}, {2, 3, 5}};
Print print;
Model model;
init_print({TriangleMesh(vertices, faces)}, print, model, config);
ModelObject *object_a = model.objects.front();
// add_object() gives the copy extruder 1, and objects only share slices when their configs match.
object_a->config.set_key_value("extruder", new ConfigOptionInt(1));
const Vec3d origin = object_a->instances.front()->get_offset();
ModelObject *object_b = model.add_object(*object_a); // shares object_a's mesh
// The first instance of object_b is turned, the second one is as straight as object_a's.
ModelInstance *turned = object_b->instances.front();
turned->set_offset(origin + Vec3d(60., 0., 0.));
turned->set_rotation(Vec3d(0., 0., PI / 3.));
ModelInstance *straight = object_b->add_instance();
straight->set_offset(origin + Vec3d(120., 0., 0.));
print.apply(model, config);
print.process();
const PrintObject *print_a = nullptr;
const PrintObject *print_straight = nullptr;
for (const PrintObject *object : print.objects())
if (object->model_object()->id() == object_a->id())
print_a = object;
REQUIRE(print_a != nullptr);
for (const PrintObject *object : print.objects())
if (object->model_object()->id() == object_b->id() && object->trafo().matrix() == print_a->trafo().matrix())
print_straight = object;
REQUIRE(print_straight != nullptr);
// What makes the objects differ, otherwise the checks below would not test anything.
REQUIRE(print_a->center_offset() != print_straight->center_offset());
CHECK(print_a->get_shared_object() == nullptr);
CHECK(print_straight->get_shared_object() == nullptr);
}
// ---------------------------------------------------------------------------
// Print::validate() warning collection
//
// validate() returns its warnings in a vector. The warning paths deliberately
// differ in how many entries they produce; these tests pin down each behaviour:
// * independent checks -> stack (one entry each)
// * motion-ability -> coalesce into one (mutually exclusive, gated)
// * clumping detection -> one independent warning
// * layered clearance -> many collisions concatenated into one entry
// * null warnings pointer -> no-op, no crash, no blocking error
// ---------------------------------------------------------------------------
namespace {
// Build `n` 20mm cubes (spread apart, or stacked at the origin when `overlap`) into
// `model`/`print` and apply `config`, leaving the print ready to validate(). No slicing needed.
void build_cubes(Slic3r::Model& model, Slic3r::Print& print,
DynamicPrintConfig config, int n, bool overlap)
{
config.set_key_value("layer_change_gcode", new ConfigOptionString("G92 E0\n")); // validate() relative-E reset
for (int i = 0; i < n; ++i) {
ModelObject* object = model.add_object();
object->add_volume(cube(20));
ModelInstance* inst = object->add_instance();
inst->set_offset(Vec3d(overlap ? 0.0 : i * 60.0, 0.0, 0.0));
}
for (ModelObject* mo : model.objects) {
mo->ensure_on_bed();
print.auto_assign_extruders(mo);
}
print.apply(model, config);
}
// Build cubes and run validate(), collecting warnings; returns the blocking error.
StringObjectException validate_cubes(const DynamicPrintConfig& config,
std::vector<StringObjectException>& warnings,
int n = 1, bool overlap = false)
{
Slic3r::Model model;
Slic3r::Print print;
build_cubes(model, print, config, n, overlap);
return print.validate(&warnings);
}
size_t count_opt_key(const std::vector<StringObjectException>& warnings, const std::string& key)
{
return std::count_if(warnings.begin(), warnings.end(),
[&](const StringObjectException& w) { return w.opt_key == key; });
}
DynamicPrintConfig dual_extruder_exclusion_config(
BedExcludeVolumeMode mode,
const std::vector<std::string> &per_extruder,
const std::vector<int> &filament_map = {1})
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_num_extruders(2);
config.set_key_value("nozzle_diameter", new ConfigOptionFloats{0.4, 0.4});
config.set_key_value("extruder_offset", new ConfigOptionPoints{Vec2d::Zero(), Vec2d(20.0, 0.0)});
config.set_key_value("extruder_printable_height", new ConfigOptionFloatsNullable{256.0, 256.0});
config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum<BedExcludeVolumeMode>(mode));
config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings(per_extruder));
config.set_key_value("filament_map_mode", new ConfigOptionEnum<FilamentMapMode>(fmmManual));
config.set_key_value("filament_map", new ConfigOptionInts(filament_map));
return config;
}
StringObjectException validate_multimaterial_cube(const DynamicPrintConfig &config)
{
Model model;
ModelObject *object = model.add_object();
ModelVolume *first = object->add_volume(cube(20));
ModelVolume *second = object->add_volume(cube(20));
first->config.set("extruder", 1);
second->config.set("extruder", 2);
object->add_instance();
object->ensure_on_bed();
Print print;
print.apply(model, config);
return print.validate();
}
// Make `default_acceleration` exceed the machine's extruding-acceleration limit.
void trigger_acceleration_warning(DynamicPrintConfig& c)
{
c.set_key_value("machine_max_acceleration_extruding", new ConfigOptionFloats{ 100. });
c.set_key_value("default_acceleration", new ConfigOptionFloatsNullable{ 100000. });
}
// Make `default_jerk` exceed the machine's jerk limit (junction deviation off so
// the jerk check is not skipped).
void trigger_jerk_warning(DynamicPrintConfig& c)
{
c.set_key_value("machine_max_junction_deviation", new ConfigOptionFloats{ 0. });
c.set_key_value("machine_max_jerk_x", new ConfigOptionFloats{ 1. });
c.set_key_value("machine_max_jerk_y", new ConfigOptionFloats{ 1. });
c.set_key_value("default_jerk", new ConfigOptionFloatsNullable{ 9999. });
}
// Precise outer wall is ignored unless the wall sequence is inner-outer.
void trigger_precise_wall_warning(DynamicPrintConfig& c)
{
c.set_key_value("precise_outer_wall", new ConfigOptionBool(true));
c.set_key_value("wall_sequence", new ConfigOptionEnum<WallSequence>(WallSequence::OuterInner));
}
} // namespace
TEST_CASE("Print validation applies individual exclusion volumes to the mapped physical extruder", "[Print][ExclusionVolume][MultiNozzle]")
{
const std::string colliding = "0..256;-100x-100,300x-100,300x300,-100x300";
std::vector<StringObjectException> warnings;
SECTION("mapped colliding extruder is rejected") {
const DynamicPrintConfig config = dual_extruder_exclusion_config(
BedExcludeVolumeMode::PerExtruder, {colliding, ""}, {1});
const StringObjectException error = validate_cubes(config, warnings);
CHECK(error.string.find("extruder 1") != std::string::npos);
}
SECTION("mapped clear extruder is accepted") {
const DynamicPrintConfig config = dual_extruder_exclusion_config(
BedExcludeVolumeMode::PerExtruder, {colliding, ""}, {2});
const StringObjectException error = validate_cubes(config, warnings);
CHECK(error.string.empty());
}
SECTION("an unrelated nozzle exclusion does not reject the object") {
const DynamicPrintConfig config = dual_extruder_exclusion_config(
BedExcludeVolumeMode::PerExtruder, {"", colliding}, {1});
const StringObjectException error = validate_cubes(config, warnings);
CHECK(error.string.empty());
}
}
TEST_CASE("Print validation applies shared exclusions and ignores volumes above the object", "[Print][ExclusionVolume]")
{
std::vector<StringObjectException> warnings;
SECTION("shared volume intersects") {
DynamicPrintConfig config = dual_extruder_exclusion_config(BedExcludeVolumeMode::Shared, {"", ""}, {2});
config.set_key_value("bed_exclude_volumes", new ConfigOptionString("0..30;-100x-100,300x-100,300x300,-100x300"));
const StringObjectException error = validate_cubes(config, warnings);
CHECK(error.string.find("extruder 2") != std::string::npos);
}
SECTION("elevated shared volume clears a 20mm cube") {
DynamicPrintConfig config = dual_extruder_exclusion_config(BedExcludeVolumeMode::Shared, {"", ""}, {1});
config.set_key_value("bed_exclude_volumes", new ConfigOptionString("30..50;-100x-100,300x-100,300x300,-100x300"));
const StringObjectException error = validate_cubes(config, warnings);
CHECK(error.string.empty());
}
}
TEST_CASE("Legacy excluded areas retain object placement validation", "[Print][ExclusionVolume][Compatibility]")
{
DynamicPrintConfig config = dual_extruder_exclusion_config(
BedExcludeVolumeMode::Shared, {"", ""}, {1});
config.set_deserialize_strict("bed_exclude_area", "-100x-100,300x-100,300x300,-100x300");
std::vector<StringObjectException> warnings;
const StringObjectException error = validate_cubes(config, warnings);
CHECK_FALSE(error.string.empty());
}
TEST_CASE("Print validation checks every nozzle used by a multimaterial object", "[Print][ExclusionVolume][MultiNozzle]")
{
const std::string colliding = "0..256;-100x-100,300x-100,300x300,-100x300";
const DynamicPrintConfig config = dual_extruder_exclusion_config(
BedExcludeVolumeMode::PerExtruder, {"", colliding}, {1, 2});
const StringObjectException error = validate_multimaterial_cube(config);
CHECK(error.string.find("extruder 2") != std::string::npos);
}
// ---------------------------------------------------------------------------
// {first_object_name} filename placeholder
// ---------------------------------------------------------------------------
namespace {
// Add a printable 20mm cube named `name` to `model`; returns it so the caller can tweak it.
ModelObject* add_named_cube(Model& model, const std::string& name)
{
ModelObject* obj = model.add_object();
obj->name = name;
obj->add_volume(make_cube(20.0, 20.0, 20.0));
obj->add_instance();
obj->ensure_on_bed();
return obj;
}
// Resolve `format` to an output file name for a print of `model`. `filename_base`, when set,
// is the saved-project name passed to output_filename().
std::string resolved_output_name(Model& model, const std::string& format, const std::string& filename_base = {})
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_key_value("filename_format", new ConfigOptionString(format));
Print print;
for (ModelObject* obj : model.objects)
print.auto_assign_extruders(obj);
print.apply(model, config);
return print.output_filename(filename_base);
}
struct ScopedLifecycleHook
{
explicit ScopedLifecycleHook(LifecycleHookFn hook) { set_lifecycle_hook_fn(std::move(hook)); }
~ScopedLifecycleHook() { set_lifecycle_hook_fn(nullptr); }
};
} // namespace
TEST_CASE("Slicing lifecycle events identify the model", "[Print][LifecycleEvents]")
{
struct ObservedEvent {
LifecycleEvent event;
std::string id;
std::string name;
};
std::vector<ObservedEvent> events;
ScopedLifecycleHook hook([&](LifecycleEvent event, const LifecycleEventContext& ctx) {
events.push_back({ event, ctx.id, ctx.name });
});
Print print;
Model model;
ModelInfo info;
info.model_name = "Lifecycle test model";
model.model_info = std::make_shared<ModelInfo>(std::move(info));
init_print({cube(20)}, print, model);
print.process();
ScopedTemporaryFile temp(".gcode");
print.export_gcode(temp.string(), nullptr, nullptr);
GCodeProcessorResult result;
print.export_gcode_from_previous_file(temp.string(), &result);
const std::string expected_id = std::to_string(print.model().id().id);
const std::vector<LifecycleEvent> expected_events = {
LifecycleEvent::SliceStarted,
LifecycleEvent::SliceGeometryFinished,
LifecycleEvent::GCodeExportStarted,
LifecycleEvent::GCodeExportFinished,
LifecycleEvent::GCodeExportStarted,
LifecycleEvent::GCodeExportFinished,
};
REQUIRE(events.size() == expected_events.size());
for (size_t i = 0; i < expected_events.size(); ++i) {
CHECK(events[i].event == expected_events[i]);
CHECK(events[i].id == expected_id);
CHECK(events[i].name == "Lifecycle test model");
}
}
TEST_CASE("Slicing lifecycle event name is empty without model metadata", "[Print][LifecycleEvents]")
{
std::string event_id;
std::string event_name = "unset";
ScopedLifecycleHook hook([&](LifecycleEvent event, const LifecycleEventContext& ctx) {
if (event == LifecycleEvent::SliceStarted) {
event_id = ctx.id;
event_name = ctx.name;
}
});
Print print;
Model model;
init_print({cube(20)}, print, model);
print.process();
CHECK(event_id == std::to_string(print.model().id().id));
CHECK(event_name.empty());
}
TEST_CASE("Output filenames with numeric statistics fail before slicing finishes", "[Print][Regression]")
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_key_value("filename_format", new ConfigOptionString("{int(total_weight*10) / 10.0}"));
Print print;
Model model;
init_print({cube(20)}, print, model, config);
CHECK_THROWS_AS(print.output_filename(), PlaceholderParserError);
}
TEST_CASE("Print: {first_object_name} names the first printable object on the plate", "[Print]")
{
Model model;
SECTION("uses the object's name") {
add_named_cube(model, "WidgetPart");
CHECK(resolved_output_name(model, "{first_object_name}") == "WidgetPart.gcode");
}
SECTION("picks the first when several objects are printable") {
add_named_cube(model, "FirstPart");
add_named_cube(model, "SecondPart");
CHECK(resolved_output_name(model, "{first_object_name}") == "FirstPart.gcode");
}
SECTION("skips objects outside the print volume (e.g. on another plate)") {
// First in model order, but not on the current plate, so is_printable() is false.
add_named_cube(model, "OtherPlatePart")->instances.front()->print_volume_state = ModelInstancePVS_Fully_Outside;
add_named_cube(model, "OnPlatePart");
CHECK(resolved_output_name(model, "{first_object_name}") == "OnPlatePart.gcode");
}
SECTION("is empty when the object has no name") {
add_named_cube(model, "");
CHECK(resolved_output_name(model, "part_{first_object_name}") == "part_.gcode");
}
}
TEST_CASE("Print: {first_object_name} is not replaced by the saved-project file name", "[Print]")
{
// Passing a saved-project file name as the filename_base must not change {first_object_name}.
Model model;
add_named_cube(model, "WidgetPart");
CHECK(resolved_output_name(model, "{first_object_name}", "SavedProject") == "WidgetPart.gcode");
}
TEST_CASE("{printing_filament_types} lists the filament types really printed", "[Print]")
{
// Two filaments of different types. The start G-code uses the placeholder too: it has to
// resolve there as well as in the file name.
DynamicPrintConfig config = multifilament_config(2, {
{ "filament_type", "ABS;PLA" },
{ "enable_prime_tower", 0 },
{ "filename_format", "{printing_filament_types}-{filament_type[initial_tool]}" },
{ "machine_start_gcode", "; printing types: {printing_filament_types}" },
});
SECTION("only the filament the object is printed with, not filament 1") {
const std::vector<std::vector<ConfigBase::SetDeserializeItem>> overrides{ { { "extruder", 2 } } };
Print print;
Model model;
init_print({ cube(20) }, print, model, config, &overrides);
const std::string gcode = Slic3r::Test::gcode(print);
CHECK(gcode.find("; printing types: PLA\n") != std::string::npos);
CHECK(print.output_filename() == "PLA-PLA.gcode");
}
SECTION("every type printed, joined with an underscore") {
const std::vector<std::vector<ConfigBase::SetDeserializeItem>> overrides{ { { "extruder", 1 } }, { { "extruder", 2 } } };
Print print;
Model model;
init_print({ cube(20), cube(20) }, print, model, config, &overrides);
const std::string gcode = Slic3r::Test::gcode(print);
CHECK(gcode.find("; printing types: ABS_PLA\n") != std::string::npos);
CHECK(print.output_filename() == "ABS_PLA-ABS.gcode");
}
}
TEST_CASE("Print::validate stacks independent warnings", "[Print][validate]")
{
// Two unrelated checks (region precise-wall + machine acceleration) must each
// contribute their own entry.
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
trigger_precise_wall_warning(config);
trigger_acceleration_warning(config);
std::vector<StringObjectException> warnings;
StringObjectException err = validate_cubes(config, warnings);
CHECK(err.string.empty());
CHECK(warnings.size() >= 2);
CHECK(count_opt_key(warnings, "precise_outer_wall") == 1); // jump-to key is preserved
for (const auto& w : warnings)
CHECK(w.is_warning); // every collected entry is a warning
}
TEST_CASE("Print::validate coalesces motion-ability warnings into one", "[Print][validate]")
{
// The jerk/junction/acceleration checks are mutually exclusive (gated on a shared
// key), so adding a second motion trigger must NOT add a second warning.
DynamicPrintConfig accel_only = DynamicPrintConfig::full_print_config();
trigger_acceleration_warning(accel_only);
std::vector<StringObjectException> w_accel;
CHECK(validate_cubes(accel_only, w_accel).string.empty());
DynamicPrintConfig accel_and_jerk = DynamicPrintConfig::full_print_config();
trigger_acceleration_warning(accel_and_jerk);
trigger_jerk_warning(accel_and_jerk);
std::vector<StringObjectException> w_both;
CHECK(validate_cubes(accel_and_jerk, w_both).string.empty());
CHECK(w_accel.size() >= 1);
CHECK(w_both.size() == w_accel.size()); // the extra motion trigger collapses into the same warning
}
TEST_CASE("Print::validate reports the clumping-detection warning", "[Print][validate]")
{
// A distinct single-shot path: clumping/wrapping detection without a prime tower warns
// (and carries the enable_prime_tower jump-to key). enable_prime_tower must be off, as
// the warning lives in the no-prime-tower branch.
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_key_value("enable_prime_tower", new ConfigOptionBool(false));
config.set_key_value("enable_wrapping_detection", new ConfigOptionBool(true));
std::vector<StringObjectException> warnings;
StringObjectException err = validate_cubes(config, warnings);
CHECK(err.string.empty());
CHECK(count_opt_key(warnings, "enable_prime_tower") == 1);
}
TEST_CASE("Print::validate concatenates layered-clearance collisions into one warning", "[Print][validate]")
{
// In by-layer mode, layered_print_cleareance_valid folds every too-close pair into a
// single warning entry (newline-joined), unlike the per-check stacking above. Isolate
// that entry by type so unrelated default-config warnings don't affect the assertion.
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
std::vector<StringObjectException> warnings;
StringObjectException err = validate_cubes(config, warnings, /*n=*/3, /*overlap=*/true);
CHECK(err.string.empty());
auto is_layered = [](const StringObjectException& w) {
return w.type == STRING_EXCEPT_OBJECT_COLLISION_IN_LAYER_PRINT; };
REQUIRE(std::count_if(warnings.begin(), warnings.end(), is_layered) == 1); // 3 objects, 2 collisions, 1 entry
auto it = std::find_if(warnings.begin(), warnings.end(), is_layered);
CHECK(it->string.find('\n') != std::string::npos); // the collisions were concatenated
}
TEST_CASE("Print::validate tolerates a null warnings pointer", "[Print][validate]")
{
// Callers may pass no warnings sink: a warning-producing config must not crash
// and must still return without a blocking error.
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
trigger_precise_wall_warning(config);
trigger_acceleration_warning(config);
Slic3r::Model model;
Slic3r::Print print;
build_cubes(model, print, config, /*n=*/1, /*overlap=*/false);
StringObjectException err = print.validate(); // warnings == nullptr
CHECK(err.string.empty());
}
TEST_CASE("Print::validate refuses a used filament with a flow ratio of 0", "[Print][validate][Regression]")
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_key_value("filament_flow_ratio", new ConfigOptionFloatsNullable{ 0. });
std::vector<StringObjectException> warnings;
StringObjectException err = validate_cubes(config, warnings);
CHECK_FALSE(err.string.empty());
CHECK_FALSE(err.is_warning);
CHECK(err.opt_key == "filament_flow_ratio");
}
TEST_CASE("Print::validate ignores a flow ratio of 0 on an unused filament", "[Print][validate]")
{
// The cube prints with filament 1, so filament 2's ratio is never used.
DynamicPrintConfig config = multifilament_config(2, { { "filament_self_index", "1,2" } });
config.set_key_value("filament_flow_ratio", new ConfigOptionFloatsNullable{ 1., 0. });
std::vector<StringObjectException> warnings;
StringObjectException err = validate_cubes(config, warnings);
CHECK(err.string.empty());
}
TEST_CASE("Purge tower selection keeps ordinary printers on the classic path", "[Print][PurgeTower][Regression]")
{
DynamicPrintConfig config = multifilament_config(2, {
{ "belt_printer", 0 },
{ "enable_prime_tower", 1 },
{ "enable_belt_purge_tower", 1 }
});
config.set_key_value("timelapse_type", new ConfigOptionEnum<TimelapseType>(TimelapseType::tlSmooth));
Model model;
Print print;
build_cubes(model, print, config, /*n=*/1, /*overlap=*/false);
CHECK(print.has_wipe_tower());
CHECK_FALSE(print.has_belt_purge_tower());
}
TEST_CASE("Belt purge planning requires its managed purge object", "[Print][PurgeTower][Regression]")
{
DynamicPrintConfig config = multifilament_config(2, {
{ "belt_printer", 1 },
{ "enable_belt_purge_tower", 1 }
});
Model model;
Print print;
build_cubes(model, print, config, /*n=*/1, /*overlap=*/false);
CHECK_FALSE(print.has_belt_purge_tower());
model.objects.front()->config.set_key_value("belt_purge_tower_object", new ConfigOptionBool(true));
print.apply(model, config);
CHECK(print.has_belt_purge_tower());
CHECK_FALSE(print.has_wipe_tower());
}
// The GUI creates the purge tower object; a project sliced without one (the CLI) must say
// that its filament changes go unpurged.
TEST_CASE("Belt purge tower enabled without a tower object warns", "[Print][PurgeTower][belt]")
{
DynamicPrintConfig config = multifilament_config(2, {
{ "belt_printer", 1 },
{ "enable_belt_purge_tower", 1 },
{ "layer_change_gcode", "G92 E0\n" }
});
auto purge_warnings = [](Print &print) {
std::vector<StringObjectException> warnings;
print.validate(&warnings);
return std::count_if(warnings.begin(), warnings.end(), [](const StringObjectException &w) {
return w.opt_key == "enable_belt_purge_tower";
});
};
Model model;
Print print;
build_cubes(model, print, config, /*n=*/2, /*overlap=*/false);
model.objects[1]->config.set_key_value("extruder", new ConfigOptionInt(2));
print.apply(model, config);
REQUIRE(print.extruders().size() > 1);
CHECK(purge_warnings(print) == 1);
model.objects.front()->config.set_key_value("belt_purge_tower_object", new ConfigOptionBool(true));
print.apply(model, config);
CHECK(purge_warnings(print) == 0);
}
TEST_CASE("Belt purge rejects multiple managed purge objects", "[Print][PurgeTower][Regression]")
{
DynamicPrintConfig config = multifilament_config(2, {
{ "belt_printer", 1 },
{ "enable_belt_purge_tower", 1 }
});
Model model;
Print print;
build_cubes(model, print, config, /*n=*/2, /*overlap=*/false);
for (ModelObject *object : model.objects)
object->config.set_key_value("belt_purge_tower_object", new ConfigOptionBool(true));
print.apply(model, config);
CHECK_FALSE(print.validate().string.empty());
}
TEST_CASE("A default slice emits perimeter, infill, and skirt", "[Print]")
{
const std::string gcode = slice({ cube(20) }, {
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "z_hop", 0 } // keep recorded Z at the printed height
});
CHECK(role_passes(gcode, "perimeter") > 0);
CHECK(role_passes(gcode, "infill") > 0);
CHECK(role_passes(gcode, "skirt") > 0);
CHECK_THAT(max_z(gcode), Catch::Matchers::WithinAbs(20.0, 1e-4));
}
// The G-code carries a config-comment block describing the resolved settings. The
// per-region width lines are always present; the support and first-layer lines appear
// only when those features are configured.
TEST_CASE("G-code lists the resolved extrusion-width settings", "[Print]")
{
const std::string gcode = slice({ cube(20) }, { { "initial_layer_line_width", 0 } });
CHECK(gcode.find("; external perimeters extrusion width") != std::string::npos);
CHECK(gcode.find("; perimeters extrusion width") != std::string::npos);
CHECK(gcode.find("; infill extrusion width") != std::string::npos);
CHECK(gcode.find("; solid infill extrusion width") != std::string::npos);
CHECK(gcode.find("; top infill extrusion width") != std::string::npos);
CHECK(gcode.find("; support material extrusion width") == std::string::npos);
CHECK(gcode.find("; first layer extrusion width") == std::string::npos);
CHECK(gcode.find("; layer_height") != std::string::npos);
CHECK(gcode.find("; sparse_infill_density") != std::string::npos);
const std::string with_support = slice({ cube(20) }, {
{ "initial_layer_line_width", 0 }, { "enable_support", true }, { "raft_layers", 3 },
});
CHECK(with_support.find("; support material extrusion width") != std::string::npos);
const std::string with_first_layer = slice({ cube(20) }, { { "initial_layer_line_width", "0.5" } });
CHECK(with_first_layer.find("; first layer extrusion width") != std::string::npos);
}
// gcode_skip_config_block suppresses the resolved-settings block while leaving the
// header and executable blocks intact.
TEST_CASE("gcode_skip_config_block omits the resolved-settings comment block", "[Print]")
{
const std::string gcode = slice({ cube(20) }, {
{ "gcode_skip_config_block", true },
{ "gcode_comments", true },
});
CHECK(gcode.find("; CONFIG_BLOCK_START") == std::string::npos);
CHECK(gcode.find("; CONFIG_BLOCK_END") == std::string::npos);
CHECK(gcode.find("; layer_height =") == std::string::npos);
CHECK(gcode.find("; fill_density =") == std::string::npos);
CHECK(gcode.find("; HEADER_BLOCK_START") != std::string::npos);
CHECK(gcode.find("; EXECUTABLE_BLOCK_START") != std::string::npos);
}
// Some firmwares only scan the last N lines of the file for "estimated printing time", so it
// must stay close to EOF regardless of the resolved-settings config block's size.
TEST_CASE("The estimated printing time comment stays near the end of the file", "[Print]")
{
const std::string gcode = slice({ cube(20) }, {});
const size_t config_block_end = gcode.find("; CONFIG_BLOCK_END");
const size_t filament_stats = gcode.find("; filament used [mm]");
const size_t time_comment = gcode.find("estimated printing time");
REQUIRE(config_block_end != std::string::npos);
REQUIRE(filament_stats != std::string::npos);
REQUIRE(time_comment != std::string::npos);
CHECK(filament_stats > config_block_end);
CHECK(time_comment > filament_stats);
const size_t line_start = gcode.rfind('\n', time_comment) + 1;
const size_t trailing_lines = std::count(gcode.begin() + line_start, gcode.end(), '\n');
CHECK(trailing_lines <= 5);
}
// The comment carries the first layer's time, not the start G-code's time. A 50 mm move at
// F60 (1 mm/s) makes the start block about 50 s, so the two times format to different
// strings and the check below tells them apart.
TEST_CASE("The estimated first layer time comment reports the first layer", "[Print][Regression]")
{
Print print;
Model model;
init_print({ cube(20) }, print, model, { { "machine_start_gcode", "G1 X50 Y50 Z0.2 F60" } });
GCodeProcessorResult result;
const std::string gcode = Test::gcode(print, &result);
const float first_layer_time = result.initial_layer_time;
const float start_gcode_time = result.print_statistics.modes[static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Normal)].prepare_time;
REQUIRE(get_time_dhms(first_layer_time) != get_time_dhms(start_gcode_time));
CHECK(gcode.find(std::string("; estimated first layer printing time (normal mode) = ") + get_time_dhms(first_layer_time)) != std::string::npos);
}
// Custom G-code templates substitute placeholders during export.
TEST_CASE("Custom G-code placeholders are substituted", "[Print]")
{
// [current_extruder] in the start G-code.
CHECK(slice({ cube(20) }, { { "machine_start_gcode", "; Extruder [current_extruder]" } })
.find("; Extruder 0") != std::string::npos);
// [layer_num] / [layer_z] in the end G-code (a 20mm cube at 0.1mm is 200 layers).
const std::string end_gcode = slice({ cube(20) }, {
{ "machine_end_gcode", "; Layer_num [layer_num]\n; Layer_z [layer_z]" },
{ "layer_height", 0.1 },
{ "initial_layer_print_height", 0.1 },
});
CHECK(end_gcode.find("; Layer_num 199") != std::string::npos);
CHECK(end_gcode.find("; Layer_z 20") != std::string::npos);
// printing_by_object_gcode is emitted between sequentially printed objects.
CHECK(slice_two_cubes_arranged({
{ "print_sequence", "by object" },
{ "printing_by_object_gcode", "; between-object-gcode" },
})
.find("; between-object-gcode") != std::string::npos);
// [layer_num] keeps counting across sequentially printed objects (199 then 399), and [max_layer_z]
// stays at the first object's 20mm top while the second object starts.
const std::string per_layer = slice_two_cubes_arranged({
{ "print_sequence", "by object" },
{ "layer_change_gcode", ";Layer:[layer_num] ([layer_z] mm) max [max_layer_z]" },
{ "layer_height", 0.1 },
{ "initial_layer_print_height", 0.1 },
});
CHECK(per_layer.find(";Layer:199 ") != std::string::npos);
CHECK(per_layer.find(";Layer:399 ") != std::string::npos);
CHECK(per_layer.find(";Layer:200 (0.1 mm) max 20\n") != std::string::npos);
}
// A finished export is reused, so a renamed plate needs the export step invalidated.
TEST_CASE("Plate name reaches the G-code once G-code export is invalidated", "[Print]")
{
Print print;
Model model;
init_print({ cube(20) }, print, model, { { "machine_start_gcode", "; Plate {plate_name}" } });
print.set_status_silent();
ScopedTemporaryFile output(".gcode");
const auto export_and_read = [&print, &output]() {
print.process();
print.export_gcode(output.string(), nullptr, nullptr);
std::ifstream in(output.string(), std::ios::binary);
return std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
};
print.set_plate_name("First");
CHECK(export_and_read().find("; Plate First") != std::string::npos);
REQUIRE(print.finished());
// Renaming alone keeps the old export.
print.set_plate_name("Second");
CHECK(print.finished());
CHECK(export_and_read().find("; Plate First") != std::string::npos);
// Invalidating the export step re-emits the name without re-slicing.
print.set_gcode_file_invalidated();
CHECK_FALSE(print.finished());
CHECK(print.objects().front()->is_step_done(posSlice));
const std::string regenerated = export_and_read();
CHECK(regenerated.find("; Plate Second") != std::string::npos);
CHECK(regenerated.find("; Plate First") == std::string::npos);
}
// The background thread drops its own export when an in-place edit of the file fails. The print's cancel
// callback stops that thread and waits for it, so the invalidation must not call it.
TEST_CASE("An export the background thread invalidates is written again without re-slicing", "[Print]")
{
// Declared before the print, whose destructor calls the cancel callback too.
bool cancel_called = false;
Print print;
Model model;
init_print({ cube(20) }, print, model);
print.set_status_silent();
print.set_cancel_callback([&cancel_called]() { cancel_called = true; });
ScopedTemporaryFile output(".gcode");
print.process();
print.export_gcode(output.string(), nullptr, nullptr);
REQUIRE(print.finished());
// What a post-processing script that failed half way leaves in the file.
std::ofstream(output.string(), std::ios::app) << "; half edited\n";
print.invalidate_gcode_export_from_worker();
CHECK_FALSE(print.finished());
CHECK_FALSE(cancel_called);
CHECK(print.objects().front()->is_step_done(posSlice));
print.process();
print.export_gcode(output.string(), nullptr, nullptr);
CHECK(print.finished());
std::ifstream in(output.string(), std::ios::binary);
const std::string gcode((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
CHECK(gcode.find("; half edited") == std::string::npos);
}
// The layer change G-code runs before its layer prints, so the layer mass it gets is the previous layer's.
TEST_CASE("Layer change G-code gets the previous layer's mass under both placeholder names", "[Print]")
{
const std::string gcode = slice({ cube(20) }, {
{ "filament_density", 1.24 },
// curr_layer_mass is Bambu Studio's name for previous_layer_mass.
{ "layer_change_gcode", ";Mass:[layer_num] {if previous_layer_mass > 0}printed{else}none{endif} "
"{if previous_layer_mass == curr_layer_mass}same{else}different{endif}" },
});
// Nothing is printed before the first layer change; layer 0 is printed before the second.
CHECK(gcode.find(";Mass:0 none same\n") != std::string::npos);
CHECK(gcode.find(";Mass:1 printed same\n") != std::string::npos);
}
TEST_CASE("Start G-code gets the wipe tower wait position under both placeholder names", "[Print]")
{
// wipe_tower_center_pos_* are Bambu Studio's names for wipe_tower_wait_pos_*.
const std::string gcode = slice({ cube(20) }, {
{ "machine_start_gcode", "; Wait {if wipe_tower_wait_pos_valid}set{else}unset{endif} "
"{if wipe_tower_center_pos_valid}set{else}unset{endif} "
"[wipe_tower_wait_pos_x],[wipe_tower_wait_pos_y] [wipe_tower_center_pos_x],[wipe_tower_center_pos_y]" },
});
// A single-filament print has no wipe tower, so neither name has a position.
CHECK(gcode.find("; Wait unset unset 0,0 0,0\n") != std::string::npos);
}
TEST_CASE("Timelapse G-code gets the snapshot placeholders on bed slingers and other printers", "[Print]")
{
const std::string structure = GENERATE(as<std::string>{}, "i3", "corexy");
CAPTURE(structure);
std::string gcode;
REQUIRE_NOTHROW(gcode = slice({ cube(20) }, {
{ "printer_structure", structure },
{ "printable_area", "0x0,200x0,200x200,0x200" },
{ "bed_exclude_area", "0x0" },
{ "extruder_clearance_radius", 40 },
{ "timelapse_type", "0" },
{ "time_lapse_gcode", "; Timelapse {if has_timelapse_safe_pos}safe{else}none{endif} [timelapse_pos_x] "
"[clear_to_x0] [curr_physical_extruder_id]" },
}));
CHECK(gcode.find("\n; Timelapse safe ") != std::string::npos);
}
TEST_CASE("The first filament start G-code on Bambu Lab printers gets the layer placeholders", "[Print]")
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_key_value("filament_start_gcode", new ConfigOptionStrings({ "; Start [layer_num] [layer_z] [max_layer_z]" }));
Print print;
Model model;
init_print({ cube(20) }, print, model, config);
print.is_BBL_printer() = true;
std::string gcode;
REQUIRE_NOTHROW(gcode = Slic3r::Test::gcode(print));
// The first filament start G-code runs before the first layer.
CHECK(gcode.find("\n; Start -1 ") != std::string::npos);
}
// The final print statistics are known only after the whole G-code is generated, yet every custom G-code,
// the file header included, gets the same values as filename_format.
TEST_CASE("Print statistics in custom G-code match the final print statistics", "[Print][Regression]")
{
const std::string gcode_key = GENERATE(as<std::string>{}, "file_start_gcode", "machine_start_gcode", "machine_end_gcode");
// Bambu printers use another tag table and G-code layout.
const bool is_bbl = GENERATE(false, true);
CAPTURE(gcode_key, is_bbl);
const std::vector<std::string> number_keys = { "total_weight", "used_filament", "total_cost", "total_wipe_tower_cost",
"total_wipe_tower_filament" };
const std::vector<std::string> time_keys = { "print_time", "normal_print_time", "silent_print_time" };
std::string templ;
for (const std::vector<std::string> *keys : { &number_keys, &time_keys })
for (const std::string &key : *keys)
templ += "; stat " + key + "={" + key + "}\n";
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ gcode_key, templ },
{ "filament_density", "1.25" },
{ "filament_cost", "20" },
{ "time_cost", "2" },
});
Print print;
Model model;
init_print({ cube(20) }, print, model, config);
print.is_BBL_printer() = is_bbl;
std::string gcode;
REQUIRE_NOTHROW(gcode = Slic3r::Test::gcode(print));
// Match whole lines only: the config block repeats the template on a single line, and Bambu printers
// write that block before the start G-code.
const std::string lines = "\n" + gcode;
const auto value_of = [&lines](const std::string &key) {
const std::string prefix = "\n; stat " + key + "=";
const size_t start = lines.find(prefix);
REQUIRE(start != std::string::npos);
const size_t begin = start + prefix.size();
return lines.substr(begin, lines.find('\n', begin) - begin);
};
// The same statistics filename_format is expanded with.
DynamicConfig stats = print.print_statistics().config();
// A 20mm cube with filament_density 1.25 weighs something, unlike the running extruded_weight_total in the header.
CHECK(stats.opt_float("total_weight") > 0.);
for (const std::string &key : number_keys) {
CAPTURE(key);
const std::string value = value_of(key);
REQUIRE(value.find('@') == std::string::npos);
// Written with two decimals.
CHECK_THAT(std::stod(value), Catch::Matchers::WithinAbs(stats.opt_float(key), 0.006));
}
for (const std::string &key : time_keys) {
CAPTURE(key);
CHECK(value_of(key) == stats.opt_string(key));
}
}
TEST_CASE("Print statistics in custom G-code cannot be used in a calculation", "[Print]")
{
const std::string key = GENERATE(as<std::string>{}, "total_weight", "used_filament", "total_cost", "print_time", "normal_print_time",
"silent_print_time", "total_wipe_tower_cost", "total_wipe_tower_filament", "print_time_total_sec",
"print_time_day", "print_time_hour", "print_time_minute", "print_time_sec", "used_filament_length");
CAPTURE(key);
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({ { "file_start_gcode", "; {" + key + " + 1}\n" } });
Print print;
Model model;
init_print({ cube(20) }, print, model, config);
CHECK_THROWS_WITH(Slic3r::Test::gcode(print), Catch::Matchers::ContainsSubstring("known only after the G-code is generated"));
}
TEST_CASE("export_gcode writes G-code without a result pointer", "[Print][export_gcode]")
{
Print print;
Model model;
Slic3r::Test::init_print({cube(20)}, print, model);
print.process();
const bool bbl_printer = GENERATE(false, true);
CAPTURE(bbl_printer);
print.is_BBL_printer() = bbl_printer;
ScopedTemporaryFile temp(".gcode");
REQUIRE_NOTHROW(print.export_gcode(temp.string(), nullptr, nullptr));
std::ifstream in(temp.string());
const std::string gcode((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
REQUIRE_FALSE(gcode.empty());
}
TEST_CASE("Exporting a sliced print again gives the same G-code", "[Print][export_gcode][Regression]")
{
const int instances = GENERATE(1, 3);
// Whether chaining reverses support or infill.
const bool support = GENERATE(false, true);
CAPTURE(instances, support);
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
TestMesh mesh = TestMesh::ipadstand;
if (support) {
mesh = TestMesh::overhang;
config.set_deserialize_strict({{"enable_support", true}, {"support_interface_pattern", "concentric"}});
} else {
config.set_deserialize_strict({{"sparse_infill_pattern", "gyroid"}});
}
Print print;
Model model;
Slic3r::Test::init_print({Slic3r::Test::mesh(mesh)}, print, model, config, nullptr, true, instances);
const auto export_without_timestamp = [&print]() {
std::string gcode = Slic3r::Test::gcode(print);
const size_t line = gcode.find("; generated by ");
REQUIRE(line != std::string::npos);
gcode.erase(line, gcode.find('\n', line) - line);
return gcode;
};
const std::string first = export_without_timestamp();
const std::string second = export_without_timestamp();
// Shows the first differing line on failure.
const size_t diff = std::mismatch(first.begin(), first.end(), second.begin(), second.end()).first - first.begin();
const size_t line_start = diff == 0 ? 0 : first.rfind('\n', diff - 1) + 1;
INFO("first export: " << first.substr(line_start, first.find('\n', diff) - line_start));
INFO("second export: " << second.substr(line_start, second.find('\n', diff) - line_start));
CHECK(diff == first.size());
CHECK(first.size() == second.size());
}
// Peak Z of the first object printed in by-object G-code: the highest extrusion before Z drops back
// to the first layer, which with by-object printing only happens at an object change.
static double first_object_peak_z(const std::string &gcode)
{
double first_object_peak_z = 0.0;
double running_peak = 0.0;
GCodeReader reader;
reader.parse_buffer(gcode, [&] (GCodeReader& self, const GCodeReader::GCodeLine& line) {
if (first_object_peak_z != 0.0 || !line.extruding(self)) return; // ignore travels (e.g. start-gcode Z lift)
if (running_peak > 1.0 && self.z() < 1.0)
first_object_peak_z = running_peak;
else
running_peak = std::max(running_peak, static_cast<double>(self.z()));
});
return first_object_peak_z;
}
TEST_CASE("Sequential printing follows model order", "[Print]")
{
// Two objects of different heights, taller one added first. Orca prints
// sequential objects in model order, so the taller one is printed first.
const std::string gcode = Slic3r::Test::slice({ cube(20), Slic3r::make_cube(20, 20, 10) }, {
{ "print_sequence", "by object" },
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "z_hop", 0 }
});
REQUIRE_THAT(first_object_peak_z(gcode), Catch::Matchers::WithinAbs(20.0, 0.3));
}
// 20 mm boxes of the given heights, in list order, 60 mm apart in X at the same Y, so they share a
// Y band but are far enough apart for the toolhead radius rule. The rod is lowered to 25 mm, so a
// 30 mm box reaches above it and a 10 mm one does not.
static void place_boxes_in_one_y_band(const std::vector<double> &heights, Print &print, Model &model)
{
std::vector<TriangleMesh> meshes;
for (size_t i = 0; i < heights.size(); ++i) {
TriangleMesh box = make_cube(20, 20, heights[i]);
box.translate(float(80 + 80 * i), 80.f, 0.f);
meshes.push_back(std::move(box));
}
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "print_sequence", "by object" },
{ "extruder_clearance_height_to_rod", 25 },
{ "skirt_loops", 0 },
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "z_hop", 0 },
{ "layer_change_gcode", "G92 E0\n" } // validate() relative-E reset
});
Test::init_print(std::move(meshes), print, model, config, nullptr, /*arrange=*/false);
}
static const StringObjectException *find_order_warning(const std::vector<StringObjectException> &warnings)
{
auto it = std::find_if(warnings.begin(), warnings.end(),
[](const StringObjectException &w) { return w.string.find("is printed later than its place in the object list") != std::string::npos; });
return it == warnings.end() ? nullptr : &*it;
}
TEST_CASE("Sequential printing accepts a taller object listed first and over the rod height", "[Print]")
{
Print print;
Model model;
place_boxes_in_one_y_band({ 30, 10 }, print, model);
std::vector<StringObjectException> warnings;
const StringObjectException error = print.validate(&warnings);
INFO(error.string);
REQUIRE(error.string.empty());
// The print no longer follows the object list, so the user is told about the taller object,
// which is held back to clear the rod, and the notification jumps to it.
const StringObjectException *order_warning = find_order_warning(warnings);
REQUIRE(order_warning != nullptr);
CHECK(order_warning->object == print.model().objects.front()->instances.front());
CHECK(order_warning->string.find('\n') == std::string::npos); // only the taller object is named
}
TEST_CASE("Sequential printing prints the shorter object first when the taller one is over the rod height", "[Print]")
{
Print print;
Model model;
place_boxes_in_one_y_band({ 30, 10 }, print, model);
REQUIRE_THAT(first_object_peak_z(Test::gcode(print)), Catch::Matchers::WithinAbs(10.0, 0.3));
}
TEST_CASE("Sequential printing keeps a list order that already clears the rod", "[Print]")
{
Print print;
Model model;
place_boxes_in_one_y_band({ 10, 30 }, print, model);
std::vector<StringObjectException> warnings;
const StringObjectException error = print.validate(&warnings);
INFO(error.string);
REQUIRE(error.string.empty());
CHECK(find_order_warning(warnings) == nullptr);
REQUIRE_THAT(first_object_peak_z(Test::gcode(print)), Catch::Matchers::WithinAbs(10.0, 0.3));
}
TEST_CASE("Sequential printing still rejects two objects over the rod height that share a Y band", "[Print]")
{
Print print;
Model model;
place_boxes_in_one_y_band({ 30, 30 }, print, model);
CHECK_THAT(print.validate().string, Catch::Matchers::ContainsSubstring("too tall"));
}
TEST_CASE("Sequential printing keeps copies of one object in their list order", "[Print]")
{
// Every copy of an object shares its object index, so ordering by that alone leaves the copies to
// the sort, which shuffles them once there are enough. Nothing here comes near the rod: 200 copies
// of a part lower than the nozzle, on a grid, so nothing needs reordering.
std::vector<TriangleMesh> meshes;
meshes.push_back(make_cube(5, 5, 2));
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "print_sequence", "by object" },
{ "skirt_loops", 0 },
{ "layer_change_gcode", "G92 E0\n" } // validate() relative-E reset
});
Print print;
Model model;
Test::init_print(std::move(meshes), print, model, config, nullptr, /*arrange=*/false, /*instances=*/200);
const ModelInstancePtrs &instances = model.objects.front()->instances;
for (size_t k = 0; k < instances.size(); ++k)
instances[k]->set_offset(Vec3d(10. + 12. * double(k % 15), 10. + 12. * double(k / 15), instances[k]->get_offset().z()));
print.apply(model, config);
std::vector<StringObjectException> warnings;
const StringObjectException error = print.validate(&warnings);
INFO(error.string);
REQUIRE(error.string.empty());
CHECK(find_order_warning(warnings) == nullptr);
// validate() records the print order on the print's own copy of the model.
const ModelInstancePtrs &copies = print.model().objects.front()->instances;
CHECK(std::is_sorted(copies.begin(), copies.end(),
[](const ModelInstance *l, const ModelInstance *r) { return l->arrange_order < r->arrange_order; }));
}
TEST_CASE("Sequential printing keeps rotated copies of one object in their list order", "[Print]")
{
// Copies of one object that differ in rotation get one PrintObject each, and print.objects() lists
// those groups by transformation. Ordering by the object index alone therefore follows that
// grouping instead of the object list, and every second copy here prints out of place.
// The mesh is centred on the object origin, so the rotation turns the footprint in place instead
// of moving it, and the grid spacing below stays clear of the clearance radius.
TriangleMesh cube = make_cube(5, 5, 2);
cube.translate(-2.5f, -2.5f, 0.f);
std::vector<TriangleMesh> meshes;
meshes.push_back(std::move(cube));
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "print_sequence", "by object" },
{ "skirt_loops", 0 },
{ "layer_change_gcode", "G92 E0\n" } // validate() relative-E reset
});
Print print;
Model model;
Test::init_print(std::move(meshes), print, model, config, nullptr, /*arrange=*/false, /*instances=*/200);
const ModelInstancePtrs &instances = model.objects.front()->instances;
for (size_t k = 0; k < instances.size(); ++k) {
instances[k]->set_offset(Vec3d(10. + 12. * double(k % 15), 10. + 12. * double(k / 15), instances[k]->get_offset().z()));
if (k % 2 != 0)
instances[k]->set_rotation(Vec3d(0., 0., PI / 2));
}
print.apply(model, config);
std::vector<StringObjectException> warnings;
const StringObjectException error = print.validate(&warnings);
INFO(error.string);
REQUIRE(error.string.empty());
CHECK(find_order_warning(warnings) == nullptr);
// validate() numbered the instances it ordered; the copies must be numbered in list order.
const ModelInstancePtrs &copies = print.model().objects.front()->instances;
for (size_t k = 0; k < copies.size(); ++k)
REQUIRE(copies[k]->arrange_order == int(k + 1));
// The G-code export orders the instances from those numbers.
const std::vector<const PrintInstance *> ordered = sort_object_instances_by_model_order(print);
REQUIRE(ordered.size() == copies.size());
for (size_t k = 0; k < copies.size(); ++k)
REQUIRE(ordered[k]->model_instance == copies[k]);
}
TEST_CASE("Sequential printing still lets objects below the rod use the rod height when the lid is lower", "[Print]")
{
// Some stock profiles put the lid below the rod, such as the Creality Ender-3 V3 KE (lid 34 mm,
// rod 47 mm). An object that shares a Y band with a later one is checked against the rod height
// instead of the lid, so two 40 mm boxes side by side in X still slice.
std::vector<TriangleMesh> meshes;
for (size_t i = 0; i < 2; ++i) {
TriangleMesh box = make_cube(20, 20, 40);
box.translate(float(80 + 80 * i), 80.f, 0.f);
meshes.push_back(std::move(box));
}
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "print_sequence", "by object" },
{ "extruder_clearance_height_to_lid", 34 },
{ "extruder_clearance_height_to_rod", 47 },
{ "skirt_loops", 0 },
{ "layer_change_gcode", "G92 E0\n" } // validate() relative-E reset
});
Print print;
Model model;
Test::init_print(std::move(meshes), print, model, config, nullptr, /*arrange=*/false);
const std::string error = print.validate().string;
INFO(error);
CHECK(error.empty());
}
TEST_CASE("Sequential printing counts only the part of an object above the rod height", "[Print]")
{
// Each object is a 2 mm slab carrying one fin on its front (-Y) or back (+Y) edge, with the rod at
// 25 mm. The slabs share a Y band, but the rod can only hit the fins. Each fin is checked against
// the other slab's footprint widened by half of extruder_clearance_radius, not against the other
// fin: facing away from each other, neither fin is within that range; facing each other, both are,
// and no print order works. With one of each, only the first slab's fin is, so the second slab has to
// print first.
enum class Fins { FacingAway, FacingEachOther, OneOfEach };
const Fins fins = GENERATE(Fins::FacingAway, Fins::FacingEachOther, Fins::OneOfEach);
// A raised object (snap to the bed turned off) whose own height is below the rod but whose top is
// above it must get the same rule.
const bool raised = GENERATE(false, true);
// A per-object skirt that reaches the rod is a wall around the whole footprint, so the rod can hit
// all of it: the plate is refused whichever way the fins face, as it was before this rule. That is
// a draft shield (as tall as the object) or a skirt whose skirt_height reaches the rod.
enum class Skirt { None, DraftShield, Tall };
const Skirt skirt = GENERATE(Skirt::None, Skirt::DraftShield, Skirt::Tall);
CAPTURE(int(fins), raised, int(skirt));
const double fin_height = raised ? 20. : 29.5;
const double raise_by = raised ? 10. : 0.;
auto slab_with_fin = [fin_height](bool fin_at_back, double x, double y) {
TriangleMesh slab = make_cube(40, 30, 2);
TriangleMesh fin = make_cube(8, 2, fin_height);
fin.translate(16.f, fin_at_back ? 28.f : 0.f, 0.f);
slab.merge(fin);
slab.translate(float(x), float(y), 0.f);
return slab;
};
// The first slab sits further back (+Y), so its front fin faces the second slab.
std::vector<TriangleMesh> meshes;
meshes.push_back(slab_with_fin(fins == Fins::FacingAway, 40, 85));
meshes.push_back(slab_with_fin(fins == Fins::FacingEachOther, 170, 45));
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "print_sequence", "by object" },
{ "extruder_clearance_height_to_rod", 25 },
// The rod reaches half of the default 40 mm radius; the fins are 18 mm clear when facing away.
{ "extruder_clearance_dist_to_rod", 20 },
{ "skirt_loops", 0 },
{ "layer_change_gcode", "G92 E0\n" } // validate() relative-E reset
});
if (skirt == Skirt::DraftShield)
config.set_deserialize_strict({
{ "draft_shield", "enabled" },
{ "skirt_type", "perobject" },
{ "skirt_loops", 1 }
});
else if (skirt == Skirt::Tall)
config.set_deserialize_strict({
{ "skirt_type", "perobject" },
{ "skirt_loops", 1 },
{ "skirt_height", 160 } // layers, well above the 25 mm rod at the default max layer height
});
Print print;
Model model;
Test::init_print(std::move(meshes), print, model, config, nullptr, /*arrange=*/false);
if (raised) {
for (ModelObject *object : model.objects) {
ModelInstance *instance = object->instances.front();
instance->set_offset(instance->get_offset() + Vec3d(0., 0., raise_by));
}
print.apply(model, config);
REQUIRE(print.objects().front()->height() <= scale_(25.));
REQUIRE(print.objects().front()->max_z() > scale_(25.));
}
const std::string error = print.validate().string;
INFO(error);
const bool refused = fins == Fins::FacingEachOther || skirt != Skirt::None;
if (refused)
CHECK(error.find("too tall") != std::string::npos);
else
CHECK(error.empty());
if (fins == Fins::OneOfEach && !refused) {
// validate() records the print order on the print's own copy of the model.
const ModelObjectPtrs &objects = print.model().objects;
CHECK(objects[1]->instances.front()->arrange_order < objects[0]->instances.front()->arrange_order);
}
}
// Two 2 mm slabs side by side in X, each with one fin above the rod, the fins facing away from each
// other so only the fins can meet the rod. Mesh coordinates, so the first slab sits further back (+Y).
static std::vector<TriangleMesh> slabs_with_fins_facing_away(double fin_height, double low_fin_height)
{
auto slab = [&](bool fin_at_back, double x, double y) {
TriangleMesh mesh = make_cube(40, 30, 2);
TriangleMesh fin = make_cube(8, 2, fin_height);
fin.translate(16.f, fin_at_back ? 28.f : 0.f, 0.f);
mesh.merge(fin);
if (low_fin_height > 0.) {
// A second, lower fin on the opposite edge, facing the other slab.
TriangleMesh low_fin = make_cube(8, 2, low_fin_height);
low_fin.translate(16.f, fin_at_back ? 0.f : 28.f, 0.f);
mesh.merge(low_fin);
}
mesh.translate(float(x), float(y), 0.f);
return mesh;
};
std::vector<TriangleMesh> meshes;
meshes.push_back(slab(true, 40, 85));
meshes.push_back(slab(false, 170, 45));
return meshes;
}
TEST_CASE("Sequential printing checks the part above the rod against the rod's full reach", "[Print]")
{
// Bambu Lab A1 mini values: half the toolhead radius is 36.5 mm, but the rod reaches 56.5 mm from the
// nozzle. The facing-away fins are farther apart than the first and closer than the second, so they only
// clear when the rod's reach is the smaller of the two.
const double dist_to_rod = GENERATE(0., 56.5);
CAPTURE(dist_to_rod);
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "print_sequence", "by object" },
{ "extruder_clearance_radius", 73 },
{ "extruder_clearance_height_to_rod", 25 },
{ "extruder_clearance_dist_to_rod", dist_to_rod },
{ "skirt_loops", 0 },
{ "layer_change_gcode", "G92 E0\n" } // validate() relative-E reset
});
Print print;
Model model;
Test::init_print(slabs_with_fins_facing_away(29.5, 0.), print, model, config, nullptr, /*arrange=*/false);
const std::string error = print.validate().string;
INFO(error);
if (dist_to_rod > 36.5)
CHECK(error.find("too tall") != std::string::npos);
else
CHECK(error.empty());
}
TEST_CASE("Sequential printing keeps the rod's reach within the object", "[Print]")
{
// Snapmaker U1 values, which leave Distance to rod at its default. The boxes clear the radius in X and
// are 38 mm apart in Y, more than half the radius but less than Distance to rod. The reach past half
// the radius only widens the part above the rod up to the object's own footprint, so they still validate.
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "print_sequence", "by object" },
{ "extruder_clearance_radius", 72.5 },
{ "extruder_clearance_height_to_rod", 27.5 },
{ "skirt_loops", 0 },
{ "layer_change_gcode", "G92 E0\n" } // validate() relative-E reset
});
REQUIRE(config.opt_float("extruder_clearance_dist_to_rod") > 38.);
std::vector<TriangleMesh> meshes;
for (const Vec2f &position : { Vec2f(20.f, 40.f), Vec2f(130.f, 110.f) }) {
TriangleMesh box = make_cube(32, 32, 32);
box.translate(position.x(), position.y(), 0.f);
meshes.push_back(std::move(box));
}
Print print;
Model model;
Test::init_print(std::move(meshes), print, model, config, nullptr, /*arrange=*/false);
const std::string error = print.validate().string;
INFO(error);
CHECK(error.empty());
}
TEST_CASE("Sequential printing counts a raft toward what reaches the rod", "[Print]")
{
// Each slab has a tall fin facing away from the other slab and a lower fin facing it. Without a raft
// the lower fin stays under the rod and the plate validates; a raft lifts it above the rod, and then
// the lower fins meet.
const bool raft = GENERATE(false, true);
CAPTURE(raft);
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "print_sequence", "by object" },
{ "extruder_clearance_height_to_rod", 25 },
{ "extruder_clearance_dist_to_rod", 20 },
{ "skirt_loops", 0 },
{ "raft_layers", raft ? 3 : 0 },
{ "layer_change_gcode", "G92 E0\n" } // validate() relative-E reset
});
Print print;
Model model;
Test::init_print(slabs_with_fins_facing_away(29.5, 24.8), print, model, config, nullptr, /*arrange=*/false);
if (raft)
REQUIRE(print.objects().front()->slicing_parameters().object_print_z_min > 0.2);
const std::string error = print.validate().string;
INFO(error);
if (raft)
CHECK(error.find("too tall") != std::string::npos);
else
CHECK(error.empty());
}
TEST_CASE("Sequential printing refuses objects a raft lifts above the rod when the lid is below it", "[Print]")
{
// With the lid below the rod, an object that shares a Y band with a later one is checked against the
// rod height instead of the lid. The fins face away from each other and stay below the rod on their
// own, but the raft lifts their tops above it. Above the rod, only the last object may also be taller
// than the lid, and both slabs are, so the plate is refused, as it is with fins that tall and no raft.
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "print_sequence", "by object" },
{ "extruder_clearance_height_to_lid", 20 },
{ "extruder_clearance_height_to_rod", 25 },
{ "extruder_clearance_dist_to_rod", 20 },
{ "skirt_loops", 0 },
{ "raft_layers", 3 },
{ "layer_change_gcode", "G92 E0\n" } // validate() relative-E reset
});
Print print;
Model model;
Test::init_print(slabs_with_fins_facing_away(24.8, 0.), print, model, config, nullptr, /*arrange=*/false);
REQUIRE(24.8 + print.objects().front()->slicing_parameters().object_print_z_min > 25.);
const std::string error = print.validate().string;
INFO(error);
CHECK(error.find("too tall") != std::string::npos);
}
TEST_CASE("Sequential printing applies an instance's rotation to the part above the rod", "[Print]")
{
// The fins face away from each other in the meshes, but each instance is turned 180 degrees about its
// own center, so on the bed they face each other and no print order works.
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "print_sequence", "by object" },
{ "extruder_clearance_height_to_rod", 25 },
{ "extruder_clearance_dist_to_rod", 20 },
{ "skirt_loops", 0 },
{ "layer_change_gcode", "G92 E0\n" } // validate() relative-E reset
});
Print print;
Model model;
Test::init_print(slabs_with_fins_facing_away(29.5, 0.), print, model, config, nullptr, /*arrange=*/false);
for (ModelObject *object : model.objects) {
ModelInstance *instance = object->instances.front();
const Vec3d center = object->instance_bounding_box(0).center();
const Vec3d offset = instance->get_offset();
instance->set_rotation(Vec3d(0., 0., PI));
// A half turn about the instance origin moves the object too; shift it back so it turns in place.
instance->set_offset(Vec3d(2. * center.x() - offset.x(), 2. * center.y() - offset.y(), offset.z()));
REQUIRE((object->instance_bounding_box(0).center() - center).norm() < EPSILON);
}
print.apply(model, config);
const std::string error = print.validate().string;
INFO(error);
CHECK(error.find("too tall") != std::string::npos);
}
TEST_CASE("By-layer As object list keeps copies of one object in their list order", "[Print]")
{
// validate() numbers the instances through sort_object_instances_by_model_order(print, true). Copies
// of one object used to all share one order key, and print.objects() does not list them in list order:
// every second copy is rotated here, which splits them into separate PrintObjects. The G-code export
// and the sequence labels print in the order those numbers assign.
std::vector<TriangleMesh> meshes;
meshes.push_back(make_cube(5, 5, 2));
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "print_sequence", "by layer" },
{ "print_order", "as_obj_list" },
{ "skirt_loops", 0 },
{ "layer_change_gcode", "G92 E0\n" } // validate() relative-E reset
});
Print print;
Model model;
Test::init_print(std::move(meshes), print, model, config, nullptr, /*arrange=*/false, /*instances=*/200);
const ModelInstancePtrs &instances = model.objects.front()->instances;
for (size_t k = 0; k < instances.size(); ++k) {
instances[k]->set_offset(Vec3d(10. + 12. * double(k % 15), 10. + 12. * double(k / 15), instances[k]->get_offset().z()));
if (k % 2 != 0)
instances[k]->set_rotation(Vec3d(0., 0., PI / 2));
}
print.apply(model, config);
std::vector<StringObjectException> warnings;
const StringObjectException error = print.validate(&warnings);
INFO(error.string);
REQUIRE(error.string.empty());
// validate() numbered the instances it ordered; copies must be numbered in list order.
const ModelInstancePtrs &copies = print.model().objects.front()->instances;
for (size_t k = 0; k < copies.size(); ++k)
REQUIRE(copies[k]->arrange_order == int(k + 1));
// The As object list path of the G-code export orders the instances from those numbers.
const std::vector<const PrintInstance *> ordered = sort_object_instances_by_model_order(print);
REQUIRE(ordered.size() == copies.size());
for (size_t k = 0; k < copies.size(); ++k)
REQUIRE(ordered[k]->model_instance == copies[k]);
}
TEST_CASE("Sequential printing prints last a raised object that only clears the lid there", "[Print]")
{
// A raised object (snap to the bed turned off) whose own height is below the lid but whose top is above
// it. Only the last object may reach above the lid, so it has to print last, although it comes first in
// the object list.
std::vector<TriangleMesh> meshes;
TriangleMesh raised = make_cube(10, 10, 10);
raised.translate(40.f, 40.f, 0.f);
meshes.push_back(std::move(raised));
TriangleMesh low = make_cube(10, 10, 5);
low.translate(140.f, 140.f, 0.f);
meshes.push_back(std::move(low));
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "print_sequence", "by object" },
{ "extruder_clearance_height_to_lid", 30 },
{ "extruder_clearance_height_to_rod", 25 },
{ "skirt_loops", 0 },
{ "layer_change_gcode", "G92 E0\n" } // validate() relative-E reset
});
Print print;
Model model;
Test::init_print(std::move(meshes), print, model, config, nullptr, /*arrange=*/false);
ModelInstance *instance = model.objects.front()->instances.front();
instance->set_offset(instance->get_offset() + Vec3d(0., 0., 25.));
print.apply(model, config);
REQUIRE(print.objects().front()->height() <= scale_(30.));
REQUIRE(print.objects().front()->max_z() > scale_(30.));
const std::string error = print.validate().string;
INFO(error);
CHECK(error.empty());
// validate() records the print order on the print's own copy of the model.
const ModelObjectPtrs &objects = print.model().objects;
CHECK(objects[0]->instances.front()->arrange_order > objects[1]->instances.front()->arrange_order);
}
TEST_CASE("Sequential printing counts a raft toward the height checked against the rod", "[Print]")
{
// Two 24.8 mm boxes that share a Y band, on a 3 layer raft. The boxes alone stay below the 25 mm rod,
// but the raft lifts their tops above it, so whichever prints first is in the rod's way while the other
// one prints.
std::vector<TriangleMesh> meshes;
for (float x : { 40.f, 150.f }) {
TriangleMesh box = make_cube(20, 20, 24.8);
box.translate(x, 80.f, 0.f);
meshes.push_back(std::move(box));
}
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "print_sequence", "by object" },
{ "extruder_clearance_height_to_rod", 25 },
{ "skirt_loops", 0 },
{ "raft_layers", 3 },
{ "layer_change_gcode", "G92 E0\n" } // validate() relative-E reset
});
Print print;
Model model;
Test::init_print(std::move(meshes), print, model, config, nullptr, /*arrange=*/false);
REQUIRE(24.8 + print.objects().front()->slicing_parameters().object_print_z_min > 25.);
const std::string error = print.validate().string;
INFO(error);
CHECK(error.find("too tall") != std::string::npos);
}
TEST_CASE("Sequential printing counts a raft toward whether an object is short", "[Print]")
{
// Objects below nozzle_height only need to clear the nozzle cone, so they may stand close together,
// and their skirt is kept at its full distance. A raft lifts a 2 mm slab past the 2.5 mm nozzle_height,
// so the slabs need the toolhead radius between them and the skirt offset of a tall object.
const bool raft = GENERATE(false, true);
std::vector<TriangleMesh> meshes;
for (size_t i = 0; i < 2; ++i) {
TriangleMesh slab = make_cube(20, 20, 2);
slab.translate(float(80 + 30 * i), 80.f, 0.f); // 10 mm apart, within the 40 mm toolhead radius
meshes.push_back(std::move(slab));
}
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "print_sequence", "by object" },
{ "nozzle_height", 2.5 },
{ "extruder_clearance_radius", 40 },
{ "skirt_loops", 1 },
{ "skirt_type", "perobject" },
{ "raft_layers", raft ? 3 : 0 },
{ "layer_change_gcode", "G92 E0\n" } // validate() relative-E reset
});
Print print;
Model model;
Test::init_print(std::move(meshes), print, model, config, nullptr, /*arrange=*/false);
REQUIRE((2. + print.objects().front()->slicing_parameters().object_print_z_min > 2.5) == raft);
CHECK(print.is_all_objects_are_short() == ! raft);
CHECK((std::get<0>(print.object_skirt_offset()) > 0.f) == ! raft);
const std::string error = print.validate().string;
INFO(error);
if (raft)
CHECK(error.find("too close to others") != std::string::npos);
else
CHECK(error.empty());
}
TEST_CASE("Sequential printing measures objects on a belt printer by the model's top", "[Print][belt]")
{
// On a belt printer object_print_z_max is the height in the tilted slicing frame: at 45 degrees a 30 mm
// cube is over 42 mm tall there. The rod clears the model's own top, so two cubes side by side in X with
// the rod at 36 mm still slice, as the printable-height check in validate() also measures them.
std::vector<TriangleMesh> meshes;
for (size_t i = 0; i < 2; ++i) {
TriangleMesh box = make_cube(30, 30, 30);
box.translate(float(80 + 80 * i), 80.f, 0.f);
meshes.push_back(std::move(box));
}
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "print_sequence", "by object" },
{ "belt_printer", 1 },
{ "belt_slice_rotation", "x" },
{ "belt_slice_rotation_angle", 45 },
{ "extruder_clearance_height_to_lid", 50 },
{ "extruder_clearance_height_to_rod", 36 },
{ "skirt_loops", 0 },
{ "z_hop", 0 },
{ "layer_change_gcode", "G92 E0\n" } // validate() relative-E reset
});
Print print;
Model model;
Test::init_print(std::move(meshes), print, model, config, nullptr, /*arrange=*/false);
REQUIRE(print.objects().front()->slicing_parameters().object_print_z_max > 36.);
const std::string error = print.validate().string;
INFO(error);
CHECK(error.empty());
}
// A sequential (by-object) print must publish the print-level nozzle group result just
// like a by-layer print, so custom g-code can index the per-nozzle placeholder tables
// (e.g. nozzle_diameter_at_nozzle_id[]) instead of failing on an empty vector.
TEST_CASE("Sequential printing publishes the nozzle group result", "[Print][MultiNozzle]")
{
SECTION("process() publishes the result") {
Print print;
Model model;
place_two_cubes_apart(60.0, { { "print_sequence", "by object" } }, print, model);
print.process();
REQUIRE(print.get_layered_nozzle_group_result() != nullptr);
}
SECTION("start g-code can index the per-nozzle diameter table") {
const std::string gcode = slice_two_cubes_arranged({
{ "print_sequence", "by object" },
{ "machine_start_gcode", "{if nozzle_diameter_at_nozzle_id[0] > 0}; SEQ-ND-OK\n{endif}" },
});
CHECK(gcode.find("; SEQ-ND-OK") != std::string::npos);
}
}
// A scarf joint starts one layer height below the layer and ramps up along the
// wall. On a tilted belt that start is a step backwards along the belt axis, into
// the previous layer's wall at the seam: 0.283 mm per 0.2 mm layer at 45 degrees.
// With an aligned seam the nozzle rams the same spot on every layer (field report
// from a BabyBelt Pro: the belt "jumped backwards" and knocked the part loose).
// Belt printers therefore never get a scarf, whatever the process preset says.
TEST_CASE("Belt printers never start a scarf seam below the layer", "[Print][belt][Seam]")
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "belt_printer", 1 },
{ "belt_slice_rotation", "x" },
{ "belt_slice_rotation_angle", 45 },
{ "gcode_remap_x", "rev_x" },
{ "gcode_remap_y", "pos_z" },
{ "gcode_remap_z", "pos_y" },
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "skirt_loops", 0 },
{ "top_shell_layers", 0 },
{ "bottom_shell_layers", 1 },
{ "wall_loops", 2 },
{ "seam_position", "back" },
{ "seam_slope_type", "external" },
{ "seam_slope_inner_walls", 1 },
{ "seam_slope_start_height", 0 },
// No z-hop: on a belt a lift is a move along the belt axis (0.4 mm / sin 45 = 0.57 mm)
// and its return would read as a back-step. The shipped belt profiles print without one.
{ "z_hop", 0 },
{ "machine_start_gcode", "T[initial_tool]\n" },
{ "layer_change_gcode", "G92 E0\n" },
});
const std::string gcode = slice({ cube(20) }, config);
REQUIRE(! gcode.empty());
// The belt axis is machine Z. Within a layer it only drifts by the frame
// coupling (well under 0.1 mm across a 20 mm cube); a scarf start is a full
// layer pitch (0.283 mm) backwards.
double last_z = std::numeric_limits<double>::lowest();
double worst_backstep = 0.;
GCodeReader parser;
parser.parse_buffer(gcode, [&](GCodeReader &, const GCodeReader::GCodeLine &line) {
if (! line.cmd_is("G1") || ! line.has_z())
return;
const double z = line.z();
if (last_z != std::numeric_limits<double>::lowest())
worst_backstep = std::max(worst_backstep, last_z - z);
last_z = z;
});
CHECK(worst_backstep < 0.2);
}
// printable_height on a belt printer is the clearance under the gantry, so an object taller
// than that is refused whatever the machine-frame transform does to the emitted coordinates.
TEST_CASE("Belt printers refuse an object taller than the gantry clearance", "[Print][belt]")
{
auto belt_config = [](double printable_height) {
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "belt_printer", 1 },
{ "belt_slice_rotation", "x" },
{ "belt_slice_rotation_angle", 45 },
{ "gcode_remap_x", "rev_x" },
{ "gcode_remap_y", "pos_z" },
{ "gcode_remap_z", "pos_y" },
{ "printable_height", printable_height },
{ "skirt_loops", 0 },
{ "layer_change_gcode", "G92 E0\n" },
});
return config;
};
SECTION("a 20 mm cube fits under 50 mm of clearance") {
Print print;
Model model;
init_print({ cube(20) }, print, model, belt_config(50));
CHECK(print.validate().string.empty());
}
SECTION("a 60 mm cube does not") {
Print print;
Model model;
init_print({ cube(60) }, print, model, belt_config(50));
CHECK(print.validate().string.find("height") != std::string::npos);
}
}
// On a belt every tilted layer starts on the belt, so "the first layers" the fan stays off
// for are a band along the belt, not the first slicing layers. The generator marks where
// each extrusion segment enters and leaves that band and the cooling buffer keeps the fan
// off inside it, on every layer. The lowest wall of each tilted layer rests on the belt with
// its nozzle half a layer plus half its width up (0.1 + 0.21 mm here), so a band of one
// first layer has to be judged from the bead, not the nozzle, to hold it.
TEST_CASE("Belt printers keep the part fan off within the band above the belt", "[Print][belt][Cooling]")
{
// Fan-off layers, and the gantry Y below which an extrusion is well inside that band.
const auto [fan_off_layers, band_y] = GENERATE(table<int, double>({ { 1, 0.35 }, { 3, 0.45 } }));
CAPTURE(fan_off_layers);
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "belt_printer", 1 },
{ "belt_slice_rotation", "x" },
{ "belt_slice_rotation_angle", 45 },
{ "gcode_remap_x", "rev_x" },
{ "gcode_remap_y", "pos_z" },
{ "gcode_remap_z", "pos_y" },
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "skirt_loops", 0 },
{ "z_hop", 0 },
{ "outer_wall_line_width", 0.42 },
{ "close_fan_the_first_x_layers", fan_off_layers },
{ "full_fan_speed_layer", 0 },
{ "fan_min_speed", 100 },
{ "fan_max_speed", 100 },
{ "slow_down_layer_time", 1000 },
{ "fan_cooling_layer_time", 1001 },
{ "reduce_fan_stop_start_freq", 0 },
{ "machine_start_gcode", "T[initial_tool]\n" },
{ "layer_change_gcode", "G92 E0\n" },
});
const std::string gcode = slice({ cube(20) }, config);
REQUIRE(! gcode.empty());
// The markers are consumed by the cooling buffer and never reach the file.
CHECK(gcode.find(";_BELT_BAND") == std::string::npos);
// With this axis mapping machine Y is the height above the belt along the gantry. Walk
// the moves with the fan state: extrusions that stay below band_y are well inside the band
// and must print with the fan off; extrusions that stay 5 mm clear of it must print with
// it on. The first fan_off_layers slicing layers have the fan off altogether.
size_t in_band = 0, in_band_fan_on = 0, clear = 0, clear_fan_off = 0;
int layer = -1;
bool fan_on = false;
double y = 0.;
std::istringstream lines(gcode);
for (std::string line; std::getline(lines, line); ) {
if (boost::starts_with(line, ";LAYER_CHANGE")) {
++ layer;
} else if (boost::starts_with(line, "M107")) {
fan_on = false;
} else if (boost::starts_with(line, "M106")) {
const size_t s = line.find('S');
fan_on = s != std::string::npos && std::atof(line.c_str() + s + 1) > 0.;
} else if (boost::starts_with(line, "G1 ")) {
const size_t comment = line.find(';');
const std::string cmd = line.substr(0, comment);
const size_t ypos = cmd.find(" Y"), epos = cmd.find(" E");
if (ypos == std::string::npos)
continue;
const double y_new = std::atof(cmd.c_str() + ypos + 2);
const bool extruding = epos != std::string::npos && std::atof(cmd.c_str() + epos + 2) > 0.;
if (extruding && layer >= fan_off_layers) {
if (std::max(y, y_new) < band_y) {
++ in_band;
in_band_fan_on += fan_on;
} else if (std::min(y, y_new) > 5.) {
++ clear;
clear_fan_off += ! fan_on;
}
}
y = y_new;
}
}
CHECK(in_band > 20);
CHECK(in_band_fan_on == 0);
CHECK(clear > 20);
CHECK(clear_fan_off == 0);
}
// On a belt one wall loop runs from the belt up the part, and whether a path is on the first
// layer, and its step of the slow_down_layers ramp, set its speed, flow and acceleration as a
// whole. Each part of the loop must take the settings of its own height above the belt,
// wherever the seam starts the loop.
TEST_CASE("Belt printers use first-layer settings only where a wall rests on the belt", "[Print][belt][Regression]")
{
const std::string seam = GENERATE("back", "random");
const int slow_down_layers = GENERATE(0, 4);
CAPTURE(seam, slow_down_layers);
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "belt_printer", 1 },
{ "belt_slice_rotation", "x" },
{ "belt_slice_rotation_angle", 45 },
{ "gcode_remap_x", "rev_x" },
{ "gcode_remap_y", "pos_z" },
{ "gcode_remap_z", "pos_y" },
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "skirt_loops", 0 },
{ "brim_type", "no_brim" },
{ "z_hop", 0 },
{ "wall_generator", "classic" },
{ "outer_wall_line_width", 0.42 },
{ "seam_position", seam },
// One path per wall loop, so nothing but the edges of the bands cut it.
{ "detect_overhang_wall", 0 },
{ "enable_overhang_speed", 0 },
{ "initial_layer_speed", 10 },
{ "outer_wall_speed", 40 },
{ "slow_down_layers", slow_down_layers },
{ "filament_max_volumetric_speed", 20 },
{ "slow_down_for_layer_cooling", 0 },
{ "set_other_flow_ratios", 1 },
{ "first_layer_flow_ratio", 0.8 },
{ "machine_start_gcode", "T[initial_tool]\n" },
{ "layer_change_gcode", "G92 E0\n" },
});
const std::string gcode = slice({ cube(20) }, config);
// As above, machine Y is the height above the belt. The outer wall's nozzle is half its
// width, 0.21 mm, higher than the belt under its edge, so the first layer, up to 0.2 mm,
// ends at Y = 0.41 and step k of the ramp spans Y = 0.21 + [0.2 k, 0.2 (k + 1)). Its wall
// resting on the belt is at Y = 0.31.
const double ramp_step_2 = 10. + (40. - 10.) * 2. / 4.;
std::vector<double> in_band_e, clear_e; // E per mm
size_t in_band = 0, in_band_fast = 0, step_2 = 0, step_2_off = 0, clear = 0, clear_slow = 0;
std::string type;
GCodeReader reader;
reader.parse_buffer(gcode, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) {
if (boost::starts_with(line.raw(), ";TYPE:")) {
type = line.raw().substr(6);
return;
}
if (type != "Outer wall" || ! line.extruding(self) || line.dist_XY(self) <= EPSILON)
return;
const double y_lo = std::min(self.y(), line.new_Y(self));
const double y_hi = std::max(self.y(), line.new_Y(self));
const double f = line.new_F(self);
// Long moves only for the flow, so that the rounding of E does not blur it.
const bool long_move = line.dist_XY(self) >= 0.5;
if (y_hi < 0.35) {
++ in_band;
in_band_fast += std::abs(f - 10. * 60.) > 1.;
if (long_move)
in_band_e.push_back(line.dist_E(self) / line.dist_XY(self));
} else if (slow_down_layers == 4 && y_lo > 0.61 - 1e-3 && y_hi < 0.81 + 1e-3) {
++ step_2;
step_2_off += std::abs(f - ramp_step_2 * 60.) > 1.;
} else if (y_lo > 1.5) {
++ clear;
clear_slow += std::abs(f - 40. * 60.) > 1.;
if (long_move)
clear_e.push_back(line.dist_E(self) / line.dist_XY(self));
}
});
REQUIRE(in_band > 20);
REQUIRE(clear > 20);
CHECK(in_band_fast == 0);
CHECK(clear_slow == 0);
if (slow_down_layers == 4) {
REQUIRE(step_2 > 10);
CHECK(step_2_off == 0);
}
// first_layer_flow_ratio on the belt and nowhere else.
auto median = [](std::vector<double> v) {
std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end());
return v[v.size() / 2];
};
CHECK_THAT(median(in_band_e) / median(clear_e), Catch::Matchers::WithinRel(0.8, 0.02));
}
// Small-area flow compensation scales a line's flow by the line's length. The cuts a belt path
// gets at the edges of the bands above the belt must not make it see the pieces as short lines.
TEST_CASE("Belt band cuts leave small-area flow compensation unchanged", "[Print][belt][Regression]")
{
// Plastic per role. The slow_down_layers ramp adds band edges every 0.2 mm above the belt,
// here up to well past the top of the part, and with them cuts through the solid infill
// under its top face, but changes nothing else about how much plastic is laid.
auto plastic = [](int slow_down_layers) {
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "belt_printer", 1 },
{ "belt_slice_rotation", "x" },
{ "belt_slice_rotation_angle", 45 },
{ "gcode_remap_x", "rev_x" },
{ "gcode_remap_y", "pos_z" },
{ "gcode_remap_z", "pos_y" },
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "skirt_loops", 0 },
{ "brim_type", "no_brim" },
{ "z_hop", 0 },
{ "bottom_shell_layers", 4 },
{ "internal_solid_infill_pattern", "monotonic" },
{ "small_area_infill_flow_compensation", 1 },
{ "slow_down_layers", slow_down_layers },
{ "machine_start_gcode", "T[initial_tool]\n" },
{ "layer_change_gcode", "G92 E0\n" },
});
std::map<std::string, double> e;
std::string type;
GCodeReader reader;
reader.parse_buffer(slice({ cube(20) }, config), [&](GCodeReader &self, const GCodeReader::GCodeLine &line) {
if (boost::starts_with(line.raw(), ";TYPE:"))
type = line.raw().substr(6);
else if (line.extruding(self) && line.dist_XY(self) > EPSILON)
e[type] += line.dist_E(self);
});
return e;
};
const std::map<std::string, double> uncut = plastic(0);
const std::map<std::string, double> cut = plastic(200);
REQUIRE(uncut.count("Internal solid infill") == 1);
REQUIRE(cut.count("Internal solid infill") == 1);
CHECK_THAT(cut.at("Internal solid infill"), Catch::Matchers::WithinRel(uncut.at("Internal solid infill"), 1e-4));
}
// Organic supports under an overhang on a belt printer reach below the object's first layer,
// where the virtual belt raft layers sit at negative Z. The lowest of them used to get a
// negative height and abort slicing with a negative flow error.
TEST_CASE("Belt printers slice organic tree supports that reach the belt", "[Print][belt][Support]")
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "belt_printer", 1 },
{ "belt_slice_rotation", "x" },
{ "belt_slice_rotation_angle", 45 },
{ "gcode_remap_x", "rev_x" },
{ "gcode_remap_y", "pos_z" },
{ "gcode_remap_z", "pos_y" },
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "skirt_loops", 0 },
{ "z_hop", 0 },
{ "enable_support", 1 },
{ "support_type", "tree(auto)" },
{ "support_style", "organic" },
{ "machine_start_gcode", "T[initial_tool]\n" },
{ "layer_change_gcode", "G92 E0\n" },
});
std::string gcode;
REQUIRE_NOTHROW(gcode = slice({ TestMesh::overhang }, config));
CHECK(! gcode.empty());
}
TEST_CASE("Slicing errors are reported per object with the object's name", "[Print]")
{
Print print;
Model model;
init_print({Slic3r::Test::cube(20.)}, print, model);
// Lift the cube off the bed: its first layer is empty, which G-code export reports per object.
ModelObject *object = model.objects.front();
object->name = "floating cube";
object->instances.front()->set_offset(object->instances.front()->get_offset() + Vec3d(0., 0., 2.));
print.apply(model, DynamicPrintConfig::full_print_config());
print.set_status_silent();
ScopedTemporaryFile temp(".gcode");
std::string message;
try {
print.process();
print.export_gcode(temp.string(), nullptr, nullptr);
FAIL("slicing did not report the empty first layer");
} catch (const SlicingErrors &errors) {
REQUIRE(errors.errors_.size() == 1);
message = print.slicing_errors_message(errors);
}
CHECK(message.rfind("floating cube: ", 0) == 0);
CHECK(message.find("empty first layer") != std::string::npos);
}
// ---------------------------------------------------------------------------
// Belt mode must be invisible when it is off, and must not leave traces behind.
// ---------------------------------------------------------------------------
// Everything the slicer decided, without the lines that legitimately differ between
// two exports of the same print: comments (the config block lists every key, the
// header carries the export time) and the thumbnail blocks.
static std::string gcode_body(const std::string &gcode)
{
std::string body;
std::istringstream in(gcode);
for (std::string line; std::getline(in, line); ) {
line.erase(std::min(line.size(), line.find(';')));
while (! line.empty() && line.back() == ' ')
line.pop_back();
if (! line.empty())
body += line + '\n';
}
return body;
}
static DynamicPrintConfig belt_test_config()
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "belt_printer", 1 },
{ "belt_slice_rotation", "x" },
{ "belt_slice_rotation_angle", 45 },
{ "gcode_remap_x", "rev_x" },
{ "gcode_remap_y", "pos_z" },
{ "gcode_remap_z", "pos_y" },
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "skirt_loops", 0 },
{ "z_hop", 0 },
{ "machine_start_gcode", "T[initial_tool]\n" },
{ "layer_change_gcode", "G92 E0\n" },
});
return config;
}
TEST_CASE("Belt-only keys at non-default values leave non-belt G-code unchanged", "[Print][belt][Regression]")
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "z_hop", 0 },
{ "brim_type", "outer_only" },
{ "brim_width", 4 },
{ "enable_support", 1 },
{ "support_type", "tree(auto)" },
{ "support_style", "organic" },
{ "sparse_infill_pattern", "adaptivecubic" },
{ "machine_start_gcode", "T[initial_tool]\n" },
{ "layer_change_gcode", "G92 E0\n" },
});
const std::string reference = gcode_body(slice({ TestMesh::overhang }, config));
REQUIRE(! reference.empty());
// Every belt key a profile can carry, at a value that would change a belt print.
// belt_printer stays off, so none of them may reach the G-code: the axis remaps are
// gated on belt mode, the rest is only read on belt printers. build_plate_tilt_x/y
// is a feature of its own on a flat bed and is left alone here; "leading_edge_only"
// prints as an outer brim by design.
config.set_deserialize_strict({
{ "belt_printer", 0 },
{ "belt_printer_infinite_y", 0 },
{ "belt_slice_rotation", "y" },
{ "belt_slice_rotation_angle", 30 },
{ "gcode_remap_x", "rev_x" },
{ "gcode_remap_y", "pos_z" },
{ "gcode_remap_z", "pos_y" },
{ "belt_frame_tilt_decouple", 1 },
{ "belt_frame_tilt_angle", 30 },
{ "belt_support_floor_offset", -5 },
{ "enable_belt_purge_tower", 1 },
{ "belt_purge_tower_width", 10 },
{ "leading_brim_length", 10 },
{ "extra_brim_width", 5 },
});
CHECK(gcode_body(slice({ TestMesh::overhang }, config)) == reference);
}
TEST_CASE("Switching a sliced project from belt to non-belt matches a fresh slice", "[Print][belt][Regression]")
{
// The organic support layers and the adaptive infill octree are placed with the
// belt global Z offset, and the mesh with the belt min-Z lift. Both are only
// written while belt mode slices, so they used to survive a switch away from it.
DynamicPrintConfig flat = DynamicPrintConfig::full_print_config();
flat.set_deserialize_strict({
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "skirt_loops", 0 },
{ "z_hop", 0 },
{ "enable_support", 1 },
{ "support_type", "tree(auto)" },
{ "support_style", "organic" },
{ "sparse_infill_pattern", "adaptivecubic" },
{ "machine_start_gcode", "T[initial_tool]\n" },
{ "layer_change_gcode", "G92 E0\n" },
});
DynamicPrintConfig belt = belt_test_config();
belt.set_deserialize_strict({
{ "enable_support", 1 },
{ "support_type", "tree(auto)" },
{ "support_style", "organic" },
{ "sparse_infill_pattern", "adaptivecubic" },
});
// Both prints are placed with the belt config, so only the slicing history differs.
auto fresh_slice = [&](const DynamicPrintConfig &target) {
Print print;
Model model;
init_print({ TestMesh::overhang }, print, model, belt);
print.apply(model, target);
const std::string out = gcode(print);
return gcode_body(out);
};
auto resliced = [&](const DynamicPrintConfig &target) {
Print print;
Model model;
init_print({ TestMesh::overhang }, print, model, belt);
REQUIRE(! gcode(print).empty());
print.apply(model, target);
const std::string out = gcode(print);
return gcode_body(out);
};
SECTION("belt printer to a flat-bed printer") {
CHECK(resliced(flat) == fresh_slice(flat));
}
SECTION("belt tilt axis set to None") {
DynamicPrintConfig untilted = belt;
untilted.set_deserialize_strict({ { "belt_slice_rotation", "none" } });
CHECK(resliced(untilted) == fresh_slice(untilted));
}
}
TEST_CASE("A support-only change on a belt purge print matches a fresh slice", "[Print][belt][PurgeTower][Regression]")
{
// Snapping the purge prism onto the parts' layer grid shifts every object's layers by
// up to half a layer. A support-only change reruns support generation without
// reslicing, so the cached belt floor and the global Z offset have to carry the
// snap too, or the supports land on the pre-snap grid.
auto make_config = [](bool support) {
DynamicPrintConfig config = multifilament_config(2, {
{ "belt_printer", 1 },
{ "belt_slice_rotation", "x" },
{ "belt_slice_rotation_angle", 45 },
{ "gcode_remap_x", "rev_x" },
{ "gcode_remap_y", "pos_z" },
{ "gcode_remap_z", "pos_y" },
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "skirt_loops", 0 },
{ "z_hop", 0 },
{ "enable_belt_purge_tower", 1 },
{ "machine_start_gcode", "T[initial_tool]\n" },
{ "layer_change_gcode", "G92 E0\n" },
});
config.set_deserialize_strict({
{ "enable_support", support ? 1 : 0 },
{ "support_type", "tree(auto)" },
{ "support_style", "organic" },
});
return config;
};
const std::vector<std::vector<Slic3r::ConfigBase::SetDeserializeItem>> overrides {
{ { "extruder", 1 } }, { { "extruder", 2 } },
};
auto build = [&](Print &print, Model &model, const DynamicPrintConfig &config) {
init_print(std::vector<TriangleMesh>{ mesh(TestMesh::overhang), cube(20) }, print, model, config, &overrides);
model.objects.back()->config.set_key_value("belt_purge_tower_object", new ConfigOptionBool(true));
print.apply(model, config);
REQUIRE(print.has_belt_purge_tower());
};
std::string fresh;
{
Print print;
Model model;
build(print, model, make_config(true));
fresh = gcode_body(gcode(print));
}
REQUIRE(! fresh.empty());
Print print;
Model model;
build(print, model, make_config(false));
REQUIRE(! gcode(print).empty());
// Support only: posSlice stays valid, posSupportMaterial reruns.
print.apply(model, make_config(true));
CHECK(gcode_body(gcode(print)) == fresh);
}
TEST_CASE("Organic tree supports place a support blocker at its own height above a raft", "[Print][Support][Regression]")
{
// TreeModelVolumes consumes the support blockers in the same index space as the
// layer outlines, where object layer i sits at num_raft_layers + i, but
// slice_support_blockers() returns them in object-layer space. Without the shift
// every blocker lands num_raft_layers too low, so branches are kept out of the
// wrong layers and may pass through the blocked ones.
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "skirt_loops", 0 },
{ "enable_support", 1 },
{ "support_type", "tree(auto)" },
{ "support_style", "organic" },
{ "raft_layers", 3 },
});
Print print;
Model model;
init_print({ cube(20) }, print, model, config);
// A blocker floating beside the cube, 8 mm to 12 mm above the bed, so a collision at
// its centre can only come from the blocker itself (the part keeps its mesh
// coordinates in object space, hence the offset relative to the part).
ModelObject *object = model.objects.front();
ModelVolume *blocker = object->add_volume(TriangleMesh(its_make_cube(6., 6., 4.)));
blocker->set_type(ModelVolumeType::SUPPORT_BLOCKER);
const Vec3d part_offset = object->volumes.front()->get_offset();
blocker->set_offset(Vec3d(part_offset.x() + 20., part_offset.y(), 10.));
print.apply(model, config);
print.set_status_silent();
print.process();
const PrintObject &print_object = *print.objects().front();
const std::vector<Vec2d> bed = { { 0., 0. }, { 200., 0. }, { 200., 200. }, { 0., 200. } };
const BuildVolume build_volume{ bed, print.config().printable_height.value, {}, {} };
TreeSupport3D::TreeModelVolumes volumes{ print_object, build_volume, scaled<coord_t>(1.), scaled<coord_t>(0.5), 0, {} };
// The generator's raft layer count: the raft itself plus the gap layers up to the object.
const size_t num_raft = TreeSupport3D::TreeSupportSettings(TreeSupport3D::TreeSupportMeshGroupSettings(print_object),
print_object.slicing_parameters()).raft_layers.size();
REQUIRE(num_raft >= 3);
// Object layers the blocker was sliced into (object-layer space, as the generator
// receives them).
const std::vector<Polygons> blockers = print_object.slice_support_blockers();
size_t first = 0, last = 0;
bool found = false;
for (size_t i = 0; i < blockers.size(); ++ i)
if (! blockers[i].empty()) {
if (! found) { first = i; found = true; }
last = i;
}
REQUIRE(found);
REQUIRE(last - first > num_raft);
// The blocker's centre in the slicing frame (add_volume centred its mesh on its offset).
const Vec3d centre3 = print_object.trafo_sliced() * blocker->get_offset();
const Point centre = Point::new_scale(centre3.x(), centre3.y());
auto collides = [&](size_t tree_layer) {
for (const Slic3r::Polygon &poly : volumes.getCollision(0, TreeSupport3D::LayerIndex(tree_layer), false))
if (poly.contains(centre))
return true;
return false;
};
// In TreeModelVolumes' index space the blocker lives at num_raft + object layer.
CHECK(collides(num_raft + first));
CHECK(collides(num_raft + last));
// The layers just below it, where an unshifted blocker would land, are free; the
// layers just above the unshifted range, which the blocker does occupy, are not.
CHECK_FALSE(collides(first));
CHECK_FALSE(collides(first + num_raft - 1));
CHECK(collides(last + 1));
CHECK(collides(last + num_raft));
}
// organic_draw_branches() trims every branch slice against the collision volume (the
// part grown by the support XY distance), the bed and, on a belt, the belt plane before
// it becomes support, so a branch never runs into the part it supports. Not a belt
// feature: this is the generator every printer uses.
TEST_CASE("Organic tree supports keep their distance from the part", "[Print][Support]")
{
// A 20 mm cube carrying a 60 x 60 mm plate: a 20 mm wide ceiling all around the
// cube, 16 mm above the bed, with the cube's four corners in the way of the branches
// that drop from it. The plate reaches into the cube so the two shells overlap
// instead of sharing a face.
indexed_triangle_set its = its_make_cube(20., 20., 20.);
indexed_triangle_set plate = its_make_cube(60., 60., 4.);
its_translate(its, Vec3f(20.f, 20.f, 0.f));
its_translate(plate, Vec3f(0.f, 0.f, 16.f));
its_merge(its, plate);
TriangleMesh mesh(std::move(its));
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "skirt_loops", 0 },
{ "enable_support", 1 },
{ "support_type", "tree(auto)" },
{ "support_style", "organic" },
{ "support_threshold_angle", 30 },
});
Print print;
Model model;
init_print({ mesh }, print, model, config);
// On the bed, not at its corner (the fixture leaves the object at the origin).
model.objects.front()->instances.front()->set_offset(Vec3d(100., 100., 0.));
print.apply(model, config);
print.set_status_silent();
print.process();
const PrintObject &object = *print.objects().front();
INFO("object layers " << object.layers().size() << ", support layers " << object.support_layers().size());
REQUIRE(! object.support_layers().empty());
// Support exists under the plate at all.
size_t support_layers_with_fills = 0;
for (const SupportLayer *layer : object.support_layers())
if (! layer->support_fills.empty())
++ support_layers_with_fills;
INFO("support layers with extrusions " << support_layers_with_fills);
CHECK(support_layers_with_fills > 20);
// Object layers by print_z, to look up the part's slice at a support layer's height.
std::map<coord_t, const Layer *> object_layers;
for (const Layer *layer : object.layers())
object_layers[scaled<coord_t>(layer->print_z)] = layer;
auto contains = [](const ExPolygons &expolys, const Point &pt) {
for (const ExPolygon &ex : expolys)
if (ex.contains(pt))
return true;
return false;
};
// No support extrusion may run closer to the part's slice than half a line width:
// the generator keeps the support XY distance (0.35 mm by default) plus the line's
// own half width away from it.
const float min_gap = scaled<float>(0.2);
size_t too_close = 0, points = 0, layers_checked = 0, layers_unmatched = 0;
for (const SupportLayer *layer : object.support_layers()) {
if (layer->support_fills.empty())
continue;
// The object layer whose slab spans this support layer's height.
auto it = object_layers.lower_bound(scaled<coord_t>(layer->print_z - EPSILON));
if (it == object_layers.end()) {
++ layers_unmatched;
continue;
}
++ layers_checked;
const ExPolygons grown = offset_ex(it->second->lslices, min_gap);
for (const ExtrusionEntity *entity : layer->support_fills.flatten().entities)
for (const Slic3r::Polyline &pl : entity->as_polylines())
for (size_t i = 0; i < pl.points.size(); ++ i) {
// The vertices and the midpoints of the segments between them.
++ points;
if (contains(grown, pl.points[i]))
++ too_close;
if (i + 1 < pl.points.size() && contains(grown, (pl.points[i] + pl.points[i + 1]) / 2))
++ too_close;
}
}
INFO("support layers checked " << layers_checked << " (unmatched " << layers_unmatched << "), support points " << points
<< ", within 0.2 mm of the part " << too_close);
CHECK(layers_checked > 20);
CHECK(layers_unmatched == 0);
REQUIRE(points > 0);
CHECK(too_close == 0);
}
// Two parts along the belt: the second part's slicing frame starts at the belt
// below its leading end, so its first layers are empty and interleave with the
// first part's printing layers. Those must not reach the G-code as layer changes
// that print nothing: the preview numbers its layers from the moves it sees, and
// a gap folded every later layer into the one before it.
TEST_CASE("Belt G-code has no layer that prints nothing", "[Print][belt][GCode][Regression]")
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "belt_printer", 1 },
{ "belt_slice_rotation", "x" },
{ "belt_slice_rotation_angle", 45 },
{ "gcode_remap_x", "rev_x" },
{ "gcode_remap_y", "pos_z" },
{ "gcode_remap_z", "pos_y" },
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "skirt_loops", 0 },
{ "z_hop", 0 },
{ "brim_type", "outer_only" },
{ "brim_width", 4 },
{ "machine_start_gcode", "T[initial_tool]\n" },
{ "layer_change_gcode", "G92 E0\n" },
});
// Both export paths drop the empty layers and count the layers the same way.
const std::string sequence = GENERATE(as<std::string>{}, "by layer", "by object");
CAPTURE(sequence);
config.set_deserialize_strict({{ "print_sequence", sequence }});
Print print;
Model model;
TriangleMesh cube_a(its_make_cube(20., 20., 20.));
TriangleMesh cube_b(its_make_cube(20., 20., 20.));
init_print({ cube_a, cube_b }, print, model, config);
// 60 mm apart along the belt: the second cube's lead-in layers fall among the
// first cube's layers.
model.objects[0]->instances.front()->set_offset(Vec3d(50., 40., 0.));
model.objects[1]->instances.front()->set_offset(Vec3d(50., 100., 0.));
print.apply(model, config);
print.set_status_silent();
const std::string gc = gcode(print);
REQUIRE(! gc.empty());
size_t layers = 0, empty = 0, total_header = 0, total_count = 0;
bool extruded = true; // before the first layer change
auto close_layer = [&]() { if (! extruded) ++ empty; };
GCodeReader reader;
reader.apply_config(config);
reader.parse_buffer(gc, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) {
const std::string &raw = line.raw();
if (raw.rfind(";LAYER_CHANGE", 0) == 0) {
close_layer();
++ layers;
extruded = false;
} else if (raw.rfind("; total layer number: ", 0) == 0) {
// Counted by the G-code processor from the layer changes it saw.
total_header = size_t(std::atoi(raw.c_str() + 22));
} else if (raw.rfind("; total layers count = ", 0) == 0) {
// GCode::m_layer_count, counted up front from the objects' layers; it also
// drives the M73 progress and the total_layer_count placeholder.
total_count = size_t(std::atoi(raw.c_str() + 23));
} else if (! extruded && line.extruding(self) && line.dist_XY(self) > EPSILON) {
// Material laid down along a move: a wipe or an unretraction does not count.
extruded = true;
}
});
close_layer();
INFO("layers " << layers << ", header " << total_header << ", count " << total_count
<< ", layers without extrusion " << empty);
CHECK(layers > 150); // both cubes, 141 layers each, overlapping along the belt
CHECK(empty == 0);
CHECK(total_header == layers);
CHECK(total_count == layers);
}
// A part with an overhang on its LEADING side (the end that prints first) needs
// supports below the object's own lowest slicing layer: the belt under that overhang
// is reached before the object's first contact with it, so the support layers sit at
// a lower slicing Z than any object layer. A generator that stops at the object's
// first layer, or at global Z = 0, leaves those supports floating above the belt.
TEST_CASE("Belt supports reach the belt under a leading overhang", "[Print][belt][Support][Regression]")
{
// default resolves to organic for tree support; tree_hybrid is the classic tree.
const auto [support_type, support_style] = GENERATE(table<const char *, const char *>({
{ "normal(auto)", "default" },
{ "tree(auto)", "default" },
{ "tree(auto)", "organic" },
{ "tree(auto)", "tree_hybrid" } }));
DYNAMIC_SECTION(support_type << " / " << support_style) {
// A 20 mm cube with a 2 mm thick fin that leaves its top edge and reaches
// 20 mm toward -Y, the end of the part that prints first, climbing at 45 deg
// as it goes (from z = 18 at the cube to z = 38 at the tip). With the layers
// leaning toward -Y at 45 deg the fin's underside is parallel to the layers:
// a ceiling 20 x 28 mm in one layer, with nothing but air between it and the
// belt, which lies up to 41 mm (of slicing Z) below the object's own lowest
// point. Support has to span all of it.
indexed_triangle_set its = its_make_cube(20., 20., 20.);
indexed_triangle_set fin = its_make_cube(20., 20., 2.);
Transform3d shear = Transform3d::Identity();
shear.matrix() << 1., 0., 0., 0.,
0., 1., 0., -20.,
0., -1., 1., 38.,
0., 0., 0., 1.;
its_transform(fin, shear);
its_merge(its, fin);
TriangleMesh mesh(std::move(its));
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "belt_printer", 1 },
{ "belt_slice_rotation", "x" },
{ "belt_slice_rotation_angle", 45 },
{ "gcode_remap_x", "rev_x" },
{ "gcode_remap_y", "pos_z" },
{ "gcode_remap_z", "pos_y" },
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "skirt_loops", 0 },
{ "z_hop", 0 },
{ "enable_support", 1 },
{ "support_type", support_type },
{ "support_style", support_style },
{ "support_threshold_angle", 30 },
{ "machine_start_gcode", "T[initial_tool]\n" },
{ "layer_change_gcode", "G92 E0\n" },
});
Print print;
Model model;
init_print({ mesh }, print, model, config);
// On the bed, not at its corner: organic tree support clips its branches to
// the bed outline, and the fixture leaves the object at the origin.
model.objects.front()->instances.front()->set_offset(Vec3d(100., 100., 0.));
print.apply(model, config);
print.set_status_silent();
print.process();
const PrintObject &object = *print.objects().front();
REQUIRE(! object.layers().empty());
// The whole part is sliced: the layers lean at 45 deg, so the part spans
// (y + z) / sqrt(2) of slicing Z, and every layer in that span has geometry.
{
double lo = std::numeric_limits<double>::max(), hi = std::numeric_limits<double>::lowest();
for (const stl_vertex &v : mesh.its.vertices) {
lo = std::min<double>(lo, v.y() + v.z());
hi = std::max<double>(hi, v.y() + v.z());
}
const double span = (hi - lo) / std::sqrt(2.);
size_t nonempty = 0;
for (const Layer *layer : object.layers())
if (! layer->lslices.empty())
++ nonempty;
INFO("non-empty object layers " << nonempty << ", slicing span " << span << " mm");
CHECK(double(nonempty) * 0.2 > span - 0.6);
}
BeltFloorContext floor;
REQUIRE(floor.init(object.slicing_parameters(), print.config()));
// The lowest support layer that prints anything, and the belt floor beneath it.
const SupportLayer *lowest = nullptr;
for (const SupportLayer *layer : object.support_layers())
if (! layer->support_fills.empty() && (lowest == nullptr || layer->print_z < lowest->print_z))
lowest = layer;
REQUIRE(lowest != nullptr);
double floor_under_lowest = std::numeric_limits<double>::max();
for (const ExtrusionEntity *entity : lowest->support_fills.flatten().entities)
for (const Slic3r::Polyline &pl : entity->as_polylines())
for (const Point &pt : pl.points)
floor_under_lowest = std::min(floor_under_lowest, floor.floor_print_z(pt));
// The object's lowest geometry. The slicing frame starts at the lowest
// belt-floor point under the footprint, so the layers below the leading
// tip of the overhang are empty.
double first_object_z = std::numeric_limits<double>::max();
for (const Layer *layer : object.layers())
if (! layer->lslices.empty()) { first_object_z = layer->print_z; break; }
REQUIRE(first_object_z < std::numeric_limits<double>::max());
INFO("lowest support z " << lowest->print_z << ", floor under it " << floor_under_lowest
<< ", first object layer " << first_object_z);
// Well below the object's own lowest layer (the belt under the tip of the fin
// is ~41 mm of slicing Z below the cube's leading edge, which rests on it)...
CHECK(lowest->print_z < first_object_z - 5.);
// ...and resting on the belt: within a few layers of the floor beneath its own lines.
CHECK(lowest->print_z - floor_under_lowest < 4. * 0.2 + EPSILON);
CHECK(lowest->print_z - floor_under_lowest > -0.2 - EPSILON);
}
}
TEST_CASE("The build height check counts the Z shrinkage compensation once", "[Print][validate][Regression]")
{
// printable_height is 100 mm and Z shrinks to 95 %, so the object is sliced 100 / 95 times taller.
// 92 mm become about 96.8 mm and fit; 97 mm become about 102.1 mm and only the compensation makes them too tall; 101 mm are too tall on their own.
const auto [height, expected] = GENERATE(table<double, std::string>({
{ 92., "" },
{ 97., "because of material shrinkage compensation" },
{ 101., "exceeds the maximum build volume height." },
}));
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "printable_height", 100. },
{ "filament_shrinkage_compensation_z", "95%" },
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "layer_change_gcode", "G92 E0\n" }, // validate() relative-E reset
});
Print print;
Model model;
init_print({ make_cube(20., 20., height) }, print, model, config);
const std::string error = print.validate().string;
INFO(error);
if (expected.empty())
CHECK(error.empty());
else
CHECK(error.find(expected) != std::string::npos);
}
TEST_CASE("The build height check counts the raft", "[Print][validate][Regression]")
{
// printable_height is 100 mm; three raft layers lift the object by 0.9 mm.
const auto [height, fits] = GENERATE(table<double, bool>({ { 98.8, true }, { 99.8, false } }));
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "printable_height", 100. },
{ "raft_layers", 3 },
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "layer_change_gcode", "G92 E0\n" }, // validate() relative-E reset
});
Print print;
Model model;
init_print({ make_cube(20., 20., height) }, print, model, config);
const SlicingParameters &slicing_params = print.objects().front()->slicing_parameters();
REQUIRE_THAT(slicing_params.object_print_z_min, Catch::Matchers::WithinAbs(0.9, EPSILON));
const std::string error = print.validate().string;
INFO(error);
if (fits)
CHECK(error.empty());
else
CHECK(error.find("maximum build volume height") != std::string::npos);
}
TEST_CASE("Filament shrinkage compensation scales the sliced object", "[Print][Regression]")
{
// A 20 mm cube printed with a filament that shrinks to xy % / z % is sliced 20 * 100 / xy wide and,
// up to one layer, 20 * 100 / z tall.
const auto [xy, z] = GENERATE(table<double, double>({ { 100., 100. }, { 90., 100. }, { 100., 95. } }));
const double layer_height = 0.2;
Print print;
init_and_process_print({ cube(20.) }, print, {
{ "filament_shrink", xy },
{ "filament_shrinkage_compensation_z", z },
{ "layer_height", layer_height },
{ "initial_layer_print_height", layer_height },
{ "precise_z_height", false },
{ "raft_layers", 0 },
{ "xy_contour_compensation", 0. },
});
const PrintObject &object = *print.objects().front();
const Layer &middle = *object.get_layer(int(object.layer_count() / 2));
const BoundingBox extents = get_extents(middle.lslices);
CHECK_THAT(unscale<double>(extents.size().x()), Catch::Matchers::WithinAbs(20. * 100. / xy, 0.01));
CHECK_THAT(unscale<double>(extents.size().y()), Catch::Matchers::WithinAbs(20. * 100. / xy, 0.01));
CHECK_THAT(object.layers().back()->print_z, Catch::Matchers::WithinAbs(20. * 100. / z, layer_height));
}
TEST_CASE("Filament shrinkage compensation follows the filaments the object prints with", "[Print][Regression]")
{
// Filament 1 shrinks to 90 %, filament 2 not at all. An unused filament does not matter; two used filaments
// that disagree switch the compensation off and validate() warns about it.
const auto [wall_filament, expected_width] = GENERATE(table<int, double>({ { 1, 20. * 100. / 90. }, { 2, 20. } }));
Print print;
init_and_process_print({ cube(20.) }, print, multifilament_config(2, {
{ "filament_shrink", "90%,100%" },
{ "outer_wall_filament_id", wall_filament },
{ "inner_wall_filament_id", wall_filament },
{ "xy_contour_compensation", 0. },
{ "layer_change_gcode", "G92 E0\n" }, // validate() relative-E reset
}));
const PrintObject &object = *print.objects().front();
const BoundingBox extents = get_extents(object.get_layer(int(object.layer_count() / 2))->lslices);
CHECK_THAT(unscale<double>(extents.size().x()), Catch::Matchers::WithinAbs(expected_width, 0.01));
std::vector<StringObjectException> warnings;
CHECK(print.validate(&warnings).string.empty());
const bool mismatch_warning = std::any_of(warnings.begin(), warnings.end(), [](const StringObjectException &w) {
return w.string.find("Filament shrinkage will not be used") != std::string::npos;
});
CHECK(mismatch_warning == (wall_filament == 2));
}
TEST_CASE("Applying the same model again keeps the filament shrinkage compensation", "[Print][Regression]")
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({ { "filament_shrink", "90%" }, { "xy_contour_compensation", 0. } });
Print print;
Model model;
init_print({ cube(20.) }, print, model, config);
const auto width = [&print]() {
print.process();
const PrintObject &object = *print.objects().front();
return unscale<double>(get_extents(object.get_layer(int(object.layer_count() / 2))->lslices).size().x());
};
CHECK_THAT(width(), Catch::Matchers::WithinAbs(20. * 100. / 90., 0.01));
print.apply(model, config);
CHECK_THAT(width(), Catch::Matchers::WithinAbs(20. * 100. / 90., 0.01));
}
TEST_CASE("Height ranges and modifiers count for the filament shrinkage compensation", "[Print][Regression]")
{
// The model is complete before the first apply(), so no PrintRegion tells yet which filaments print.
enum class Setup { RangeWall, ModifierInfill, ModifierInheritingObjectFilament };
const Setup setup = GENERATE(Setup::RangeWall, Setup::ModifierInfill, Setup::ModifierInheritingObjectFilament);
// The object prints with the filament that shrinks to 90 %, the other one does not shrink.
const bool object_on_filament_2 = setup == Setup::ModifierInheritingObjectFilament;
DynamicPrintConfig config = multifilament_config(2, {
{ "filament_shrink", object_on_filament_2 ? "100%,90%" : "90%,100%" },
{ "xy_contour_compensation", 0. },
{ "layer_change_gcode", "G92 E0\n" }, // validate() relative-E reset
});
Model model;
ModelObject *object = model.add_object();
object->add_volume(cube(20.));
DynamicPrintConfig override;
switch (setup) {
case Setup::RangeWall:
// The walls of a height range print with the other filament.
override.set_key_value("outer_wall_filament_id", new ConfigOptionInt(2));
// Every layer range must carry a layer_height (see layer_height_profile_from_ranges).
override.set_key_value("layer_height", new ConfigOptionFloat(0.2));
object->layer_config_ranges[{ 5., 10. }].assign_config(std::move(override));
break;
case Setup::ModifierInfill:
// The infill inside a modifier prints with the other filament.
override.set_key_value("sparse_infill_filament_id", new ConfigOptionInt(2));
object->add_volume(cube(10.), ModelVolumeType::PARAMETER_MODIFIER, false)->config.apply(override);
break;
case Setup::ModifierInheritingObjectFilament:
// The modifier only changes the infill density and keeps printing with the filament of the object.
object->config.set_key_value("extruder", new ConfigOptionInt(2));
override.set_key_value("sparse_infill_density", new ConfigOptionPercent(30));
object->add_volume(cube(10.), ModelVolumeType::PARAMETER_MODIFIER, false)->config.apply(override);
break;
}
object->add_instance()->set_offset(Vec3d(90., 90., 0.));
object->ensure_on_bed();
Print print;
print.apply(model, config);
print.process();
const PrintObject &print_object = *print.objects().front();
const BoundingBox extents = get_extents(print_object.get_layer(int(print_object.layer_count() / 2))->lslices);
const double expected_width = object_on_filament_2 ? 20. * 100. / 90. : 20.;
CHECK_THAT(unscale<double>(extents.size().x()), Catch::Matchers::WithinAbs(expected_width, 0.01));
std::vector<StringObjectException> warnings;
CHECK(print.validate(&warnings).string.empty());
const bool mismatch_warning = std::any_of(warnings.begin(), warnings.end(), [](const StringObjectException &w) {
return w.string.find("Filament shrinkage will not be used") != std::string::npos;
});
CHECK(mismatch_warning == ! object_on_filament_2);
}
TEST_CASE("Changing G-code precision invalidates only G-code export", "[Print][Regression]")
{
const std::string key = "high_precision_gcode";
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict(key, "0");
Print print;
Model model;
init_print({cube(2.0)}, print, model, config);
print.process();
print.set_gcode_file_ready();
// A key that Print::invalidate_state_by_config_options() does not list invalidates every print step,
// so the wipe tower and the skirt tell it apart from a key that invalidates only the G-code export.
REQUIRE(print.is_step_done(psGCodeExport));
REQUIRE(print.is_step_done(psWipeTower));
REQUIRE(print.is_step_done(psSkirtBrim));
REQUIRE(print.objects().front()->is_step_done(posSlice));
REQUIRE(print.objects().front()->is_step_done(posPerimeters));
config.set_deserialize_strict(key, "1");
print.apply(model, config);
CHECK_FALSE(print.is_step_done(psGCodeExport));
CHECK(print.is_step_done(psWipeTower));
CHECK(print.is_step_done(psSkirtBrim));
CHECK(print.objects().front()->is_step_done(posSlice));
CHECK(print.objects().front()->is_step_done(posPerimeters));
}
namespace {
// A plate printed by layer with the prime tower on and both filaments loaded. The tower stands in a corner
// of the 200 mm bed, far from where the objects are placed.
DynamicPrintConfig prime_tower_config(std::initializer_list<Slic3r::ConfigBase::SetDeserializeItem> extra = {})
{
DynamicPrintConfig config = multifilament_config(2, {
{ "enable_prime_tower", 1 },
{ "printable_area", "0x0,200x0,200x200,0x200" },
{ "wipe_tower_x", 160 },
{ "wipe_tower_y", 160 },
{ "prime_tower_width", 20 },
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "skirt_loops", 0 },
{ "brim_type", "no_brim" },
{ "layer_change_gcode", "G92 E0\n" }, // validate() relative-E reset
});
config.set_deserialize_strict(extra);
return config;
}
// Support on filament 1 with its interface on filament 2, for the objects that need any.
const std::initializer_list<Slic3r::ConfigBase::SetDeserializeItem> support_interface_on_filament_2 = {
{ "enable_support", 1 },
{ "support_type", "normal(auto)" },
{ "support_threshold_angle", 30 },
{ "support_filament", 1 },
{ "support_interface_filament", 2 },
};
ModelObject *add_object(Model &model, TriangleMesh &&mesh, double x, double y)
{
ModelObject *object = model.add_object();
object->add_volume(std::move(mesh));
object->add_instance()->set_offset(Vec3d(x, y, 0.));
object->ensure_on_bed();
return object;
}
// Slices the lower half of a 20 mm cube at 0.1 mm, so that it shares none of its layers there with an
// object sliced at 0.2 mm.
void slice_lower_half_finer(ModelObject &object)
{
DynamicPrintConfig range;
range.set_key_value("layer_height", new ConfigOptionFloat(0.1));
object.layer_config_ranges[{ 0., 10. }].assign_config(std::move(range));
}
void print_upper_part_with_filament_2(ModelObject &object, double from_z, double to_z)
{
DynamicPrintConfig range;
range.set_key_value("extruder", new ConfigOptionInt(2));
// Every layer range must carry a layer_height (see layer_height_profile_from_ranges).
range.set_key_value("layer_height", new ConfigOptionFloat(0.2));
object.layer_config_ranges[{ from_z, to_z }].assign_config(std::move(range));
}
// The slicing parameters of an object printed with one filament, on a printer whose first extruder
// allows layers up to 0.32 mm and the second one up to 0.28 mm. The layers are 0.2 mm, within both.
SlicingParameters slicing_parameters_on_filament(unsigned int filament)
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "nozzle_diameter", "0.4,0.4" },
{ "min_layer_height", "0.08,0.08" },
{ "max_layer_height", "0.32,0.28" },
{ "layer_height", 0.2 },
{ "enable_support", 0 },
{ "raft_layers", 0 },
});
PrintConfig print_config;
PrintObjectConfig object_config;
print_config.apply(config, true);
object_config.apply(config, true);
// The extruders of an object are 0-based.
return SlicingParameters::create_from_config(print_config, object_config, 20., { filament - 1 }, Vec3d(1., 1., 1.));
}
} // namespace
// The parts use one filament and only their support would use the other, so the plate changes filaments
// only if slicing generates support. Without any, no tower is printed, and the objects need not share
// their layers.
TEST_CASE("A plate is sliced with objects that do not share their layers when no support changes filaments", "[Print][PrimeTower]")
{
Model model;
slice_lower_half_finer(*add_object(model, cube(20), 20., 20.));
add_object(model, cube(20), 60., 20.);
Print print;
print.apply(model, prime_tower_config(support_interface_on_filament_2));
CHECK(print.validate().string.empty());
REQUIRE_NOTHROW(print.process());
CHECK(print.wipe_tower_data().tool_changes.empty());
}
TEST_CASE("Objects that do not share their layers are refused once their support changes filaments", "[Print][PrimeTower]")
{
Model model;
slice_lower_half_finer(*add_object(model, cube(20), 20., 20.));
TriangleMesh overhang = mesh(TestMesh::overhang);
overhang.scale(2.f);
add_object(model, std::move(overhang), 60., 20.);
Print print;
print.apply(model, prime_tower_config(support_interface_on_filament_2));
// Before slicing it is not known whether the overhang gets support.
CHECK(print.validate().string.empty());
REQUIRE_THROWS_WITH(print.process(), Catch::Matchers::ContainsSubstring("prime tower"));
}
TEST_CASE("Objects that do not share their layers are refused before slicing when their parts use two filaments", "[Print][PrimeTower]")
{
Model model;
slice_lower_half_finer(*add_object(model, cube(20), 20., 20.));
add_object(model, cube(20), 60., 20.)->config.set_key_value("extruder", new ConfigOptionInt(2));
Print print;
print.apply(model, prime_tower_config());
CHECK_THAT(print.validate().string, Catch::Matchers::ContainsSubstring("prime tower"));
}
// "No sparse layers" refuses an object that rises too far above the compacted tower. Away from the
// toolhead that limit is the lid clearance above the tower, which slicing alone tells how tall it is.
TEST_CASE("No sparse layers lets an object away from the tower rise past the lid clearance when the tower keeps up", "[Print][PrimeTower]")
{
Model model;
// A tool change on every layer, so the compacted tower is as tall as the objects.
add_object(model, make_cube(20., 20., 40.), 20., 20.);
add_object(model, make_cube(20., 20., 40.), 60., 20.)->config.set_key_value("extruder", new ConfigOptionInt(2));
Print print;
print.apply(model, prime_tower_config({
{ "wipe_tower_no_sparse_layers", 1 },
{ "extruder_clearance_height_to_lid", 20 },
{ "extruder_clearance_height_to_rod", 20 },
}));
CHECK(print.validate().string.empty());
REQUIRE_NOTHROW(print.process());
CHECK_FALSE(print.wipe_tower_data().tool_changes.empty());
}
TEST_CASE("No sparse layers still refuses an object that rises past the lid clearance above the tower", "[Print][PrimeTower]")
{
Model model;
// The filament only changes from 30 mm up, by when the compacted tower is still a few layers tall.
print_upper_part_with_filament_2(*add_object(model, make_cube(20., 20., 40.), 20., 20.), 30., 40.);
Print print;
print.apply(model, prime_tower_config({
{ "wipe_tower_no_sparse_layers", 1 },
{ "extruder_clearance_height_to_lid", 20 },
{ "extruder_clearance_height_to_rod", 20 },
}));
CHECK(print.validate().string.empty());
REQUIRE_THROWS_WITH(print.process(), Catch::Matchers::ContainsSubstring("No sparse layers"));
}
// Only the layers below an object's top count toward its rise above the compacted tower, and a raft lifts that
// top. The 20 mm cube shares the tower's Y band and may rise 20 mm above it. The tower starts on the first layer
// above 19.6 mm, where the taller object's second part changes filament, and keeps pace from there, so without a
// raft the cube rises 19.6 mm at most. The raft lifts the cube's top with every layer, and it is refused.
TEST_CASE("No sparse layers counts a raft toward an object's rise above the compacted tower", "[Print][PrimeTower]")
{
const bool raft = GENERATE(false, true);
Model model;
add_object(model, make_cube(20., 20., 20.), 20., 140.);
ModelObject *tall = add_object(model, make_cube(20., 20., 19.6), 60., 20.);
TriangleMesh upper = make_cube(20., 20., 20.4);
upper.translate(0.f, 0.f, 19.6f);
tall->add_volume(std::move(upper))->config.set_key_value("extruder", new ConfigOptionInt(2));
Print print;
print.apply(model, prime_tower_config({
{ "wipe_tower_no_sparse_layers", 1 },
{ "wipe_tower_x", 120 }, // with its rib wall the tower is over 40 mm across
{ "wipe_tower_y", 140 },
{ "extruder_clearance_height_to_lid", 30 }, // the taller cube, away from the rod's band, rises as much
{ "extruder_clearance_height_to_rod", 20 },
{ "raft_layers", raft ? 3 : 0 },
}));
REQUIRE((print.objects().front()->slicing_parameters().object_print_z_min > 0.4) == raft);
const std::string error = print.validate().string;
INFO(error);
CHECK(error.empty());
if (raft)
REQUIRE_THROWS_WITH(print.process(), Catch::Matchers::ContainsSubstring("No sparse layers"));
else
REQUIRE_NOTHROW(print.process());
}
// Within the toolhead radius of the tower the head body limits an object to nozzle_height, however tall the tower
// grows, so validate() refuses it before slicing.
TEST_CASE("No sparse layers refuses before slicing an object that rises within the toolhead radius of the tower", "[Print][PrimeTower]")
{
Model model;
// 10 mm from the tower in X and in Y, within the 40 mm toolhead radius, and taller than the 2.5 mm nozzle cone.
add_object(model, make_cube(10., 10., 10.), 140., 140.);
add_object(model, make_cube(20., 20., 10.), 20., 20.)->config.set_key_value("extruder", new ConfigOptionInt(2));
Print print;
print.apply(model, prime_tower_config({ { "wipe_tower_no_sparse_layers", 1 } }));
CHECK_THAT(print.validate().string, Catch::Matchers::ContainsSubstring("No sparse layers"));
}
// The head body passes over an object that stays below nozzle_height however close to the tower it stands. A
// raft lifts a 2 mm slab past the 2.5 mm nozzle_height, so the same slab within the toolhead radius is refused
// before slicing once it stands on one.
TEST_CASE("No sparse layers counts a raft toward whether an object near the tower is short", "[Print][PrimeTower]")
{
const bool raft = GENERATE(false, true);
Model model;
add_object(model, make_cube(10., 10., 2.), 140., 140.); // 10 mm from the tower in X and in Y
add_object(model, make_cube(20., 20., 10.), 20., 20.)->config.set_key_value("extruder", new ConfigOptionInt(2));
Print print;
print.apply(model, prime_tower_config({
{ "wipe_tower_no_sparse_layers", 1 },
{ "nozzle_height", 2.5 },
{ "raft_layers", raft ? 3 : 0 },
}));
REQUIRE((2. + print.objects().front()->slicing_parameters().object_print_z_min > 2.5) == raft);
const std::string error = print.validate().string;
INFO(error);
if (raft)
CHECK(error.find("No sparse layers") != std::string::npos);
else
CHECK(error.empty());
}
TEST_CASE("An object takes the layer height limits of the extruder of its own filament", "[Print]")
{
CHECK_THAT(slicing_parameters_on_filament(1).max_layer_height, Catch::Matchers::WithinAbs(0.32, EPSILON));
CHECK_THAT(slicing_parameters_on_filament(2).max_layer_height, Catch::Matchers::WithinAbs(0.28, EPSILON));
}
// The limits only bound a variable layer height, so with fixed 0.2 mm layers both objects share every layer.
TEST_CASE("Objects on extruders with different layer height limits can share a prime tower", "[Print]")
{
DynamicPrintConfig config = multifilament_config(3);
config.set_num_extruders(3);
config.set_deserialize_strict({
{ "nozzle_diameter", "0.4,0.4,0.4" },
{ "min_layer_height", "0.08,0.08,0.08" },
{ "max_layer_height", "0.32,0.28,0.28" },
{ "layer_height", 0.2 },
{ "enable_prime_tower", 1 },
{ "wipe_tower_x", 150 }, // the default Y is off the default bed
{ "wipe_tower_y", 20 },
{ "layer_change_gcode", "G92 E0\n" }, // validate() relative-E reset
});
size_flush_to_nozzles(config);
const std::vector<std::vector<Slic3r::ConfigBase::SetDeserializeItem>> overrides { { { "extruder", 1 } }, { { "extruder", 3 } } };
Print print;
Model model;
init_print(std::vector<TriangleMesh>{ cube(20), cube(20) }, print, model, config, &overrides);
const StringObjectException error = print.validate();
INFO(error.string);
CHECK(error.string.empty());
}
TEST_CASE("Belt printers apply the Z shrinkage compensation to the slicing height once", "[Print][belt][Regression]")
{
// A 20 mm cube printed with a filament that shrinks to xy % / z % is sliced like an uncompensated box
// 20 * 100 / xy wide and 20 * 100 / z tall. The span of the layers is compared, as the belt Z offset
// depends on where the object is centred.
const auto [xy, z, angle] = GENERATE(table<double, double, double>({ { 100., 95., 45. }, { 100., 105., 45. }, { 90., 95., 45. }, { 100., 105., 0. } }));
const auto sliced_height = [](const TriangleMesh &mesh, double xy, double z, double angle) {
DynamicPrintConfig config = belt_test_config();
config.set_deserialize_strict({ { "filament_shrink", xy }, { "filament_shrinkage_compensation_z", z }, { "belt_slice_rotation_angle", angle } });
Print print;
init_and_process_print({ mesh }, print, config);
const PrintObject &object = *print.objects().front();
return std::make_pair(object.slicing_parameters().object_print_z_max,
object.layers().back()->print_z - object.layers().front()->print_z);
};
const auto [compensated_max_z, compensated_span] = sliced_height(cube(20.), xy, z, angle);
const auto [expected_max_z, expected_span] = sliced_height(make_cube(20. * 100. / xy, 20. * 100. / xy, 20. * 100. / z), 100., 100., angle);
CHECK_THAT(compensated_max_z, Catch::Matchers::WithinAbs(expected_max_z, EPSILON));
CHECK_THAT(compensated_span, Catch::Matchers::WithinAbs(expected_span, 0.2 * 100. / z));
}
TEST_CASE("The belt build height check uses the compensated height", "[Print][belt][validate][Regression]")
{
// printable_height is 100 mm. Z shrinkage 105 % prints 101 mm at about 96.2 mm, which fits, and 106 mm at
// about 101 mm, which does not; with 95 % a 97 mm object only becomes too tall through the compensation.
const auto [z, height, expected] = GENERATE(table<double, double, std::string>({
{ 105., 101., "" },
{ 105., 106., "exceeds the maximum build volume height." },
{ 95., 92., "" },
{ 95., 97., "because of material shrinkage compensation" },
}));
DynamicPrintConfig config = belt_test_config();
config.set_deserialize_strict({ { "printable_height", 100. }, { "filament_shrinkage_compensation_z", z } });
Print print;
Model model;
init_print({ make_cube(20., 20., height) }, print, model, config);
const std::string error = print.validate().string;
INFO(error);
if (expected.empty())
CHECK(error.empty());
else
CHECK(error.find(expected) != std::string::npos);
}
// A 20 mm cube on the bed with a height range override.
static ModelObject* cube_with_height_range(Model &model, const t_layer_height_range &range, DynamicPrintConfig &&range_config)
{
ModelObject *object = model.add_object();
object->add_volume(cube(20.));
// Every layer range must carry a layer_height (see layer_height_profile_from_ranges).
object->layer_config_ranges[range].assign_config(std::move(range_config));
object->add_instance()->set_offset(Vec3d(90., 90., 0.));
object->ensure_on_bed();
return object;
}
static DynamicPrintConfig height_range_test_config(double shrinkage_z)
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "filament_shrinkage_compensation_z", shrinkage_z },
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "precise_z_height", false },
{ "sparse_infill_density", "15%" },
});
return config;
}
// The 0.1 mm / 50 % height range [10, 15] has to print both its layer height and its infill from 10 * 100 / z
// up to 15 * 100 / z of the object.
static void check_thin_dense_height_range(const PrintObject &print_object, double shrinkage_z)
{
size_t mismatched = 0;
double first_dense_z = -1.;
for (const Layer *layer : print_object.layers()) {
const bool thin = layer->height < 0.15;
const bool dense = std::any_of(layer->regions().begin(), layer->regions().end(), [](const LayerRegion *region) {
return ! region->slices.empty() && region->region().config().sparse_infill_density.value > 40.;
});
if (thin != dense)
++ mismatched;
if (dense && first_dense_z < 0.)
first_dense_z = layer->slice_z;
}
CHECK(mismatched == 0);
CHECK_THAT(first_dense_z, Catch::Matchers::WithinAbs(10. * 100. / shrinkage_z, 0.2));
}
static DynamicPrintConfig thin_dense_height_range()
{
DynamicPrintConfig range;
range.set_key_value("layer_height", new ConfigOptionFloat(0.1));
range.set_key_value("sparse_infill_density", new ConfigOptionPercent(50));
return range;
}
TEST_CASE("A height range above the object keeps its layer height up to the compensated top", "[Print][Regression]")
{
// The range [10, 100] covers the top of the 20 mm cube, which the Z shrinkage compensation moves to 20 * 100 / z.
const double z = GENERATE(95., 105.);
DynamicPrintConfig range;
range.set_key_value("layer_height", new ConfigOptionFloat(0.1));
Model model;
cube_with_height_range(model, { 10., 100. }, std::move(range));
Print print;
print.apply(model, height_range_test_config(z));
print.process();
const PrintObject &print_object = *print.objects().front();
CHECK_THAT(print_object.layers().back()->print_z, Catch::Matchers::WithinAbs(20. * 100. / z, 0.1));
const size_t thick_layers_in_range = std::count_if(print_object.layers().begin(), print_object.layers().end(),
[z](const Layer *layer) { return layer->slice_z > 11. * 100. / z && layer->height > 0.15; });
CHECK(thick_layers_in_range == 0);
}
TEST_CASE("Height range settings apply where the height range prints", "[Print][Regression]")
{
// The range [10, 15] prints with 0.1 mm layers and 50 % infill. The Z shrinkage compensation moves both
// to 10 * 100 / z ... 15 * 100 / z.
const double z = GENERATE(100., 95., 105.);
Model model;
cube_with_height_range(model, { 10., 15. }, thin_dense_height_range());
Print print;
print.apply(model, height_range_test_config(z));
print.process();
check_thin_dense_height_range(*print.objects().front(), z);
}
TEST_CASE("Height range settings follow a Z shrinkage change that comes with a modifier change", "[Print][Regression]")
{
// Adding a modifier lets Print::apply() reuse the cached regions; the cached height ranges were
// compensated for the old Z shrinkage.
Model model;
ModelObject *object = cube_with_height_range(model, { 10., 15. }, thin_dense_height_range());
Print print;
print.apply(model, height_range_test_config(100.));
print.process();
DynamicPrintConfig modifier_config;
modifier_config.set_key_value("wall_loops", new ConfigOptionInt(3));
object->add_volume(cube(5.), ModelVolumeType::PARAMETER_MODIFIER, false)->config.apply(modifier_config);
print.apply(model, height_range_test_config(95.));
print.process();
check_thin_dense_height_range(*print.objects().front(), 95.);
}
namespace {
// Four distinct objects: they run each slicing step together.
std::vector<TriangleMesh> distinct_objects()
{
std::vector<TriangleMesh> meshes;
for (TestMesh m : { TestMesh::cube_with_hole, TestMesh::pyramid, TestMesh::sphere_50mm, TestMesh::overhang })
meshes.emplace_back(Test::mesh(m));
return meshes;
}
// The moves of a G-code, without the export time in the header or the configuration block. The block also lists the
// filament maps slicing writes back, which the GUI passes to the next apply() and these tests do not.
std::string toolpaths(const std::string &gcode)
{
std::istringstream in(gcode);
std::string out, line;
bool config = false;
while (std::getline(in, line)) {
if (line.rfind("; CONFIG_BLOCK_START", 0) == 0)
config = true;
else if (line.rfind("; CONFIG_BLOCK_END", 0) == 0)
config = false;
else if (! config && line.rfind("; generated by", 0) != 0)
out += line + '\n';
}
return out;
}
std::string fresh_slice_toolpaths(const DynamicPrintConfig &config)
{
Print print;
Model model;
Test::init_print(distinct_objects(), print, model, config);
return toolpaths(Test::gcode(print));
}
// Copies of a model of a cube with a hole, one at each scale, sliced together. Each scale gets a PrintObject of its
// own, all of them made from the one ModelObject. With `only` set, the other copies stay in the model but do not
// print, so that copy's PrintObject is the only one and keeps the coordinates it has among the others.
void slice_copies_at_scales(const std::vector<double> &scales, const DynamicPrintConfig &config, Model &model, Print &print,
std::optional<size_t> only = std::nullopt)
{
ModelObject *object = model.add_object();
object->add_volume(Test::mesh(TestMesh::cube_with_hole));
for (size_t i = 0; i < scales.size(); ++ i) {
ModelInstance *instance = object->add_instance();
instance->set_scaling_factor(Vec3d(scales[i], scales[i], scales[i]));
instance->set_offset(Vec3d(40. + 30. * double(i), 100., 0.));
instance->printable = ! only || *only == i;
}
object->ensure_on_bed();
print.auto_assign_extruders(object);
print.apply(model, config);
print.set_status_silent();
print.process();
}
// The perimeters and the infill of every layer of a PrintObject, in its own coordinates.
std::string layer_extrusions(const PrintObject &object)
{
std::ostringstream out;
for (const Layer *layer : object.layers()) {
out << "layer " << layer->print_z << '\n';
for (const LayerRegion *layerm : layer->regions())
for (const ExtrusionEntityCollection *extrusions : { &layerm->perimeters, &layerm->fills })
for (const ExtrusionEntity *extrusion : extrusions->flatten().entities) {
for (const Point &point : extrusion->as_polyline().points)
out << point.x() << ',' << point.y() << ' ';
out << '\n';
}
}
return out.str();
}
// The project of an Assembly crash report: one object of a 27 mm cube and a cylinder of the same size lying along X,
// in an instance scaled 2x along X, on the bed.
ModelObject *add_cube_and_lying_cylinder(Model &model)
{
ModelObject *object = model.add_object();
object->add_volume(cube(27.))->set_offset(Vec3d(0., 18., 0.));
ModelVolume *cylinder = object->add_volume(make_cylinder(13.5, 27.));
cylinder->set_rotation(Vec3d(0., 0.5 * PI, 0.));
cylinder->set_offset(Vec3d(0., -18., 0.));
ModelInstance *instance = object->add_instance();
instance->set_scaling_factor(Vec3d(2., 1., 1.));
instance->set_offset(Vec3d(100., 100., 13.5));
return object;
}
// The Assembly tool's Parallel with the cube's top face picked first and an end face of the cylinder second, which
// GLGizmoMeasure::set_to_parallel() does by turning the cylinder until that end face points down.
// - Turning its whole world transformation about its origin, as set_to_parallel() does now, keeps the cylinder round
// and 54 mm long. It stands about its centre, 13.5 mm above the bed, so 13.5 mm of it goes below the bed.
// - Setting its rotation only, as the crash build's set_to_parallel() did, lets the instance's scaling stretch it
// along X instead: it stands 27 mm tall on the bed, an ellipse twice as wide as it is deep.
void turn_cylinder_end_face_down(ModelObject &object, const Vec3d &end_face_normal, bool whole_transformation)
{
ModelVolume &cylinder = *object.volumes.back();
const Transform3d instance = object.instances.front()->get_matrix();
Transform3d world = instance * cylinder.get_matrix();
Vec3d axis;
double angle;
Matrix3d rotation;
Geometry::rotation_from_two_vectors(end_face_normal, -Vec3d::UnitZ(), axis, angle, &rotation);
if (whole_transformation) {
world.linear() = rotation * world.linear().eval();
cylinder.set_transformation(instance.inverse() * world);
} else {
const Transform3d turned = Transform3d(rotation) * Geometry::Transformation(world).get_rotation_matrix();
const Transform3d instance_rotation = object.instances.front()->get_transformation().get_rotation_matrix();
cylinder.set_rotation(Geometry::extract_euler_angles(instance_rotation.inverse() * turned));
}
object.invalidate_bounding_box();
}
// The area of the islands of the lowest layer at or above z, in mm².
double island_area_at(const PrintObject &object, double z)
{
const auto it = std::find_if(object.layers().begin(), object.layers().end(), [z](const Layer *layer) { return layer->print_z >= z; });
REQUIRE(it != object.layers().end());
return area((*it)->lslices) * SCALING_FACTOR * SCALING_FACTOR;
}
// One tray of the device AMS inventory, with the keys build_filament_ams_list() puts in the payload.
DynamicPrintConfig loaded_filament_tray(const std::string &colour, const std::string &type, const std::string &tray_name)
{
DynamicPrintConfig tray;
tray.set_key_value("filament_colour", new ConfigOptionStrings{ colour });
tray.set_key_value("filament_type", new ConfigOptionStrings{ type });
tray.set_key_value("tray_name", new ConfigOptionStrings{ tray_name });
tray.set_key_value("filament_id", new ConfigOptionStrings{ "GFA00" });
tray.set_key_value("filament_is_support", new ConfigOptionBools{ false });
return tray;
}
// Two extruders with one nozzle each, slicing red and green PLA in Convenience (auto for match) mode
// with the prime tower that the grouping step feeds.
DynamicPrintConfig machine_inventory_config()
{
DynamicPrintConfig config = multifilament_config(2, {
{ "printer_technology", "FFF" },
{ "print_sequence", "by layer" },
{ "nozzle_diameter", "0.4,0.4" },
{ "printer_extruder_id", "1,2" },
{ "printer_extruder_variant", "Direct Drive Standard;Direct Drive Standard" },
{ "extruder_printable_height", "0,0" },
{ "single_extruder_multi_material", 0 },
{ "extruder_ams_count", "1#0|4#1;1#0|4#1" },
{ "filament_ids", "GFA00;GFA00" },
{ "filament_map", "1,1" },
{ "filament_map_mode", "Auto For Match" },
{ "enable_prime_tower", 1 },
{ "wipe_tower_type", "type1" },
{ "prime_tower_width", 35 },
{ "wipe_tower_x", "50" },
{ "wipe_tower_y", "50" },
{ "layer_height", "0.3" },
// init_print applies it on top, so re-applying this config has no diff of its own.
{ "gcode_comments", "1" },
});
size_flush_to_nozzles(config);
return config;
}
} // namespace
TEST_CASE("Re-processing several objects after a setting change gives the toolpaths of a fresh slice", "[Print]")
{
// The settings invalidate the perimeters, the infill regions and everything after them, the infill, the ironing,
// or only the G-code export.
const auto [key, before, after] = GENERATE(table<std::string, std::string, std::string>({
{ "wall_loops", "2", "3" },
{ "top_shell_layers", "3", "5" },
{ "sparse_infill_density", "15%", "40%" },
{ "sparse_infill_pattern", "grid", "gyroid" },
{ "ironing_type", "no ironing", "top" },
{ "seam_position", "aligned", "nearest" },
{ "outer_wall_speed", "60", "40" },
}));
INFO(key << ": " << before << " -> " << after);
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
// init_print() turns the G-code comments on, the second apply() has to keep them.
config.set_deserialize_strict({ { "gcode_comments", "1" }, { key, before } });
Print print;
Model model;
Test::init_print(distinct_objects(), print, model, config);
REQUIRE(print.objects().size() == 4);
Test::gcode(print);
config.set_deserialize_strict(key, after);
print.apply(model, config);
const std::string reprocessed = toolpaths(Test::gcode(print));
REQUIRE(! reprocessed.empty());
CHECK(reprocessed == fresh_slice_toolpaths(config));
}
TEST_CASE("Slicing several objects cancelled from another thread and run again gives the toolpaths of a fresh slice", "[Print]")
{
// As the GUI does it: the print is processed on a thread of its own, which the status updates reach from the
// threads processing the objects, and a cancel makes process() throw before the print is processed again.
const int cancel_at_update = GENERATE(1, 3, 6, 9);
INFO("cancelled at status update " << cancel_at_update);
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({ { "gcode_comments", "1" } });
Print print;
Model model;
Test::init_print(distinct_objects(), print, model, config);
REQUIRE(print.objects().size() == 4);
std::atomic<int> updates { 0 };
print.set_status_callback([&print, &updates, cancel_at_update](const PrintBase::SlicingStatus &) {
if (++ updates == cancel_at_update)
print.cancel();
});
bool canceled = false;
bool other_error = false;
std::thread background([&print, &canceled, &other_error] {
try {
print.process();
} catch (const CanceledException &) {
canceled = true;
} catch (...) {
other_error = true;
}
});
background.join();
CHECK(canceled);
CHECK_FALSE(other_error);
print.restart();
const std::string resumed = toolpaths(Test::gcode(print));
REQUIRE(! resumed.empty());
CHECK(resumed == fresh_slice_toolpaths(config));
}
TEST_CASE("Slicing several objects calls the status callback one status at a time", "[Print]")
{
// The objects run their steps concurrently, while a callback such as the command line's appends the warnings
// to a vector of its own.
Print print;
Model model;
Test::init_print(distinct_objects(), print, model, DynamicPrintConfig::full_print_config());
REQUIRE(print.objects().size() == 4);
std::atomic<int> calls { 0 };
std::atomic<int> running { 0 };
std::atomic<bool> overlapped { false };
print.set_status_callback([&calls, &running, &overlapped](const PrintBase::SlicingStatus &) {
++ calls;
if (++ running > 1)
overlapped = true;
// Stay in the callback long enough for the other objects to report meanwhile.
std::this_thread::sleep_for(std::chrono::milliseconds(2));
-- running;
});
print.process();
REQUIRE(calls > 1);
CHECK_FALSE(overlapped);
}
TEST_CASE("Slicing copies of one object at different scales gives each copy the layers it gets alone", "[Print]")
{
// The PrintObjects of the copies share the volumes of their ModelObject and run each slicing step together, while
// a copy that is the only one printing runs its steps by itself.
const std::vector<double> scales { 1., 0.9, 0.8, 0.7 };
const DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
Model model;
Print print;
slice_copies_at_scales(scales, config, model, print);
REQUIRE(print.objects().size() == scales.size());
for (size_t i = 0; i < scales.size(); ++ i) {
const double scale = scales[i];
INFO("scale " << scale);
Model alone_model;
Print alone;
slice_copies_at_scales(scales, config, alone_model, alone, i);
REQUIRE(alone.objects().size() == 1);
const auto copy = std::find_if(print.objects().begin(), print.objects().end(), [scale](const PrintObject *object) {
return std::abs(object->instances().front().model_instance->get_scaling_factor().x() - scale) < EPSILON;
});
REQUIRE(copy != print.objects().end());
// The copy has walls, so the layers compare extrusions and not only their heights.
REQUIRE(std::any_of((*copy)->layers().begin(), (*copy)->layers().end(), [](const Layer *layer) {
return ! layer->regions().empty() && ! layer->regions().front()->perimeters.empty();
}));
CHECK(layer_extrusions(**copy) == layer_extrusions(*alone.objects().front()));
}
}
TEST_CASE("Slicing after the Assembly tool's Parallel turns a part of a scaled object gives the toolpaths of a fresh slice", "[Print]")
{
// The steps of a crash report: Parallel turns the cylinder, and the GUI applies and validates the changed model.
// The GUI processes the print only while the Preview is open, so it may have been processed before or not. The
// crash build set the cylinder's rotation only, and either end face can be the one picked.
const bool whole_transformation = GENERATE(false, true);
const double end_face = GENERATE(1., -1.);
const bool processed_before = GENERATE(false, true);
INFO((whole_transformation ? "whole transformation" : "rotation only") << ", end face normal " << end_face << " * X, "
<< (processed_before ? "processed" : "not processed") << " before");
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "layer_height", "0.2" },
{ "initial_layer_print_height", "0.2" },
// validate() wants the extruder position reset at each layer for the default relative extrusion.
{ "layer_change_gcode", "G92 E0" },
});
Model model;
ModelObject *object = add_cube_and_lying_cylinder(model);
Print print;
print.apply(model, config);
REQUIRE_THAT(print.validate().string, Catch::Matchers::Equals(std::string()));
if (processed_before)
Test::gcode(print);
turn_cylinder_end_face_down(*object, end_face * Vec3d::UnitX(), whole_transformation);
print.apply(model, config);
CHECK_THAT(print.validate().string, Catch::Matchers::Equals(std::string()));
const std::string sliced = toolpaths(Test::gcode(print));
// Only what is above the bed prints. Up to the cube's top at 27 mm, that is its 54 x 27 mm and the cylinder's
// cross-section: the round cylinder's circle of radius 13.5 mm, alone above the cube up to 40.5 mm, or the stretched
// cylinder's ellipse, twice as wide, which ends at 27 mm.
REQUIRE(print.objects().size() == 1);
const PrintObject &print_object = *print.objects().front();
REQUIRE(! print_object.layers().empty());
const double cylinder_area = whole_transformation ? PI * 13.5 * 13.5 : PI * 27. * 13.5;
CHECK_THAT(print_object.layers().back()->print_z, Catch::Matchers::WithinAbs(whole_transformation ? 40.5 : 27., 0.2));
CHECK_THAT(island_area_at(print_object, 13.5), Catch::Matchers::WithinRel(54. * 27. + cylinder_area, 0.01));
if (whole_transformation)
CHECK_THAT(island_area_at(print_object, 34.), Catch::Matchers::WithinRel(cylinder_area, 0.01));
Model fresh_model;
turn_cylinder_end_face_down(*add_cube_and_lying_cylinder(fresh_model), end_face * Vec3d::UnitX(), whole_transformation);
Print fresh;
fresh.apply(fresh_model, config);
REQUIRE(! sliced.empty());
CHECK(sliced == toolpaths(Test::gcode(fresh)));
}
// The AMS inventory is device state that only feeds filament grouping. A changed inventory has to
// invalidate the grouping steps, while the refreshes a connected device keeps sending -- the same
// trays, volatile metadata, or an empty payload while it reconnects -- must not.
TEST_CASE("A changed AMS filament inventory invalidates the grouping steps", "[Print][MultiNozzle][Regression]")
{
DynamicPrintConfig config = machine_inventory_config();
Print print;
Model model;
init_print({ cube(20) }, print, model, config);
// A single-extruder print returns early in grouping, which would make the test vacuous.
REQUIRE(print.config().nozzle_diameter.size() == 2);
print.is_BBL_printer() = true;
print.process();
// invalidate_step() only takes back a step that is done.
REQUIRE(print.is_step_done(psWipeTower));
REQUIRE(print.is_step_done(psSkirtBrim));
const std::vector<std::vector<DynamicPrintConfig>> red_green = {
{ loaded_filament_tray("#FF0000", "PLA", "A1") },
{ loaded_filament_tray("#00FF00", "PLA", "Ext") },
};
// The setter only stashes the payload, apply() installs it.
print.set_extruder_filament_info(red_green);
CHECK(print.get_extruder_filament_info().empty());
// No inventory on the print before this pass means "unknown", not a change.
print.apply(model, config);
REQUIRE(print.get_extruder_filament_info().size() == 2);
// The same inventory sent again must not invalidate, even though the engine wrote its grouping
// result back into the filament maps during process(), which on its own reports a config change.
print.set_extruder_filament_info(red_green);
CHECK(print.apply(model, config) != PrintBase::APPLY_STATUS_INVALIDATED);
// The grouping steps must still be done here, or the invalidation below proves nothing.
REQUIRE(print.is_step_done(psWipeTower));
REQUIRE(print.is_step_done(psSkirtBrim));
// One tray's colour changed and both grouping steps were done, so they are taken back.
std::vector<std::vector<DynamicPrintConfig>> cyan_green = red_green;
cyan_green[0] = { loaded_filament_tray("#00FFFF", "PLA", "A1") };
print.set_extruder_filament_info(cyan_green);
CHECK(print.apply(model, config) == PrintBase::APPLY_STATUS_INVALIDATED);
CHECK_FALSE(print.is_step_done(psWipeTower));
CHECK_FALSE(print.is_step_done(psSkirtBrim));
print.process();
REQUIRE(print.is_step_done(psWipeTower));
// Volatile device metadata: the loaded filaments are unchanged, so nothing is invalidated.
std::vector<std::vector<DynamicPrintConfig>> retagged = cyan_green;
retagged[0][0].set_key_value("filament_changed", new ConfigOptionBool(true));
retagged[0][0].set_key_value("tag_uid", new ConfigOptionStrings{ "A1B2C3D4" });
retagged[0][0].set_key_value("slot_id", new ConfigOptionStrings{ "0" });
print.set_extruder_filament_info(retagged);
CHECK(print.apply(model, config) != PrintBase::APPLY_STATUS_INVALIDATED);
// An empty payload means "inventory unknown" (AMS disconnected): install it, never invalidate.
print.set_extruder_filament_info({});
CHECK(print.apply(model, config) != PrintBase::APPLY_STATUS_INVALIDATED);
CHECK(print.get_extruder_filament_info().empty());
}
TEST_CASE("Print validation warns about crossing sparse infill walls of more than 3 lines", "[Print]")
{
const auto [pattern, strategy, lines, warned] = GENERATE(table<std::string, std::string, int, bool>({
{ "grid", "crossing", 4, true },
{ "adaptivecubic", "crossing", 4, true },
{ "grid", "crossing", 3, false },
{ "grid", "non_crossing", 4, false },
{ "grid", "default", 4, false },
{ "gyroid", "crossing", 4, false } }));
CAPTURE(pattern, strategy, lines);
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({ { "sparse_infill_pattern", pattern },
{ "sparse_infill_strategy", strategy },
{ "fill_multiline", lines },
{ "sparse_infill_density", "20%" } });
std::vector<StringObjectException> warnings;
REQUIRE(validate_cubes(config, warnings).string.empty());
CHECK(count_opt_key(warnings, "sparse_infill_strategy") == (warned ? 1u : 0u));
}