Add the full source of BambuStudio

using version 1.0.10
This commit is contained in:
lane.wei 2022-07-15 23:37:19 +08:00 committed by Lane.Wei
parent 30bcadab3e
commit 1555904bef
3771 changed files with 1251328 additions and 0 deletions

View file

@ -0,0 +1,138 @@
#include "Circle.hpp"
#include "../Polygon.hpp"
#include <numeric>
#include <random>
#include <boost/log/trivial.hpp>
namespace Slic3r { namespace Geometry {
Point circle_center_taubin_newton(const Points::const_iterator& input_begin, const Points::const_iterator& input_end, size_t cycles)
{
Vec2ds tmp;
tmp.reserve(std::distance(input_begin, input_end));
std::transform(input_begin, input_end, std::back_inserter(tmp), [] (const Point& in) { return unscale(in); } );
Vec2d center = circle_center_taubin_newton(tmp.cbegin(), tmp.end(), cycles);
return Point::new_scale(center.x(), center.y());
}
/// Adapted from work in "Circular and Linear Regression: Fitting circles and lines by least squares", pg 126
/// Returns a point corresponding to the center of a circle for which all of the points from input_begin to input_end
/// lie on.
Vec2d circle_center_taubin_newton(const Vec2ds::const_iterator& input_begin, const Vec2ds::const_iterator& input_end, size_t cycles)
{
// calculate the centroid of the data set
const Vec2d sum = std::accumulate(input_begin, input_end, Vec2d(0,0));
const size_t n = std::distance(input_begin, input_end);
const double n_flt = static_cast<double>(n);
const Vec2d centroid { sum / n_flt };
// Compute the normalized moments of the data set.
double Mxx = 0, Myy = 0, Mxy = 0, Mxz = 0, Myz = 0, Mzz = 0;
for (auto it = input_begin; it < input_end; ++it) {
// center/normalize the data.
double Xi {it->x() - centroid.x()};
double Yi {it->y() - centroid.y()};
double Zi {Xi*Xi + Yi*Yi};
Mxy += (Xi*Yi);
Mxx += (Xi*Xi);
Myy += (Yi*Yi);
Mxz += (Xi*Zi);
Myz += (Yi*Zi);
Mzz += (Zi*Zi);
}
// divide by number of points to get the moments
Mxx /= n_flt;
Myy /= n_flt;
Mxy /= n_flt;
Mxz /= n_flt;
Myz /= n_flt;
Mzz /= n_flt;
// Compute the coefficients of the characteristic polynomial for the circle
// eq 5.60
const double Mz {Mxx + Myy}; // xx + yy = z
const double Cov_xy {Mxx*Myy - Mxy*Mxy}; // this shows up a couple times so cache it here.
const double C3 {4.0*Mz};
const double C2 {-3.0*(Mz*Mz) - Mzz};
const double C1 {Mz*(Mzz - (Mz*Mz)) + 4.0*Mz*Cov_xy - (Mxz*Mxz) - (Myz*Myz)};
const double C0 {(Mxz*Mxz)*Myy + (Myz*Myz)*Mxx - 2.0*Mxz*Myz*Mxy - Cov_xy*(Mzz - (Mz*Mz))};
const double C22 = {C2 + C2};
const double C33 = {C3 + C3 + C3};
// solve the characteristic polynomial with Newton's method.
double xnew = 0.0;
double ynew = 1e20;
for (size_t i = 0; i < cycles; ++i) {
const double yold {ynew};
ynew = C0 + xnew * (C1 + xnew*(C2 + xnew * C3));
if (std::abs(ynew) > std::abs(yold)) {
BOOST_LOG_TRIVIAL(error) << "Geometry: Fit is going in the wrong direction.\n";
return Vec2d(std::nan(""), std::nan(""));
}
const double Dy {C1 + xnew*(C22 + xnew*C33)};
const double xold {xnew};
xnew = xold - (ynew / Dy);
if (std::abs((xnew-xold) / xnew) < 1e-12) i = cycles; // converged, we're done here
if (xnew < 0) {
// reset, we went negative
xnew = 0.0;
}
}
// compute the determinant and the circle's parameters now that we've solved.
double DET = xnew*xnew - xnew*Mz + Cov_xy;
Vec2d center(Mxz * (Myy - xnew) - Myz * Mxy, Myz * (Mxx - xnew) - Mxz*Mxy);
center /= (DET * 2.);
return center + centroid;
}
Circled circle_taubin_newton(const Vec2ds& input, size_t cycles)
{
Circled out;
if (input.size() < 3) {
out = Circled::make_invalid();
} else {
out.center = circle_center_taubin_newton(input, cycles);
out.radius = std::accumulate(input.begin(), input.end(), 0., [&out](double acc, const Vec2d& pt) { return (pt - out.center).norm() + acc; });
out.radius /= double(input.size());
}
return out;
}
Circled circle_ransac(const Vec2ds& input, size_t iterations)
{
if (input.size() < 3)
return Circled::make_invalid();
std::mt19937 rng;
std::vector<Vec2d> samples;
Circled circle_best = Circled::make_invalid();
double err_min = std::numeric_limits<double>::max();
for (size_t iter = 0; iter < iterations; ++ iter) {
samples.clear();
std::sample(input.begin(), input.end(), std::back_inserter(samples), 3, rng);
Circled c;
c.center = Geometry::circle_center(samples[0], samples[1], samples[2], EPSILON);
c.radius = std::accumulate(input.begin(), input.end(), 0., [&c](double acc, const Vec2d& pt) { return (pt - c.center).norm() + acc; });
c.radius /= double(input.size());
double err = 0;
for (const Vec2d &pt : input)
err = std::max(err, std::abs((pt - c.center).norm() - c.radius));
if (err < err_min) {
err_min = err;
circle_best = c;
}
}
return circle_best;
}
} } // namespace Slic3r::Geometry

View file

@ -0,0 +1,187 @@
#ifndef slic3r_Geometry_Circle_hpp_
#define slic3r_Geometry_Circle_hpp_
#include "../Point.hpp"
#include <Eigen/Geometry>
namespace Slic3r { namespace Geometry {
// https://en.wikipedia.org/wiki/Circumscribed_circle
// Circumcenter coordinates, Cartesian coordinates
template<typename Vector>
Vector circle_center(const Vector &a, const Vector &bsrc, const Vector &csrc, typename Vector::Scalar epsilon)
{
using Scalar = typename Vector::Scalar;
Vector b = bsrc - a;
Vector c = csrc - a;
Scalar lb = b.squaredNorm();
Scalar lc = c.squaredNorm();
if (Scalar d = b.x() * c.y() - b.y() * c.x(); std::abs(d) < epsilon) {
// The three points are collinear. Take the center of the two points
// furthest away from each other.
Scalar lbc = (csrc - bsrc).squaredNorm();
return Scalar(0.5) * (
lb > lc && lb > lbc ? a + bsrc :
lc > lb && lc > lbc ? a + csrc : bsrc + csrc);
} else {
Vector v = lc * b - lb * c;
return a + Vector(- v.y(), v.x()) / (2 * d);
}
}
// 2D circle defined by its center and squared radius
template<typename Vector>
struct CircleSq {
using Scalar = typename Vector::Scalar;
Vector center;
Scalar radius2;
CircleSq() {}
CircleSq(const Vector &center, const Scalar radius2) : center(center), radius2(radius2) {}
CircleSq(const Vector &a, const Vector &b) : center(Scalar(0.5) * (a + b)) { radius2 = (a - center).squaredNorm(); }
CircleSq(const Vector &a, const Vector &b, const Vector &c, Scalar epsilon) {
this->center = circle_center(a, b, c, epsilon);
this->radius2 = (a - this->center).squaredNorm();
}
bool invalid() const { return this->radius2 < 0; }
bool valid() const { return ! this->invalid(); }
bool contains(const Vector &p) const { return (p - this->center).squaredNorm() < this->radius2; }
bool contains(const Vector &p, const Scalar epsilon2) const { return (p - this->center).squaredNorm() < this->radius2 + epsilon2; }
CircleSq inflated(Scalar epsilon) const
{ assert(this->radius2 >= 0); Scalar r = sqrt(this->radius2) + epsilon; return { this->center, r * r }; }
static CircleSq make_invalid() { return CircleSq { { 0, 0 }, -1 }; }
};
// 2D circle defined by its center and radius
template<typename Vector>
struct Circle {
using Scalar = typename Vector::Scalar;
Vector center;
Scalar radius;
Circle() {}
Circle(const Vector &center, const Scalar radius) : center(center), radius(radius) {}
Circle(const Vector &a, const Vector &b) : center(Scalar(0.5) * (a + b)) { radius = (a - center).norm(); }
Circle(const Vector &a, const Vector &b, const Vector &c, const Scalar epsilon) { *this = CircleSq(a, b, c, epsilon); }
// Conversion from CircleSq
template<typename Vector2>
explicit Circle(const CircleSq<Vector2> &c) : center(c.center), radius(c.radius2 <= 0 ? c.radius2 : sqrt(c.radius2)) {}
template<typename Vector2>
Circle operator=(const CircleSq<Vector2>& c) { this->center = c.center; this->radius = c.radius2 <= 0 ? c.radius2 : sqrt(c.radius2); }
bool invalid() const { return this->radius < 0; }
bool valid() const { return ! this->invalid(); }
bool contains(const Vector &p) const { return (p - this->center).squaredNorm() <= this->radius * this->radius; }
bool contains(const Vector &p, const Scalar epsilon) const
{ Scalar re = this->radius + epsilon; return (p - this->center).squaredNorm() < re * re; }
Circle inflated(Scalar epsilon) const { assert(this->radius >= 0); return { this->center, this->radius + epsilon }; }
static Circle make_invalid() { return Circle { { 0, 0 }, -1 }; }
};
using Circlef = Circle<Vec2f>;
using Circled = Circle<Vec2d>;
using CircleSqf = CircleSq<Vec2f>;
using CircleSqd = CircleSq<Vec2d>;
/// Find the center of the circle corresponding to the vector of Points as an arc.
Point circle_center_taubin_newton(const Points::const_iterator& input_start, const Points::const_iterator& input_end, size_t cycles = 20);
inline Point circle_center_taubin_newton(const Points& input, size_t cycles = 20) { return circle_center_taubin_newton(input.cbegin(), input.cend(), cycles); }
/// Find the center of the circle corresponding to the vector of Pointfs as an arc.
Vec2d circle_center_taubin_newton(const Vec2ds::const_iterator& input_start, const Vec2ds::const_iterator& input_end, size_t cycles = 20);
inline Vec2d circle_center_taubin_newton(const Vec2ds& input, size_t cycles = 20) { return circle_center_taubin_newton(input.cbegin(), input.cend(), cycles); }
Circled circle_taubin_newton(const Vec2ds& input, size_t cycles = 20);
// Find circle using RANSAC randomized algorithm.
Circled circle_ransac(const Vec2ds& input, size_t iterations = 20);
// Randomized algorithm by Emo Welzl, working with squared radii for efficiency. The returned circle radius is inflated by epsilon.
template<typename Vector, typename Points>
CircleSq<Vector> smallest_enclosing_circle2_welzl(const Points &points, const typename Vector::Scalar epsilon)
{
using Scalar = typename Vector::Scalar;
CircleSq<Vector> circle;
if (! points.empty()) {
const auto &p0 = points[0].template cast<Scalar>();
if (points.size() == 1) {
circle.center = p0;
circle.radius2 = epsilon * epsilon;
} else {
circle = CircleSq<Vector>(p0, points[1].template cast<Scalar>()).inflated(epsilon);
for (size_t i = 2; i < points.size(); ++ i)
if (const Vector &p = points[i].template cast<Scalar>(); ! circle.contains(p)) {
// p is the first point on the smallest circle enclosing points[0..i]
circle = CircleSq<Vector>(p0, p).inflated(epsilon);
for (size_t j = 1; j < i; ++ j)
if (const Vector &q = points[j].template cast<Scalar>(); ! circle.contains(q)) {
// q is the second point on the smallest circle enclosing points[0..i]
circle = CircleSq<Vector>(p, q).inflated(epsilon);
for (size_t k = 0; k < j; ++ k)
if (const Vector &r = points[k].template cast<Scalar>(); ! circle.contains(r))
circle = CircleSq<Vector>(p, q, r, epsilon).inflated(epsilon);
}
}
}
}
return circle;
}
// Randomized algorithm by Emo Welzl. The returned circle radius is inflated by epsilon.
template<typename Vector, typename Points>
Circle<Vector> smallest_enclosing_circle_welzl(const Points &points, const typename Vector::Scalar epsilon)
{
return Circle<Vector>(smallest_enclosing_circle2_welzl<Vector, Points>(points, epsilon));
}
// Randomized algorithm by Emo Welzl. The returned circle radius is inflated by SCALED_EPSILON.
inline Circled smallest_enclosing_circle_welzl(const Points &points)
{
return smallest_enclosing_circle_welzl<Vec2d, Points>(points, SCALED_EPSILON);
}
// Ugly named variant, that accepts the squared line
// Don't call me with a nearly zero length vector!
// sympy:
// factor(solve([a * x + b * y + c, x**2 + y**2 - r**2], [x, y])[0])
// factor(solve([a * x + b * y + c, x**2 + y**2 - r**2], [x, y])[1])
template<typename T>
int ray_circle_intersections_r2_lv2_c(T r2, T a, T b, T lv2, T c, std::pair<Eigen::Matrix<T, 2, 1, Eigen::DontAlign>, Eigen::Matrix<T, 2, 1, Eigen::DontAlign>> &out)
{
T x0 = - a * c;
T y0 = - b * c;
T d2 = r2 * lv2 - c * c;
if (d2 < T(0))
return 0;
T d = sqrt(d2);
out.first.x() = (x0 + b * d) / lv2;
out.first.y() = (y0 - a * d) / lv2;
out.second.x() = (x0 - b * d) / lv2;
out.second.y() = (y0 + a * d) / lv2;
return d == T(0) ? 1 : 2;
}
template<typename T>
int ray_circle_intersections(T r, T a, T b, T c, std::pair<Eigen::Matrix<T, 2, 1, Eigen::DontAlign>, Eigen::Matrix<T, 2, 1, Eigen::DontAlign>> &out)
{
T lv2 = a * a + b * b;
if (lv2 < T(SCALED_EPSILON * SCALED_EPSILON)) {
//FIXME what is the correct epsilon?
// What if the line touches the circle?
return false;
}
return ray_circle_intersections_r2_lv2_c2(r * r, a, b, a * a + b * b, c, out);
}
} } // namespace Slic3r::Geometry
#endif // slic3r_Geometry_Circle_hpp_

