mirror of
https://github.com/QIDITECH/QIDISlicer.git
synced 2026-02-01 16:38:43 +03:00
QIDISlicer1.0.0
This commit is contained in:
291
src/libslic3r/Geometry/Bicubic.hpp
Normal file
291
src/libslic3r/Geometry/Bicubic.hpp
Normal file
@@ -0,0 +1,291 @@
|
||||
#ifndef BICUBIC_HPP
|
||||
#define BICUBIC_HPP
|
||||
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
#include <cmath>
|
||||
|
||||
#include <Eigen/Dense>
|
||||
|
||||
namespace Slic3r {
|
||||
|
||||
namespace Geometry {
|
||||
|
||||
namespace BicubicInternal {
|
||||
// Linear kernel, to be able to test cubic methods with hat kernels.
|
||||
template<typename T>
|
||||
struct LinearKernel
|
||||
{
|
||||
typedef T FloatType;
|
||||
|
||||
static T a00() {
|
||||
return T(0.);
|
||||
}
|
||||
static T a01() {
|
||||
return T(0.);
|
||||
}
|
||||
static T a02() {
|
||||
return T(0.);
|
||||
}
|
||||
static T a03() {
|
||||
return T(0.);
|
||||
}
|
||||
static T a10() {
|
||||
return T(1.);
|
||||
}
|
||||
static T a11() {
|
||||
return T(-1.);
|
||||
}
|
||||
static T a12() {
|
||||
return T(0.);
|
||||
}
|
||||
static T a13() {
|
||||
return T(0.);
|
||||
}
|
||||
static T a20() {
|
||||
return T(0.);
|
||||
}
|
||||
static T a21() {
|
||||
return T(1.);
|
||||
}
|
||||
static T a22() {
|
||||
return T(0.);
|
||||
}
|
||||
static T a23() {
|
||||
return T(0.);
|
||||
}
|
||||
static T a30() {
|
||||
return T(0.);
|
||||
}
|
||||
static T a31() {
|
||||
return T(0.);
|
||||
}
|
||||
static T a32() {
|
||||
return T(0.);
|
||||
}
|
||||
static T a33() {
|
||||
return T(0.);
|
||||
}
|
||||
};
|
||||
|
||||
// Interpolation kernel aka Catmul-Rom aka Keyes kernel.
|
||||
template<typename T>
|
||||
struct CubicCatmulRomKernel
|
||||
{
|
||||
typedef T FloatType;
|
||||
|
||||
static T a00() {
|
||||
return 0;
|
||||
}
|
||||
static T a01() {
|
||||
return T( -0.5);
|
||||
}
|
||||
static T a02() {
|
||||
return T( 1.);
|
||||
}
|
||||
static T a03() {
|
||||
return T( -0.5);
|
||||
}
|
||||
static T a10() {
|
||||
return T( 1.);
|
||||
}
|
||||
static T a11() {
|
||||
return 0;
|
||||
}
|
||||
static T a12() {
|
||||
return T( -5. / 2.);
|
||||
}
|
||||
static T a13() {
|
||||
return T( 3. / 2.);
|
||||
}
|
||||
static T a20() {
|
||||
return 0;
|
||||
}
|
||||
static T a21() {
|
||||
return T( 0.5);
|
||||
}
|
||||
static T a22() {
|
||||
return T( 2.);
|
||||
}
|
||||
static T a23() {
|
||||
return T( -3. / 2.);
|
||||
}
|
||||
static T a30() {
|
||||
return 0;
|
||||
}
|
||||
static T a31() {
|
||||
return 0;
|
||||
}
|
||||
static T a32() {
|
||||
return T( -0.5);
|
||||
}
|
||||
static T a33() {
|
||||
return T( 0.5);
|
||||
}
|
||||
};
|
||||
|
||||
// B-spline kernel
|
||||
template<typename T>
|
||||
struct CubicBSplineKernel
|
||||
{
|
||||
typedef T FloatType;
|
||||
|
||||
static T a00() {
|
||||
return T( 1. / 6.);
|
||||
}
|
||||
static T a01() {
|
||||
return T( -3. / 6.);
|
||||
}
|
||||
static T a02() {
|
||||
return T( 3. / 6.);
|
||||
}
|
||||
static T a03() {
|
||||
return T( -1. / 6.);
|
||||
}
|
||||
static T a10() {
|
||||
return T( 4. / 6.);
|
||||
}
|
||||
static T a11() {
|
||||
return 0;
|
||||
}
|
||||
static T a12() {
|
||||
return T( -6. / 6.);
|
||||
}
|
||||
static T a13() {
|
||||
return T( 3. / 6.);
|
||||
}
|
||||
static T a20() {
|
||||
return T( 1. / 6.);
|
||||
}
|
||||
static T a21() {
|
||||
return T( 3. / 6.);
|
||||
}
|
||||
static T a22() {
|
||||
return T( 3. / 6.);
|
||||
}
|
||||
static T a23() {
|
||||
return T( -3. / 6.);
|
||||
}
|
||||
static T a30() {
|
||||
return 0;
|
||||
}
|
||||
static T a31() {
|
||||
return 0;
|
||||
}
|
||||
static T a32() {
|
||||
return 0;
|
||||
}
|
||||
static T a33() {
|
||||
return T( 1. / 6.);
|
||||
}
|
||||
};
|
||||
|
||||
template<class T>
|
||||
inline T clamp(T a, T lower, T upper)
|
||||
{
|
||||
return (a < lower) ? lower :
|
||||
(a > upper) ? upper : a;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename Kernel>
|
||||
struct CubicKernelWrapper
|
||||
{
|
||||
typedef typename Kernel::FloatType FloatType;
|
||||
|
||||
static constexpr size_t kernel_span = 4;
|
||||
|
||||
static FloatType kernel(FloatType x)
|
||||
{
|
||||
x = fabs(x);
|
||||
if (x >= (FloatType) 2.)
|
||||
return 0.0f;
|
||||
if (x <= (FloatType) 1.) {
|
||||
FloatType x2 = x * x;
|
||||
FloatType x3 = x2 * x;
|
||||
return Kernel::a10() + Kernel::a11() * x + Kernel::a12() * x2 + Kernel::a13() * x3;
|
||||
}
|
||||
assert(x > (FloatType )1. && x < (FloatType )2.);
|
||||
x -= (FloatType) 1.;
|
||||
FloatType x2 = x * x;
|
||||
FloatType x3 = x2 * x;
|
||||
return Kernel::a00() + Kernel::a01() * x + Kernel::a02() * x2 + Kernel::a03() * x3;
|
||||
}
|
||||
|
||||
static FloatType interpolate(FloatType f0, FloatType f1, FloatType f2, FloatType f3, FloatType x)
|
||||
{
|
||||
const FloatType x2 = x * x;
|
||||
const FloatType x3 = x * x * x;
|
||||
return f0 * (Kernel::a00() + Kernel::a01() * x + Kernel::a02() * x2 + Kernel::a03() * x3) +
|
||||
f1 * (Kernel::a10() + Kernel::a11() * x + Kernel::a12() * x2 + Kernel::a13() * x3) +
|
||||
f2 * (Kernel::a20() + Kernel::a21() * x + Kernel::a22() * x2 + Kernel::a23() * x3) +
|
||||
f3 * (Kernel::a30() + Kernel::a31() * x + Kernel::a32() * x2 + Kernel::a33() * x3);
|
||||
}
|
||||
};
|
||||
|
||||
// Linear splines
|
||||
template<typename NumberType>
|
||||
using LinearKernel = CubicKernelWrapper<BicubicInternal::LinearKernel<NumberType>>;
|
||||
|
||||
// Catmul-Rom splines
|
||||
template<typename NumberType>
|
||||
using CubicCatmulRomKernel = CubicKernelWrapper<BicubicInternal::CubicCatmulRomKernel<NumberType>>;
|
||||
|
||||
// Cubic B-splines
|
||||
template<typename NumberType>
|
||||
using CubicBSplineKernel = CubicKernelWrapper<BicubicInternal::CubicBSplineKernel<NumberType>>;
|
||||
|
||||
template<typename KernelWrapper>
|
||||
static typename KernelWrapper::FloatType cubic_interpolate(const Eigen::ArrayBase<typename KernelWrapper::FloatType> &F,
|
||||
const typename KernelWrapper::FloatType pt) {
|
||||
typedef typename KernelWrapper::FloatType T;
|
||||
const int w = int(F.size());
|
||||
const int ix = (int) floor(pt);
|
||||
const T s = pt - T( ix);
|
||||
|
||||
if (ix > 1 && ix + 2 < w) {
|
||||
// Inside the fully interpolated region.
|
||||
return KernelWrapper::interpolate(F[ix - 1], F[ix], F[ix + 1], F[ix + 2], s);
|
||||
}
|
||||
// Transition region. Extend with a constant function.
|
||||
auto f = [&F, w](T x) {
|
||||
return F[BicubicInternal::clamp(x, 0, w - 1)];
|
||||
};
|
||||
return KernelWrapper::interpolate(f(ix - 1), f(ix), f(ix + 1), f(ix + 2), s);
|
||||
}
|
||||
|
||||
template<typename Kernel, typename Derived>
|
||||
static float bicubic_interpolate(const Eigen::MatrixBase<Derived> &F,
|
||||
const Eigen::Matrix<typename Kernel::FloatType, 2, 1, Eigen::DontAlign> &pt) {
|
||||
typedef typename Kernel::FloatType T;
|
||||
const int w = F.cols();
|
||||
const int h = F.rows();
|
||||
const int ix = (int) floor(pt[0]);
|
||||
const int iy = (int) floor(pt[1]);
|
||||
const T s = pt[0] - T( ix);
|
||||
const T t = pt[1] - T( iy);
|
||||
|
||||
if (ix > 1 && ix + 2 < w && iy > 1 && iy + 2 < h) {
|
||||
// Inside the fully interpolated region.
|
||||
return Kernel::interpolate(
|
||||
Kernel::interpolate(F(ix - 1, iy - 1), F(ix, iy - 1), F(ix + 1, iy - 1), F(ix + 2, iy - 1), s),
|
||||
Kernel::interpolate(F(ix - 1, iy), F(ix, iy), F(ix + 1, iy), F(ix + 2, iy), s),
|
||||
Kernel::interpolate(F(ix - 1, iy + 1), F(ix, iy + 1), F(ix + 1, iy + 1), F(ix + 2, iy + 1), s),
|
||||
Kernel::interpolate(F(ix - 1, iy + 2), F(ix, iy + 2), F(ix + 1, iy + 2), F(ix + 2, iy + 2), s), t);
|
||||
}
|
||||
// Transition region. Extend with a constant function.
|
||||
auto f = [&F, w, h](int x, int y) {
|
||||
return F(BicubicInternal::clamp(x, 0, w - 1), BicubicInternal::clamp(y, 0, h - 1));
|
||||
};
|
||||
return Kernel::interpolate(
|
||||
Kernel::interpolate(f(ix - 1, iy - 1), f(ix, iy - 1), f(ix + 1, iy - 1), f(ix + 2, iy - 1), s),
|
||||
Kernel::interpolate(f(ix - 1, iy), f(ix, iy), f(ix + 1, iy), f(ix + 2, iy), s),
|
||||
Kernel::interpolate(f(ix - 1, iy + 1), f(ix, iy + 1), f(ix + 1, iy + 1), f(ix + 2, iy + 1), s),
|
||||
Kernel::interpolate(f(ix - 1, iy + 2), f(ix, iy + 2), f(ix + 1, iy + 2), f(ix + 2, iy + 2), s), t);
|
||||
}
|
||||
|
||||
} //namespace Geometry
|
||||
|
||||
} // namespace Slic3r
|
||||
|
||||
#endif /* BICUBIC_HPP */
|
||||
140
src/libslic3r/Geometry/Circle.cpp
Normal file
140
src/libslic3r/Geometry/Circle.cpp
Normal file
@@ -0,0 +1,140 @@
|
||||
#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, double* min_error)
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
if (min_error)
|
||||
*min_error = err_min;
|
||||
return circle_best;
|
||||
}
|
||||
|
||||
} } // namespace Slic3r::Geometry
|
||||
187
src/libslic3r/Geometry/Circle.hpp
Normal file
187
src/libslic3r/Geometry/Circle.hpp
Normal 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 ¢er, 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 ¢er, 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, double* min_error = nullptr);
|
||||
|
||||
// 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_
|
||||
423
src/libslic3r/Geometry/ConvexHull.cpp
Normal file
423
src/libslic3r/Geometry/ConvexHull.cpp
Normal file
@@ -0,0 +1,423 @@
|
||||
#include "libslic3r.h"
|
||||
#include "ConvexHull.hpp"
|
||||
#include "BoundingBox.hpp"
|
||||
#include "../Geometry.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 && Geometry::orient(pts[i], hull[k-2], hull[k-1]) != Geometry::ORIENTATION_CCW)
|
||||
-- k;
|
||||
hull[k ++] = pts[i];
|
||||
}
|
||||
// Build upper hull
|
||||
for (int i = n-2, t = k+1; i >= 0; i--) {
|
||||
while (k >= t && Geometry::orient(pts[i], hull[k-2], hull[k-1]) != Geometry::ORIENTATION_CCW)
|
||||
-- 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 (Geometry::orient(p, k2, k1) != Geometry::ORIENTATION_CCW)
|
||||
--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 (Geometry::orient(p, k2, k1) != Geometry::ORIENTATION_CCW)
|
||||
--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));
|
||||
}
|
||||
|
||||
Polygon convex_hull(const ExPolygons &expolygons)
|
||||
{
|
||||
Points pp;
|
||||
size_t sz = 0;
|
||||
for (const auto &expoly : expolygons)
|
||||
sz += expoly.contour.size();
|
||||
pp.reserve(sz);
|
||||
for (const auto &expoly : expolygons)
|
||||
pp.insert(pp.end(), expoly.contour.points.begin(), expoly.contour.points.end());
|
||||
return convex_hull(pp);
|
||||
}
|
||||
|
||||
Polygon convex_hulll(const Polylines &polylines)
|
||||
{
|
||||
Points pp;
|
||||
size_t sz = 0;
|
||||
for (const auto &polyline : polylines)
|
||||
sz += polyline.points.size();
|
||||
pp.reserve(sz);
|
||||
for (const auto &polyline : polylines)
|
||||
pp.insert(pp.end(), polyline.points.begin(), polyline.points.end());
|
||||
return convex_hull(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() && 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
|
||||
|
||||
35
src/libslic3r/Geometry/ConvexHull.hpp
Normal file
35
src/libslic3r/Geometry/ConvexHull.hpp
Normal file
@@ -0,0 +1,35 @@
|
||||
#ifndef slic3r_Geometry_ConvexHull_hpp_
|
||||
#define slic3r_Geometry_ConvexHull_hpp_
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "../Polygon.hpp"
|
||||
|
||||
namespace Slic3r {
|
||||
|
||||
class ExPolygon;
|
||||
using ExPolygons = std::vector<ExPolygon>;
|
||||
|
||||
namespace Geometry {
|
||||
|
||||
Pointf3s convex_hull(Pointf3s points);
|
||||
Polygon convex_hull(Points points);
|
||||
Polygon convex_hull(const Polygons &polygons);
|
||||
Polygon convex_hull(const ExPolygons &expolygons);
|
||||
Polygon convex_hulll(const Polylines &polylines);
|
||||
|
||||
// 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
|
||||
218
src/libslic3r/Geometry/Curves.hpp
Normal file
218
src/libslic3r/Geometry/Curves.hpp
Normal file
@@ -0,0 +1,218 @@
|
||||
#ifndef SRC_LIBSLIC3R_GEOMETRY_CURVES_HPP_
|
||||
#define SRC_LIBSLIC3R_GEOMETRY_CURVES_HPP_
|
||||
|
||||
#include "libslic3r/Point.hpp"
|
||||
#include "Bicubic.hpp"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
//#define LSQR_DEBUG
|
||||
|
||||
namespace Slic3r {
|
||||
namespace Geometry {
|
||||
|
||||
template<int Dimension, typename NumberType>
|
||||
struct PolynomialCurve {
|
||||
Eigen::MatrixXf coefficients;
|
||||
|
||||
Vec<Dimension, NumberType> get_fitted_value(const NumberType& value) const {
|
||||
Vec<Dimension, NumberType> result = Vec<Dimension, NumberType>::Zero();
|
||||
size_t order = this->coefficients.rows() - 1;
|
||||
auto x = NumberType(1.);
|
||||
for (size_t index = 0; index < order + 1; ++index, x *= value)
|
||||
result += x * this->coefficients.col(index);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
//https://towardsdatascience.com/least-square-polynomial-CURVES-using-c-eigen-package-c0673728bd01
|
||||
template<int Dimension, typename NumberType>
|
||||
PolynomialCurve<Dimension, NumberType> fit_polynomial(const std::vector<Vec<Dimension, NumberType>> &observations,
|
||||
const std::vector<NumberType> &observation_points,
|
||||
const std::vector<NumberType> &weights, size_t order) {
|
||||
// check to make sure inputs are correct
|
||||
size_t cols = order + 1;
|
||||
assert(observation_points.size() >= cols);
|
||||
assert(observation_points.size() == weights.size());
|
||||
assert(observations.size() == weights.size());
|
||||
|
||||
Eigen::MatrixXf data_points(Dimension, observations.size());
|
||||
Eigen::MatrixXf T(observations.size(), cols);
|
||||
for (size_t i = 0; i < weights.size(); ++i) {
|
||||
auto squared_weight = sqrt(weights[i]);
|
||||
data_points.col(i) = observations[i] * squared_weight;
|
||||
// Populate the matrix
|
||||
auto x = squared_weight;
|
||||
auto c = observation_points[i];
|
||||
for (size_t j = 0; j < cols; ++j, x *= c)
|
||||
T(i, j) = x;
|
||||
}
|
||||
|
||||
const auto QR = T.householderQr();
|
||||
Eigen::MatrixXf coefficients(Dimension, cols);
|
||||
// Solve for linear least square fit
|
||||
for (size_t dim = 0; dim < Dimension; ++dim) {
|
||||
coefficients.row(dim) = QR.solve(data_points.row(dim).transpose());
|
||||
}
|
||||
|
||||
return {std::move(coefficients)};
|
||||
}
|
||||
|
||||
template<size_t Dimension, typename NumberType, typename KernelType>
|
||||
struct PiecewiseFittedCurve {
|
||||
using Kernel = KernelType;
|
||||
|
||||
Eigen::MatrixXf coefficients;
|
||||
NumberType start;
|
||||
NumberType segment_size;
|
||||
size_t endpoints_level_of_freedom;
|
||||
|
||||
Vec<Dimension, NumberType> get_fitted_value(const NumberType &observation_point) const {
|
||||
Vec<Dimension, NumberType> result = Vec<Dimension, NumberType>::Zero();
|
||||
|
||||
//find corresponding segment index; expects kernels to be centered
|
||||
int middle_right_segment_index = floor((observation_point - start) / segment_size);
|
||||
//find index of first segment that is affected by the point i; this can be deduced from kernel_span
|
||||
int start_segment_idx = middle_right_segment_index - Kernel::kernel_span / 2 + 1;
|
||||
for (int segment_index = start_segment_idx; segment_index < int(start_segment_idx + Kernel::kernel_span);
|
||||
segment_index++) {
|
||||
NumberType segment_start = start + segment_index * segment_size;
|
||||
NumberType normalized_segment_distance = (segment_start - observation_point) / segment_size;
|
||||
|
||||
int parameter_index = segment_index + endpoints_level_of_freedom;
|
||||
parameter_index = std::clamp(parameter_index, 0, int(coefficients.cols()) - 1);
|
||||
result += Kernel::kernel(normalized_segment_distance) * coefficients.col(parameter_index);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
// observations: data to be fitted by the curve
|
||||
// observation points: growing sequence of points where the observations were made.
|
||||
// In other words, for function f(x) = y, observations are y0...yn, and observation points are x0...xn
|
||||
// weights: how important the observation is
|
||||
// segments_count: number of segments inside the valid length of the curve
|
||||
// endpoints_level_of_freedom: number of additional parameters at each end; reasonable values depend on the kernel span
|
||||
template<typename Kernel, int Dimension, typename NumberType>
|
||||
PiecewiseFittedCurve<Dimension, NumberType, Kernel> fit_curve(
|
||||
const std::vector<Vec<Dimension, NumberType>> &observations,
|
||||
const std::vector<NumberType> &observation_points,
|
||||
const std::vector<NumberType> &weights,
|
||||
size_t segments_count,
|
||||
size_t endpoints_level_of_freedom) {
|
||||
|
||||
// check to make sure inputs are correct
|
||||
assert(segments_count > 0);
|
||||
assert(observations.size() > 0);
|
||||
assert(observation_points.size() == observations.size());
|
||||
assert(observation_points.size() == weights.size());
|
||||
assert(segments_count <= observations.size());
|
||||
|
||||
//prepare sqrt of weights, which will then be applied to both matrix T and observed data: https://en.wikipedia.org/wiki/Weighted_least_squares
|
||||
std::vector<NumberType> sqrt_weights(weights.size());
|
||||
for (size_t index = 0; index < weights.size(); ++index) {
|
||||
assert(weights[index] > 0);
|
||||
sqrt_weights[index] = sqrt(weights[index]);
|
||||
}
|
||||
|
||||
// prepare result and compute metadata
|
||||
PiecewiseFittedCurve<Dimension, NumberType, Kernel> result { };
|
||||
|
||||
NumberType valid_length = observation_points.back() - observation_points.front();
|
||||
NumberType segment_size = valid_length / NumberType(segments_count);
|
||||
result.start = observation_points.front();
|
||||
result.segment_size = segment_size;
|
||||
result.endpoints_level_of_freedom = endpoints_level_of_freedom;
|
||||
|
||||
// prepare observed data
|
||||
// Eigen defaults to column major memory layout.
|
||||
Eigen::MatrixXf data_points(Dimension, observations.size());
|
||||
for (size_t index = 0; index < observations.size(); ++index) {
|
||||
data_points.col(index) = observations[index] * sqrt_weights[index];
|
||||
}
|
||||
// parameters count is always increased by one to make the parametric space of the curve symmetric.
|
||||
// without this fix, the end of the curve is less flexible than the beginning
|
||||
size_t parameters_count = segments_count + 1 + 2 * endpoints_level_of_freedom;
|
||||
//Create weight matrix T for each point and each segment;
|
||||
Eigen::MatrixXf T(observation_points.size(), parameters_count);
|
||||
T.setZero();
|
||||
//Fill the weight matrix
|
||||
for (size_t i = 0; i < observation_points.size(); ++i) {
|
||||
NumberType observation_point = observation_points[i];
|
||||
//find corresponding segment index; expects kernels to be centered
|
||||
int middle_right_segment_index = floor((observation_point - result.start) / result.segment_size);
|
||||
//find index of first segment that is affected by the point i; this can be deduced from kernel_span
|
||||
int start_segment_idx = middle_right_segment_index - int(Kernel::kernel_span / 2) + 1;
|
||||
for (int segment_index = start_segment_idx; segment_index < int(start_segment_idx + Kernel::kernel_span);
|
||||
segment_index++) {
|
||||
NumberType segment_start = result.start + segment_index * result.segment_size;
|
||||
NumberType normalized_segment_distance = (segment_start - observation_point) / result.segment_size;
|
||||
|
||||
int parameter_index = segment_index + endpoints_level_of_freedom;
|
||||
parameter_index = std::clamp(parameter_index, 0, int(parameters_count) - 1);
|
||||
T(i, parameter_index) += Kernel::kernel(normalized_segment_distance) * sqrt_weights[i];
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef LSQR_DEBUG
|
||||
std::cout << "weight matrix: " << std::endl;
|
||||
for (int obs = 0; obs < observation_points.size(); ++obs) {
|
||||
std::cout << std::endl;
|
||||
for (int segment = 0; segment < parameters_count; ++segment) {
|
||||
std::cout << T(obs, segment) << " ";
|
||||
}
|
||||
}
|
||||
std::cout << std::endl;
|
||||
#endif
|
||||
|
||||
// Solve for linear least square fit
|
||||
result.coefficients.resize(Dimension, parameters_count);
|
||||
const auto QR = T.fullPivHouseholderQr();
|
||||
for (size_t dim = 0; dim < Dimension; ++dim) {
|
||||
result.coefficients.row(dim) = QR.solve(data_points.row(dim).transpose());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
template<int Dimension, typename NumberType>
|
||||
PiecewiseFittedCurve<Dimension, NumberType, LinearKernel<NumberType>>
|
||||
fit_linear_spline(
|
||||
const std::vector<Vec<Dimension, NumberType>> &observations,
|
||||
std::vector<NumberType> observation_points,
|
||||
std::vector<NumberType> weights,
|
||||
size_t segments_count,
|
||||
size_t endpoints_level_of_freedom = 0) {
|
||||
return fit_curve<LinearKernel<NumberType>>(observations, observation_points, weights, segments_count,
|
||||
endpoints_level_of_freedom);
|
||||
}
|
||||
|
||||
template<int Dimension, typename NumberType>
|
||||
PiecewiseFittedCurve<Dimension, NumberType, CubicBSplineKernel<NumberType>>
|
||||
fit_cubic_bspline(
|
||||
const std::vector<Vec<Dimension, NumberType>> &observations,
|
||||
std::vector<NumberType> observation_points,
|
||||
std::vector<NumberType> weights,
|
||||
size_t segments_count,
|
||||
size_t endpoints_level_of_freedom = 0) {
|
||||
return fit_curve<CubicBSplineKernel<NumberType>>(observations, observation_points, weights, segments_count,
|
||||
endpoints_level_of_freedom);
|
||||
}
|
||||
|
||||
template<int Dimension, typename NumberType>
|
||||
PiecewiseFittedCurve<Dimension, NumberType, CubicCatmulRomKernel<NumberType>>
|
||||
fit_catmul_rom_spline(
|
||||
const std::vector<Vec<Dimension, NumberType>> &observations,
|
||||
std::vector<NumberType> observation_points,
|
||||
std::vector<NumberType> weights,
|
||||
size_t segments_count,
|
||||
size_t endpoints_level_of_freedom = 0) {
|
||||
return fit_curve<CubicCatmulRomKernel<NumberType>>(observations, observation_points, weights, segments_count,
|
||||
endpoints_level_of_freedom);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
#endif /* SRC_LIBSLIC3R_GEOMETRY_CURVES_HPP_ */
|
||||
687
src/libslic3r/Geometry/MedialAxis.cpp
Normal file
687
src/libslic3r/Geometry/MedialAxis.cpp
Normal file
@@ -0,0 +1,687 @@
|
||||
#include "MedialAxis.hpp"
|
||||
|
||||
#include "clipper.hpp"
|
||||
#include "VoronoiOffset.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;
|
||||
};
|
||||
|
||||
MedialAxis::MedialAxis(double min_width, double max_width, const ExPolygon &expolygon) :
|
||||
m_expolygon(expolygon), m_lines(expolygon.lines()), m_min_width(min_width), m_max_width(max_width)
|
||||
{
|
||||
(void)m_expolygon; // supress unused variable warning
|
||||
}
|
||||
|
||||
void MedialAxis::build(ThickPolylines* polylines)
|
||||
{
|
||||
construct_voronoi(m_lines.begin(), m_lines.end(), &m_vd);
|
||||
Slic3r::Voronoi::annotate_inside_outside(m_vd, m_lines);
|
||||
// static constexpr double threshold_alpha = M_PI / 12.; // 30 degrees
|
||||
// std::vector<Vec2d> skeleton_edges = Slic3r::Voronoi::skeleton_edges_rough(vd, lines, threshold_alpha);
|
||||
|
||||
/*
|
||||
// DEBUG: dump all Voronoi edges
|
||||
{
|
||||
for (VD::const_edge_iterator edge = m_vd.edges().begin(); edge != m_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;
|
||||
}
|
||||
*/
|
||||
|
||||
// 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
|
||||
m_edge_data.assign(m_vd.edges().size() / 2, EdgeData{});
|
||||
for (VD::const_edge_iterator edge = m_vd.edges().begin(); edge != m_vd.edges().end(); edge += 2)
|
||||
if (edge->is_primary() && edge->is_finite() &&
|
||||
(Voronoi::vertex_category(edge->vertex0()) == Voronoi::VertexCategory::Inside ||
|
||||
Voronoi::vertex_category(edge->vertex1()) == Voronoi::VertexCategory::Inside) &&
|
||||
this->validate_edge(&*edge)) {
|
||||
// Valid skeleton edge.
|
||||
this->edge_data(*edge).first.active = true;
|
||||
}
|
||||
|
||||
// iterate through the valid edges to build polylines
|
||||
ThickPolyline reverse_polyline;
|
||||
for (VD::const_edge_iterator seed_edge = m_vd.edges().begin(); seed_edge != m_vd.edges().end(); seed_edge += 2)
|
||||
if (EdgeData &seed_edge_data = this->edge_data(*seed_edge).first; seed_edge_data.active) {
|
||||
// Mark this edge as visited.
|
||||
seed_edge_data.active = false;
|
||||
|
||||
// Start a polyline.
|
||||
ThickPolyline polyline;
|
||||
polyline.points.emplace_back(seed_edge->vertex0()->x(), seed_edge->vertex0()->y());
|
||||
polyline.points.emplace_back(seed_edge->vertex1()->x(), seed_edge->vertex1()->y());
|
||||
polyline.width.emplace_back(seed_edge_data.width_start);
|
||||
polyline.width.emplace_back(seed_edge_data.width_end);
|
||||
// Grow the polyline in a forward direction.
|
||||
this->process_edge_neighbors(&*seed_edge, &polyline);
|
||||
assert(polyline.width.size() == polyline.points.size() * 2 - 2);
|
||||
|
||||
// Grow the polyline in a backward direction.
|
||||
reverse_polyline.clear();
|
||||
this->process_edge_neighbors(seed_edge->twin(), &reverse_polyline);
|
||||
polyline.points.insert(polyline.points.begin(), reverse_polyline.points.rbegin(), reverse_polyline.points.rend());
|
||||
polyline.width.insert(polyline.width.begin(), reverse_polyline.width.rbegin(), reverse_polyline.width.rend());
|
||||
polyline.endpoints.first = reverse_polyline.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->emplace_back(std::move(polyline));
|
||||
}
|
||||
|
||||
#ifdef SLIC3R_DEBUG
|
||||
{
|
||||
static int iRun = 0;
|
||||
dump_voronoi_to_svg(m_lines, m_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->reserve(polylines->size() + tp.size());
|
||||
for (auto &pl : tp)
|
||||
polylines->emplace_back(pl.points);
|
||||
}
|
||||
|
||||
void MedialAxis::process_edge_neighbors(const VD::edge_type *edge, ThickPolyline* polyline)
|
||||
{
|
||||
for (;;) {
|
||||
// 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
|
||||
size_t num_neighbors = 0;
|
||||
const VD::edge_type *first_neighbor = nullptr;
|
||||
for (const VD::edge_type *neighbor = twin->rot_next(); neighbor != twin; neighbor = neighbor->rot_next())
|
||||
if (this->edge_data(*neighbor).first.active) {
|
||||
if (num_neighbors == 0)
|
||||
first_neighbor = neighbor;
|
||||
++ num_neighbors;
|
||||
}
|
||||
|
||||
// if we have a single neighbor then we can continue recursively
|
||||
if (num_neighbors == 1) {
|
||||
if (std::pair<EdgeData&, bool> neighbor_data = this->edge_data(*first_neighbor);
|
||||
neighbor_data.first.active) {
|
||||
neighbor_data.first.active = false;
|
||||
polyline->points.emplace_back(first_neighbor->vertex1()->x(), first_neighbor->vertex1()->y());
|
||||
if (neighbor_data.second) {
|
||||
polyline->width.push_back(neighbor_data.first.width_end);
|
||||
polyline->width.push_back(neighbor_data.first.width_start);
|
||||
} else {
|
||||
polyline->width.push_back(neighbor_data.first.width_start);
|
||||
polyline->width.push_back(neighbor_data.first.width_end);
|
||||
}
|
||||
edge = first_neighbor;
|
||||
// Continue chaining.
|
||||
continue;
|
||||
}
|
||||
} else if (num_neighbors == 0) {
|
||||
polyline->endpoints.second = true;
|
||||
} else {
|
||||
// T-shaped or star-shaped joint
|
||||
}
|
||||
// Stop chaining.
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
bool MedialAxis::validate_edge(const VD::edge_type* edge)
|
||||
{
|
||||
auto retrieve_segment = [this](const VD::cell_type* cell) -> const Line& { return m_lines[cell->source_index()]; };
|
||||
auto retrieve_endpoint = [retrieve_segment](const VD::cell_type* cell) -> const Point& {
|
||||
const Line &line = retrieve_segment(cell);
|
||||
return cell->source_category() == boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT ? line.a : line.b;
|
||||
};
|
||||
|
||||
// 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({ edge->vertex0()->x(), edge->vertex0()->y() },
|
||||
{ edge->vertex1()->x(), edge->vertex1()->y() });
|
||||
|
||||
// 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 = retrieve_segment(cell_l);
|
||||
const Line &segment_r = retrieve_segment(cell_r);
|
||||
|
||||
/*
|
||||
SVG svg("edge.svg");
|
||||
svg.draw(m_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
|
||||
: (retrieve_endpoint(cell_r) - line.a).cast<double>().norm()*2;
|
||||
|
||||
coordf_t w1 = cell_l->contains_segment()
|
||||
? segment_l.distance_to(line.b)*2
|
||||
: (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() >= m_min_width)
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (w0 < SCALED_EPSILON || w1 < SCALED_EPSILON)
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((w0 >= m_min_width || w1 >= m_min_width) &&
|
||||
(w0 <= m_max_width || w1 <= m_max_width)) {
|
||||
std::pair<EdgeData&, bool> ed = this->edge_data(*edge);
|
||||
if (ed.second)
|
||||
std::swap(w0, w1);
|
||||
ed.first.width_start = w0;
|
||||
ed.first.width_end = w1;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
} } // namespace Slicer::Geometry
|
||||
46
src/libslic3r/Geometry/MedialAxis.hpp
Normal file
46
src/libslic3r/Geometry/MedialAxis.hpp
Normal file
@@ -0,0 +1,46 @@
|
||||
#ifndef slic3r_Geometry_MedialAxis_hpp_
|
||||
#define slic3r_Geometry_MedialAxis_hpp_
|
||||
|
||||
#include "Voronoi.hpp"
|
||||
#include "../ExPolygon.hpp"
|
||||
|
||||
namespace Slic3r::Geometry {
|
||||
|
||||
class MedialAxis {
|
||||
public:
|
||||
MedialAxis(double min_width, double max_width, const ExPolygon &expolygon);
|
||||
void build(ThickPolylines* polylines);
|
||||
void build(Polylines* polylines);
|
||||
|
||||
private:
|
||||
// Input
|
||||
const ExPolygon &m_expolygon;
|
||||
Lines m_lines;
|
||||
// for filtering of the skeleton edges
|
||||
double m_min_width;
|
||||
double m_max_width;
|
||||
|
||||
// Voronoi Diagram.
|
||||
using VD = VoronoiDiagram;
|
||||
VD m_vd;
|
||||
|
||||
// Annotations of the VD skeleton edges.
|
||||
struct EdgeData {
|
||||
bool active { false };
|
||||
double width_start { 0 };
|
||||
double width_end { 0 };
|
||||
};
|
||||
// Returns a reference to EdgeData and a "reversed" boolean.
|
||||
std::pair<EdgeData&, bool> edge_data(const VD::edge_type &edge) {
|
||||
size_t edge_id = &edge - &m_vd.edges().front();
|
||||
return { m_edge_data[edge_id / 2], (edge_id & 1) != 0 };
|
||||
}
|
||||
std::vector<EdgeData> m_edge_data;
|
||||
|
||||
void process_edge_neighbors(const VD::edge_type* edge, ThickPolyline* polyline);
|
||||
bool validate_edge(const VD::edge_type* edge);
|
||||
};
|
||||
|
||||
} // namespace Slicer::Geometry
|
||||
|
||||
#endif // slic3r_Geometry_MedialAxis_hpp_
|
||||
33
src/libslic3r/Geometry/Voronoi.hpp
Normal file
33
src/libslic3r/Geometry/Voronoi.hpp
Normal 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_
|
||||
1636
src/libslic3r/Geometry/VoronoiOffset.cpp
Normal file
1636
src/libslic3r/Geometry/VoronoiOffset.cpp
Normal file
File diff suppressed because it is too large
Load Diff
145
src/libslic3r/Geometry/VoronoiOffset.hpp
Normal file
145
src/libslic3r/Geometry/VoronoiOffset.hpp
Normal file
@@ -0,0 +1,145 @@
|
||||
// Polygon offsetting using Voronoi diagram produced 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_
|
||||
283
src/libslic3r/Geometry/VoronoiUtilsCgal.cpp
Normal file
283
src/libslic3r/Geometry/VoronoiUtilsCgal.cpp
Normal file
@@ -0,0 +1,283 @@
|
||||
#include <CGAL/Exact_predicates_exact_constructions_kernel.h>
|
||||
#include <CGAL/Arr_segment_traits_2.h>
|
||||
#include <CGAL/Surface_sweep_2_algorithms.h>
|
||||
|
||||
#include "libslic3r/Geometry/Voronoi.hpp"
|
||||
#include "libslic3r/Arachne/utils/VoronoiUtils.hpp"
|
||||
|
||||
#include "VoronoiUtilsCgal.hpp"
|
||||
|
||||
using VD = Slic3r::Geometry::VoronoiDiagram;
|
||||
using namespace Slic3r::Arachne;
|
||||
|
||||
namespace Slic3r::Geometry {
|
||||
|
||||
// The tangent vector of the parabola is computed based on the Proof of the reflective property.
|
||||
// https://en.wikipedia.org/wiki/Parabola#Proof_of_the_reflective_property
|
||||
// https://math.stackexchange.com/q/2439647/2439663#comment5039739_2439663
|
||||
namespace impl {
|
||||
using K = CGAL::Simple_cartesian<double>;
|
||||
using FK = CGAL::Simple_cartesian<CGAL::Interval_nt_advanced>;
|
||||
using EK = CGAL::Simple_cartesian<CGAL::MP_Float>;
|
||||
using C2E = CGAL::Cartesian_converter<K, EK>;
|
||||
using C2F = CGAL::Cartesian_converter<K, FK>;
|
||||
class Epick : public CGAL::Filtered_kernel_adaptor<CGAL::Type_equality_wrapper<K::Base<Epick>::Type, Epick>, true> {};
|
||||
|
||||
template<typename K>
|
||||
inline typename K::Vector_2 calculate_parabolic_tangent_vector(
|
||||
// Test point on the parabola, where the tangent will be calculated.
|
||||
const typename K::Point_2 &p,
|
||||
// Focus point of the parabola.
|
||||
const typename K::Point_2 &f,
|
||||
// Points of a directrix of the parabola.
|
||||
const typename K::Point_2 &u,
|
||||
const typename K::Point_2 &v,
|
||||
// On which side of the parabolic segment endpoints the focus point is, which determines the orientation of the tangent.
|
||||
const typename K::Orientation &tangent_orientation)
|
||||
{
|
||||
using RT = typename K::RT;
|
||||
using Vector_2 = typename K::Vector_2;
|
||||
|
||||
const Vector_2 directrix_vec = v - u;
|
||||
const RT directrix_vec_sqr_length = CGAL::scalar_product(directrix_vec, directrix_vec);
|
||||
Vector_2 focus_vec = (f - u) * directrix_vec_sqr_length - directrix_vec * CGAL::scalar_product(directrix_vec, p - u);
|
||||
Vector_2 tangent_vec = focus_vec.perpendicular(tangent_orientation);
|
||||
return tangent_vec;
|
||||
}
|
||||
|
||||
template<typename K> struct ParabolicTangentToSegmentOrientationPredicate
|
||||
{
|
||||
using Point_2 = typename K::Point_2;
|
||||
using Vector_2 = typename K::Vector_2;
|
||||
using Orientation = typename K::Orientation;
|
||||
using result_type = typename K::Orientation;
|
||||
|
||||
result_type operator()(
|
||||
// Test point on the parabola, where the tangent will be calculated.
|
||||
const Point_2 &p,
|
||||
// End of the linear segment (p, q), for which orientation towards the tangent to parabola will be evaluated.
|
||||
const Point_2 &q,
|
||||
// Focus point of the parabola.
|
||||
const Point_2 &f,
|
||||
// Points of a directrix of the parabola.
|
||||
const Point_2 &u,
|
||||
const Point_2 &v,
|
||||
// On which side of the parabolic segment endpoints the focus point is, which determines the orientation of the tangent.
|
||||
const Orientation &tangent_orientation) const
|
||||
{
|
||||
assert(tangent_orientation == CGAL::Orientation::LEFT_TURN || tangent_orientation == CGAL::Orientation::RIGHT_TURN);
|
||||
|
||||
Vector_2 tangent_vec = calculate_parabolic_tangent_vector<K>(p, f, u, v, tangent_orientation);
|
||||
Vector_2 linear_vec = q - p;
|
||||
|
||||
return CGAL::sign(tangent_vec.x() * linear_vec.y() - tangent_vec.y() * linear_vec.x());
|
||||
}
|
||||
};
|
||||
|
||||
template<typename K> struct ParabolicTangentToParabolicTangentOrientationPredicate
|
||||
{
|
||||
using Point_2 = typename K::Point_2;
|
||||
using Vector_2 = typename K::Vector_2;
|
||||
using Orientation = typename K::Orientation;
|
||||
using result_type = typename K::Orientation;
|
||||
|
||||
result_type operator()(
|
||||
// Common point on both parabolas, where the tangent will be calculated.
|
||||
const Point_2 &p,
|
||||
// Focus point of the first parabola.
|
||||
const Point_2 &f_0,
|
||||
// Points of a directrix of the first parabola.
|
||||
const Point_2 &u_0,
|
||||
const Point_2 &v_0,
|
||||
// On which side of the parabolic segment endpoints the focus point is, which determines the orientation of the tangent.
|
||||
const Orientation &tangent_orientation_0,
|
||||
// Focus point of the second parabola.
|
||||
const Point_2 &f_1,
|
||||
// Points of a directrix of the second parabola.
|
||||
const Point_2 &u_1,
|
||||
const Point_2 &v_1,
|
||||
// On which side of the parabolic segment endpoints the focus point is, which determines the orientation of the tangent.
|
||||
const Orientation &tangent_orientation_1) const
|
||||
{
|
||||
assert(tangent_orientation_0 == CGAL::Orientation::LEFT_TURN || tangent_orientation_0 == CGAL::Orientation::RIGHT_TURN);
|
||||
assert(tangent_orientation_1 == CGAL::Orientation::LEFT_TURN || tangent_orientation_1 == CGAL::Orientation::RIGHT_TURN);
|
||||
|
||||
Vector_2 tangent_vec_0 = calculate_parabolic_tangent_vector<K>(p, f_0, u_0, v_0, tangent_orientation_0);
|
||||
Vector_2 tangent_vec_1 = calculate_parabolic_tangent_vector<K>(p, f_1, u_1, v_1, tangent_orientation_1);
|
||||
|
||||
return CGAL::sign(tangent_vec_0.x() * tangent_vec_1.y() - tangent_vec_0.y() * tangent_vec_1.x());
|
||||
}
|
||||
};
|
||||
|
||||
using ParabolicTangentToSegmentOrientationPredicateFiltered = CGAL::Filtered_predicate<ParabolicTangentToSegmentOrientationPredicate<EK>, ParabolicTangentToSegmentOrientationPredicate<FK>, C2E, C2F>;
|
||||
using ParabolicTangentToParabolicTangentOrientationPredicateFiltered = CGAL::Filtered_predicate<ParabolicTangentToParabolicTangentOrientationPredicate<EK>, ParabolicTangentToParabolicTangentOrientationPredicate<FK>, C2E, C2F>;
|
||||
} // namespace impl
|
||||
|
||||
using ParabolicTangentToSegmentOrientation = impl::ParabolicTangentToSegmentOrientationPredicateFiltered;
|
||||
using ParabolicTangentToParabolicTangentOrientation = impl::ParabolicTangentToParabolicTangentOrientationPredicateFiltered;
|
||||
using CGAL_Point = impl::K::Point_2;
|
||||
|
||||
inline static CGAL_Point to_cgal_point(const VD::vertex_type *pt) { return {pt->x(), pt->y()}; }
|
||||
inline static CGAL_Point to_cgal_point(const Point &pt) { return {pt.x(), pt.y()}; }
|
||||
inline static CGAL_Point to_cgal_point(const Vec2d &pt) { return {pt.x(), pt.y()}; }
|
||||
|
||||
inline static Linef make_linef(const VD::edge_type &edge)
|
||||
{
|
||||
const VD::vertex_type *v0 = edge.vertex0();
|
||||
const VD::vertex_type *v1 = edge.vertex1();
|
||||
return {Vec2d(v0->x(), v0->y()), Vec2d(v1->x(), v1->y())};
|
||||
}
|
||||
|
||||
[[maybe_unused]] inline static bool is_equal(const VD::vertex_type &first, const VD::vertex_type &second) { return first.x() == second.x() && first.y() == second.y(); }
|
||||
|
||||
// FIXME Lukas H.: Also includes parabolic segments.
|
||||
bool VoronoiUtilsCgal::is_voronoi_diagram_planar_intersection(const VD &voronoi_diagram)
|
||||
{
|
||||
using CGAL_Point = CGAL::Exact_predicates_exact_constructions_kernel::Point_2;
|
||||
using CGAL_Segment = CGAL::Arr_segment_traits_2<CGAL::Exact_predicates_exact_constructions_kernel>::Curve_2;
|
||||
auto to_cgal_point = [](const VD::vertex_type &pt) -> CGAL_Point { return {pt.x(), pt.y()}; };
|
||||
|
||||
assert(std::all_of(voronoi_diagram.edges().cbegin(), voronoi_diagram.edges().cend(),
|
||||
[](const VD::edge_type &edge) { return edge.color() == 0; }));
|
||||
|
||||
std::vector<CGAL_Segment> segments;
|
||||
segments.reserve(voronoi_diagram.num_edges());
|
||||
|
||||
for (const VD::edge_type &edge : voronoi_diagram.edges()) {
|
||||
if (edge.color() != 0)
|
||||
continue;
|
||||
|
||||
if (edge.is_finite() && edge.is_linear() && edge.vertex0() != nullptr && edge.vertex1() != nullptr &&
|
||||
VoronoiUtils::is_finite(*edge.vertex0()) && VoronoiUtils::is_finite(*edge.vertex1())) {
|
||||
segments.emplace_back(to_cgal_point(*edge.vertex0()), to_cgal_point(*edge.vertex1()));
|
||||
edge.color(1);
|
||||
assert(edge.twin() != nullptr);
|
||||
edge.twin()->color(1);
|
||||
}
|
||||
}
|
||||
|
||||
for (const VD::edge_type &edge : voronoi_diagram.edges())
|
||||
edge.color(0);
|
||||
|
||||
std::vector<CGAL_Point> intersections_pt;
|
||||
CGAL::compute_intersection_points(segments.begin(), segments.end(), std::back_inserter(intersections_pt));
|
||||
return intersections_pt.empty();
|
||||
}
|
||||
|
||||
struct ParabolicSegment
|
||||
{
|
||||
const Point focus;
|
||||
const Line directrix;
|
||||
// Two points on the parabola;
|
||||
const Linef segment;
|
||||
// Indicate if focus point is on the left side or right side relative to parabolic segment endpoints.
|
||||
const CGAL::Orientation is_focus_on_left;
|
||||
};
|
||||
|
||||
inline static ParabolicSegment get_parabolic_segment(const VD::edge_type &edge, const std::vector<VoronoiUtils::Segment> &segments)
|
||||
{
|
||||
assert(edge.is_curved());
|
||||
|
||||
const VD::cell_type *left_cell = edge.cell();
|
||||
const VD::cell_type *right_cell = edge.twin()->cell();
|
||||
|
||||
const Point focus_pt = VoronoiUtils::getSourcePoint(*(left_cell->contains_point() ? left_cell : right_cell), segments);
|
||||
const VoronoiUtils::Segment &directrix = VoronoiUtils::getSourceSegment(*(left_cell->contains_point() ? right_cell : left_cell), segments);
|
||||
CGAL::Orientation focus_side = CGAL::opposite(CGAL::orientation(to_cgal_point(edge.vertex0()), to_cgal_point(edge.vertex1()), to_cgal_point(focus_pt)));
|
||||
|
||||
assert(focus_side == CGAL::Orientation::LEFT_TURN || focus_side == CGAL::Orientation::RIGHT_TURN);
|
||||
return {focus_pt, Line(directrix.from(), directrix.to()), make_linef(edge), focus_side};
|
||||
}
|
||||
|
||||
inline static CGAL::Orientation orientation_of_two_edges(const VD::edge_type &edge_a, const VD::edge_type &edge_b, const std::vector<VoronoiUtils::Segment> &segments) {
|
||||
assert(is_equal(*edge_a.vertex0(), *edge_b.vertex0()));
|
||||
CGAL::Orientation orientation;
|
||||
if (edge_a.is_linear() && edge_b.is_linear()) {
|
||||
orientation = CGAL::orientation(to_cgal_point(edge_a.vertex0()), to_cgal_point(edge_a.vertex1()), to_cgal_point(edge_b.vertex1()));
|
||||
} else if (edge_a.is_curved() && edge_b.is_curved()) {
|
||||
const ParabolicSegment parabolic_a = get_parabolic_segment(edge_a, segments);
|
||||
const ParabolicSegment parabolic_b = get_parabolic_segment(edge_b, segments);
|
||||
orientation = ParabolicTangentToParabolicTangentOrientation{}(to_cgal_point(parabolic_a.segment.a),
|
||||
to_cgal_point(parabolic_a.focus),
|
||||
to_cgal_point(parabolic_a.directrix.a),
|
||||
to_cgal_point(parabolic_a.directrix.b),
|
||||
parabolic_a.is_focus_on_left,
|
||||
to_cgal_point(parabolic_b.focus),
|
||||
to_cgal_point(parabolic_b.directrix.a),
|
||||
to_cgal_point(parabolic_b.directrix.b),
|
||||
parabolic_b.is_focus_on_left);
|
||||
return orientation;
|
||||
} else {
|
||||
assert(edge_a.is_curved() != edge_b.is_curved());
|
||||
|
||||
const VD::edge_type &linear_edge = edge_a.is_curved() ? edge_b : edge_a;
|
||||
const VD::edge_type ¶bolic_edge = edge_a.is_curved() ? edge_a : edge_b;
|
||||
const ParabolicSegment parabolic = get_parabolic_segment(parabolic_edge, segments);
|
||||
orientation = ParabolicTangentToSegmentOrientation{}(to_cgal_point(parabolic.segment.a), to_cgal_point(linear_edge.vertex1()),
|
||||
to_cgal_point(parabolic.focus),
|
||||
to_cgal_point(parabolic.directrix.a),
|
||||
to_cgal_point(parabolic.directrix.b),
|
||||
parabolic.is_focus_on_left);
|
||||
|
||||
if (edge_b.is_curved())
|
||||
orientation = CGAL::opposite(orientation);
|
||||
}
|
||||
|
||||
return orientation;
|
||||
}
|
||||
|
||||
static bool check_if_three_edges_are_ccw(const VD::edge_type &first, const VD::edge_type &second, const VD::edge_type &third, const std::vector<VoronoiUtils::Segment> &segments)
|
||||
{
|
||||
assert(is_equal(*first.vertex0(), *second.vertex0()) && is_equal(*second.vertex0(), *third.vertex0()));
|
||||
|
||||
CGAL::Orientation orientation = orientation_of_two_edges(first, second, segments);
|
||||
if (orientation == CGAL::Orientation::COLLINEAR) {
|
||||
// The first two edges are collinear, so the third edge must be on the right side on the first of them.
|
||||
return orientation_of_two_edges(first, third, segments) == CGAL::Orientation::RIGHT_TURN;
|
||||
} else if (orientation == CGAL::Orientation::LEFT_TURN) {
|
||||
// CCW oriented angle between vectors (common_pt, pt1) and (common_pt, pt2) is bellow PI.
|
||||
// So we need to check if test_pt isn't between them.
|
||||
CGAL::Orientation orientation1 = orientation_of_two_edges(first, third, segments);
|
||||
CGAL::Orientation orientation2 = orientation_of_two_edges(second, third, segments);
|
||||
return (orientation1 != CGAL::Orientation::LEFT_TURN || orientation2 != CGAL::Orientation::RIGHT_TURN);
|
||||
} else {
|
||||
assert(orientation == CGAL::Orientation::RIGHT_TURN);
|
||||
// CCW oriented angle between vectors (common_pt, pt1) and (common_pt, pt2) is upper PI.
|
||||
// So we need to check if test_pt is between them.
|
||||
CGAL::Orientation orientation1 = orientation_of_two_edges(first, third, segments);
|
||||
CGAL::Orientation orientation2 = orientation_of_two_edges(second, third, segments);
|
||||
return (orientation1 == CGAL::Orientation::RIGHT_TURN || orientation2 == CGAL::Orientation::LEFT_TURN);
|
||||
}
|
||||
}
|
||||
|
||||
bool VoronoiUtilsCgal::is_voronoi_diagram_planar_angle(const VoronoiDiagram &voronoi_diagram, const std::vector<VoronoiUtils::Segment> &segments)
|
||||
{
|
||||
for (const VD::vertex_type &vertex : voronoi_diagram.vertices()) {
|
||||
std::vector<const VD::edge_type *> edges;
|
||||
const VD::edge_type *edge = vertex.incident_edge();
|
||||
|
||||
do {
|
||||
if (edge->is_finite() && edge->vertex0() != nullptr && edge->vertex1() != nullptr &&
|
||||
VoronoiUtils::is_finite(*edge->vertex0()) && VoronoiUtils::is_finite(*edge->vertex1()))
|
||||
edges.emplace_back(edge);
|
||||
|
||||
edge = edge->rot_next();
|
||||
} while (edge != vertex.incident_edge());
|
||||
|
||||
// Checking for CCW make sense for three and more edges.
|
||||
if (edges.size() > 2) {
|
||||
for (auto edge_it = edges.begin() ; edge_it != edges.end(); ++edge_it) {
|
||||
const Geometry::VoronoiDiagram::edge_type *prev_edge = edge_it == edges.begin() ? edges.back() : *std::prev(edge_it);
|
||||
const Geometry::VoronoiDiagram::edge_type *curr_edge = *edge_it;
|
||||
const Geometry::VoronoiDiagram::edge_type *next_edge = std::next(edge_it) == edges.end() ? edges.front() : *std::next(edge_it);
|
||||
|
||||
if (!check_if_three_edges_are_ccw(*prev_edge, *curr_edge, *next_edge, segments))
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace Slic3r::Geometry
|
||||
22
src/libslic3r/Geometry/VoronoiUtilsCgal.hpp
Normal file
22
src/libslic3r/Geometry/VoronoiUtilsCgal.hpp
Normal file
@@ -0,0 +1,22 @@
|
||||
#ifndef slic3r_VoronoiUtilsCgal_hpp_
|
||||
#define slic3r_VoronoiUtilsCgal_hpp_
|
||||
|
||||
#include "Voronoi.hpp"
|
||||
#include "../Arachne/utils/VoronoiUtils.hpp"
|
||||
|
||||
namespace Slic3r::Geometry {
|
||||
class VoronoiDiagram;
|
||||
|
||||
class VoronoiUtilsCgal
|
||||
{
|
||||
public:
|
||||
// Check if the Voronoi diagram is planar using CGAL sweeping edge algorithm for enumerating all intersections between lines.
|
||||
static bool is_voronoi_diagram_planar_intersection(const VoronoiDiagram &voronoi_diagram);
|
||||
|
||||
// Check if the Voronoi diagram is planar using verification that all neighboring edges are ordered CCW for each vertex.
|
||||
static bool is_voronoi_diagram_planar_angle(const VoronoiDiagram &voronoi_diagram, const std::vector<Arachne::VoronoiUtils::Segment> &segments);
|
||||
|
||||
};
|
||||
} // namespace Slic3r::Geometry
|
||||
|
||||
#endif // slic3r_VoronoiUtilsCgal_hpp_
|
||||
453
src/libslic3r/Geometry/VoronoiVisualUtils.hpp
Normal file
453
src/libslic3r/Geometry/VoronoiVisualUtils.hpp
Normal 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
|
||||
Reference in New Issue
Block a user