PrusaSlicer-NonPlainar/src/libslic3r/ModelArrange.cpp

1128 lines
40 KiB
C++
Raw Normal View History

2018-11-12 13:52:52 +00:00
#include "ModelArrange.hpp"
//#include "Model.hpp"
#include "Geometry.hpp"
2018-11-12 13:52:52 +00:00
#include "SVG.hpp"
#include "MTUtils.hpp"
2018-11-12 13:52:52 +00:00
#include <libnest2d.h>
#include <numeric>
#include <ClipperUtils.hpp>
#include <boost/geometry/index/rtree.hpp>
#include <boost/multiprecision/integer.hpp>
#include <boost/rational.hpp>
namespace libnest2d {
#if !defined(_MSC_VER) && defined(__SIZEOF_INT128__) && !defined(__APPLE__)
using LargeInt = __int128;
#else
using LargeInt = boost::multiprecision::int128_t;
template<> struct _NumTag<LargeInt> { using Type = ScalarTag; };
#endif
template<class T> struct _NumTag<boost::rational<T>> { using Type = RationalTag; };
namespace nfp {
template<class S>
struct NfpImpl<S, NfpLevel::CONVEX_ONLY>
{
NfpResult<S> operator()(const S &sh, const S &other)
{
return nfpConvexOnly<S, boost::rational<LargeInt>>(sh, other);
}
};
}
}
2018-11-12 13:52:52 +00:00
namespace Slic3r {
namespace arr {
using namespace libnest2d;
2019-06-27 19:13:44 +00:00
using Shape = ClipperLib::Polygon;
2019-01-21 09:34:10 +00:00
// Only for debugging. Prints the model object vertices on stdout.
//std::string toString(const Model& model, bool holes = true) {
// std::stringstream ss;
2018-11-12 13:52:52 +00:00
// ss << "{\n";
2018-11-12 13:52:52 +00:00
// for(auto objptr : model.objects) {
// if(!objptr) continue;
2018-11-12 13:52:52 +00:00
// auto rmesh = objptr->raw_mesh();
2018-11-12 13:52:52 +00:00
// for(auto objinst : objptr->instances) {
// if(!objinst) continue;
2018-11-12 13:52:52 +00:00
// Slic3r::TriangleMesh tmpmesh = rmesh;
// // CHECK_ME -> Is the following correct ?
// tmpmesh.scale(objinst->get_scaling_factor());
// objinst->transform_mesh(&tmpmesh);
// ExPolygons expolys = tmpmesh.horizontal_projection();
// for(auto& expoly_complex : expolys) {
2019-06-26 09:10:41 +00:00
// ExPolygons tmp = expoly_complex.simplify(scaled<double>(1.));
// if(tmp.empty()) continue;
// ExPolygon expoly = tmp.front();
// expoly.contour.make_clockwise();
// for(auto& h : expoly.holes) h.make_counter_clockwise();
// ss << "\t{\n";
// ss << "\t\t{\n";
// for(auto v : expoly.contour.points) ss << "\t\t\t{"
// << v(0) << ", "
// << v(1) << "},\n";
// {
// auto v = expoly.contour.points.front();
// ss << "\t\t\t{" << v(0) << ", " << v(1) << "},\n";
// }
// ss << "\t\t},\n";
// // Holes:
// ss << "\t\t{\n";
// if(holes) for(auto h : expoly.holes) {
// ss << "\t\t\t{\n";
// for(auto v : h.points) ss << "\t\t\t\t{"
// << v(0) << ", "
// << v(1) << "},\n";
// {
// auto v = h.points.front();
// ss << "\t\t\t\t{" << v(0) << ", " << v(1) << "},\n";
// }
// ss << "\t\t\t},\n";
// }
// ss << "\t\t},\n";
// ss << "\t},\n";
// }
// }
// }
// ss << "}\n";
// return ss.str();
//}
2018-11-12 13:52:52 +00:00
2019-01-21 09:34:10 +00:00
// Debugging: Save model to svg file.
//void toSVG(SVG& svg, const Model& model) {
// for(auto objptr : model.objects) {
// if(!objptr) continue;
2018-11-12 13:52:52 +00:00
// auto rmesh = objptr->raw_mesh();
2018-11-12 13:52:52 +00:00
// for(auto objinst : objptr->instances) {
// if(!objinst) continue;
2018-11-12 13:52:52 +00:00
// Slic3r::TriangleMesh tmpmesh = rmesh;
// tmpmesh.scale(objinst->get_scaling_factor());
// objinst->transform_mesh(&tmpmesh);
// ExPolygons expolys = tmpmesh.horizontal_projection();
// svg.draw(expolys);
// }
// }
//}
2018-11-12 13:52:52 +00:00
namespace bgi = boost::geometry::index;
using SpatElement = std::pair<Box, unsigned>;
using SpatIndex = bgi::rtree< SpatElement, bgi::rstar<16, 4> >;
2019-06-27 19:13:44 +00:00
using ItemGroup = std::vector<std::reference_wrapper<_Item<Shape>>>;
2018-11-12 13:52:52 +00:00
const double BIG_ITEM_TRESHOLD = 0.02;
Box boundingBox(const Box& pilebb, const Box& ibb ) {
auto& pminc = pilebb.minCorner();
auto& pmaxc = pilebb.maxCorner();
auto& iminc = ibb.minCorner();
auto& imaxc = ibb.maxCorner();
PointImpl minc, maxc;
setX(minc, std::min(getX(pminc), getX(iminc)));
setY(minc, std::min(getY(pminc), getY(iminc)));
setX(maxc, std::max(getX(pmaxc), getX(imaxc)));
setY(maxc, std::max(getY(pmaxc), getY(imaxc)));
return Box(minc, maxc);
}
2019-01-21 09:34:10 +00:00
// This is "the" object function which is evaluated many times for each vertex
// (decimated with the accuracy parameter) of each object. Therefore it is
// upmost crucial for this function to be as efficient as it possibly can be but
// at the same time, it has to provide reasonable results.
2018-11-12 13:52:52 +00:00
std::tuple<double /*score*/, Box /*farthest point from bin center*/>
objfunc(const PointImpl& bincenter,
2019-06-27 19:13:44 +00:00
const TMultiShape<Shape>& merged_pile,
2018-11-12 13:52:52 +00:00
const Box& pilebb,
const ItemGroup& items,
2019-06-27 19:13:44 +00:00
const _Item<Shape> &item,
2018-11-12 13:52:52 +00:00
double bin_area,
double norm, // A norming factor for physical dimensions
// a spatial index to quickly get neighbors of the candidate item
const SpatIndex& spatindex,
const SpatIndex& smalls_spatindex,
const ItemGroup& remaining
)
{
// We will treat big items (compared to the print bed) differently
auto isBig = [bin_area](double a) {
return a/bin_area > BIG_ITEM_TRESHOLD ;
};
// Candidate item bounding box
auto ibb = sl::boundingBox(item.transformedShape());
// Calculate the full bounding box of the pile with the candidate item
auto fullbb = boundingBox(pilebb, ibb);
// The bounding box of the big items (they will accumulate in the center
// of the pile
Box bigbb;
if(spatindex.empty()) bigbb = fullbb;
else {
auto boostbb = spatindex.bounds();
boost::geometry::convert(boostbb, bigbb);
}
// Will hold the resulting score
double score = 0;
if(isBig(item.area()) || spatindex.empty()) {
// This branch is for the bigger items..
auto minc = ibb.minCorner(); // bottom left corner
auto maxc = ibb.maxCorner(); // top right corner
// top left and bottom right corners
auto top_left = PointImpl{getX(minc), getY(maxc)};
auto bottom_right = PointImpl{getX(maxc), getY(minc)};
// Now the distance of the gravity center will be calculated to the
// five anchor points and the smallest will be chosen.
std::array<double, 5> dists;
auto cc = fullbb.center(); // The gravity center
dists[0] = pl::distance(minc, cc);
dists[1] = pl::distance(maxc, cc);
dists[2] = pl::distance(ibb.center(), cc);
dists[3] = pl::distance(top_left, cc);
dists[4] = pl::distance(bottom_right, cc);
// The smalles distance from the arranged pile center:
auto dist = *(std::min_element(dists.begin(), dists.end())) / norm;
auto bindist = pl::distance(ibb.center(), bincenter) / norm;
dist = 0.8*dist + 0.2*bindist;
// Density is the pack density: how big is the arranged pile
double density = 0;
if(remaining.empty()) {
auto mp = merged_pile;
mp.emplace_back(item.transformedShape());
auto chull = sl::convexHull(mp);
2019-06-27 19:13:44 +00:00
placers::EdgeCache<Shape> ec(chull);
2018-11-12 13:52:52 +00:00
double circ = ec.circumference() / norm;
double bcirc = 2.0*(fullbb.width() + fullbb.height()) / norm;
score = 0.5*circ + 0.5*bcirc;
} else {
// Prepare a variable for the alignment score.
// This will indicate: how well is the candidate item aligned with
// its neighbors. We will check the alignment with all neighbors and
// return the score for the best alignment. So it is enough for the
// candidate to be aligned with only one item.
auto alignment_score = 1.0;
density = std::sqrt((fullbb.width() / norm )*
(fullbb.height() / norm));
auto querybb = item.boundingBox();
// Query the spatial index for the neighbors
std::vector<SpatElement> result;
result.reserve(spatindex.size());
if(isBig(item.area())) {
spatindex.query(bgi::intersects(querybb),
std::back_inserter(result));
} else {
smalls_spatindex.query(bgi::intersects(querybb),
std::back_inserter(result));
}
for(auto& e : result) { // now get the score for the best alignment
auto idx = e.second;
2019-06-27 19:13:44 +00:00
_Item<Shape>& p = items[idx];
2018-11-12 13:52:52 +00:00
auto parea = p.area();
if(std::abs(1.0 - parea/item.area()) < 1e-6) {
auto bb = boundingBox(p.boundingBox(), ibb);
auto bbarea = bb.area();
auto ascore = 1.0 - (item.area() + parea)/bbarea;
if(ascore < alignment_score) alignment_score = ascore;
}
}
// The final mix of the score is the balance between the distance
// from the full pile center, the pack density and the
// alignment with the neighbors
if(result.empty())
score = 0.5 * dist + 0.5 * density;
else
score = 0.40 * dist + 0.40 * density + 0.2 * alignment_score;
}
} else {
// Here there are the small items that should be placed around the
// already processed bigger items.
// No need to play around with the anchor points, the center will be
// just fine for small items
score = pl::distance(ibb.center(), bigbb.center()) / norm;
}
return std::make_tuple(score, fullbb);
}
2019-01-21 09:34:10 +00:00
// Fill in the placer algorithm configuration with values carefully chosen for
// Slic3r.
2018-11-12 13:52:52 +00:00
template<class PConf>
void fillConfig(PConf& pcfg) {
// Align the arranged pile into the center of the bin
pcfg.alignment = PConf::Alignment::CENTER;
// Start placing the items from the center of the print bed
pcfg.starting_point = PConf::Alignment::CENTER;
// TODO cannot use rotations until multiple objects of same geometry can
// handle different rotations
// arranger.useMinimumBoundigBoxRotation();
pcfg.rotations = { 0.0 };
// The accuracy of optimization.
// Goes from 0.0 to 1.0 and scales performance as well
pcfg.accuracy = 0.65f;
pcfg.parallel = true;
}
2019-01-21 09:34:10 +00:00
// Type trait for an arranger class for different bin types (box, circle,
// polygon, etc...)
2018-11-12 13:52:52 +00:00
template<class TBin>
class AutoArranger {};
2019-01-21 09:34:10 +00:00
// A class encapsulating the libnest2d Nester class and extending it with other
// management and spatial index structures for acceleration.
2018-11-12 13:52:52 +00:00
template<class TBin>
class _ArrBase {
2019-06-19 10:04:11 +00:00
public:
2018-11-12 13:52:52 +00:00
2019-01-21 09:34:10 +00:00
// Useful type shortcuts...
2019-06-27 19:13:44 +00:00
using Placer = typename placers::_NofitPolyPlacer<Shape, TBin>;
using Selector = selections::_FirstFitSelection<Shape>;
2018-11-12 13:52:52 +00:00
using Packer = Nester<Placer, Selector>;
using PConfig = typename Packer::PlacementConfig;
using Distance = TCoord<PointImpl>;
2019-06-27 19:13:44 +00:00
using Pile = TMultiShape<Shape>;
2019-06-19 10:04:11 +00:00
protected:
2018-11-12 13:52:52 +00:00
Packer m_pck;
2019-01-21 09:34:10 +00:00
PConfig m_pconf; // Placement configuration
2018-11-12 13:52:52 +00:00
double m_bin_area;
2019-01-21 09:34:10 +00:00
SpatIndex m_rtree; // spatial index for the normal (bigger) objects
SpatIndex m_smallsrtree; // spatial index for only the smaller items
double m_norm; // A coefficient to scale distances
Pile m_merged_pile; // The already merged pile (vector of items)
Box m_pilebb; // The bounding box of the merged pile.
ItemGroup m_remaining; // Remaining items (m_items at the beginning)
ItemGroup m_items; // The items to be packed
2018-11-12 13:52:52 +00:00
public:
_ArrBase(const TBin& bin, Distance dist,
std::function<void(unsigned)> progressind,
std::function<bool(void)> stopcond):
m_pck(bin, dist), m_bin_area(sl::area(bin)),
m_norm(std::sqrt(sl::area(bin)))
{
fillConfig(m_pconf);
2019-01-21 09:34:10 +00:00
// Set up a callback that is called just before arranging starts
// This functionality is provided by the Nester class (m_pack).
2018-11-12 13:52:52 +00:00
m_pconf.before_packing =
[this](const Pile& merged_pile, // merged pile
const ItemGroup& items, // packed items
const ItemGroup& remaining) // future items to be packed
{
m_items = items;
m_merged_pile = merged_pile;
m_remaining = remaining;
m_pilebb = sl::boundingBox(merged_pile);
m_rtree.clear();
m_smallsrtree.clear();
// We will treat big items (compared to the print bed) differently
auto isBig = [this](double a) {
return a/m_bin_area > BIG_ITEM_TRESHOLD ;
};
for(unsigned idx = 0; idx < items.size(); ++idx) {
2019-06-27 19:13:44 +00:00
_Item<Shape>& itm = items[idx];
2018-11-12 13:52:52 +00:00
if(isBig(itm.area())) m_rtree.insert({itm.boundingBox(), idx});
m_smallsrtree.insert({itm.boundingBox(), idx});
}
};
m_pck.progressIndicator(progressind);
m_pck.stopCondition(stopcond);
}
2019-06-27 19:13:44 +00:00
template<class...Args> inline _PackGroup<Shape> operator()(Args&&...args) {
2018-11-12 13:52:52 +00:00
m_rtree.clear();
2019-06-27 19:13:44 +00:00
return m_pck.execute(std::forward<Args>(args)...);
2018-11-12 13:52:52 +00:00
}
2019-06-27 19:13:44 +00:00
inline void preload(const _PackGroup<Shape>& pg) {
m_pconf.alignment = PConfig::Alignment::DONT_ALIGN;
m_pconf.object_function = nullptr; // drop the special objectfunction
m_pck.preload(pg);
// Build the rtree for queries to work
for(const ItemGroup& grp : pg)
for(unsigned idx = 0; idx < grp.size(); ++idx) {
2019-06-27 19:13:44 +00:00
_Item<Shape>& itm = grp[idx];
m_rtree.insert({itm.boundingBox(), idx});
}
m_pck.configure(m_pconf);
}
2019-06-27 19:13:44 +00:00
bool is_colliding(const _Item<Shape>& item) {
if(m_rtree.empty()) return false;
std::vector<SpatElement> result;
m_rtree.query(bgi::intersects(item.boundingBox()),
std::back_inserter(result));
return !result.empty();
}
2018-11-12 13:52:52 +00:00
};
2019-01-21 09:34:10 +00:00
// Arranger specialization for a Box shaped bin.
template<> class AutoArranger<Box>: public _ArrBase<Box> {
2018-11-12 13:52:52 +00:00
public:
AutoArranger(const Box& bin, Distance dist,
std::function<void(unsigned)> progressind = [](unsigned){},
std::function<bool(void)> stopcond = [](){return false;}):
2018-11-12 13:52:52 +00:00
_ArrBase<Box>(bin, dist, progressind, stopcond)
{
2019-01-21 09:34:10 +00:00
// Here we set up the actual object function that calls the common
// object function for all bin shapes than does an additional inside
// check for the arranged pile.
2019-06-27 19:13:44 +00:00
m_pconf.object_function = [this, bin] (const _Item<Shape> &item) {
2018-11-12 13:52:52 +00:00
auto result = objfunc(bin.center(),
m_merged_pile,
m_pilebb,
m_items,
item,
m_bin_area,
m_norm,
m_rtree,
m_smallsrtree,
m_remaining);
double score = std::get<0>(result);
auto& fullbb = std::get<1>(result);
double miss = Placer::overfit(fullbb, bin);
miss = miss > 0? miss : 0;
score += miss*miss;
return score;
};
m_pck.configure(m_pconf);
}
};
using lnCircle = libnest2d::_Circle<libnest2d::PointImpl>;
inline lnCircle to_lnCircle(const Circle& circ) {
return lnCircle({circ.center()(0), circ.center()(1)}, circ.radius());
}
2019-01-21 09:34:10 +00:00
// Arranger specialization for circle shaped bin.
template<> class AutoArranger<lnCircle>: public _ArrBase<lnCircle> {
2018-11-12 13:52:52 +00:00
public:
AutoArranger(const lnCircle& bin, Distance dist,
std::function<void(unsigned)> progressind = [](unsigned){},
std::function<bool(void)> stopcond = [](){return false;}):
2018-11-12 13:52:52 +00:00
_ArrBase<lnCircle>(bin, dist, progressind, stopcond) {
2019-01-21 09:34:10 +00:00
// As with the box, only the inside check is different.
2019-06-27 19:13:44 +00:00
m_pconf.object_function = [this, &bin] (const _Item<Shape> &item) {
2018-11-12 13:52:52 +00:00
auto result = objfunc(bin.center(),
m_merged_pile,
m_pilebb,
m_items,
item,
m_bin_area,
m_norm,
m_rtree,
m_smallsrtree,
m_remaining);
double score = std::get<0>(result);
2019-06-27 19:13:44 +00:00
auto isBig = [this](const _Item<Shape>& itm) {
2018-11-12 13:52:52 +00:00
return itm.area()/m_bin_area > BIG_ITEM_TRESHOLD ;
};
if(isBig(item)) {
auto mp = m_merged_pile;
mp.push_back(item.transformedShape());
auto chull = sl::convexHull(mp);
double miss = Placer::overfit(chull, bin);
if(miss < 0) miss = 0;
score += miss*miss;
}
return score;
};
m_pck.configure(m_pconf);
}
};
2019-01-21 09:34:10 +00:00
// Arranger specialization for a generalized polygon.
// Warning: this is unfinished business. It may or may not work.
template<> class AutoArranger<PolygonImpl>: public _ArrBase<PolygonImpl> {
2018-11-12 13:52:52 +00:00
public:
AutoArranger(const PolygonImpl& bin, Distance dist,
std::function<void(unsigned)> progressind = [](unsigned){},
std::function<bool(void)> stopcond = [](){return false;}):
2018-11-12 13:52:52 +00:00
_ArrBase<PolygonImpl>(bin, dist, progressind, stopcond)
{
2019-06-27 19:13:44 +00:00
m_pconf.object_function = [this, &bin] (const _Item<Shape> &item) {
2018-11-12 13:52:52 +00:00
auto binbb = sl::boundingBox(bin);
auto result = objfunc(binbb.center(),
m_merged_pile,
m_pilebb,
m_items,
item,
m_bin_area,
m_norm,
m_rtree,
m_smallsrtree,
m_remaining);
double score = std::get<0>(result);
return score;
};
m_pck.configure(m_pconf);
}
};
2019-01-21 09:34:10 +00:00
// Specialization with no bin. In this case the arranger should just arrange
// all objects into a minimum sized pile but it is not limited by a bin. A
// consequence is that only one pile should be created.
template<> class AutoArranger<bool>: public _ArrBase<Box> {
2018-11-12 13:52:52 +00:00
public:
2019-06-27 19:13:44 +00:00
AutoArranger(bool, Distance dist, std::function<void(unsigned)> progressind,
2018-11-12 13:52:52 +00:00
std::function<bool(void)> stopcond):
_ArrBase<Box>(Box(0, 0), dist, progressind, stopcond)
{
2019-06-27 19:13:44 +00:00
this->m_pconf.object_function = [this] (const _Item<Shape> &item) {
2018-11-12 13:52:52 +00:00
auto result = objfunc({0, 0},
m_merged_pile,
m_pilebb,
m_items,
item,
0,
m_norm,
m_rtree,
m_smallsrtree,
m_remaining);
return std::get<0>(result);
};
this->m_pck.configure(m_pconf);
}
};
// A container which stores a pointer to the 3D object and its projected
// 2D shape from top view.
//using ShapeData2D = std::vector<std::pair<Slic3r::ModelInstance*, Item>>;
//ShapeData2D projectModelFromTop(const Slic3r::Model &model,
// const WipeTowerInfo &wti,
// double tolerance)
//{
// ShapeData2D ret;
// // Count all the items on the bin (all the object's instances)
// auto s = std::accumulate(model.objects.begin(), model.objects.end(),
// size_t(0), [](size_t s, ModelObject* o)
// {
// return s + o->instances.size();
// });
// ret.reserve(s);
// for(ModelObject* objptr : model.objects) {
// if (! objptr->instances.empty()) {
// // TODO export the exact 2D projection. Cannot do it as libnest2d
// // does not support concave shapes (yet).
// ClipperLib::Path clpath;
// // Object instances should carry the same scaling and
// // x, y rotation that is why we use the first instance.
// {
// ModelInstance *finst = objptr->instances.front();
// Vec3d rotation = finst->get_rotation();
// rotation.z() = 0.;
// Transform3d trafo_instance = Geometry::assemble_transform(
// Vec3d::Zero(),
// rotation,
// finst->get_scaling_factor(),
// finst->get_mirror());
// Polygon p = objptr->convex_hull_2d(trafo_instance);
2019-06-19 10:04:11 +00:00
// assert(!p.points.empty());
2019-06-19 10:04:11 +00:00
// // this may happen for malformed models, see:
// // https://github.com/prusa3d/PrusaSlicer/issues/2209
// if (p.points.empty()) continue;
2019-06-19 10:04:11 +00:00
// if(tolerance > EPSILON) {
// Polygons pp { p };
// pp = p.simplify(scaled<double>(tolerance));
// if (!pp.empty()) p = pp.front();
// }
2019-06-19 10:04:11 +00:00
// p.reverse();
// assert(!p.is_counter_clockwise());
// clpath = Slic3rMultiPoint_to_ClipperPath(p);
// auto firstp = clpath.front(); clpath.emplace_back(firstp);
// }
// Vec3d rotation0 = objptr->instances.front()->get_rotation();
// rotation0(2) = 0.;
// for(ModelInstance* objinst : objptr->instances) {
// ClipperLib::Polygon pn;
// pn.Contour = clpath;
// // Efficient conversion to item.
// Item item(std::move(pn));
// // Invalid geometries would throw exceptions when arranging
// if(item.vertexCount() > 3) {
// item.rotation(Geometry::rotation_diff_z(rotation0, objinst->get_rotation()));
// item.translation({
// scaled<ClipperLib::cInt>(objinst->get_offset(X)),
// scaled<ClipperLib::cInt>(objinst->get_offset(Y))
// });
// ret.emplace_back(objinst, item);
// }
// }
// }
// }
// // The wipe tower is a separate case (in case there is one), let's duplicate the code
// if (wti.is_wipe_tower) {
// Points pts;
// pts.emplace_back(coord_t(scale_(0.)), coord_t(scale_(0.)));
// pts.emplace_back(coord_t(scale_(wti.bb_size(0))), coord_t(scale_(0.)));
// pts.emplace_back(coord_t(scale_(wti.bb_size(0))), coord_t(scale_(wti.bb_size(1))));
// pts.emplace_back(coord_t(scale_(-0.)), coord_t(scale_(wti.bb_size(1))));
// pts.emplace_back(coord_t(scale_(-0.)), coord_t(scale_(0.)));
// Polygon p(std::move(pts));
// ClipperLib::Path clpath = Slic3rMultiPoint_to_ClipperPath(p);
// ClipperLib::Polygon pn;
// pn.Contour = clpath;
// // Efficient conversion to item.
// Item item(std::move(pn));
// item.rotation(wti.rotation),
// item.translation({
// scaled<ClipperLib::cInt>(wti.pos(0)),
// scaled<ClipperLib::cInt>(wti.pos(1))
// });
// ret.emplace_back(nullptr, item);
// }
// return ret;
//}
2018-11-12 13:52:52 +00:00
// Apply the calculated translations and rotations (currently disabled) to
// the Model object instances.
//void applyResult(IndexedPackGroup::value_type &group,
// ClipperLib::cInt batch_offset,
// ShapeData2D & shapemap,
// WipeTowerInfo & wti)
//{
// for(auto& r : group) {
// auto idx = r.first; // get the original item index
// Item& item = r.second; // get the item itself
// // Get the model instance from the shapemap using the index
// ModelInstance *inst_ptr = shapemap[idx].first;
// // Get the transformation data from the item object and scale it
// // appropriately
// auto off = item.translation();
// Radians rot = item.rotation();
// Vec3d foff(unscaled(off.X + batch_offset),
// unscaled(off.Y),
// inst_ptr ? inst_ptr->get_offset()(Z) : 0.);
// if (inst_ptr) {
// // write the transformation data into the model instance
// inst_ptr->set_rotation(Z, rot);
// inst_ptr->set_offset(foff);
// }
// else { // this is the wipe tower - we will modify the struct with the info
// // and leave it up to the called to actually move the wipe tower
// wti.pos = Vec2d(foff(0), foff(1));
// wti.rotation = rot;
// }
// }
//}
2018-11-12 13:52:52 +00:00
2019-01-21 09:34:10 +00:00
// Get the type of bed geometry from a simple vector of points.
2018-11-12 13:52:52 +00:00
BedShapeHint bedShape(const Polyline &bed) {
BedShapeHint ret;
auto x = [](const Point& p) { return p(0); };
auto y = [](const Point& p) { return p(1); };
auto width = [x](const BoundingBox& box) {
return x(box.max) - x(box.min);
};
auto height = [y](const BoundingBox& box) {
return y(box.max) - y(box.min);
};
auto area = [&width, &height](const BoundingBox& box) {
double w = width(box);
double h = height(box);
return w*h;
};
auto poly_area = [](Polyline p) {
Polygon pp; pp.points.reserve(p.points.size() + 1);
pp.points = std::move(p.points);
pp.points.emplace_back(pp.points.front());
return std::abs(pp.area());
};
auto distance_to = [x, y](const Point& p1, const Point& p2) {
double dx = x(p2) - x(p1);
double dy = y(p2) - y(p1);
return std::sqrt(dx*dx + dy*dy);
};
auto bb = bed.bounding_box();
auto isCircle = [bb, distance_to](const Polyline& polygon) {
auto center = bb.center();
std::vector<double> vertex_distances;
double avg_dist = 0;
for (auto pt: polygon.points)
{
double distance = distance_to(center, pt);
vertex_distances.push_back(distance);
avg_dist += distance;
}
avg_dist /= vertex_distances.size();
Circle ret(center, avg_dist);
for(auto el : vertex_distances)
2018-11-12 13:52:52 +00:00
{
if (std::abs(el - avg_dist) > 10 * SCALED_EPSILON) {
2018-11-12 13:52:52 +00:00
ret = Circle();
break;
}
2018-11-12 13:52:52 +00:00
}
return ret;
};
auto parea = poly_area(bed);
if( (1.0 - parea/area(bb)) < 1e-3 ) {
ret.type = BedShapeType::BOX;
ret.shape.box = bb;
}
else if(auto c = isCircle(bed)) {
ret.type = BedShapeType::CIRCLE;
ret.shape.circ = c;
} else {
ret.type = BedShapeType::IRREGULAR;
ret.shape.polygon = bed;
}
// Determine the bed shape by hand
return ret;
}
2019-06-27 19:13:44 +00:00
//static const SLIC3R_CONSTEXPR double SIMPLIFY_TOLERANCE_MM = 0.1;
2019-06-19 11:19:11 +00:00
2019-06-27 19:13:44 +00:00
template<class BinT>
_PackGroup<Shape> _arrange(std::vector<Shape> &shapes,
const BinT & bin,
coord_t minobjd,
std::function<void(unsigned)> prind,
std::function<bool()> stopfn)
{
AutoArranger<BinT> arranger{bin, minobjd, prind, stopfn};
return arranger(shapes.begin(), shapes.end());
}
//template<class BinT>
//IndexedPackGroup _arrange(std::vector<std::reference_wrapper<Item>> &shapes,
// const PackGroup & preshapes,
// std::vector<ModelInstance *> &minstances,
// const BinT & bin,
// coord_t minobjd)
//{
// auto binbb = sl::boundingBox(bin);
// AutoArranger<BinT> arranger{bin, minobjd};
// if(!preshapes.front().empty()) { // If there is something on the plate
// arranger.preload(preshapes);
// // Try to put the first item to the center, as the arranger will not
// // do this for us.
// auto shptrit = minstances.begin();
// for(auto shit = shapes.begin(); shit != shapes.end(); ++shit, ++shptrit)
// {
// // Try to place items to the center
// Item& itm = *shit;
// auto ibb = itm.boundingBox();
// auto d = binbb.center() - ibb.center();
// itm.translate(d);
// if(!arranger.is_colliding(itm)) {
// arranger.preload({{itm}});
// auto offset = itm.translation();
// Radians rot = itm.rotation();
// ModelInstance *minst = *shptrit;
// Vec3d foffset(unscaled(offset.X),
// unscaled(offset.Y),
// minst->get_offset()(Z));
// // write the transformation data into the model instance
// minst->set_rotation(Z, rot);
// minst->set_offset(foffset);
// shit = shapes.erase(shit);
// shptrit = minstances.erase(shptrit);
// break;
// }
// }
// }
// return arranger(shapes.begin(), shapes.end());
//}
2019-06-27 19:13:44 +00:00
inline SLIC3R_CONSTEXPR coord_t stride_padding(coord_t w)
{
return w + w / 5;
}
2019-06-27 19:13:44 +00:00
bool arrange(ArrangeableRefs & arrangables,
coord_t min_obj_distance,
BedShapeHint bedhint,
std::function<void(unsigned)> progressind,
std::function<bool()> stopcondition)
{
bool ret = true;
std::vector<Shape> shapes;
shapes.reserve(arrangables.size());
size_t id = 0;
for (Arrangeable &iref : arrangables) {
Polygon p = iref.get_arrange_polygon();
p.reverse();
assert(!p.is_counter_clockwise());
Shape clpath(/*id++,*/ Slic3rMultiPoint_to_ClipperPath(p));
auto firstp = clpath.Contour.front(); clpath.Contour.emplace_back(firstp);
shapes.emplace_back(std::move(clpath));
}
_PackGroup<Shape> result;
auto& cfn = stopcondition;
// Integer ceiling the min distance from the bed perimeters
coord_t md = min_obj_distance - SCALED_EPSILON;
md = (md % 2) ? md / 2 + 1 : md / 2;
coord_t binwidth = 0;
switch (bedhint.type) {
case BedShapeType::BOX: {
// Create the arranger for the box shaped bed
BoundingBox bbb = bedhint.shape.box;
auto binbb = Box({ClipperLib::cInt{bbb.min(0)} - md,
ClipperLib::cInt{bbb.min(1)} - md},
{ClipperLib::cInt{bbb.max(0)} + md,
ClipperLib::cInt{bbb.max(1)} + md});
result = _arrange(shapes, binbb, min_obj_distance, progressind, cfn);
binwidth = coord_t(binbb.width());
break;
}
case BedShapeType::CIRCLE: {
auto c = bedhint.shape.circ;
auto cc = to_lnCircle(c);
result = _arrange(shapes, cc, min_obj_distance, progressind, cfn);
binwidth = scaled(c.radius());
break;
}
case BedShapeType::IRREGULAR: {
auto ctour = Slic3rMultiPoint_to_ClipperPath(bedhint.shape.polygon);
ClipperLib::Polygon irrbed = sl::create<PolygonImpl>(std::move(ctour));
result = _arrange(shapes, irrbed, min_obj_distance, progressind, cfn);
BoundingBox polybb(bedhint.shape.polygon);
binwidth = (polybb.max(X) - polybb.min(X));
break;
}
case BedShapeType::WHO_KNOWS: {
result = _arrange(shapes, false, min_obj_distance, progressind, cfn);
break;
}
};
if(result.empty() || stopcondition()) return false;
ClipperLib::cInt stride = stride_padding(binwidth);
ClipperLib::cInt batch_offset = 0;
for (const auto &group : result) {
for (_Item<Shape> &itm : group) {
ClipperLib::IntPoint offs = itm.translation();
// arrangables[itm.id()].get().set_arrange_result({offs.X, offs.Y},
// itm.rotation());
}
// Only the first pack group can be placed onto the print bed. The
// other objects which could not fit will be placed next to the
// print bed
batch_offset += stride;
}
return ret;
}
//// The final client function to arrange the Model. A progress indicator and
//// a stop predicate can be also be passed to control the process.
//bool arrange(Model &model, // The model with the geometries
// WipeTowerInfo& wti, // Wipe tower info
// coord_t min_obj_distance, // Has to be in scaled (clipper) measure
// const Polyline &bed, // The bed geometry.
// BedShapeHint bedhint, // Hint about the bed geometry type.
// bool first_bin_only, // What to do is not all items fit.
// // Controlling callbacks.
// std::function<void (unsigned)> progressind,
// std::function<bool ()> stopcondition)
//{
// bool ret = true;
2019-06-19 10:04:11 +00:00
// // Get the 2D projected shapes with their 3D model instance pointers
// auto shapemap = arr::projectModelFromTop(model, wti, SIMPLIFY_TOLERANCE_MM);
2018-11-12 13:52:52 +00:00
// // Copy the references for the shapes only as the arranger expects a
// // sequence of objects convertible to Item or ClipperPolygon
// std::vector<std::reference_wrapper<Item>> shapes;
// shapes.reserve(shapemap.size());
// std::for_each(shapemap.begin(), shapemap.end(),
// [&shapes] (ShapeData2D::value_type& it)
// {
// shapes.push_back(std::ref(it.second));
// });
2018-11-12 13:52:52 +00:00
// IndexedPackGroup result;
2018-11-12 13:52:52 +00:00
// // If there is no hint about the shape, we will try to guess
// if(bedhint.type == BedShapeType::WHO_KNOWS) bedhint = bedShape(bed);
2018-11-12 13:52:52 +00:00
// BoundingBox bbb(bed);
2018-11-12 13:52:52 +00:00
// auto& cfn = stopcondition;
// // Integer ceiling the min distance from the bed perimeters
// coord_t md = min_obj_distance - SCALED_EPSILON;
// md = (md % 2) ? md / 2 + 1 : md / 2;
// auto binbb = Box({ClipperLib::cInt{bbb.min(0)} - md,
// ClipperLib::cInt{bbb.min(1)} - md},
// {ClipperLib::cInt{bbb.max(0)} + md,
// ClipperLib::cInt{bbb.max(1)} + md});
// switch(bedhint.type) {
// case BedShapeType::BOX: {
// // Create the arranger for the box shaped bed
// result = _arrange(shapes, binbb, min_obj_distance, progressind, cfn);
// break;
// }
// case BedShapeType::CIRCLE: {
// auto c = bedhint.shape.circ;
// auto cc = to_lnCircle(c);
// result = _arrange(shapes, cc, min_obj_distance, progressind, cfn);
// break;
// }
// case BedShapeType::IRREGULAR:
// case BedShapeType::WHO_KNOWS: {
// auto ctour = Slic3rMultiPoint_to_ClipperPath(bed);
// ClipperLib::Polygon irrbed = sl::create<PolygonImpl>(std::move(ctour));
// result = _arrange(shapes, irrbed, min_obj_distance, progressind, cfn);
// break;
// }
// };
// if(result.empty() || stopcondition()) return false;
// if(first_bin_only) {
// applyResult(result.front(), 0, shapemap, wti);
// } else {
// ClipperLib::cInt stride = stride_padding(binbb.width());
// ClipperLib::cInt batch_offset = 0;
// for(auto& group : result) {
// applyResult(group, batch_offset, shapemap, wti);
// // Only the first pack group can be placed onto the print bed. The
// // other objects which could not fit will be placed next to the
// // print bed
// batch_offset += stride;
// }
// }
// for(auto objptr : model.objects) objptr->invalidate_bounding_box();
// return ret && result.size() == 1;
//}
//void find_new_position(const Model &model,
// ModelInstancePtrs toadd,
// coord_t min_obj_distance,
// const Polyline &bed,
// WipeTowerInfo& wti)
//{
// // Get the 2D projected shapes with their 3D model instance pointers
// auto shapemap = arr::projectModelFromTop(model, wti, SIMPLIFY_TOLERANCE_MM);
// // Copy the references for the shapes only, as the arranger expects a
// // sequence of objects convertible to Item or ClipperPolygon
// PackGroup preshapes; preshapes.emplace_back();
// ItemGroup shapes;
// preshapes.front().reserve(shapemap.size());
// std::vector<ModelInstance*> shapes_ptr; shapes_ptr.reserve(toadd.size());
// IndexedPackGroup result;
// // If there is no hint about the shape, we will try to guess
// BedShapeHint bedhint = bedShape(bed);
// BoundingBox bbb(bed);
// // Integer ceiling the min distance from the bed perimeters
// coord_t md = min_obj_distance - SCALED_EPSILON;
// md = (md % 2) ? md / 2 + 1 : md / 2;
// auto binbb = Box({ClipperLib::cInt{bbb.min(0)} - md,
// ClipperLib::cInt{bbb.min(1)} - md},
// {ClipperLib::cInt{bbb.max(0)} + md,
// ClipperLib::cInt{bbb.max(1)} + md});
// for(auto it = shapemap.begin(); it != shapemap.end(); ++it) {
// // `toadd` vector contains the instance pointers which have to be
// // considered by arrange. If `it` points to an ModelInstance, which
// // is NOT in `toadd`, add it to preshapes.
// if(std::find(toadd.begin(), toadd.end(), it->first) == toadd.end()) {
// if(it->second.isInside(binbb)) // just ignore items which are outside
// preshapes.front().emplace_back(std::ref(it->second));
// }
// else {
// shapes_ptr.emplace_back(it->first);
// shapes.emplace_back(std::ref(it->second));
// }
// }
// switch(bedhint.type) {
// case BedShapeType::BOX: {
// // Create the arranger for the box shaped bed
// result = _arrange(shapes, preshapes, shapes_ptr, binbb, min_obj_distance);
// break;
// }
// case BedShapeType::CIRCLE: {
// auto c = bedhint.shape.circ;
// auto cc = to_lnCircle(c);
// result = _arrange(shapes, preshapes, shapes_ptr, cc, min_obj_distance);
// break;
// }
// case BedShapeType::IRREGULAR:
// case BedShapeType::WHO_KNOWS: {
// auto ctour = Slic3rMultiPoint_to_ClipperPath(bed);
// ClipperLib::Polygon irrbed = sl::create<PolygonImpl>(std::move(ctour));
// result = _arrange(shapes, preshapes, shapes_ptr, irrbed, min_obj_distance);
// break;
// }
// };
// // Now we go through the result which will contain the fixed and the moving
// // polygons as well. We will have to search for our item.
// ClipperLib::cInt stride = stride_padding(binbb.width());
// ClipperLib::cInt batch_offset = 0;
// for(auto& group : result) {
// for(auto& r : group) if(r.first < shapes.size()) {
// Item& resultitem = r.second;
// unsigned idx = r.first;
// auto offset = resultitem.translation();
// Radians rot = resultitem.rotation();
// ModelInstance *minst = shapes_ptr[idx];
// Vec3d foffset(unscaled(offset.X + batch_offset),
// unscaled(offset.Y),
// minst->get_offset()(Z));
// // write the transformation data into the model instance
// minst->set_rotation(Z, rot);
// minst->set_offset(foffset);
// }
// batch_offset += stride;
// }
//}
2018-11-12 13:52:52 +00:00
}
2018-11-12 13:52:52 +00:00
}