View file

@ -0,0 +1,399 @@
#include "libslic3r.h"
#include "ConvexHull.hpp"
#include "BoundingBox.hpp"
#include <boost/multiprecision/integer.hpp>
namespace Slic3r { namespace Geometry {
// This implementation is based on Andrew's monotone chain 2D convex hull algorithm
Polygon convex_hull(Points pts)
{
std::sort(pts.begin(), pts.end(), [](const Point& a, const Point& b) { return a.x() < b.x() || (a.x() == b.x() && a.y() < b.y()); });
pts.erase(std::unique(pts.begin(), pts.end(), [](const Point& a, const Point& b) { return a.x() == b.x() && a.y() == b.y(); }), pts.end());
Polygon hull;
int n = (int)pts.size();
if (n >= 3) {
int k = 0;
hull.points.resize(2 * n);
// Build lower hull
for (int i = 0; i < n; ++ i) {
while (k >= 2 && pts[i].ccw(hull[k-2], hull[k-1]) <= 0)
-- k;
hull[k ++] = pts[i];
}
// Build upper hull
for (int i = n-2, t = k+1; i >= 0; i--) {
while (k >= t && pts[i].ccw(hull[k-2], hull[k-1]) <= 0)
-- k;
hull[k ++] = pts[i];
}
hull.points.resize(k);
assert(hull.points.front() == hull.points.back());
hull.points.pop_back();
}
return hull;
}
Pointf3s convex_hull(Pointf3s points)
{
assert(points.size() >= 3);
// sort input points
std::sort(points.begin(), points.end(), [](const Vec3d &a, const Vec3d &b){ return a.x() < b.x() || (a.x() == b.x() && a.y() < b.y()); });
int n = points.size(), k = 0;
Pointf3s hull;
if (n >= 3)
{
hull.resize(2 * n);
// Build lower hull
for (int i = 0; i < n; ++i)
{
Point p = Point::new_scale(points[i](0), points[i](1));
while (k >= 2)
{
Point k1 = Point::new_scale(hull[k - 1](0), hull[k - 1](1));
Point k2 = Point::new_scale(hull[k - 2](0), hull[k - 2](1));
if (p.ccw(k2, k1) <= 0)
--k;
else
break;
}
hull[k++] = points[i];
}
// Build upper hull
for (int i = n - 2, t = k + 1; i >= 0; --i)
{
Point p = Point::new_scale(points[i](0), points[i](1));
while (k >= t)
{
Point k1 = Point::new_scale(hull[k - 1](0), hull[k - 1](1));
Point k2 = Point::new_scale(hull[k - 2](0), hull[k - 2](1));
if (p.ccw(k2, k1) <= 0)
--k;
else
break;
}
hull[k++] = points[i];
}
hull.resize(k);
assert(hull.front() == hull.back());
hull.pop_back();
}
return hull;
}
Polygon convex_hull(const Polygons &polygons)
{
Points pp;
for (Polygons::const_iterator p = polygons.begin(); p != polygons.end(); ++p) {
pp.insert(pp.end(), p->points.begin(), p->points.end());
}
return convex_hull(std::move(pp));
}
namespace rotcalip {
using int256_t = boost::multiprecision::int256_t;
using int128_t = boost::multiprecision::int128_t;
template<class Scalar = int64_t>
inline Scalar magnsq(const Point &p)
{
return Scalar(p.x()) * p.x() + Scalar(p.y()) * p.y();
}
template<class Scalar = int64_t>
inline Scalar dot(const Point &a, const Point &b)
{
return Scalar(a.x()) * b.x() + Scalar(a.y()) * b.y();
}
template<class Scalar = int64_t>
inline Scalar dotperp(const Point &a, const Point &b)
{
return Scalar(a.x()) * b.y() - Scalar(a.y()) * b.x();
}
using boost::multiprecision::abs;
// Compares the angle enclosed by vectors dir and dirA (alpha) with the angle
// enclosed by -dir and dirB (beta). Returns -1 if alpha is less than beta, 0
// if they are equal and 1 if alpha is greater than beta. Note that dir is
// reversed for beta, because it represents the opposite side of a caliper.
int cmp_angles(const Point &dir, const Point &dirA, const Point &dirB) {
int128_t dotA = dot(dir, dirA);
int128_t dotB = dot(-dir, dirB);
int256_t dcosa = int256_t(magnsq(dirB)) * int256_t(abs(dotA)) * dotA;
int256_t dcosb = int256_t(magnsq(dirA)) * int256_t(abs(dotB)) * dotB;
int256_t diff = dcosa - dcosb;
return diff > 0? -1 : (diff < 0 ? 1 : 0);
}
// A helper class to navigate on a polygon. Given a vertex index, one can
// get the edge belonging to that vertex, the coordinates of the vertex, the
// next and previous edges. Stuff that is needed in the rotating calipers algo.
class Idx
{
size_t m_idx;
const Polygon *m_poly;
public:
explicit Idx(const Polygon &p): m_idx{0}, m_poly{&p} {}
explicit Idx(size_t idx, const Polygon &p): m_idx{idx}, m_poly{&p} {}
size_t idx() const { return m_idx; }
void set_idx(size_t i) { m_idx = i; }
size_t next() const { return (m_idx + 1) % m_poly->size(); }
size_t inc() { return m_idx = (m_idx + 1) % m_poly->size(); }
Point prev_dir() const {
return pt() - (*m_poly)[(m_idx + m_poly->size() - 1) % m_poly->size()];
}
const Point &pt() const { return (*m_poly)[m_idx]; }
const Point dir() const { return (*m_poly)[next()] - pt(); }
const Point next_dir() const
{
return (*m_poly)[(m_idx + 2) % m_poly->size()] - (*m_poly)[next()];
}
const Polygon &poly() const { return *m_poly; }
};
enum class AntipodalVisitMode { Full, EdgesOnly };
// Visit all antipodal pairs starting from the initial ia, ib pair which
// has to be a valid antipodal pair (not checked). fn is called for every
// antipodal pair encountered including the initial one.
// The callback Fn has a signiture of bool(size_t i, size_t j, const Point &dir)
// where i,j are the vertex indices of the antipodal pair and dir is the
// direction of the calipers touching the i vertex.
template<AntipodalVisitMode mode = AntipodalVisitMode::Full, class Fn>
void visit_antipodals (Idx& ia, Idx &ib, Fn &&fn)
{
// Set current caliper direction to be the lower edge angle from X axis
int cmp = cmp_angles(ia.prev_dir(), ia.dir(), ib.dir());
Idx *current = cmp <= 0 ? &ia : &ib, *other = cmp <= 0 ? &ib : &ia;
Idx *initial = current;
bool visitor_continue = true;
size_t start = initial->idx();
bool finished = false;
while (visitor_continue && !finished) {
Point current_dir_a = current == &ia ? current->dir() : -current->dir();
visitor_continue = fn(ia.idx(), ib.idx(), current_dir_a);
// Parallel edges encountered. An additional pair of antipodals
// can be yielded.
if constexpr (mode == AntipodalVisitMode::Full)
if (cmp == 0 && visitor_continue) {
visitor_continue = fn(current == &ia ? ia.idx() : ia.next(),
current == &ib ? ib.idx() : ib.next(),
current_dir_a);
}
cmp = cmp_angles(current->dir(), current->next_dir(), other->dir());
current->inc();
if (cmp > 0) {
std::swap(current, other);
}
if (initial->idx() == start) finished = true;
}
}
} // namespace rotcalip
bool convex_polygons_intersect(const Polygon &A, const Polygon &B)
{
using namespace rotcalip;
// Establish starting antipodals as extremes in XY plane. Use the
// easily obtainable bounding boxes to check if A and B is disjoint
// and return false if the are.
struct BB
{
size_t xmin = 0, xmax = 0, ymin = 0, ymax = 0;
const Polygon &P;
static bool cmpy(const Point &l, const Point &u)
{
return l.y() < u.y() || (l.y() == u.y() && l.x() < u.x());
}
BB(const Polygon &poly): P{poly}
{
for (size_t i = 0; i < P.size(); ++i) {
if (P[i] < P[xmin]) xmin = i;
if (P[xmax] < P[i]) xmax = i;
if (cmpy(P[i], P[ymin])) ymin = i;
if (cmpy(P[ymax], P[i])) ymax = i;
}
}
};
BB bA{A}, bB{B};
BoundingBox bbA{{A[bA.xmin].x(), A[bA.ymin].y()}, {A[bA.xmax].x(), A[bA.ymax].y()}};
BoundingBox bbB{{B[bB.xmin].x(), B[bB.ymin].y()}, {B[bB.xmax].x(), B[bB.ymax].y()}};
// if (!bbA.overlap(bbB))
// return false;
// Establish starting antipodals as extreme vertex pairs in X or Y direction
// which reside on different polygons. If no such pair is found, the two
// polygons are certainly not disjoint.
Idx imin{bA.xmin, A}, imax{bB.xmax, B};
if (B[bB.xmin] < imin.pt()) imin = Idx{bB.xmin, B};
if (imax.pt() < A[bA.xmax]) imax = Idx{bA.xmax, A};
if (&imin.poly() == &imax.poly()) {
imin = Idx{bA.ymin, A};
imax = Idx{bB.ymax, B};
if (B[bB.ymin] < imin.pt()) imin = Idx{bB.ymin, B};
if (imax.pt() < A[bA.ymax]) imax = Idx{bA.ymax, A};
}
if (&imin.poly() == &imax.poly())
return true;
bool found_divisor = false;
visit_antipodals<AntipodalVisitMode::EdgesOnly>(
imin, imax,
[&imin, &imax, &found_divisor](size_t ia, size_t ib, const Point &dir) {
// std::cout << "A" << ia << " B" << ib << " dir " <<
// dir.x() << " " << dir.y() << std::endl;
const Polygon &A = imin.poly(), &B = imax.poly();
Point ref_a = A[(ia + 2) % A.size()], ref_b = B[(ib + 2) % B.size()];
bool is_left_a = dotperp( dir, ref_a - A[ia]) > 0;
bool is_left_b = dotperp(-dir, ref_b - B[ib]) > 0;
// If both reference points are on the left (or right) of their
// respective support lines and the opposite support line is to
// the right (or left), the divisor line is found. We only test
// the reference point, as by definition, if that is on one side,
// all the other points must be on the same side of a support
// line. If the support lines are collinear, the polygons must be
// on the same side of their respective support lines.
auto d = dotperp(dir, B[ib] - A[ia]);
if (d == 0) {
// The caliper lines are collinear, not just parallel
found_divisor = (is_left_a && is_left_b) || (!is_left_a && !is_left_b);
} else if (d > 0) { // B is to the left of (A, A+1)
found_divisor = !is_left_a && !is_left_b;
} else { // B is to the right of (A, A+1)
found_divisor = is_left_a && is_left_b;
}
return !found_divisor;
});
// Intersects if the divisor was not found
return !found_divisor;
}
// Decompose source convex hull points into a top / bottom chains with monotonically increasing x,
// creating an implicit trapezoidal decomposition of the source convex polygon.
// The source convex polygon has to be CCW oriented. O(n) time complexity.
std::pair<std::vector<Vec2d>, std::vector<Vec2d>> decompose_convex_polygon_top_bottom(const std::vector<Vec2d> &src)
{
std::pair<std::vector<Vec2d>, std::vector<Vec2d>> out;
std::vector<Vec2d> &bottom = out.first;
std::vector<Vec2d> &top = out.second;
// Find the minimum point.
auto left_bottom = std::min_element(src.begin(), src.end(), [](const auto &l, const auto &r) { return l.x() < r.x() || (l.x() == r.x() && l.y() < r.y()); });
auto right_top = std::max_element(src.begin(), src.end(), [](const auto &l, const auto &r) { return l.x() < r.x() || (l.x() == r.x() && l.y() < r.y()); });
if (left_bottom != src.end() && left_bottom != right_top) {
// Produce the bottom and bottom chains.
if (left_bottom < right_top) {
bottom.assign(left_bottom, right_top + 1);
size_t cnt = (src.end() - right_top) + (left_bottom + 1 - src.begin());
top.reserve(cnt);
top.assign(right_top, src.end());
top.insert(top.end(), src.begin(), left_bottom + 1);
} else {
size_t cnt = (src.end() - left_bottom) + (right_top + 1 - src.begin());
bottom.reserve(cnt);
bottom.assign(left_bottom, src.end());
bottom.insert(bottom.end(), src.begin(), right_top + 1);
top.assign(right_top, left_bottom + 1);
}
// Remove strictly vertical segments at the end.
if (bottom.size() > 1) {
auto it = bottom.end();
for (-- it; it != bottom.begin() && (it - 1)->x() == bottom.back().x(); -- it) ;
bottom.erase(it + 1, bottom.end());
}
if (top.size() > 1) {
auto it = top.end();
for (-- it; it != top.begin() && (it - 1)->x() == top.back().x(); -- it) ;
top.erase(it + 1, top.end());
}
std::reverse(top.begin(), top.end());
}
if (top.size() < 2 || bottom.size() < 2) {
// invalid
top.clear();
bottom.clear();
}
return out;
}
// Convex polygon check using a top / bottom chain decomposition with O(log n) time complexity.
bool inside_convex_polygon(const std::pair<std::vector<Vec2d>, std::vector<Vec2d>> &top_bottom_decomposition, const Vec2d &pt)
{
auto it_bottom = std::lower_bound(top_bottom_decomposition.first.begin(), top_bottom_decomposition.first.end(), pt, [](const auto &l, const auto &r){ return l.x() < r.x(); });
auto it_top = std::lower_bound(top_bottom_decomposition.second.begin(), top_bottom_decomposition.second.end(), pt, [](const auto &l, const auto &r){ return l.x() < r.x(); });
if (it_bottom == top_bottom_decomposition.first.end()) {
// Above max x.
assert(it_top == top_bottom_decomposition.second.end());
return false;
}
if (it_bottom == top_bottom_decomposition.first.begin()) {
// Below or at min x.
if (pt.x() < it_bottom->x()) {
// Below min x.
assert(pt.x() < it_top->x());
return false;
}
// At min x.
assert(pt.x() == it_bottom->x());
assert(pt.x() == it_top->x());
assert(it_bottom->y() <= pt.y() <= it_top->y());
return pt.y() >= it_bottom->y() && pt.y() <= it_top->y();
}
// Trapezoid or a triangle.
assert(it_bottom != top_bottom_decomposition.first .begin() && it_bottom != top_bottom_decomposition.first .end());
assert(it_top != top_bottom_decomposition.second.begin() && it_top != top_bottom_decomposition.second.end());
assert(pt.x() <= it_bottom->x());
assert(pt.x() <= it_top->x());
auto it_top_prev = it_top - 1;
auto it_bottom_prev = it_bottom - 1;
assert(pt.x() >= it_top_prev->x());
assert(pt.x() >= it_bottom_prev->x());
double det = cross2(*it_bottom - *it_bottom_prev, pt - *it_bottom_prev);
if (det < 0)
return false;
det = cross2(*it_top - *it_top_prev, pt - *it_top_prev);
return det <= 0;
}
} // namespace Geometry
} // namespace Slic3r

