Speed up slicing without changing the G-code of a fresh slice (#17335)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Warren GreenandClaude Opus 5.5 authored and GitHub committed 2026-11-21 10:59:12 -03:00
1 parent 5a1ffc6a63
commit 1174b39004
25 files changed
+1034 -155

No files matched your search

@@ -817,9 +817,18 @@ namespace Clipper2Lib {
std::stable_sort(minima_list_.begin(), minima_list_.end(), LocMinSorter()); //#594
minima_list_sorted_ = true;
}
LocalMinimaList::const_reverse_iterator i;
for (i = minima_list_.rbegin(); i != minima_list_.rend(); ++i)
InsertScanline((*i)->vertex->pt.y);
// Orca: PopScanline() returns each pending y once, however many times it was inserted, so only the
// distinct ys of the local minima are queued. Sorted by descending y they already form a max-heap;
// inserting them one by one in ascending order made every insertion climb to the top of the heap.
std::vector<int64_t> minima_ys;
minima_ys.reserve(minima_list_.size());
for (const LocalMinima_ptr& lm : minima_list_)
if (minima_ys.empty() || minima_ys.back() != lm->vertex->pt.y)
minima_ys.push_back(lm->vertex->pt.y);
if (scanline_list_.empty())
scanline_list_ = std::priority_queue<int64_t>(std::less<int64_t>(), std::move(minima_ys));
else
for (int64_t y : minima_ys) InsertScanline(y);
current_locmin_iter_ = minima_list_.begin();
actives_ = nullptr;
@@ -883,7 +892,9 @@ namespace Clipper2Lib {
void ClipperBase::InsertScanline(int64_t y)
{
scanline_list_.push(y);
// Orca: a y already at the top is popped together with this one anyway.
if (scanline_list_.empty() || scanline_list_.top() != y)
scanline_list_.push(y);
}
+3 -2
View File
@@ -29,10 +29,10 @@ as for predictable geometry.
## Vendored Clipper2
`deps_src/clipper2` builds the static target `Clipper2`. It carries five
`deps_src/clipper2` builds the static target `Clipper2`. It carries six
changes to the upstream sources that must be carried over when Clipper2 is
updated. The namespace switch sits at the top of every header and source, the
other four are marked with `Orca:` comments.
other five are marked with `Orca:` comments.
| Change | Files | Why |
| --- | --- | --- |
@@ -40,6 +40,7 @@ other four are marked with `Orca:` comments.
| Engine nodes from tbbmalloc | `clipper.engine.h`, `clipper.engine.cpp` | Vertices, active edges, output points and records, local minima and `PolyTree` nodes are allocated one by one. `CLIPPER2_NODE_ALLOCATOR` routes them through `scalable_malloc`, because the default heap does not scale when all slicing threads clip at once. |
| Concave joins at the edge crossing | `clipper.offset.cpp` | For closed paths, a concave corner is joined at the crossing of the two offset edges when that point lies within half of both adjacent edges. The upstream 3-point loop makes inward offsets of dense curves very slow to union. |
| Rounded arc steps | `clipper.offset.cpp` | Round joins use the rounded number of steps, not the ceiling, which keeps the vertex count of round offsets that the rest of the code is tuned for. |
| Distinct scan lines | `clipper.engine.cpp` | `Reset()` builds the scan line heap from the distinct y of the local minima in one pass, and `InsertScanline()` skips a y already at the top. Upstream inserts the minima one by one in ascending order, so each climbs to the top of the heap. Scan lines are popped in the same order either way. |
| No intersection sort for edges in order | `clipper.engine.h`, `clipper.engine.cpp` | `AdjustCurrXAndCopyToSEL()` reports whether the active edges kept their order at the top of the scanbeam, and `BuildIntersectList()` returns before its merge sort when they did. Most scanbeams have no crossing, and the sort was a large part of every boolean on dense support layers. |
## ClipperUtils semantics
+81 -46
View File
@@ -10,6 +10,7 @@
#include <algorithm>
#include <cstddef>
#include <cassert>
#include <iterator>
#include <limits>
#include <type_traits>
#include <utility>
@@ -397,51 +398,87 @@ namespace detail {
return eps;
}
template<typename RayIntersectorType, typename Scalar>
static inline bool intersect_ray_recursive_first_hit(
RayIntersectorType &ray_intersector,
size_t node_idx,
Scalar min_t,
igl::Hit<float> &hit)
// ray_box_intersect_invdir() for a ray whose direction signs are known at compile time: NegX etc. tell
// which slabs are entered through the max face. The comparisons select the same entry and exit parameters
// as the early returns of ray_box_intersect_invdir() and give the same answer for any input, NaN included,
// but without the unpredictable branches.
template<bool NegX, bool NegY, bool NegZ, typename Scalar, typename VectorType, typename BoxScalar>
inline bool ray_box_intersect_invdir_signs(
const VectorType &origin,
const VectorType &inv_dir,
const Eigen::AlignedBox<BoxScalar,3> &box,
const Scalar t0,
const Scalar t1)
{
const auto &node = ray_intersector.tree.node(node_idx);
assert(node.is_valid());
if (! ray_box_intersect_invdir(ray_intersector.origin, ray_intersector.invdir, node.bbox.template cast<Scalar>(), Scalar(0), min_t))
return false;
const Scalar tx0 = (Scalar(NegX ? box.max().x() : box.min().x()) - origin.x()) * inv_dir.x();
const Scalar tx1 = (Scalar(NegX ? box.min().x() : box.max().x()) - origin.x()) * inv_dir.x();
const Scalar ty0 = (Scalar(NegY ? box.max().y() : box.min().y()) - origin.y()) * inv_dir.y();
const Scalar ty1 = (Scalar(NegY ? box.min().y() : box.max().y()) - origin.y()) * inv_dir.y();
const Scalar tz0 = (Scalar(NegZ ? box.max().z() : box.min().z()) - origin.z()) * inv_dir.z();
const Scalar tz1 = (Scalar(NegZ ? box.min().z() : box.max().z()) - origin.z()) * inv_dir.z();
const Scalar txy_min = ty0 > tx0 ? ty0 : tx0;
const Scalar txy_max = ty1 < tx1 ? ty1 : tx1;
const Scalar tmin = tz0 > txy_min ? tz0 : txy_min;
const Scalar tmax = tz1 < txy_max ? tz1 : txy_max;
return tmin <= tmax && tmin < t1 && tmax > t0;
}
if (node.is_leaf()) {
// shoot ray, record hit
auto face = ray_intersector.faces[node.idx];
double t, u, v;
if (intersect_triangle(
ray_intersector.origin, ray_intersector.dir,
ray_intersector.vertices[face(0)], ray_intersector.vertices[face(1)], ray_intersector.vertices[face(2)],
t, u, v, ray_intersector.eps)
&& t > 0.) {
hit = igl::Hit<float> { int(node.idx), -1, float(u), float(v), float(t) };
return true;
} else
return false;
} else {
// Left / right child node index.
size_t left = node_idx * 2 + 1;
size_t right = left + 1;
igl::Hit<float> left_hit;
igl::Hit<float> right_hit;
bool left_ret = intersect_ray_recursive_first_hit(ray_intersector, left, min_t, left_hit);
if (left_ret && left_hit.t < min_t) {
min_t = left_hit.t;
hit = left_hit;
} else
left_ret = false;
bool right_ret = intersect_ray_recursive_first_hit(ray_intersector, right, min_t, right_hit);
if (right_ret && right_hit.t < min_t)
hit = right_hit;
else
right_ret = false;
return left_ret || right_ret;
}
// The depth-first, left to right search for the first hit, the nearest hit found so far bounding the ray
// interval tested against the boxes. Iterative, with the ray direction signs resolved at compile time.
template<bool NegX, bool NegY, bool NegZ, typename RayIntersectorType>
static inline bool intersect_ray_first_hit_signs(const RayIntersectorType &ray_intersector, igl::Hit<float> &hit)
{
using Scalar = typename RayIntersectorType::VectorType::Scalar;
const auto &nodes = ray_intersector.tree.nodes();
Scalar min_t = std::numeric_limits<Scalar>::infinity();
bool found = false;
// Nodes waiting for their left sibling's subtree: at most one per level, plus the left sibling itself.
size_t stack[65];
size_t stack_size = 0;
stack[stack_size ++] = 0;
while (stack_size > 0) {
const size_t node_idx = stack[-- stack_size];
const auto &node = nodes[node_idx];
assert(node.is_valid());
if (! ray_box_intersect_invdir_signs<NegX, NegY, NegZ>(ray_intersector.origin, ray_intersector.invdir, node.bbox, Scalar(0), min_t))
continue;
if (node.is_leaf()) {
auto face = ray_intersector.faces[node.idx];
double t, u, v;
// A leaf at the root has no parent to reject a hit beyond min_t.
if (intersect_triangle(
ray_intersector.origin, ray_intersector.dir,
ray_intersector.vertices[face(0)], ray_intersector.vertices[face(1)], ray_intersector.vertices[face(2)],
t, u, v, ray_intersector.eps)
&& t > 0. && (float(t) < min_t || node_idx == 0)) {
hit = igl::Hit<float> { int(node.idx), -1, float(u), float(v), float(t) };
min_t = hit.t;
found = true;
}
} else {
assert(stack_size + 2 <= std::size(stack));
// Push the right child first, so that the left subtree is searched first.
stack[stack_size ++] = node_idx * 2 + 2;
stack[stack_size ++] = node_idx * 2 + 1;
}
}
return found;
}
template<typename RayIntersectorType>
static inline bool intersect_ray_first_hit_dispatch(const RayIntersectorType &ray_intersector, igl::Hit<float> &hit)
{
const auto &inv_dir = ray_intersector.invdir;
switch (int(inv_dir.x() < 0) | (int(inv_dir.y() < 0) << 1) | (int(inv_dir.z() < 0) << 2)) {
case 0: return intersect_ray_first_hit_signs<false, false, false>(ray_intersector, hit);
case 1: return intersect_ray_first_hit_signs<true, false, false>(ray_intersector, hit);
case 2: return intersect_ray_first_hit_signs<false, true, false>(ray_intersector, hit);
case 3: return intersect_ray_first_hit_signs<true, true, false>(ray_intersector, hit);
case 4: return intersect_ray_first_hit_signs<false, false, true >(ray_intersector, hit);
case 5: return intersect_ray_first_hit_signs<true, false, true >(ray_intersector, hit);
case 6: return intersect_ray_first_hit_signs<false, true, true >(ray_intersector, hit);
default: return intersect_ray_first_hit_signs<true, true, true >(ray_intersector, hit);
}
}
template<typename RayIntersectorType>
@@ -741,14 +778,12 @@ inline bool intersect_ray_first_hit(
// Epsilon for the ray-triangle intersection, it should be proportional to an average triangle edge length.
const double eps = 0.000001)
{
using Scalar = typename VectorType::Scalar;
auto ray_intersector = detail::RayIntersector<VertexType, IndexedFaceType, TreeType, VectorType> {
vertices, faces, tree,
origin, dir, VectorType(dir.cwiseInverse()),
eps
};
return ! tree.empty() && detail::intersect_ray_recursive_first_hit(
ray_intersector, size_t(0), std::numeric_limits<Scalar>::infinity(), hit);
return ! tree.empty() && detail::intersect_ray_first_hit_dispatch(ray_intersector, hit);
}
// Find all intersections of a ray with indexed triangle set.
+1
View File
@@ -396,6 +396,7 @@ set(lisbslic3r_sources
Optimize/Optimizer.hpp
Orient.cpp
Orient.hpp
ParallelForFirstError.hpp
ParallelResolve.hpp
ParameterUtils.cpp
ParameterUtils.hpp
+16
View File
@@ -92,6 +92,22 @@ bool ExPolygon::contains(const Polyline &polyline) const
if (!bbox1.overlap(bbox2))
return false;
// A polyline reaching further than SCALED_EPSILON out of the bounding box of all the outlines runs
// outside of them all there, which the difference keeps: no need to compute it. This does not hold for
// a polyline of a single point, which the difference drops.
if (bbox2.min != bbox2.max) {
auto reaches_out = [&bbox2](BoundingBox outlines) {
outlines.offset(SCALED_EPSILON);
return !outlines.contains(bbox2.min) || !outlines.contains(bbox2.max);
};
if (reaches_out(bbox1)) {
for (const Polygon &hole : this->holes)
bbox1.merge(get_extents(hole));
if (reaches_out(bbox1))
return false;
}
}
return diff_pl(polyline, *this).empty();
}
+17 -11
View File
@@ -2854,6 +2854,7 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessorResult* resu
// BBS
m_curr_print = print;
m_overhang_layers_cache.valid = false;
m_skirt_group_done.clear();
m_pending_start_gcode_position.reset();
m_exclusion_volume_travel_avoidance.init(print->config(), print->get_plate_origin());
@@ -10854,12 +10855,22 @@ bool GCode::needs_retraction(const Polyline &travel, ExtrusionRole role, LiftTyp
std::pair<float, float> z_range;
z_range.second = m_layer ? m_layer->print_z : 0.f;
z_range.first = std::max(0.f, z_range.second - protect_z);
std::vector<LayerPtrs> layers_of_objects;
std::vector<BoundingBox> boundingBox_for_objects;
VecOfPoints objects_instances_shift;
std::vector<size_t> idx_of_object_sorted = m_curr_print->layers_sorted_for_object(z_range.first, z_range.second, layers_of_objects, boundingBox_for_objects, objects_instances_shift);
std::vector<bool> is_layers_of_objects_sorted(layers_of_objects.size(), false);
OverhangLayersCache &cache = m_overhang_layers_cache;
if (!cache.valid || cache.z_min != z_range.first || cache.z_max != z_range.second) {
cache.layers_of_objects.clear();
cache.boundingBox_for_objects.clear();
cache.idx_of_object_sorted = m_curr_print->layers_sorted_for_object(z_range.first, z_range.second, cache.layers_of_objects,
cache.boundingBox_for_objects, cache.objects_instances_shift);
for (LayerPtrs &layers : cache.layers_of_objects)
std::sort(layers.begin(), layers.end(), [](auto left, auto right) { return left->loverhangs_bbox.area() > right->loverhangs_bbox.area();});
cache.z_min = z_range.first;
cache.z_max = z_range.second;
cache.valid = true;
}
const std::vector<LayerPtrs> &layers_of_objects = cache.layers_of_objects;
const std::vector<BoundingBox> &boundingBox_for_objects = cache.boundingBox_for_objects;
const VecOfPoints &objects_instances_shift = cache.objects_instances_shift;
const std::vector<size_t> &idx_of_object_sorted = cache.idx_of_object_sorted;
for (size_t idx : idx_of_object_sorted) {
for (const Point & instance_shift : objects_instances_shift[idx]) {
@@ -10877,11 +10888,6 @@ bool GCode::needs_retraction(const Polyline &travel, ExtrusionRole role, LiftTyp
if (intersection_pl(travel, temp).empty())
continue;
if (!is_layers_of_objects_sorted[idx]) {
std::sort(layers_of_objects[idx].begin(), layers_of_objects[idx].end(), [](auto left, auto right) { return left->loverhangs_bbox.area() > right->loverhangs_bbox.area();});
is_layers_of_objects_sorted[idx] = true;
}
for (const auto& layer : layers_of_objects[idx]) {
for (ExPolygon overhang : layer->loverhangs) {
overhang.translate(instance_shift);
+13
View File
@@ -932,6 +932,19 @@ protected:
// BBS
Print* m_curr_print = nullptr;
// The layers of every object below the layer being exported, which needs_retraction() searches for
// overhangs a travel crosses: collected once per z range rather than once per travel.
struct OverhangLayersCache
{
bool valid = false;
float z_min = 0.f;
float z_max = 0.f;
std::vector<size_t> idx_of_object_sorted;
// Of each object, sorted by the area of their overhangs' bounding box, largest first.
std::vector<LayerPtrs> layers_of_objects;
std::vector<BoundingBox> boundingBox_for_objects;
VecOfPoints objects_instances_shift;
} m_overhang_layers_cache;
unsigned int m_toolchange_count;
coordf_t m_nominal_z;
// Mixed-color sublayer state. Non-zero only while emitting a mixed slot's sub-layer:
+18 -11
View File
@@ -18,8 +18,9 @@
#include <tbb/parallel_for.h>
#include <tbb/concurrent_vector.h>
#include <map>
#include <functional>
#include <iterator>
#include <unordered_map>
#include <atomic>
#include <utility>
#include <vector>
@@ -40,9 +41,10 @@ inline IndexPair point_map_grid_index(const Point &pt, int64_t xdist, int64_t yd
inline bool nearly_equal(const Point &p1, const Point &p2) { return std::abs(p1.x() - p2.x()) < SCALED_EPSILON && std::abs(p1.y() - p2.y()) < SCALED_EPSILON; }
inline Grids line_rasterization(const Line &line, int64_t xdist = scale_(1), int64_t ydist = scale_(1))
// The grid cells the line passes through, in order, into res.
inline void line_rasterization(const Line &line, Grids &res, int64_t xdist = scale_(1), int64_t ydist = scale_(1))
{
Grids res;
res.clear();
Point rayStart = line.a;
Point rayEnd = line.b;
IndexPair currentVoxel = point_map_grid_index(rayStart, xdist, ydist);
@@ -99,9 +101,12 @@ inline Grids line_rasterization(const Line &line, int64_t xdist = scale_(1), int
assert(0);
}
}
return res;
}
struct IndexPairHash
{
size_t operator()(const IndexPair &p) const { return std::hash<int64_t>()(p.first) ^ (std::hash<int64_t>()(p.second) * 0x9e3779b97f4a7c15ull); }
};
} // namespace RasterizationImpl
void LinesBucketQueue::emplace_back_bucket(ExtrusionLayers &&els, const void *objPtr, Point offset)
@@ -207,7 +212,7 @@ ObjectExtrusions getAllLayersExtrusionPathsFromObject(PrintObject *obj)
for (auto layerPtr : obj->layers()) {
auto perimeters = getExtrusionPathsFromLayer(layerPtr->regions());
oe.perimeters.insert(oe.perimeters.end(), perimeters.begin(), perimeters.end());
oe.perimeters.insert(oe.perimeters.end(), std::make_move_iterator(perimeters.begin()), std::make_move_iterator(perimeters.end()));
}
for (auto supportLayerPtr : obj->support_layers()) { oe.support.push_back(getExtrusionPathsFromSupportLayer(supportLayerPtr)); }
@@ -218,18 +223,20 @@ ObjectExtrusions getAllLayersExtrusionPathsFromObject(PrintObject *obj)
ConflictComputeOpt ConflictChecker::find_inter_of_lines(const LineWithIDs &lines)
{
using namespace RasterizationImpl;
std::map<IndexPair, std::vector<int>> indexToLine;
// Only looked up, never iterated, so the order of the cells does not matter.
std::unordered_map<IndexPair, std::vector<int>, IndexPairHash> indexToLine;
Grids indexes;
for (int i = 0; i < lines.size(); ++i) {
const LineWithID &l1 = lines[i];
auto indexes = line_rasterization(l1._line);
const LineWithID &l1 = lines[i];
line_rasterization(l1._line, indexes);
for (auto index : indexes) {
const auto &possibleIntersectIdxs = indexToLine[index];
auto &possibleIntersectIdxs = indexToLine[index];
for (auto possibleIntersectIdx : possibleIntersectIdxs) {
const LineWithID &l2 = lines[possibleIntersectIdx];
if (auto interRes = line_intersect(l1, l2); interRes.has_value()) { return interRes; }
}
indexToLine[index].push_back(i);
possibleIntersectIdxs.push_back(i);
}
}
return {};
+1 -1
View File
@@ -71,7 +71,7 @@ public:
Point _offset;
public:
LinesBucket(ExtrusionLayers &&paths, const void* id, Point offset) : _piles(paths), _id(id), _offset(offset) {}
LinesBucket(ExtrusionLayers &&paths, const void* id, Point offset) : _piles(std::move(paths)), _id(id), _offset(offset) {}
LinesBucket(LinesBucket &&) = default;
std::pair<int, int> curRange() const
+55 -29
View File
@@ -11,6 +11,7 @@
#include "libslic3r/PrintBase.hpp"
#include "PrintConfig.hpp"
#include "libslic3r/libslic3r.h"
#include "libslic3r/ParallelForFirstError.hpp"
#include "libslic3r/TriangleMesh.hpp"
#include "libslic3r/TriangleSelector.hpp"
#include "tbb/parallel_for.h"
@@ -390,20 +391,18 @@ struct GlobalModelInfo {
}
float calculate_point_visibility(const Vec3f &position) const {
std::vector<size_t> points = find_nearby_points(mesh_samples_tree, position, mesh_samples_radius);
if (points.empty()) {
return 1.0f;
}
auto compute_dist_to_plane = [](const Vec3f &position, const Vec3f &plane_origin, const Vec3f &plane_normal) {
Vec3f orig_to_point = position - plane_origin;
return std::abs(orig_to_point.dot(plane_normal));
};
// Accumulated in the order find_nearby_points() lists the samples, without collecting them first:
// this runs for every seam candidate.
bool any_sample = false;
float total_weight = 0;
float total_visibility = 0;
for (size_t i = 0; i < points.size(); ++i) {
size_t sample_idx = points[i];
visit_nearby_points(mesh_samples_tree, position, mesh_samples_radius, [&](size_t sample_idx) {
any_sample = true;
Vec3f sample_point = this->mesh_samples.positions[sample_idx];
Vec3f sample_normal = this->mesh_samples.normals[sample_idx];
@@ -412,10 +411,9 @@ struct GlobalModelInfo {
weight += (mesh_samples_radius - (position - sample_point).norm());
total_visibility += weight * mesh_samples_visibility[sample_idx];
total_weight += weight;
}
return total_visibility / total_weight;
});
return any_sample ? total_visibility / total_weight : 1.0f;
}
#ifdef DEBUG_FILES
@@ -1627,7 +1625,7 @@ Vec3f place_on_loop(const std::vector<SeamCandidate> &points, size_t index, cons
void SeamPlacer::gather_seam_candidates(const PrintObject *po, const SeamPlacerImpl::GlobalModelInfo &global_model_info,
PreciseSeam::PreciseSeamWarnings* warnings) {
using namespace SeamPlacerImpl;
PrintObjectSeamData &seam_data = m_seam_per_object.emplace(po, PrintObjectSeamData { }).first->second;
PrintObjectSeamData &seam_data = m_seam_per_object.at(po);
seam_data.layers.resize(po->layer_count());
tbb::parallel_for(tbb::blocked_range<size_t>(0, po->layers().size()),
@@ -1660,7 +1658,7 @@ void SeamPlacer::gather_seam_candidates(const PrintObject *po, const SeamPlacerI
void SeamPlacer::calculate_candidates_visibility(const PrintObject *po,
const SeamPlacerImpl::GlobalModelInfo &global_model_info) {
std::vector<PrintObjectSeamData::LayerSeams> &layers = m_seam_per_object[po].layers;
std::vector<PrintObjectSeamData::LayerSeams> &layers = m_seam_per_object.at(po).layers;
tbb::parallel_for(tbb::blocked_range<size_t>(0, layers.size()),
[&layers, &global_model_info](tbb::blocked_range<size_t> r) {
for (size_t layer_idx = r.begin(); layer_idx < r.end(); ++layer_idx) {
@@ -1676,7 +1674,7 @@ void SeamPlacer::calculate_overhangs_and_layer_embedding(const PrintObject *po)
using namespace SeamPlacerImpl;
using PerimeterDistancer = AABBTreeLines::LinesDistancer<Linef>;
std::vector<PrintObjectSeamData::LayerSeams> &layers = m_seam_per_object[po].layers;
std::vector<PrintObjectSeamData::LayerSeams> &layers = m_seam_per_object.at(po).layers;
tbb::parallel_for(tbb::blocked_range<size_t>(0, layers.size()),
[po, &layers](tbb::blocked_range<size_t> r) {
std::unique_ptr<PerimeterDistancer> prev_layer_distancer;
@@ -1896,7 +1894,7 @@ void SeamPlacer::align_seam_points(const PrintObject *po, const SeamPlacerImpl::
#endif
//gather vector of all seams on the print_object - pair of layer_index and seam__index within that layer
const std::vector<PrintObjectSeamData::LayerSeams> &layers = m_seam_per_object[po].layers;
const std::vector<PrintObjectSeamData::LayerSeams> &layers = m_seam_per_object.at(po).layers;
// Share the largest nozzle diameter between contour bounds and corner protection.
double max_nozzle_diameter = 0.0;
for (double diameter : po->print()->config().nozzle_diameter.values)
@@ -2112,7 +2110,33 @@ void SeamPlacer::init(const Print &print, std::function<void(void)> throw_if_can
// Warning flags for Precise Seam processing — shared across all objects
PreciseSeam::PreciseSeamWarnings precise_seam_warnings;
// The objects get their seams independently of each other, so they are processed concurrently. Their seam data
// and the usage tracking of their Precise Seam modifiers are created first: the objects only look them up.
struct ObjectSeams {
const PrintObject *po;
PrintObjectSeamData *seam_data;
std::vector<const ModelVolume*> precise_seam_strong_volumes;
std::vector<const ModelVolume*> precise_seam_weak_volumes;
};
std::vector<ObjectSeams> objects;
objects.reserve(print.objects().size());
for (const PrintObject *po : print.objects()) {
ObjectSeams &object = objects.emplace_back(ObjectSeams{ po, &m_seam_per_object[po], {}, {} });
PreciseSeam::init_precise_seam_data(
object.precise_seam_strong_volumes,
object.precise_seam_weak_volumes,
object.seam_data->has_precise_seam_strong_volumes,
po->model_object());
// Workers only set the usage flags. Several print objects of one model object share volumes, and
// try_emplace keeps what earlier ones recorded.
for (const ModelVolume* vol : object.precise_seam_strong_volumes)
precise_seam_warnings.modifier_usage.try_emplace(vol);
for (const ModelVolume* vol : object.precise_seam_weak_volumes)
precise_seam_warnings.modifier_usage.try_emplace(vol);
}
auto place_seams = [this, &throw_if_canceled_func, &precise_seam_warnings](ObjectSeams &object) {
const PrintObject *po = object.po;
throw_if_canceled_func();
SeamPosition configured_seam_preference = po->config().seam_position.value;
SeamComparator comparator { configured_seam_preference };
@@ -2120,23 +2144,14 @@ void SeamPlacer::init(const Print &print, std::function<void(void)> throw_if_can
{
GlobalModelInfo global_model_info { };
gather_enforcers_blockers(global_model_info, po);
PreciseSeam::init_precise_seam_data(
global_model_info.precise_seam_strong_volumes,
global_model_info.precise_seam_weak_volumes,
m_seam_per_object[po].has_precise_seam_strong_volumes,
po->model_object());
global_model_info.precise_seam_strong_volumes = std::move(object.precise_seam_strong_volumes);
global_model_info.precise_seam_weak_volumes = std::move(object.precise_seam_weak_volumes);
// Slice each Precise Seam modifier once per object; both consumers read the cache.
for (const ModelVolume* vol : global_model_info.precise_seam_strong_volumes)
global_model_info.precise_seam_slices[vol] = PreciseSeam::prepare_modifier_slices(po->slice_single_volume_regions(vol));
for (const ModelVolume* vol : global_model_info.precise_seam_weak_volumes)
global_model_info.precise_seam_slices[vol] = PreciseSeam::prepare_modifier_slices(po->slice_single_volume_regions(vol));
// Register usage tracking before the parallel phase; workers only set its flags. Several print
// objects of one model object share volumes, and try_emplace keeps what earlier ones recorded.
for (const ModelVolume* vol : global_model_info.precise_seam_strong_volumes)
precise_seam_warnings.modifier_usage.try_emplace(vol);
for (const ModelVolume* vol : global_model_info.precise_seam_weak_volumes)
precise_seam_warnings.modifier_usage.try_emplace(vol);
throw_if_canceled_func();
if (configured_seam_preference == spAligned || configured_seam_preference == spNearest || configured_seam_preference == spAlignedBack) {
@@ -2169,7 +2184,7 @@ void SeamPlacer::init(const Print &print, std::function<void(void)> throw_if_can
BOOST_LOG_TRIVIAL(debug)
<< "SeamPlacer: pick_seam_point : start";
//pick seam point
std::vector<PrintObjectSeamData::LayerSeams> &layers = m_seam_per_object[po].layers;
std::vector<PrintObjectSeamData::LayerSeams> &layers = object.seam_data->layers;
tbb::parallel_for(tbb::blocked_range<size_t>(0, layers.size()),
[&layers, configured_seam_preference, comparator](tbb::blocked_range<size_t> r) {
for (size_t layer_idx = r.begin(); layer_idx < r.end(); ++layer_idx) {
@@ -2195,13 +2210,24 @@ void SeamPlacer::init(const Print &print, std::function<void(void)> throw_if_can
}
// Restore precise seam positions that were potentially modified
if (m_seam_per_object[po].has_precise_seam_strong_volumes) {
PreciseSeam::restore_precise_seam_positions(m_seam_per_object[po].layers);
if (object.seam_data->has_precise_seam_strong_volumes) {
PreciseSeam::restore_precise_seam_positions(object.seam_data->layers);
}
#ifdef DEBUG_FILES
debug_export_points(m_seam_per_object[po].layers, po->bounding_box(), comparator);
debug_export_points(object.seam_data->layers, po->bounding_box(), comparator);
#endif
};
if (objects.size() == 1)
place_seams(objects.front());
else if (objects.size() > 1) {
// One object at a time, its serial steps (mesh decimation, building the search trees, aligning the seams)
// keep most of the cores idle. A few objects at once overlap them with the others' parallel steps; no more,
// as each holds its sampled mesh until it is done.
constexpr size_t max_objects_at_once = 4;
const size_t objects_per_task = (objects.size() + max_objects_at_once - 1) / max_objects_at_once;
parallel_for_first_error(objects.size(), objects_per_task, [&objects, &place_seams](size_t i) { place_seams(objects[i]); });
}
// Prepare one combined Precise Seam warning; G-code export issues it. Keep it single: separate
+3
View File
@@ -444,7 +444,10 @@ void Layer::make_perimeters()
append(clipped, diff_ex(l->raw_slices, group_slices));
clipped = union_ex(clipped);
if (layerms.size() == 1 && clipped.empty()) { // optimization
// The perimeter generator appends to these, so perimeters made again (other walls) start from none, as a first
// slice does.
(*layerm)->fill_surfaces.surfaces.clear();
(*layerm)->fill_no_overlap_expolygons.clear();
(*layerm)->make_perimeters((*layerm)->slices, {*layerm}, &(*layerm)->fill_surfaces, &(*layerm)->fill_no_overlap_expolygons);
(*layerm)->fill_expolygons = to_expolygons((*layerm)->fill_surfaces.surfaces);
} else {
+14 -5
View File
@@ -72,6 +72,7 @@
#include <map>
#include <utility>
#include <memory>
#include <mutex>
#include <iterator>
#include <limits>
#include <sstream>
@@ -2885,11 +2886,19 @@ int ModelVolume::extruder_id() const
bool ModelVolume::is_splittable() const
{
// the call mesh.is_splittable() is expensive, so cache the value to calculate it only once
if (m_is_splittable == -1)
m_is_splittable = its_is_splittable(this->mesh().its);
return m_is_splittable == 1;
// The call its_is_splittable() is expensive, so cache the value to calculate it only once. The PrintObjects made from
// one ModelObject ask at the same time while they prepare their infill, so the cache is read and written under a
// lock; the call itself runs outside it, and only callers that find the cache empty at the same time make it twice.
static std::mutex cache_mutex;
{
std::scoped_lock<std::mutex> lock(cache_mutex);
if (m_is_splittable != -1)
return m_is_splittable == 1;
}
const int splittable = its_is_splittable(this->mesh().its) ? 1 : 0;
std::scoped_lock<std::mutex> lock(cache_mutex);
m_is_splittable = splittable;
return splittable == 1;
}
// BBS
+46
View File
@@ -0,0 +1,46 @@
#pragma once
#include <atomic>
#include <cstddef>
#include <exception>
#include <vector>
#include <tbb/blocked_range.h>
#include <tbb/parallel_for.h>
#include <tbb/partitioner.h>
#include <tbb/task_arena.h>
namespace Slic3r {
// Calls process(i) for every i in [0, count) on the TBB threads, items_per_task consecutive items in each task, and
// throws what calling them in order would: the exception of the lowest i that threw. Items after it that have not
// started yet are skipped, as a loop stops at its first error.
//
// Each task runs isolated: while it waits in the parallel loops of its own items, its thread takes no other task of
// this loop. Otherwise it could start another item meanwhile, which holds up the waiting item until that one is
// done, keeps more items in memory at once than there are threads, and breaks code that keeps a lock or thread-local
// scratch across a parallel loop.
template<class Process>
void parallel_for_first_error(size_t count, size_t items_per_task, Process &&process)
{
std::vector<std::exception_ptr> errors(count);
std::atomic<size_t> first_error { count };
tbb::parallel_for(tbb::blocked_range<size_t>(0, count, items_per_task), [&](const tbb::blocked_range<size_t> &range) {
tbb::this_task_arena::isolate([&]() {
for (size_t i = range.begin(); i < range.end() && i < first_error.load(std::memory_order_relaxed); ++ i)
try {
process(i);
} catch (...) {
errors[i] = std::current_exception();
size_t lowest = first_error.load(std::memory_order_relaxed);
while (i < lowest && ! first_error.compare_exchange_weak(lowest, i, std::memory_order_relaxed))
;
}
});
}, tbb::simple_partitioner());
for (const std::exception_ptr &error : errors)
if (error)
std::rethrow_exception(error);
}
} // namespace Slic3r
+46 -41
View File
@@ -68,6 +68,7 @@
#include "Geometry/ConvexHull.hpp"
#include "I18N.hpp"
#include "LifecycleEvents.hpp"
#include "ParallelForFirstError.hpp"
#include "ShortestPath.hpp"
#include "Thread.hpp"
#include "Time.hpp"
@@ -3602,16 +3603,37 @@ void Print::process(long long *time_cost_with_cache, bool use_cache)
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": total object counts %1% in current print, need to slice %2%")%m_objects.size()%need_slicing_objects.size();
BOOST_LOG_TRIVIAL(info) << "Starting the slicing process." << log_memory_info();
// Runs a step on the objects `needs` selects and `skip` on the others. A step of an object reads that object and
// the print's configuration only, which the support step has always relied on, so the objects run the step
// together: one after another, each object's serial parts and slowest layers kept most of the cores idle.
// A slicing pipeline plugin runs its hook between the objects, so with one active they keep their order.
// Nothing enforces that rule. In particular, the PrintObjects made from one ModelObject, one per distinct instance
// transformation, share its ModelVolumes, whose lazily filled caches are not guarded: a step must not fill them
// (ModelVolume::is_splittable() is the exception, under a lock).
auto for_each_object_step = [this](auto &&needs, auto &&process, auto &&skip) {
std::vector<PrintObject*> objects;
for (PrintObject *obj : m_objects)
if (! needs(obj))
skip(obj);
else if (m_pipeline_plugin_active)
process(obj);
else
objects.push_back(obj);
if (objects.size() == 1)
process(objects.front());
else if (objects.size() > 1)
parallel_for_first_error(objects.size(), 1, [&process, &objects](size_t i) { process(objects[i]); });
};
if (!use_cache) {
// Fire the SlicingPipeline hook for `obj` iff it just (re)computed `pstep` this pass.
auto hook_after = [this](PrintObject* obj, bool was_done, PrintObjectStep pstep, SlicingPipelineStepPlugin sstep) {
if (m_pipeline_plugin_active && !was_done && obj->is_step_done(pstep))
run_pipeline_hook(sstep, obj);
};
auto needs_slicing = [&need_slicing_objects](PrintObject *obj) { return need_slicing_objects.count(obj) != 0; };
// SlicingPipeline: dedicated slice loop so the Slice boundary is hookable before perimeters.
for (PrintObject *obj : m_objects) {
if (need_slicing_objects.count(obj) != 0) {
for_each_object_step(needs_slicing, [&](PrintObject *obj) {
const bool was_done = obj->is_step_done(posSlice);
obj->slice();
hook_after(obj, was_done, posSlice, SlicingPipelineStepPlugin::posSlice);
@@ -3626,32 +3648,25 @@ void Print::process(long long *time_cost_with_cache, bool use_cache)
if (m_pipeline_plugin_active && !was_done && obj->is_step_done(posSlice))
for (Layer *layer : obj->layers())
layer->backup_untyped_slices();
} else {
}, [](PrintObject *obj) {
if (obj->set_started(posSlice)) obj->set_done(posSlice); // shared/duplicate — no hook
}
}
for (PrintObject *obj : m_objects) {
if (need_slicing_objects.count(obj) != 0) {
});
for_each_object_step(needs_slicing, [&](PrintObject *obj) {
const bool was_done = obj->is_step_done(posPerimeters);
obj->make_perimeters(); // slice() inside is a no-op: posSlice already DONE
hook_after(obj, was_done, posPerimeters, SlicingPipelineStepPlugin::posPerimeters);
} else {
}, [](PrintObject *obj) {
if (obj->set_started(posPerimeters)) obj->set_done(posPerimeters);
}
}
for (PrintObject *obj : m_objects) {
if (need_slicing_objects.count(obj) != 0) {
});
for_each_object_step(needs_slicing, [&](PrintObject *obj) {
const bool was_done = obj->is_step_done(posEstimateCurledExtrusions);
obj->estimate_curled_extrusions();
hook_after(obj, was_done, posEstimateCurledExtrusions, SlicingPipelineStepPlugin::posEstimateCurledExtrusions);
}
else {
}, [](PrintObject *obj) {
if (obj->set_started(posEstimateCurledExtrusions))
obj->set_done(posEstimateCurledExtrusions);
}
}
for (PrintObject *obj : m_objects) {
if (need_slicing_objects.count(obj) != 0) {
});
for_each_object_step(needs_slicing, [&](PrintObject *obj) {
// split prepare_infill (fill-surface prep) from infill (make_fills) so a
// plugin can mutate fill surfaces at the PrepareInfill seam and have make_fills
// consume them (unlike the Infill seam, which fires after the fills are already
@@ -3663,25 +3678,20 @@ void Print::process(long long *time_cost_with_cache, bool use_cache)
const bool was_done = obj->is_step_done(posInfill);
obj->infill();
hook_after(obj, was_done, posInfill, SlicingPipelineStepPlugin::posInfill);
}
else {
}, [](PrintObject *obj) {
if (obj->set_started(posPrepareInfill))
obj->set_done(posPrepareInfill);
if (obj->set_started(posInfill))
obj->set_done(posInfill);
}
}
for (PrintObject *obj : m_objects) {
if (need_slicing_objects.count(obj) != 0) {
});
for_each_object_step(needs_slicing, [&](PrintObject *obj) {
const bool was_done = obj->is_step_done(posIroning);
obj->ironing();
hook_after(obj, was_done, posIroning, SlicingPipelineStepPlugin::posIroning);
}
else {
}, [](PrintObject *obj) {
if (obj->set_started(posIroning))
obj->set_done(posIroning);
}
}
});
// Z-Contouring
for (PrintObject *obj : m_objects) {
@@ -3729,17 +3739,14 @@ void Print::process(long long *time_cost_with_cache, bool use_cache)
&& m_objects[i]->is_step_done(posSupportMaterial))
run_pipeline_hook(SlicingPipelineStepPlugin::posSupportMaterial, m_objects[i]);
for (PrintObject* obj : m_objects) {
if (need_slicing_objects.count(obj) != 0) {
for_each_object_step(needs_slicing, [&](PrintObject *obj) {
const bool was_done = obj->is_step_done(posDetectOverhangsForLift);
obj->detect_overhangs_for_lift();
hook_after(obj, was_done, posDetectOverhangsForLift, SlicingPipelineStepPlugin::posDetectOverhangsForLift);
}
else {
}, [](PrintObject *obj) {
if (obj->set_started(posDetectOverhangsForLift))
obj->set_done(posDetectOverhangsForLift);
}
}
});
}
else {
for (PrintObject *obj : m_objects) {
@@ -4104,9 +4111,9 @@ void Print::process(long long *time_cost_with_cache, bool use_cache)
}
}
//BBS
for (PrintObject *obj : m_objects) {
if (((!use_cache)&&(need_slicing_objects.count(obj) != 0))
|| (use_cache &&(re_slicing_objects.count(obj) != 0))){
for_each_object_step([&](PrintObject *obj) {
return (!use_cache && need_slicing_objects.count(obj) != 0) || (use_cache && re_slicing_objects.count(obj) != 0);
}, [&](PrintObject *obj) {
const bool was_done = obj->is_step_done(posSimplifyPath);
obj->simplify_extrusion_path();
// Unlike every other seam (all inside the `if (!use_cache)` block above), this loop is
@@ -4114,16 +4121,14 @@ void Print::process(long long *time_cost_with_cache, bool use_cache)
// explicitly here to keep hooks from ever firing on cache-loaded (plugin-final) objects.
if (!use_cache && m_pipeline_plugin_active && !was_done && obj->is_step_done(posSimplifyPath))
run_pipeline_hook(SlicingPipelineStepPlugin::posSimplifyPath, obj);
}
else {
}, [](PrintObject *obj) {
if (obj->set_started(posSimplifyPath))
obj->set_done(posSimplifyPath);
if (obj->set_started(posSimplifyInfill))
obj->set_done(posSimplifyInfill);
if (obj->set_started(posSimplifySupportPath))
obj->set_done(posSimplifySupportPath);
}
}
});
// BBS
bool has_adaptive_layer_height = false;
+4 -2
View File
@@ -123,6 +123,7 @@ std::string PrintBase::output_filepath(const std::string &path, const std::strin
//BBS: move set_status from hpp to cpp
void PrintBase::set_status(int percent, const std::string &message, unsigned int flags, int warning_step) const
{
std::scoped_lock<std::mutex> lock(m_status_callback_mutex);
if (m_status_callback)
m_status_callback(SlicingStatus(percent, message, flags, warning_step));
else
@@ -132,6 +133,7 @@ void PrintBase::set_status(int percent, const std::string &message, unsigned in
void PrintBase::status_update_warnings(int step, PrintStateBase::WarningLevel warning_level,
const std::string &message, const PrintObjectBase* print_object, PrintStateBase::SlicingNotificationType message_id)
{
std::scoped_lock<std::mutex> lock(m_status_callback_mutex);
if (this->m_status_callback) {
auto status = print_object ? SlicingStatus(*print_object, step, message, message_id, warning_level) : SlicingStatus(*this, step, message, message_id, warning_level);
m_status_callback(status);
@@ -145,9 +147,9 @@ void PrintBase::status_update_warnings(int step, PrintStateBase::WarningLevel wa
const std::string& message, PrintObjectBase &object, PrintStateBase::SlicingNotificationType message_id)
{
//BBS: add object it into slicing status
if (this->m_status_callback) {
std::scoped_lock<std::mutex> lock(m_status_callback_mutex);
if (this->m_status_callback)
m_status_callback(SlicingStatus(object, step, message, message_id, warning_level));
}
else if (!message.empty())
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(", PrintObject warning: %1%\n")% message.c_str();
}
+6 -3
View File
@@ -481,11 +481,11 @@ public:
};
typedef std::function<void(const SlicingStatus&)> status_callback_type;
// Default status console print out in the form of percent => message.
void set_status_default() { m_status_callback = nullptr; }
void set_status_default() { set_status_callback(nullptr); }
// No status output or callback whatsoever, useful mostly for automatic tests.
void set_status_silent() { m_status_callback = [](const SlicingStatus&){}; }
void set_status_silent() { set_status_callback([](const SlicingStatus&){}); }
// Register a custom status callback.
void set_status_callback(status_callback_type cb) { m_status_callback = cb; }
void set_status_callback(status_callback_type cb) { std::scoped_lock<std::mutex> lock(m_status_callback_mutex); m_status_callback = std::move(cb); }
// Calls a registered callback to update the status, or print out the default message.
void set_status(int percent, const std::string &message, unsigned int flags = SlicingStatus::DEFAULT, int warning_step = -1) const;
@@ -583,6 +583,9 @@ private:
// The mutex will be used to guard the worker thread against entering a stage
// while the data influencing the stage is modified.
mutable std::mutex m_state_mutex;
// Held while the status callback runs or is replaced: the objects run their steps concurrently, a callback may keep
// state of its own, such as the warnings the command line collects, and the GUI replaces it while a slice runs.
mutable std::mutex m_status_callback_mutex;
friend PrintTryCancel;
};
+1
View File
@@ -6,6 +6,7 @@ add_executable(${_TEST_NAME}_tests
test_adaptive_pressure_advance.cpp
test_bridge.cpp
test_calib.cpp
test_conflict_checker.cpp
test_cooling.cpp
test_extrusion_entity.cpp
test_extrusion_processor.cpp
+75
View File
@@ -0,0 +1,75 @@
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include "libslic3r/Config.hpp"
#include "libslic3r/GCode/GCodeProcessor.hpp"
#include "libslic3r/Model.hpp"
#include "libslic3r/Print.hpp"
#include "libslic3r/PrintConfig.hpp"
#include "libslic3r/TriangleMesh.hpp"
#include <utility>
#include <vector>
#include "test_helpers.hpp"
using namespace Slic3r;
using namespace Slic3r::Test;
namespace {
// Two 10 mm cubes printed as separate objects, the second shifted along X by `offset`, at the
// positions given (not arranged apart).
ConflictResultOpt conflict_between_cubes(double offset)
{
TriangleMesh first = make_cube(10., 10., 10.);
TriangleMesh second = make_cube(10., 10., 10.);
first.translate(50.f, 50.f, 0.f);
second.translate(float(50. + offset), 50.f, 0.f);
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({ { "layer_height", "0.2" }, { "initial_layer_print_height", "0.2" } });
Print print;
Model model;
init_print({ std::move(first), std::move(second) }, print, model, config, nullptr, false);
print.process();
return print.get_conflict_result();
}
} // namespace
TEST_CASE("Objects whose extrusions cross are reported as a path conflict", "[ConflictChecker]")
{
// A 5 mm shift puts half of each cube inside the other, so their walls cross on every layer of the
// 10 mm high cubes.
const ConflictResultOpt conflict = conflict_between_cubes(5.);
REQUIRE(conflict.has_value());
CHECK(conflict->_obj1 != conflict->_obj2);
CHECK(conflict->_height <= 10.);
}
TEST_CASE("Objects apart from each other have no path conflict", "[ConflictChecker]")
{
// 30 mm between the cube origins leaves a 20 mm gap between the 10 mm cubes.
CHECK_FALSE(conflict_between_cubes(30.).has_value());
}
TEST_CASE("Copies of an object printed over each other are reported as a path conflict", "[ConflictChecker]")
{
// Two instances of one 10 mm cube: not arranged, both stay at the origin of the object; arranged, they are
// placed apart.
const bool arranged = GENERATE(false, true);
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({ { "layer_height", "0.2" }, { "initial_layer_print_height", "0.2" } });
TriangleMesh cube = make_cube(10., 10., 10.);
cube.translate(50.f, 50.f, 0.f);
Print print;
Model model;
std::vector<TriangleMesh> meshes;
meshes.emplace_back(std::move(cube));
init_print(std::move(meshes), print, model, config, nullptr, arranged, 2);
print.process();
CHECK(print.get_conflict_result().has_value() == ! arranged);
}
+307
View File
@@ -36,6 +36,8 @@
#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>
@@ -56,11 +58,15 @@
#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>
@@ -69,6 +75,7 @@
#include "libslic3r/SurfaceCollection.hpp"
#include "libslic3r/BoundingBox.hpp"
#include "libslic3r/ExPolygon.hpp"
#include "libslic3r/Geometry.hpp"
using namespace Slic3r;
using namespace Slic3r::Test;
@@ -3517,6 +3524,128 @@ TEST_CASE("Height range settings follow a Z shrinkage change that comes with a m
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)
{
@@ -3560,6 +3689,184 @@ DynamicPrintConfig machine_inventory_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.
+34
View File
@@ -1538,3 +1538,37 @@ TEST_CASE("Seam extraction preserves unknown boundary roles for open extrusion p
REQUIRE(perimeters.size() == 1);
CHECK(perimeters.front().contour_reliable == !open);
}
TEST_CASE("Seams are picked on every loop of every object when init() places several objects at once", "[SeamPlacer]")
{
// Random seams are picked by the workers of each object alone, and they finalize every loop. Sixteen objects make
// four tasks of four objects each.
const size_t object_count = 16;
std::vector<TriangleMesh> meshes;
for (size_t i = 0; i < object_count; ++ i)
meshes.emplace_back(its_make_cube(10, 10, 1));
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict("seam_position", "random"); // Random needs no visibility ray tracing.
Model model;
Print print;
Test::init_print(std::move(meshes), print, model, config);
REQUIRE(print.objects().size() == object_count);
print.process();
SeamPlacer placer;
placer.init(print, [] {});
size_t loops = 0, picked = 0;
for (const PrintObject *object : print.objects()) {
const std::vector<PrintObjectSeamData::LayerSeams> &layers = placer.m_seam_per_object.at(object).layers;
REQUIRE(layers.size() == object->layers().size());
for (const PrintObjectSeamData::LayerSeams &layer : layers)
for (const SeamPlacerImpl::Perimeter &perimeter : layer.perimeters) {
++ loops;
if (perimeter.finalized)
++ picked;
}
}
REQUIRE(loops >= object_count);
CHECK(picked == loops);
}
+2
View File
@@ -37,6 +37,7 @@ add_executable(${_TEST_NAME}_tests
test_drc.cpp
test_gcodereader.cpp
test_toolordering_nozzle_group.cpp
test_parallel_for_first_error.cpp
test_parallel_resolve.cpp
test_preset_bundle_loading.cpp
test_preset_collection.cpp
@@ -47,6 +48,7 @@ add_executable(${_TEST_NAME}_tests
test_preset_options.cpp
test_edge_grid.cpp
test_elephant_foot_compensation.cpp
test_expolygon.cpp
test_exclusion_volumes.cpp
test_fill_corner_smoothing.cpp
test_filament_mixer.cpp
+127
View File
@@ -1,13 +1,18 @@
#include <catch2/catch_all.hpp>
#include <catch2/catch_test_macros.hpp>
#include <catch2/catch_approx.hpp>
#include <catch2/generators/catch_generators.hpp>
#include <igl/Hit.h>
#include <cstddef>
#include <libslic3r/TriangleMesh.hpp>
#include <libslic3r/AABBTreeIndirect.hpp>
#include <limits>
#include <random>
#include <utility>
#include <vector>
#include "libslic3r/Point.hpp"
#include "libslic3r/libslic3r.h"
using namespace Slic3r;
@@ -63,3 +68,125 @@ TEST_CASE("Building a tree over a box, ray caster and closest query", "[AABBIndi
REQUIRE(closest_point.y() == Catch::Approx(0.5));
REQUIRE(closest_point.z() == Catch::Approx(1.));
}
namespace {
// The depth-first, left to right traversal intersect_ray_first_hit() used before it visited the nearest
// child first. The ordered traversal must return the very same hit.
template<typename RayIntersectorType, typename Scalar>
bool reference_first_hit(const RayIntersectorType &ray_intersector, size_t node_idx, Scalar min_t, igl::Hit<float> &hit)
{
const auto &node = ray_intersector.tree.node(node_idx);
if (! AABBTreeIndirect::detail::ray_box_intersect_invdir(ray_intersector.origin, ray_intersector.invdir,
node.bbox.template cast<Scalar>(), Scalar(0), min_t))
return false;
if (node.is_leaf()) {
auto face = ray_intersector.faces[node.idx];
double t, u, v;
if (AABBTreeIndirect::detail::intersect_triangle(ray_intersector.origin, ray_intersector.dir,
ray_intersector.vertices[face(0)], ray_intersector.vertices[face(1)],
ray_intersector.vertices[face(2)], t, u, v, ray_intersector.eps) &&
t > 0.) {
hit = igl::Hit<float>{int(node.idx), -1, float(u), float(v), float(t)};
return true;
}
return false;
}
igl::Hit<float> left_hit;
igl::Hit<float> right_hit;
bool left_ret = reference_first_hit(ray_intersector, node_idx * 2 + 1, min_t, left_hit);
if (left_ret && left_hit.t < min_t) {
min_t = left_hit.t;
hit = left_hit;
} else
left_ret = false;
bool right_ret = reference_first_hit(ray_intersector, node_idx * 2 + 2, min_t, right_hit);
if (right_ret && right_hit.t < min_t)
hit = right_hit;
else
right_ret = false;
return left_ret || right_ret;
}
// Unit cube faces split into an n x n grid of triangles: many coplanar triangles sharing edges, so rays
// through edges and vertices hit several triangles at the same distance.
indexed_triangle_set grid_cube(int n)
{
indexed_triangle_set its;
for (int axis = 0; axis < 3; ++axis)
for (int side = 0; side < 2; ++side)
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) {
auto vertex = [&](int a, int b) {
Vec3f p;
p[axis] = float(side);
p[(axis + 1) % 3] = float(a) / n;
p[(axis + 2) % 3] = float(b) / n;
its.vertices.emplace_back(p);
return int(its.vertices.size()) - 1;
};
int v0 = vertex(i, j), v1 = vertex(i + 1, j), v2 = vertex(i + 1, j + 1), v3 = vertex(i, j + 1);
its.indices.emplace_back(v0, v1, v2);
its.indices.emplace_back(v0, v2, v3);
}
return its;
}
} // namespace
TEST_CASE("First ray hit matches the depth-first search", "[AABBIndirect]")
{
std::mt19937 rng(42);
std::uniform_real_distribution<double> coord(-1.5, 2.5);
std::uniform_real_distribution<double> unit(-1., 1.);
indexed_triangle_set soup;
for (int i = 0; i < 300; ++i) {
Vec3f a(coord(rng), coord(rng), coord(rng));
int base = int(soup.vertices.size());
soup.vertices.emplace_back(a);
soup.vertices.emplace_back(a + Vec3f(unit(rng), unit(rng), unit(rng)) * 0.5f);
soup.vertices.emplace_back(a + Vec3f(unit(rng), unit(rng), unit(rng)) * 0.5f);
soup.indices.emplace_back(base, base + 1, base + 2);
}
const indexed_triangle_set mesh = GENERATE_COPY(grid_cube(8), its_make_sphere(1., PI / 20.), soup);
const auto tree = AABBTreeIndirect::build_aabb_tree_over_indexed_triangle_set(mesh.vertices, mesh.indices);
REQUIRE(! tree.empty());
// Directions with zero components make the inverse direction infinite. Origins on the grid, aimed
// along the axes or the diagonals, put the rays through shared edges and vertices.
std::vector<std::pair<Vec3d, Vec3d>> rays;
const Vec3d axis_dirs[] = {Vec3d::UnitX(), -Vec3d::UnitX(), Vec3d::UnitY(), -Vec3d::UnitY(), Vec3d::UnitZ(), -Vec3d::UnitZ(),
Vec3d(1., 1., 0.).normalized(), Vec3d(1., 1., 1.).normalized(), Vec3d(-1., 0., 1.).normalized()};
for (int i = -2; i <= 10; ++i)
for (int j = -2; j <= 10; ++j)
for (const Vec3d &dir : axis_dirs)
rays.emplace_back(Vec3d(i / 8., j / 8., -1.) - dir * 2., dir);
// Random rays aimed at random mesh vertices, so that most of them hit.
std::uniform_int_distribution<size_t> vertex_idx(0, mesh.vertices.size() - 1);
for (int i = 0; i < 20000; ++i) {
const Vec3d origin(coord(rng), coord(rng), coord(rng));
const Vec3d target = mesh.vertices[vertex_idx(rng)].cast<double>() + Vec3d(unit(rng), unit(rng), unit(rng)) * 0.01;
if ((target - origin).squaredNorm() > 1e-6)
rays.emplace_back(origin, (target - origin).normalized());
}
size_t hits = 0;
size_t mismatches = 0;
for (const auto &[origin, dir] : rays) {
igl::Hit<float> hit{-1, -1, 0.f, 0.f, 0.f};
const bool found = AABBTreeIndirect::intersect_ray_first_hit(mesh.vertices, mesh.indices, tree, origin, dir, hit);
const auto ray_intersector = AABBTreeIndirect::detail::RayIntersector<stl_vertex, stl_triangle_vertex_indices, AABBTreeIndirect::Tree<3, float>, Vec3d>{
mesh.vertices, mesh.indices, tree, origin, dir, Vec3d(dir.cwiseInverse()), 0.000001};
igl::Hit<float> expected{-1, -1, 0.f, 0.f, 0.f};
const bool expected_found = reference_first_hit(ray_intersector, size_t(0), std::numeric_limits<double>::infinity(), expected);
hits += found;
if (found != expected_found || (found && (hit.id != expected.id || hit.t != expected.t || hit.u != expected.u || hit.v != expected.v)))
++mismatches;
}
CHECK(hits > rays.size() / 2);
CHECK(mismatches == 0);
}
+65
View File
@@ -0,0 +1,65 @@
#include <catch2/catch_test_macros.hpp>
#include "libslic3r/ExPolygon.hpp"
#include "libslic3r/Point.hpp"
#include "libslic3r/Polygon.hpp"
#include "libslic3r/Polyline.hpp"
#include "libslic3r/libslic3r.h"
#include <initializer_list>
#include <utility>
using namespace Slic3r;
namespace {
Polygon square(double x0, double y0, double size)
{
return Polygon{ Point::new_scale(x0, y0), Point::new_scale(x0 + size, y0), Point::new_scale(x0 + size, y0 + size),
Point::new_scale(x0, y0 + size) };
}
Polyline polyline(std::initializer_list<Vec2d> points)
{
Polyline out;
for (const Vec2d &p : points)
out.points.emplace_back(Point::new_scale(p.x(), p.y()));
return out;
}
// A 10 mm square with a 2 mm square hole at its center.
ExPolygon square_with_hole()
{
ExPolygon expoly(square(0., 0., 10.));
Polygon hole = square(4., 4., 2.);
hole.reverse();
expoly.holes.emplace_back(std::move(hole));
return expoly;
}
} // namespace
TEST_CASE("A polyline running inside an expolygon is contained in it", "[ExPolygon]")
{
const ExPolygon expoly = square_with_hole();
CHECK(expoly.contains(polyline({ { 1., 1. }, { 9., 1. }, { 9., 9. } })));
}
TEST_CASE("A polyline leaving an expolygon is not contained in it", "[ExPolygon]")
{
const ExPolygon expoly = square_with_hole();
// Out through the contour, far beyond the bounding box and just past it.
CHECK_FALSE(expoly.contains(polyline({ { 1., 1. }, { 20., 1. } })));
CHECK_FALSE(expoly.contains(polyline({ { 1., 1. }, { 10.01, 1. } })));
// Across the hole.
CHECK_FALSE(expoly.contains(polyline({ { 1., 5. }, { 9., 5. } })));
}
TEST_CASE("A polyline within the bounding box but outside of a concave expolygon is not contained in it", "[ExPolygon]")
{
// An L shape: the 10 mm square without its top right 5 mm quarter.
const ExPolygon l_shape(Polygon{ Point::new_scale(0., 0.), Point::new_scale(10., 0.), Point::new_scale(10., 5.),
Point::new_scale(5., 5.), Point::new_scale(5., 10.), Point::new_scale(0., 10.) });
CHECK_FALSE(l_shape.contains(polyline({ { 1., 1. }, { 9., 1. }, { 9., 9. } })));
CHECK(l_shape.contains(polyline({ { 1., 1. }, { 9., 1. }, { 4., 4. }, { 1., 9. } })));
}
+20
View File
@@ -1,6 +1,7 @@
#include <catch2/catch_all.hpp>
#include <algorithm>
#include <cstddef>
#include <thread>
#include <utility>
#include <vector>
#include "libslic3r/TriangleMesh.hpp"
@@ -135,6 +136,25 @@ TEST_CASE("Splitting a part drops pieces enclosing no volume and keeps the part
}
}
TEST_CASE("A part asked from several threads at once whether it can be split answers the same for all", "[Model]")
{
// The PrintObjects made from one ModelObject prepare their infill at the same time, and each asks the object's first
// part whether it can be split, which fills a cache in the part. Without the lock around the cache the answers
// still agree on most runs: ThreadSanitizer is what reports the race.
Model model;
ModelObject *object = model.add_object();
const ModelVolume *volume = object->add_volume(flat_triangle_then_cubes({0., 30.}), ModelVolumeType::MODEL_PART, false);
std::vector<char> answers(8, 0);
std::vector<std::thread> threads;
for (size_t i = 0; i < answers.size(); ++ i)
threads.emplace_back([volume, &answers, i] { answers[i] = volume->is_splittable() ? 1 : 0; });
for (std::thread &thread : threads)
thread.join();
CHECK(std::all_of(answers.begin(), answers.end(), [](char answer) { return answer == 1; }));
}
TEST_CASE("Splitting a part with a single solid piece keeps just that piece", "[Model]")
{
Model model;
@@ -0,0 +1,64 @@
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include <catch2/catch_message.hpp>
#include <atomic>
#include <cmath>
#include <cstddef>
#include <stdexcept>
#include <string>
#include <vector>
#include <tbb/blocked_range.h>
#include <tbb/parallel_for.h>
#include "libslic3r/ParallelForFirstError.hpp"
using namespace Slic3r;
TEST_CASE("parallel_for_first_error throws the error of the lowest item that threw, after every item below it ran", "[ParallelForFirstError]")
{
// Items 9 and 3 throw. A loop over the items stops at item 3, so its error is the one thrown, and the items before
// it all run. Each item is written by one task only, and read after the loop.
const size_t items_per_task = GENERATE(size_t(1), size_t(4));
INFO(items_per_task << " items per task");
const size_t count = 64;
std::vector<char> ran(count, 0);
std::string thrown;
try {
parallel_for_first_error(count, items_per_task, [&ran](size_t i) {
ran[i] = 1;
if (i == 3 || i == 9)
throw std::runtime_error("item " + std::to_string(i));
});
} catch (const std::runtime_error &error) {
thrown = error.what();
}
CHECK(thrown == "item 3");
for (size_t i = 0; i <= 3; ++ i)
CHECK(ran[i] == 1);
}
TEST_CASE("parallel_for_first_error starts no item on a thread that waits in another item's parallel loop", "[ParallelForFirstError]")
{
// Each item runs a parallel loop of its own. A thread waiting for its item's loop could otherwise take another
// item meanwhile, which would then run nested in the first one on that thread.
static thread_local int items_on_thread = 0;
std::atomic<bool> nested { false };
parallel_for_first_error(64, 1, [&nested](size_t) {
if (items_on_thread > 0)
nested = true;
++ items_on_thread;
tbb::parallel_for(tbb::blocked_range<size_t>(0, 256), [](const tbb::blocked_range<size_t> &range) {
double sum = 0.;
for (size_t i = range.begin(); i < range.end(); ++ i)
for (int k = 1; k < 2000; ++ k)
sum += std::sqrt(double(i * size_t(k)));
// Keeps the work from being optimized away.
if (sum < 0.)
throw std::logic_error("negative sum");
});
-- items_on_thread;
});
CHECK_FALSE(nested);
}