View file

@ -0,0 +1,27 @@
#ifndef slic3r_Geometry_ConvexHull_hpp_
#define slic3r_Geometry_ConvexHull_hpp_
#include "../Polygon.hpp"
namespace Slic3r {
namespace Geometry {
Pointf3s convex_hull(Pointf3s points);
Polygon convex_hull(Points points);
Polygon convex_hull(const Polygons &polygons);
// Returns true if the intersection of the two convex polygons A and B
// is not an empty set.
bool convex_polygons_intersect(const Polygon &A, const Polygon &B);
// Decompose source convex hull points into top / bottom chains with monotonically increasing x,
// creating an implicit trapezoidal decomposition of the source convex polygon.
// The source convex polygon has to be CCW oriented. O(n) time complexity.
std::pair<std::vector<Vec2d>, std::vector<Vec2d>> decompose_convex_polygon_top_bottom(const std::vector<Vec2d> &src);
// Convex polygon check using a top / bottom chain decomposition with O(log n) time complexity.
bool inside_convex_polygon(const std::pair<std::vector<Vec2d>, std::vector<Vec2d>> &top_bottom_decomposition, const Vec2d &pt);
} } // namespace Slicer::Geometry
#endif

View file

@ -0,0 +1,712 @@
#include "MedialAxis.hpp"
#include "clipper.hpp"
#ifdef SLIC3R_DEBUG
namespace boost { namespace polygon {
// The following code for the visualization of the boost Voronoi diagram is based on:
//
// Boost.Polygon library voronoi_graphic_utils.hpp header file
// Copyright Andrii Sydorchuk 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
template <typename CT>
class voronoi_visual_utils {
public:
// Discretize parabolic Voronoi edge.
// Parabolic Voronoi edges are always formed by one point and one segment
// from the initial input set.
//
// Args:
// point: input point.
// segment: input segment.
// max_dist: maximum discretization distance.
// discretization: point discretization of the given Voronoi edge.
//
// Template arguments:
// InCT: coordinate type of the input geometries (usually integer).
// Point: point type, should model point concept.
// Segment: segment type, should model segment concept.
//
// Important:
// discretization should contain both edge endpoints initially.
template <class InCT1, class InCT2,
template<class> class Point,
template<class> class Segment>
static
typename enable_if<
typename gtl_and<
typename gtl_if<
typename is_point_concept<
typename geometry_concept< Point<InCT1> >::type
>::type
>::type,
typename gtl_if<
typename is_segment_concept<
typename geometry_concept< Segment<InCT2> >::type
>::type
>::type
>::type,
void
>::type discretize(
const Point<InCT1>& point,
const Segment<InCT2>& segment,
const CT max_dist,
std::vector< Point<CT> >* discretization) {
// Apply the linear transformation to move start point of the segment to
// the point with coordinates (0, 0) and the direction of the segment to
// coincide the positive direction of the x-axis.
CT segm_vec_x = cast(x(high(segment))) - cast(x(low(segment)));
CT segm_vec_y = cast(y(high(segment))) - cast(y(low(segment)));
CT sqr_segment_length = segm_vec_x * segm_vec_x + segm_vec_y * segm_vec_y;
// Compute x-coordinates of the endpoints of the edge
// in the transformed space.
CT projection_start = sqr_segment_length *
get_point_projection((*discretization)[0], segment);
CT projection_end = sqr_segment_length *
get_point_projection((*discretization)[1], segment);
// Compute parabola parameters in the transformed space.
// Parabola has next representation:
// f(x) = ((x-rot_x)^2 + rot_y^2) / (2.0*rot_y).
CT point_vec_x = cast(x(point)) - cast(x(low(segment)));
CT point_vec_y = cast(y(point)) - cast(y(low(segment)));
CT rot_x = segm_vec_x * point_vec_x + segm_vec_y * point_vec_y;
CT rot_y = segm_vec_x * point_vec_y - segm_vec_y * point_vec_x;
// Save the last point.
Point<CT> last_point = (*discretization)[1];
discretization->pop_back();
// Use stack to avoid recursion.
std::stack<CT> point_stack;
point_stack.push(projection_end);
CT cur_x = projection_start;
CT cur_y = parabola_y(cur_x, rot_x, rot_y);
// Adjust max_dist parameter in the transformed space.
const CT max_dist_transformed = max_dist * max_dist * sqr_segment_length;
while (!point_stack.empty()) {
CT new_x = point_stack.top();
CT new_y = parabola_y(new_x, rot_x, rot_y);
// Compute coordinates of the point of the parabola that is
// furthest from the current line segment.
CT mid_x = (new_y - cur_y) / (new_x - cur_x) * rot_y + rot_x;
CT mid_y = parabola_y(mid_x, rot_x, rot_y);
// Compute maximum distance between the given parabolic arc
// and line segment that discretize it.
CT dist = (new_y - cur_y) * (mid_x - cur_x) -
(new_x - cur_x) * (mid_y - cur_y);
dist = dist * dist / ((new_y - cur_y) * (new_y - cur_y) +
(new_x - cur_x) * (new_x - cur_x));
if (dist <= max_dist_transformed) {
// Distance between parabola and line segment is less than max_dist.
point_stack.pop();
CT inter_x = (segm_vec_x * new_x - segm_vec_y * new_y) /
sqr_segment_length + cast(x(low(segment)));
CT inter_y = (segm_vec_x * new_y + segm_vec_y * new_x) /
sqr_segment_length + cast(y(low(segment)));
discretization->push_back(Point<CT>(inter_x, inter_y));
cur_x = new_x;
cur_y = new_y;
} else {
point_stack.push(mid_x);
}
}
// Update last point.
discretization->back() = last_point;
}
private:
// Compute y(x) = ((x - a) * (x - a) + b * b) / (2 * b).
static CT parabola_y(CT x, CT a, CT b) {
return ((x - a) * (x - a) + b * b) / (b + b);
}
// Get normalized length of the distance between:
// 1) point projection onto the segment
// 2) start point of the segment
// Return this length divided by the segment length. This is made to avoid
// sqrt computation during transformation from the initial space to the
// transformed one and vice versa. The assumption is made that projection of
// the point lies between the start-point and endpoint of the segment.
template <class InCT,
template<class> class Point,
template<class> class Segment>
static
typename enable_if<
typename gtl_and<
typename gtl_if<
typename is_point_concept<
typename geometry_concept< Point<int> >::type
>::type
>::type,
typename gtl_if<
typename is_segment_concept<
typename geometry_concept< Segment<long> >::type
>::type
>::type
>::type,
CT
>::type get_point_projection(
const Point<CT>& point, const Segment<InCT>& segment) {
CT segment_vec_x = cast(x(high(segment))) - cast(x(low(segment)));
CT segment_vec_y = cast(y(high(segment))) - cast(y(low(segment)));
CT point_vec_x = x(point) - cast(x(low(segment)));
CT point_vec_y = y(point) - cast(y(low(segment)));
CT sqr_segment_length =
segment_vec_x * segment_vec_x + segment_vec_y * segment_vec_y;
CT vec_dot = segment_vec_x * point_vec_x + segment_vec_y * point_vec_y;
return vec_dot / sqr_segment_length;
}
template <typename InCT>
static CT cast(const InCT& value) {
return static_cast<CT>(value);
}
};
} } // namespace boost::polygon
#endif // SLIC3R_DEBUG
namespace Slic3r { namespace Geometry {
#ifdef SLIC3R_DEBUG
// The following code for the visualization of the boost Voronoi diagram is based on:
//
// Boost.Polygon library voronoi_visualizer.cpp file
// Copyright Andrii Sydorchuk 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
namespace Voronoi { namespace Internal {
typedef double coordinate_type;
typedef boost::polygon::point_data<coordinate_type> point_type;
typedef boost::polygon::segment_data<coordinate_type> segment_type;
typedef boost::polygon::rectangle_data<coordinate_type> rect_type;
typedef boost::polygon::voronoi_diagram<coordinate_type> VD;
typedef VD::cell_type cell_type;
typedef VD::cell_type::source_index_type source_index_type;
typedef VD::cell_type::source_category_type source_category_type;
typedef VD::edge_type edge_type;
typedef VD::cell_container_type cell_container_type;
typedef VD::cell_container_type vertex_container_type;
typedef VD::edge_container_type edge_container_type;
typedef VD::const_cell_iterator const_cell_iterator;
typedef VD::const_vertex_iterator const_vertex_iterator;
typedef VD::const_edge_iterator const_edge_iterator;
static const std::size_t EXTERNAL_COLOR = 1;
inline void color_exterior(const VD::edge_type* edge)
{
if (edge->color() == EXTERNAL_COLOR)
return;
edge->color(EXTERNAL_COLOR);
edge->twin()->color(EXTERNAL_COLOR);
const VD::vertex_type* v = edge->vertex1();
if (v == NULL || !edge->is_primary())
return;
v->color(EXTERNAL_COLOR);
const VD::edge_type* e = v->incident_edge();
do {
color_exterior(e);
e = e->rot_next();
} while (e != v->incident_edge());
}
inline point_type retrieve_point(const std::vector<segment_type> &segments, const cell_type& cell)
{
assert(cell.source_category() == boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT || cell.source_category() == boost::polygon::SOURCE_CATEGORY_SEGMENT_END_POINT);
return (cell.source_category() == boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT) ? low(segments[cell.source_index()]) : high(segments[cell.source_index()]);
}
inline void clip_infinite_edge(const std::vector<segment_type> &segments, const edge_type& edge, coordinate_type bbox_max_size, std::vector<point_type>* clipped_edge)
{
const cell_type& cell1 = *edge.cell();
const cell_type& cell2 = *edge.twin()->cell();
point_type origin, direction;
// Infinite edges could not be created by two segment sites.
if (cell1.contains_point() && cell2.contains_point()) {
point_type p1 = retrieve_point(segments, cell1);
point_type p2 = retrieve_point(segments, cell2);
origin.x((p1.x() + p2.x()) * 0.5);
origin.y((p1.y() + p2.y()) * 0.5);
direction.x(p1.y() - p2.y());
direction.y(p2.x() - p1.x());
} else {
origin = cell1.contains_segment() ? retrieve_point(segments, cell2) : retrieve_point(segments, cell1);
segment_type segment = cell1.contains_segment() ? segments[cell1.source_index()] : segments[cell2.source_index()];
coordinate_type dx = high(segment).x() - low(segment).x();
coordinate_type dy = high(segment).y() - low(segment).y();
if ((low(segment) == origin) ^ cell1.contains_point()) {
direction.x(dy);
direction.y(-dx);
} else {
direction.x(-dy);
direction.y(dx);
}
}
coordinate_type koef = bbox_max_size / (std::max)(fabs(direction.x()), fabs(direction.y()));
if (edge.vertex0() == NULL) {
clipped_edge->push_back(point_type(
origin.x() - direction.x() * koef,
origin.y() - direction.y() * koef));
} else {
clipped_edge->push_back(
point_type(edge.vertex0()->x(), edge.vertex0()->y()));
}
if (edge.vertex1() == NULL) {
clipped_edge->push_back(point_type(
origin.x() + direction.x() * koef,
origin.y() + direction.y() * koef));
} else {
clipped_edge->push_back(
point_type(edge.vertex1()->x(), edge.vertex1()->y()));
}
}
inline void sample_curved_edge(const std::vector<segment_type> &segments, const edge_type& edge, std::vector<point_type> &sampled_edge, coordinate_type max_dist)
{
point_type point = edge.cell()->contains_point() ?
retrieve_point(segments, *edge.cell()) :
retrieve_point(segments, *edge.twin()->cell());
segment_type segment = edge.cell()->contains_point() ?
segments[edge.twin()->cell()->source_index()] :
segments[edge.cell()->source_index()];
::boost::polygon::voronoi_visual_utils<coordinate_type>::discretize(point, segment, max_dist, &sampled_edge);
}
} /* namespace Internal */ } // namespace Voronoi
void dump_voronoi_to_svg(const Lines &lines, /* const */ boost::polygon::voronoi_diagram<double> &vd, const ThickPolylines *polylines, const char *path)
{
const double scale = 0.2;
const std::string inputSegmentPointColor = "lightseagreen";
const coord_t inputSegmentPointRadius = coord_t(0.09 * scale / SCALING_FACTOR);
const std::string inputSegmentColor = "lightseagreen";
const coord_t inputSegmentLineWidth = coord_t(0.03 * scale / SCALING_FACTOR);
const std::string voronoiPointColor = "black";
const coord_t voronoiPointRadius = coord_t(0.06 * scale / SCALING_FACTOR);
const std::string voronoiLineColorPrimary = "black";
const std::string voronoiLineColorSecondary = "green";
const std::string voronoiArcColor = "red";
const coord_t voronoiLineWidth = coord_t(0.02 * scale / SCALING_FACTOR);
const bool internalEdgesOnly = false;
const bool primaryEdgesOnly = false;
BoundingBox bbox = BoundingBox(lines);
bbox.min(0) -= coord_t(1. / SCALING_FACTOR);
bbox.min(1) -= coord_t(1. / SCALING_FACTOR);
bbox.max(0) += coord_t(1. / SCALING_FACTOR);
bbox.max(1) += coord_t(1. / SCALING_FACTOR);
::Slic3r::SVG svg(path, bbox);
if (polylines != NULL)
svg.draw(*polylines, "lime", "lime", voronoiLineWidth);
// bbox.scale(1.2);
// For clipping of half-lines to some reasonable value.
// The line will then be clipped by the SVG viewer anyway.
const double bbox_dim_max = double(bbox.max(0) - bbox.min(0)) + double(bbox.max(1) - bbox.min(1));
// For the discretization of the Voronoi parabolic segments.
const double discretization_step = 0.0005 * bbox_dim_max;
// Make a copy of the input segments with the double type.
std::vector<Voronoi::Internal::segment_type> segments;
for (Lines::const_iterator it = lines.begin(); it != lines.end(); ++ it)
segments.push_back(Voronoi::Internal::segment_type(
Voronoi::Internal::point_type(double(it->a(0)), double(it->a(1))),
Voronoi::Internal::point_type(double(it->b(0)), double(it->b(1)))));
// Color exterior edges.
for (boost::polygon::voronoi_diagram<double>::const_edge_iterator it = vd.edges().begin(); it != vd.edges().end(); ++it)
if (!it->is_finite())
Voronoi::Internal::color_exterior(&(*it));
// Draw the end points of the input polygon.
for (Lines::const_iterator it = lines.begin(); it != lines.end(); ++it) {
svg.draw(it->a, inputSegmentPointColor, inputSegmentPointRadius);
svg.draw(it->b, inputSegmentPointColor, inputSegmentPointRadius);
}
// Draw the input polygon.
for (Lines::const_iterator it = lines.begin(); it != lines.end(); ++it)
svg.draw(Line(Point(coord_t(it->a(0)), coord_t(it->a(1))), Point(coord_t(it->b(0)), coord_t(it->b(1)))), inputSegmentColor, inputSegmentLineWidth);
#if 1
// Draw voronoi vertices.
for (boost::polygon::voronoi_diagram<double>::const_vertex_iterator it = vd.vertices().begin(); it != vd.vertices().end(); ++it)
if (! internalEdgesOnly || it->color() != Voronoi::Internal::EXTERNAL_COLOR)
svg.draw(Point(coord_t(it->x()), coord_t(it->y())), voronoiPointColor, voronoiPointRadius);
for (boost::polygon::voronoi_diagram<double>::const_edge_iterator it = vd.edges().begin(); it != vd.edges().end(); ++it) {
if (primaryEdgesOnly && !it->is_primary())
continue;
if (internalEdgesOnly && (it->color() == Voronoi::Internal::EXTERNAL_COLOR))
continue;
std::vector<Voronoi::Internal::point_type> samples;
std::string color = voronoiLineColorPrimary;
if (!it->is_finite()) {
Voronoi::Internal::clip_infinite_edge(segments, *it, bbox_dim_max, &samples);
if (! it->is_primary())
color = voronoiLineColorSecondary;
} else {
// Store both points of the segment into samples. sample_curved_edge will split the initial line
// until the discretization_step is reached.
samples.push_back(Voronoi::Internal::point_type(it->vertex0()->x(), it->vertex0()->y()));
samples.push_back(Voronoi::Internal::point_type(it->vertex1()->x(), it->vertex1()->y()));
if (it->is_curved()) {
Voronoi::Internal::sample_curved_edge(segments, *it, samples, discretization_step);
color = voronoiArcColor;
} else if (! it->is_primary())
color = voronoiLineColorSecondary;
}
for (std::size_t i = 0; i + 1 < samples.size(); ++i)
svg.draw(Line(Point(coord_t(samples[i].x()), coord_t(samples[i].y())), Point(coord_t(samples[i+1].x()), coord_t(samples[i+1].y()))), color, voronoiLineWidth);
}
#endif
if (polylines != NULL)
svg.draw(*polylines, "blue", voronoiLineWidth);
svg.Close();
}
#endif // SLIC3R_DEBUG
template<typename VD, typename SEGMENTS>
inline const typename VD::point_type retrieve_cell_point(const typename VD::cell_type& cell, const SEGMENTS &segments)
{
assert(cell.source_category() == boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT || cell.source_category() == boost::polygon::SOURCE_CATEGORY_SEGMENT_END_POINT);
return (cell.source_category() == boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT) ? low(segments[cell.source_index()]) : high(segments[cell.source_index()]);
}
template<typename VD, typename SEGMENTS>
inline std::pair<typename VD::coord_type, typename VD::coord_type>
measure_edge_thickness(const VD &vd, const typename VD::edge_type& edge, const SEGMENTS &segments)
{
typedef typename VD::coord_type T;
const typename VD::point_type pa(edge.vertex0()->x(), edge.vertex0()->y());
const typename VD::point_type pb(edge.vertex1()->x(), edge.vertex1()->y());
const typename VD::cell_type &cell1 = *edge.cell();
const typename VD::cell_type &cell2 = *edge.twin()->cell();
if (cell1.contains_segment()) {
if (cell2.contains_segment()) {
// Both cells contain a linear segment, the left / right cells are symmetric.
// Project pa, pb to the left segment.
const typename VD::segment_type segment1 = segments[cell1.source_index()];
const typename VD::point_type p1a = project_point_to_segment(segment1, pa);
const typename VD::point_type p1b = project_point_to_segment(segment1, pb);
return std::pair<T, T>(T(2.)*dist(pa, p1a), T(2.)*dist(pb, p1b));
} else {
// 1st cell contains a linear segment, 2nd cell contains a point.
// The medial axis between the cells is a parabolic arc.
// Project pa, pb to the left segment.
const typename VD::point_type p2 = retrieve_cell_point<VD>(cell2, segments);
return std::pair<T, T>(T(2.)*dist(pa, p2), T(2.)*dist(pb, p2));
}
} else if (cell2.contains_segment()) {
// 1st cell contains a point, 2nd cell contains a linear segment.
// The medial axis between the cells is a parabolic arc.
const typename VD::point_type p1 = retrieve_cell_point<VD>(cell1, segments);
return std::pair<T, T>(T(2.)*dist(pa, p1), T(2.)*dist(pb, p1));
} else {
// Both cells contain a point. The left / right regions are triangular and symmetric.
const typename VD::point_type p1 = retrieve_cell_point<VD>(cell1, segments);
return std::pair<T, T>(T(2.)*dist(pa, p1), T(2.)*dist(pb, p1));
}
}
// Converts the Line instances of Lines vector to VD::segment_type.
template<typename VD>
class Lines2VDSegments
{
public:
Lines2VDSegments(const Lines &alines) : lines(alines) {}
typename VD::segment_type operator[](size_t idx) const {
return typename VD::segment_type(
typename VD::point_type(typename VD::coord_type(lines[idx].a(0)), typename VD::coord_type(lines[idx].a(1))),
typename VD::point_type(typename VD::coord_type(lines[idx].b(0)), typename VD::coord_type(lines[idx].b(1))));
}
private:
const Lines &lines;
};
void
MedialAxis::build(ThickPolylines* polylines)
{
construct_voronoi(this->lines.begin(), this->lines.end(), &this->vd);
/*
// DEBUG: dump all Voronoi edges
{
for (VD::const_edge_iterator edge = this->vd.edges().begin(); edge != this->vd.edges().end(); ++edge) {
if (edge->is_infinite()) continue;
ThickPolyline polyline;
polyline.points.push_back(Point( edge->vertex0()->x(), edge->vertex0()->y() ));
polyline.points.push_back(Point( edge->vertex1()->x(), edge->vertex1()->y() ));
polylines->push_back(polyline);
}
return;
}
*/
//typedef const VD::vertex_type vert_t;
typedef const VD::edge_type edge_t;
// collect valid edges (i.e. prune those not belonging to MAT)
// note: this keeps twins, so it inserts twice the number of the valid edges
this->valid_edges.clear();
{
std::set<const VD::edge_type*> seen_edges;
for (VD::const_edge_iterator edge = this->vd.edges().begin(); edge != this->vd.edges().end(); ++edge) {
// if we only process segments representing closed loops, none if the
// infinite edges (if any) would be part of our MAT anyway
if (edge->is_secondary() || edge->is_infinite()) continue;
// don't re-validate twins
if (seen_edges.find(&*edge) != seen_edges.end()) continue; // TODO: is this needed?
seen_edges.insert(&*edge);
seen_edges.insert(edge->twin());
if (!this->validate_edge(&*edge)) continue;
this->valid_edges.insert(&*edge);
this->valid_edges.insert(edge->twin());
}
}
this->edges = this->valid_edges;
// iterate through the valid edges to build polylines
while (!this->edges.empty()) {
const edge_t* edge = *this->edges.begin();
// start a polyline
ThickPolyline polyline;
polyline.points.push_back(Point( edge->vertex0()->x(), edge->vertex0()->y() ));
polyline.points.push_back(Point( edge->vertex1()->x(), edge->vertex1()->y() ));
polyline.width.push_back(this->thickness[edge].first);
polyline.width.push_back(this->thickness[edge].second);
// remove this edge and its twin from the available edges
(void)this->edges.erase(edge);
(void)this->edges.erase(edge->twin());
// get next points
this->process_edge_neighbors(edge, &polyline);
// get previous points
{
ThickPolyline rpolyline;
this->process_edge_neighbors(edge->twin(), &rpolyline);
polyline.points.insert(polyline.points.begin(), rpolyline.points.rbegin(), rpolyline.points.rend());
polyline.width.insert(polyline.width.begin(), rpolyline.width.rbegin(), rpolyline.width.rend());
polyline.endpoints.first = rpolyline.endpoints.second;
}
assert(polyline.width.size() == polyline.points.size()*2 - 2);
// prevent loop endpoints from being extended
if (polyline.first_point() == polyline.last_point()) {
polyline.endpoints.first = false;
polyline.endpoints.second = false;
}
// append polyline to result
polylines->push_back(polyline);
}
#ifdef SLIC3R_DEBUG
{
static int iRun = 0;
dump_voronoi_to_svg(this->lines, this->vd, polylines, debug_out_path("MedialAxis-%d.svg", iRun ++).c_str());
printf("Thick lines: ");
for (ThickPolylines::const_iterator it = polylines->begin(); it != polylines->end(); ++ it) {
ThickLines lines = it->thicklines();
for (ThickLines::const_iterator it2 = lines.begin(); it2 != lines.end(); ++ it2) {
printf("%f,%f ", it2->a_width, it2->b_width);
}
}
printf("\n");
}
#endif /* SLIC3R_DEBUG */
}
void
MedialAxis::build(Polylines* polylines)
{
ThickPolylines tp;
this->build(&tp);
polylines->insert(polylines->end(), tp.begin(), tp.end());
}
void
MedialAxis::process_edge_neighbors(const VD::edge_type* edge, ThickPolyline* polyline)
{
while (true) {
// Since rot_next() works on the edge starting point but we want
// to find neighbors on the ending point, we just swap edge with
// its twin.
const VD::edge_type* twin = edge->twin();
// count neighbors for this edge
std::vector<const VD::edge_type*> neighbors;
for (const VD::edge_type* neighbor = twin->rot_next(); neighbor != twin;
neighbor = neighbor->rot_next()) {
if (this->valid_edges.count(neighbor) > 0) neighbors.push_back(neighbor);
}
// if we have a single neighbor then we can continue recursively
if (neighbors.size() == 1) {
const VD::edge_type* neighbor = neighbors.front();
// break if this is a closed loop
if (this->edges.count(neighbor) == 0) return;
Point new_point(neighbor->vertex1()->x(), neighbor->vertex1()->y());
polyline->points.push_back(new_point);
polyline->width.push_back(this->thickness[neighbor].first);
polyline->width.push_back(this->thickness[neighbor].second);
(void)this->edges.erase(neighbor);
(void)this->edges.erase(neighbor->twin());
edge = neighbor;
} else if (neighbors.size() == 0) {
polyline->endpoints.second = true;
return;
} else {
// T-shaped or star-shaped joint
return;
}
}
}
bool MedialAxis::validate_edge(const VD::edge_type* edge)
{
// prevent overflows and detect almost-infinite edges
#ifndef CLIPPERLIB_INT32
if (std::abs(edge->vertex0()->x()) > double(CLIPPER_MAX_COORD_UNSCALED) ||
std::abs(edge->vertex0()->y()) > double(CLIPPER_MAX_COORD_UNSCALED) ||
std::abs(edge->vertex1()->x()) > double(CLIPPER_MAX_COORD_UNSCALED) ||
std::abs(edge->vertex1()->y()) > double(CLIPPER_MAX_COORD_UNSCALED))
return false;
#endif // CLIPPERLIB_INT32
// construct the line representing this edge of the Voronoi diagram
const Line line(
Point( edge->vertex0()->x(), edge->vertex0()->y() ),
Point( edge->vertex1()->x(), edge->vertex1()->y() )
);
// discard edge if it lies outside the supplied shape
// this could maybe be optimized (checking inclusion of the endpoints
// might give false positives as they might belong to the contour itself)
if (this->expolygon != NULL) {
if (line.a == line.b) {
// in this case, contains(line) returns a false positive
if (!this->expolygon->contains(line.a)) return false;
} else {
if (!this->expolygon->contains(line)) return false;
}
}
// retrieve the original line segments which generated the edge we're checking
const VD::cell_type* cell_l = edge->cell();
const VD::cell_type* cell_r = edge->twin()->cell();
const Line &segment_l = this->retrieve_segment(cell_l);
const Line &segment_r = this->retrieve_segment(cell_r);
/*
SVG svg("edge.svg");
svg.draw(*this->expolygon);
svg.draw(line);
svg.draw(segment_l, "red");
svg.draw(segment_r, "blue");
svg.Close();
*/
/* Calculate thickness of the cross-section at both the endpoints of this edge.
Our Voronoi edge is part of a CCW sequence going around its Voronoi cell
located on the left side. (segment_l).
This edge's twin goes around segment_r. Thus, segment_r is
oriented in the same direction as our main edge, and segment_l is oriented
in the same direction as our twin edge.
We used to only consider the (half-)distances to segment_r, and that works
whenever segment_l and segment_r are almost specular and facing. However,
at curves they are staggered and they only face for a very little length
(our very short edge represents such visibility).
Both w0 and w1 can be calculated either towards cell_l or cell_r with equal
results by Voronoi definition.
When cell_l or cell_r don't refer to the segment but only to an endpoint, we
calculate the distance to that endpoint instead. */
coordf_t w0 = cell_r->contains_segment()
? segment_r.distance_to(line.a)*2
: (this->retrieve_endpoint(cell_r) - line.a).cast<double>().norm()*2;
coordf_t w1 = cell_l->contains_segment()
? segment_l.distance_to(line.b)*2
: (this->retrieve_endpoint(cell_l) - line.b).cast<double>().norm()*2;
if (cell_l->contains_segment() && cell_r->contains_segment()) {
// calculate the relative angle between the two boundary segments
double angle = fabs(segment_r.orientation() - segment_l.orientation());
if (angle > PI) angle = 2*PI - angle;
assert(angle >= 0 && angle <= PI);
// fabs(angle) ranges from 0 (collinear, same direction) to PI (collinear, opposite direction)
// we're interested only in segments close to the second case (facing segments)
// so we allow some tolerance.
// this filter ensures that we're dealing with a narrow/oriented area (longer than thick)
// we don't run it on edges not generated by two segments (thus generated by one segment
// and the endpoint of another segment), since their orientation would not be meaningful
if (PI - angle > PI/8) {
// angle is not narrow enough
// only apply this filter to segments that are not too short otherwise their
// angle could possibly be not meaningful
if (w0 < SCALED_EPSILON || w1 < SCALED_EPSILON || line.length() >= this->min_width)
return false;
}
} else {
if (w0 < SCALED_EPSILON || w1 < SCALED_EPSILON)
return false;
}
//BBS
if (w0 < this->min_width || w1 < this->min_width)
return false;
//BBS
if (w0 > this->max_width || w1 > this->max_width)
return false;
this->thickness[edge] = std::make_pair(w0, w1);
this->thickness[edge->twin()] = std::make_pair(w1, w0);
return true;
}
const Line& MedialAxis::retrieve_segment(const VD::cell_type* cell) const
{
return this->lines[cell->source_index()];
}
const Point& MedialAxis::retrieve_endpoint(const VD::cell_type* cell) const
{
const Line& line = this->retrieve_segment(cell);
if (cell->source_category() == boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT) {
return line.a;
} else {
return line.b;
}
}
} } // namespace Slicer::Geometry

View file

@ -0,0 +1,33 @@
#ifndef slic3r_Geometry_MedialAxis_hpp_
#define slic3r_Geometry_MedialAxis_hpp_
#include "Voronoi.hpp"
#include "../ExPolygon.hpp"
namespace Slic3r { namespace Geometry {
class MedialAxis {
public:
Lines lines;
const ExPolygon* expolygon;
double max_width;
double min_width;
MedialAxis(double _max_width, double _min_width, const ExPolygon* _expolygon = NULL)
: expolygon(_expolygon), max_width(_max_width), min_width(_min_width) {};
void build(ThickPolylines* polylines);
void build(Polylines* polylines);
private:
using VD = VoronoiDiagram;
VD vd;
std::set<const VD::edge_type*> edges, valid_edges;
std::map<const VD::edge_type*, std::pair<coordf_t,coordf_t> > thickness;
void process_edge_neighbors(const VD::edge_type* edge, ThickPolyline* polyline);
bool validate_edge(const VD::edge_type* edge);
const Line& retrieve_segment(const VD::cell_type* cell) const;
const Point& retrieve_endpoint(const VD::cell_type* cell) const;
};
} } // namespace Slicer::Geometry
#endif // slic3r_Geometry_MedialAxis_hpp_

View file

@ -0,0 +1,33 @@
#ifndef slic3r_Geometry_Voronoi_hpp_
#define slic3r_Geometry_Voronoi_hpp_
#include "../Line.hpp"
#include "../Polyline.hpp"
#define BOOST_VORONOI_USE_GMP 1
#ifdef _MSC_VER
// Suppress warning C4146 in OpenVDB: unary minus operator applied to unsigned type, result still unsigned
#pragma warning(push)
#pragma warning(disable : 4146)
#endif // _MSC_VER
#include "boost/polygon/voronoi.hpp"
#ifdef _MSC_VER
#pragma warning(pop)
#endif // _MSC_VER
namespace Slic3r {
namespace Geometry {
class VoronoiDiagram : public boost::polygon::voronoi_diagram<double> {
public:
typedef double coord_type;
typedef boost::polygon::point_data<coordinate_type> point_type;
typedef boost::polygon::segment_data<coordinate_type> segment_type;
typedef boost::polygon::rectangle_data<coordinate_type> rect_type;
};
} } // namespace Slicer::Geometry
#endif // slic3r_Geometry_Voronoi_hpp_

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,145 @@
// Polygon offsetting using Voronoi diagram prodiced by boost::polygon.
#ifndef slic3r_VoronoiOffset_hpp_
#define slic3r_VoronoiOffset_hpp_
#include "../libslic3r.h"
#include "Voronoi.hpp"
namespace Slic3r {
namespace Voronoi {
using VD = Slic3r::Geometry::VoronoiDiagram;
inline const Point& contour_point(const VD::cell_type &cell, const Line &line)
{ return ((cell.source_category() == boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT) ? line.a : line.b); }
inline Point& contour_point(const VD::cell_type &cell, Line &line)
{ return ((cell.source_category() == boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT) ? line.a : line.b); }
inline const Point& contour_point(const VD::cell_type &cell, const Lines &lines)
{ return contour_point(cell, lines[cell.source_index()]); }
inline Point& contour_point(const VD::cell_type &cell, Lines &lines)
{ return contour_point(cell, lines[cell.source_index()]); }
inline Vec2d vertex_point(const VD::vertex_type &v) { return Vec2d(v.x(), v.y()); }
inline Vec2d vertex_point(const VD::vertex_type *v) { return Vec2d(v->x(), v->y()); }
// "Color" stored inside the boost::polygon Voronoi vertex.
enum class VertexCategory : unsigned char
{
// Voronoi vertex is on the input contour.
// VD::vertex_type stores coordinates in double, though the coordinates shall match exactly
// with the coordinates of the input contour when converted to int32_t.
OnContour,
// Vertex is inside the CCW input contour, holes are respected.
Inside,
// Vertex is outside the CCW input contour, holes are respected.
Outside,
// Not known yet.
Unknown,
};
// "Color" stored inside the boost::polygon Voronoi edge.
// The Voronoi edge as represented by boost::polygon Voronoi module is really a half-edge,
// the half-edges are classified based on the target vertex (VD::vertex_type::vertex1())
enum class EdgeCategory : unsigned char
{
// This half-edge points onto the contour, this VD::edge_type::vertex1().color() is OnContour.
PointsToContour,
// This half-edge points inside, this VD::edge_type::vertex1().color() is Inside.
PointsInside,
// This half-edge points outside, this VD::edge_type::vertex1().color() is Outside.
PointsOutside,
// Not known yet.
Unknown
};
// "Color" stored inside the boost::polygon Voronoi cell.
enum class CellCategory : unsigned char
{
// This Voronoi cell is split by an input segment to two halves, one is inside, the other is outside.
Boundary,
// This Voronoi cell is completely inside.
Inside,
// This Voronoi cell is completely outside.
Outside,
// Not known yet.
Unknown
};
inline VertexCategory vertex_category(const VD::vertex_type &v)
{ return static_cast<VertexCategory>(v.color()); }
inline VertexCategory vertex_category(const VD::vertex_type *v)
{ return static_cast<VertexCategory>(v->color()); }
inline void set_vertex_category(VD::vertex_type &v, VertexCategory c)
{ v.color(static_cast<VD::vertex_type::color_type>(c)); }
inline void set_vertex_category(VD::vertex_type *v, VertexCategory c)
{ v->color(static_cast<VD::vertex_type::color_type>(c)); }
inline EdgeCategory edge_category(const VD::edge_type &e)
{ return static_cast<EdgeCategory>(e.color()); }
inline EdgeCategory edge_category(const VD::edge_type *e)
{ return static_cast<EdgeCategory>(e->color()); }
inline void set_edge_category(VD::edge_type &e, EdgeCategory c)
{ e.color(static_cast<VD::edge_type::color_type>(c)); }
inline void set_edge_category(VD::edge_type *e, EdgeCategory c)
{ e->color(static_cast<VD::edge_type::color_type>(c)); }
inline CellCategory cell_category(const VD::cell_type &v)
{ return static_cast<CellCategory>(v.color()); }
inline CellCategory cell_category(const VD::cell_type *v)
{ return static_cast<CellCategory>(v->color()); }
inline void set_cell_category(const VD::cell_type &v, CellCategory c)
{ v.color(static_cast<VD::cell_type::color_type>(c)); }
inline void set_cell_category(const VD::cell_type *v, CellCategory c)
{ v->color(static_cast<VD::cell_type::color_type>(c)); }
// Mark the "Color" of VD vertices, edges and cells as Unknown.
void reset_inside_outside_annotations(VD &vd);
// Assign "Color" to VD vertices, edges and cells signifying whether the entity is inside or outside
// the input polygons defined by Lines.
void annotate_inside_outside(VD &vd, const Lines &lines);
// Returns a signed distance to Voronoi vertices from the input polygons.
// (negative distances inside, positive distances outside).
std::vector<double> signed_vertex_distances(const VD &vd, const Lines &lines);
static inline bool edge_offset_no_intersection(const Vec2d &intersection_point)
{ return std::isnan(intersection_point.x()); }
static inline bool edge_offset_has_intersection(const Vec2d &intersection_point)
{ return ! edge_offset_no_intersection(intersection_point); }
std::vector<Vec2d> edge_offset_contour_intersections(
const VD &vd, const Lines &lines, const std::vector<double> &distances,
double offset_distance);
std::vector<Vec2d> skeleton_edges_rough(
const VD &vd,
const Lines &lines,
const double threshold_alpha);
Polygons offset(
const Geometry::VoronoiDiagram &vd,
const Lines &lines,
const std::vector<double> &signed_vertex_distances,
double offset_distance,
double discretization_error);
// Offset a polygon or a set of polygons possibly with holes by traversing a Voronoi diagram.
// The input polygons are stored in lines and lines are referenced by vd.
// Outer curve will be extracted for a positive offset_distance,
// inner curve will be extracted for a negative offset_distance.
// Circular arches will be discretized to achieve discretization_error.
Polygons offset(
const VD &vd,
const Lines &lines,
double offset_distance,
double discretization_error);
} // namespace Voronoi
} // namespace Slic3r
#endif // slic3r_VoronoiOffset_hpp_

View file

@ -0,0 +1,453 @@
#include <stack>
#include <libslic3r/Geometry.hpp>
#include <libslic3r/Line.hpp>
#include <libslic3r/Polygon.hpp>
#include <libslic3r/SVG.hpp>
#include "VoronoiOffset.hpp"
namespace boost { namespace polygon {
// The following code for the visualization of the boost Voronoi diagram is based on:
//
// Boost.Polygon library voronoi_graphic_utils.hpp header file
// Copyright Andrii Sydorchuk 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
template <typename CT>
class voronoi_visual_utils {
public:
// Discretize parabolic Voronoi edge.
// Parabolic Voronoi edges are always formed by one point and one segment
// from the initial input set.
//
// Args:
// point: input point.
// segment: input segment.
// max_dist: maximum discretization distance.
// discretization: point discretization of the given Voronoi edge.
//
// Template arguments:
// InCT: coordinate type of the input geometries (usually integer).
// Point: point type, should model point concept.
// Segment: segment type, should model segment concept.
//
// Important:
// discretization should contain both edge endpoints initially.
template <class InCT1, class InCT2,
template<class> class Point,
template<class> class Segment>
static
typename enable_if<
typename gtl_and<
typename gtl_if<
typename is_point_concept<
typename geometry_concept< Point<InCT1> >::type
>::type
>::type,
typename gtl_if<
typename is_segment_concept<
typename geometry_concept< Segment<InCT2> >::type
>::type
>::type
>::type,
void
>::type discretize(
const Point<InCT1>& point,
const Segment<InCT2>& segment,
const CT max_dist,
std::vector< Point<CT> >* discretization) {
// Apply the linear transformation to move start point of the segment to
// the point with coordinates (0, 0) and the direction of the segment to
// coincide the positive direction of the x-axis.
CT segm_vec_x = cast(x(high(segment))) - cast(x(low(segment)));
CT segm_vec_y = cast(y(high(segment))) - cast(y(low(segment)));
CT sqr_segment_length = segm_vec_x * segm_vec_x + segm_vec_y * segm_vec_y;
// Compute x-coordinates of the endpoints of the edge
// in the transformed space.
CT projection_start = sqr_segment_length *
get_point_projection((*discretization)[0], segment);
CT projection_end = sqr_segment_length *
get_point_projection((*discretization)[1], segment);
assert(projection_start != projection_end);
// Compute parabola parameters in the transformed space.
// Parabola has next representation:
// f(x) = ((x-rot_x)^2 + rot_y^2) / (2.0*rot_y).
CT point_vec_x = cast(x(point)) - cast(x(low(segment)));
CT point_vec_y = cast(y(point)) - cast(y(low(segment)));
CT rot_x = segm_vec_x * point_vec_x + segm_vec_y * point_vec_y;
CT rot_y = segm_vec_x * point_vec_y - segm_vec_y * point_vec_x;
// Save the last point.
Point<CT> last_point = (*discretization)[1];
discretization->pop_back();
// Use stack to avoid recursion.
std::stack<CT> point_stack;
point_stack.push(projection_end);
CT cur_x = projection_start;
CT cur_y = parabola_y(cur_x, rot_x, rot_y);
// Adjust max_dist parameter in the transformed space.
const CT max_dist_transformed = max_dist * max_dist * sqr_segment_length;
while (!point_stack.empty()) {
CT new_x = point_stack.top();
CT new_y = parabola_y(new_x, rot_x, rot_y);
// Compute coordinates of the point of the parabola that is
// furthest from the current line segment.
CT mid_x = (new_y - cur_y) / (new_x - cur_x) * rot_y + rot_x;
CT mid_y = parabola_y(mid_x, rot_x, rot_y);
assert(mid_x != cur_x || mid_y != cur_y);
assert(mid_x != new_x || mid_y != new_y);
// Compute maximum distance between the given parabolic arc
// and line segment that discretize it.
CT dist = (new_y - cur_y) * (mid_x - cur_x) -
(new_x - cur_x) * (mid_y - cur_y);
CT div = (new_y - cur_y) * (new_y - cur_y) + (new_x - cur_x) * (new_x - cur_x);
assert(div != 0);
dist = dist * dist / div;
if (dist <= max_dist_transformed) {
// Distance between parabola and line segment is less than max_dist.
point_stack.pop();
CT inter_x = (segm_vec_x * new_x - segm_vec_y * new_y) /
sqr_segment_length + cast(x(low(segment)));
CT inter_y = (segm_vec_x * new_y + segm_vec_y * new_x) /
sqr_segment_length + cast(y(low(segment)));
discretization->push_back(Point<CT>(inter_x, inter_y));
cur_x = new_x;
cur_y = new_y;
} else {
point_stack.push(mid_x);
}
}
// Update last point.
discretization->back() = last_point;
}
private:
// Compute y(x) = ((x - a) * (x - a) + b * b) / (2 * b).
static CT parabola_y(CT x, CT a, CT b) {
return ((x - a) * (x - a) + b * b) / (b + b);
}
// Get normalized length of the distance between:
// 1) point projection onto the segment
// 2) start point of the segment
// Return this length divided by the segment length. This is made to avoid
// sqrt computation during transformation from the initial space to the
// transformed one and vice versa. The assumption is made that projection of
// the point lies between the start-point and endpoint of the segment.
template <class InCT,
template<class> class Point,
template<class> class Segment>
static
typename enable_if<
typename gtl_and<
typename gtl_if<
typename is_point_concept<
typename geometry_concept< Point<int> >::type
>::type
>::type,
typename gtl_if<
typename is_segment_concept<
typename geometry_concept< Segment<long> >::type
>::type
>::type
>::type,
CT
>::type get_point_projection(
const Point<CT>& point, const Segment<InCT>& segment) {
CT segment_vec_x = cast(x(high(segment))) - cast(x(low(segment)));
CT segment_vec_y = cast(y(high(segment))) - cast(y(low(segment)));
CT point_vec_x = x(point) - cast(x(low(segment)));
CT point_vec_y = y(point) - cast(y(low(segment)));
CT sqr_segment_length =
segment_vec_x * segment_vec_x + segment_vec_y * segment_vec_y;
CT vec_dot = segment_vec_x * point_vec_x + segment_vec_y * point_vec_y;
return vec_dot / sqr_segment_length;
}
template <typename InCT>
static CT cast(const InCT& value) {
return static_cast<CT>(value);
}
};
} } // namespace boost::polygon
namespace Slic3r
{
// The following code for the visualization of the boost Voronoi diagram is based on:
//
// Boost.Polygon library voronoi_visualizer.cpp file
// Copyright Andrii Sydorchuk 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
namespace Voronoi { namespace Internal {
using VD = Geometry::VoronoiDiagram;
typedef double coordinate_type;
typedef boost::polygon::point_data<coordinate_type> point_type;
typedef boost::polygon::segment_data<coordinate_type> segment_type;
typedef boost::polygon::rectangle_data<coordinate_type> rect_type;
typedef VD::cell_type cell_type;
typedef VD::cell_type::source_index_type source_index_type;
typedef VD::cell_type::source_category_type source_category_type;
typedef VD::edge_type edge_type;
typedef VD::cell_container_type cell_container_type;
typedef VD::cell_container_type vertex_container_type;
typedef VD::edge_container_type edge_container_type;
typedef VD::const_cell_iterator const_cell_iterator;
typedef VD::const_vertex_iterator const_vertex_iterator;
typedef VD::const_edge_iterator const_edge_iterator;
static const std::size_t EXTERNAL_COLOR = 1;
inline void color_exterior(const VD::edge_type* edge)
{
if (edge->color() == EXTERNAL_COLOR)
return;
edge->color(EXTERNAL_COLOR);
edge->twin()->color(EXTERNAL_COLOR);
const VD::vertex_type* v = edge->vertex1();
if (v == NULL || !edge->is_primary())
return;
v->color(EXTERNAL_COLOR);
const VD::edge_type* e = v->incident_edge();
do {
color_exterior(e);
e = e->rot_next();
} while (e != v->incident_edge());
}
inline point_type retrieve_point(const Points &points, const std::vector<segment_type> &segments, const cell_type& cell)
{
assert(cell.source_category() == boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT || cell.source_category() == boost::polygon::SOURCE_CATEGORY_SEGMENT_END_POINT ||
cell.source_category() == boost::polygon::SOURCE_CATEGORY_SINGLE_POINT);
return cell.source_category() == boost::polygon::SOURCE_CATEGORY_SINGLE_POINT ?
Voronoi::Internal::point_type(double(points[cell.source_index()].x()), double(points[cell.source_index()].y())) :
(cell.source_category() == boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT) ?
low(segments[cell.source_index()]) : high(segments[cell.source_index()]);
}
inline void clip_infinite_edge(const Points &points, const std::vector<segment_type> &segments, const edge_type& edge, coordinate_type bbox_max_size, std::vector<point_type>* clipped_edge)
{
assert(edge.is_infinite());
assert((edge.vertex0() == nullptr) != (edge.vertex1() == nullptr));
const cell_type& cell1 = *edge.cell();
const cell_type& cell2 = *edge.twin()->cell();
// Infinite edges could not be created by two segment sites.
assert(cell1.contains_point() || cell2.contains_point());
if (! cell1.contains_point() && ! cell2.contains_point()) {
printf("Error! clip_infinite_edge - infinite edge separates two segment cells\n");
return;
}
point_type direction;
if (cell1.contains_point() && cell2.contains_point()) {
assert(! edge.is_secondary());
point_type p1 = retrieve_point(points, segments, cell1);
point_type p2 = retrieve_point(points, segments, cell2);
if (edge.vertex0() == nullptr)
std::swap(p1, p2);
direction.x(p1.y() - p2.y());
direction.y(p2.x() - p1.x());
} else {
assert(edge.is_secondary());
segment_type segment = cell1.contains_segment() ? segments[cell1.source_index()] : segments[cell2.source_index()];
direction.x(high(segment).y() - low(segment).y());
direction.y(low(segment).x() - high(segment).x());
}
coordinate_type koef = bbox_max_size / (std::max)(fabs(direction.x()), fabs(direction.y()));
if (edge.vertex0() == nullptr) {
clipped_edge->push_back(point_type(edge.vertex1()->x() + direction.x() * koef, edge.vertex1()->y() + direction.y() * koef));
clipped_edge->push_back(point_type(edge.vertex1()->x(), edge.vertex1()->y()));
} else {
clipped_edge->push_back(point_type(edge.vertex0()->x(), edge.vertex0()->y()));
clipped_edge->push_back(point_type(edge.vertex0()->x() + direction.x() * koef, edge.vertex0()->y() + direction.y() * koef));
}
}
inline void sample_curved_edge(const Points &points, const std::vector<segment_type> &segments, const edge_type& edge, std::vector<point_type> &sampled_edge, coordinate_type max_dist)
{
point_type point = edge.cell()->contains_point() ?
retrieve_point(points, segments, *edge.cell()) :
retrieve_point(points, segments, *edge.twin()->cell());
segment_type segment = edge.cell()->contains_point() ?
segments[edge.twin()->cell()->source_index()] :
segments[edge.cell()->source_index()];
::boost::polygon::voronoi_visual_utils<coordinate_type>::discretize(point, segment, max_dist, &sampled_edge);
}
} /* namespace Internal */ } // namespace Voronoi
BoundingBox get_extents(const Lines &lines);
static inline void dump_voronoi_to_svg(
const char *path,
const Geometry::VoronoiDiagram &vd,
const Points &points,
const Lines &lines,
const Polygons &offset_curves = Polygons(),
const Lines &helper_lines = Lines(),
double scale = 0)
{
const bool internalEdgesOnly = false;
BoundingBox bbox;
bbox.merge(get_extents(points));
bbox.merge(get_extents(lines));
bbox.merge(get_extents(offset_curves));
bbox.merge(get_extents(helper_lines));
for (boost::polygon::voronoi_diagram<double>::const_vertex_iterator it = vd.vertices().begin(); it != vd.vertices().end(); ++it)
if (! internalEdgesOnly || it->color() != Voronoi::Internal::EXTERNAL_COLOR)
bbox.merge(Point(it->x(), it->y()));
bbox.min -= (0.01 * bbox.size().cast<double>()).cast<coord_t>();
bbox.max += (0.01 * bbox.size().cast<double>()).cast<coord_t>();
if (scale == 0)
scale =
// 0.1
0.01
* std::min(bbox.size().x(), bbox.size().y());
else
scale *= SCALING_FACTOR;
const std::string inputSegmentPointColor = "lightseagreen";
const coord_t inputSegmentPointRadius = std::max<coord_t>(1, coord_t(0.09 * scale));
const std::string inputSegmentColor = "lightseagreen";
const coord_t inputSegmentLineWidth = coord_t(0.03 * scale);
const std::string voronoiPointColor = "black";
const std::string voronoiPointColorOutside = "red";
const std::string voronoiPointColorInside = "blue";
const coord_t voronoiPointRadius = std::max<coord_t>(1, coord_t(0.06 * scale));
const std::string voronoiLineColorPrimary = "black";
const std::string voronoiLineColorSecondary = "green";
const std::string voronoiArcColor = "red";
const coord_t voronoiLineWidth = coord_t(0.02 * scale);
const std::string offsetCurveColor = "magenta";
const coord_t offsetCurveLineWidth = coord_t(0.02 * scale);
const std::string helperLineColor = "orange";
const coord_t helperLineWidth = coord_t(0.04 * scale);
const bool primaryEdgesOnly = false;
::Slic3r::SVG svg(path, bbox);
// For clipping of half-lines to some reasonable value.
// The line will then be clipped by the SVG viewer anyway.
const double bbox_dim_max = double(std::max(bbox.size().x(), bbox.size().y()));
// For the discretization of the Voronoi parabolic segments.
const double discretization_step = 0.0002 * bbox_dim_max;
// Make a copy of the input segments with the double type.
std::vector<Voronoi::Internal::segment_type> segments;
for (Lines::const_iterator it = lines.begin(); it != lines.end(); ++ it)
segments.push_back(Voronoi::Internal::segment_type(
Voronoi::Internal::point_type(double(it->a(0)), double(it->a(1))),
Voronoi::Internal::point_type(double(it->b(0)), double(it->b(1)))));
// Color exterior edges.
if (internalEdgesOnly) {
for (boost::polygon::voronoi_diagram<double>::const_edge_iterator it = vd.edges().begin(); it != vd.edges().end(); ++it)
if (!it->is_finite())
Voronoi::Internal::color_exterior(&(*it));
}
// Draw the end points of the input polygon.
for (Lines::const_iterator it = lines.begin(); it != lines.end(); ++it) {
svg.draw(it->a, inputSegmentPointColor, inputSegmentPointRadius);
svg.draw(it->b, inputSegmentPointColor, inputSegmentPointRadius);
}
// Draw the input polygon.
for (Lines::const_iterator it = lines.begin(); it != lines.end(); ++it)
svg.draw(Line(Point(coord_t(it->a(0)), coord_t(it->a(1))), Point(coord_t(it->b(0)), coord_t(it->b(1)))), inputSegmentColor, inputSegmentLineWidth);
#if 1
// Draw voronoi vertices.
for (boost::polygon::voronoi_diagram<double>::const_vertex_iterator it = vd.vertices().begin(); it != vd.vertices().end(); ++it)
if (! internalEdgesOnly || it->color() != Voronoi::Internal::EXTERNAL_COLOR) {
const std::string *color = nullptr;
switch (Voronoi::vertex_category(*it)) {
case Voronoi::VertexCategory::OnContour: color = &voronoiPointColor; break;
case Voronoi::VertexCategory::Outside: color = &voronoiPointColorOutside; break;
case Voronoi::VertexCategory::Inside: color = &voronoiPointColorInside; break;
default: color = &voronoiPointColor; // assert(false);
}
Point pt(coord_t(it->x()), coord_t(it->y()));
if (it->x() * pt.x() >= 0. && it->y() * pt.y() >= 0.)
// Conversion to coord_t is valid.
svg.draw(Point(coord_t(it->x()), coord_t(it->y())), *color, voronoiPointRadius);
}
for (boost::polygon::voronoi_diagram<double>::const_edge_iterator it = vd.edges().begin(); it != vd.edges().end(); ++it) {
if (primaryEdgesOnly && !it->is_primary())
continue;
if (internalEdgesOnly && (it->color() == Voronoi::Internal::EXTERNAL_COLOR))
continue;
std::vector<Voronoi::Internal::point_type> samples;
std::string color = voronoiLineColorPrimary;
if (!it->is_finite()) {
Voronoi::Internal::clip_infinite_edge(points, segments, *it, bbox_dim_max, &samples);
if (! it->is_primary())
color = voronoiLineColorSecondary;
} else {
// Store both points of the segment into samples. sample_curved_edge will split the initial line
// until the discretization_step is reached.
samples.push_back(Voronoi::Internal::point_type(it->vertex0()->x(), it->vertex0()->y()));
samples.push_back(Voronoi::Internal::point_type(it->vertex1()->x(), it->vertex1()->y()));
if (it->is_curved()) {
Voronoi::Internal::sample_curved_edge(points, segments, *it, samples, discretization_step);
color = voronoiArcColor;
} else if (! it->is_primary())
color = voronoiLineColorSecondary;
}
for (std::size_t i = 0; i + 1 < samples.size(); ++ i) {
Vec2d a(samples[i].x(), samples[i].y());
Vec2d b(samples[i+1].x(), samples[i+1].y());
// Convert to coord_t.
Point ia = a.cast<coord_t>();
Point ib = b.cast<coord_t>();
// Is the conversion possible? Do the resulting points fit into int32_t?
auto in_range = [](const Point &ip, const Vec2d &p) { return p.x() * ip.x() >= 0. && p.y() * ip.y() >= 0.; };
bool a_in_range = in_range(ia, a);
bool b_in_range = in_range(ib, b);
if (! a_in_range || ! b_in_range) {
if (! a_in_range && ! b_in_range)
// None fits, ignore.
continue;
// One fit, the other does not. Try to clip.
Vec2d v = b - a;
v.normalize();
v *= bbox.size().cast<double>().norm();
auto p = a_in_range ? Vec2d(a + v) : Vec2d(b - v);
Point ip = p.cast<coord_t>();
if (! in_range(ip, p))
continue;
(a_in_range ? ib : ia) = ip;
}
svg.draw(Line(ia, ib), color, voronoiLineWidth);
}
}
#endif
svg.draw_outline(offset_curves, offsetCurveColor, offsetCurveLineWidth);
svg.draw(helper_lines, helperLineColor, helperLineWidth);
svg.Close();
}
} // namespace Slic3r