Update to Clipper 1.2+

Updates to Clipper2 742614f, which includes bug fixes for specific KiCad
boards beyond Clipper2 itself

Fixes https://gitlab.com/kicad/code/kicad/issues/14294
This commit is contained in:
Seth Hillbrand 2022-10-28 21:30:59 -07:00
parent 2e2da951a5
commit 97558b62ec
12 changed files with 5269 additions and 4984 deletions

View File

@ -1396,9 +1396,9 @@ private:
void importPaths( Clipper2Lib::Paths64& paths,
const std::vector<CLIPPER_Z_VALUE>& aZValueBuffer,
const std::vector<SHAPE_ARC>& aArcBuffe );
void importPolyPath( Clipper2Lib::PolyPath64* aPolyPath,
const std::vector<CLIPPER_Z_VALUE>& aZValueBuffer,
const std::vector<SHAPE_ARC>& aArcBuffer );
void importPolyPath( const std::unique_ptr<Clipper2Lib::PolyPath64>& aPolyPath,
const std::vector<CLIPPER_Z_VALUE>& aZValueBuffer,
const std::vector<SHAPE_ARC>& aArcBuffer );
void inflate1( int aAmount, int aCircleSegCount, CORNER_STRATEGY aCornerStrategy );
void inflate2( int aAmount, int aCircleSegCount, CORNER_STRATEGY aCornerStrategy );

View File

@ -1069,17 +1069,9 @@ void SHAPE_POLY_SET::inflate2( int aAmount, int aCircleSegCount, CORNER_STRATEGY
c.ArcTolerance( std::abs( aAmount ) * coeff );
c.MiterLimit( miterLimit );
c.MergeGroups( true );
Paths64 solution = c.Execute( aAmount );
// We get paths back but we need the tree to assign the holes to the correct
// outlines
Clipper64 c2;
PolyTree64 tree;
c2.PreserveCollinear = false;
c2.ReverseSolution = false;
c2.AddSubject( solution );
c2.Execute(ClipType::Union, FillRule::Positive, tree);
c.Execute( aAmount, tree );
importTree( tree, zValues, arcBuffer );
tree.Clear();
@ -1119,9 +1111,9 @@ void SHAPE_POLY_SET::importTree( ClipperLib::PolyTree* tree,
}
void SHAPE_POLY_SET::importPolyPath( Clipper2Lib::PolyPath64* aPolyPath,
const std::vector<CLIPPER_Z_VALUE>& aZValueBuffer,
const std::vector<SHAPE_ARC>& aArcBuffer )
void SHAPE_POLY_SET::importPolyPath( const std::unique_ptr<Clipper2Lib::PolyPath64>& aPolyPath,
const std::vector<CLIPPER_Z_VALUE>& aZValueBuffer,
const std::vector<SHAPE_ARC>& aArcBuffer )
{
if( !aPolyPath->IsHole() )
{
@ -1129,11 +1121,11 @@ void SHAPE_POLY_SET::importPolyPath( Clipper2Lib::PolyPath64* aPolyPa
paths.reserve( aPolyPath->Count() + 1 );
paths.emplace_back( aPolyPath->Polygon(), aZValueBuffer, aArcBuffer );
for( Clipper2Lib::PolyPath64* child : *aPolyPath )
for( const std::unique_ptr<Clipper2Lib::PolyPath64>& child : *aPolyPath )
{
paths.emplace_back( child->Polygon(), aZValueBuffer, aArcBuffer );
for( Clipper2Lib::PolyPath64* grandchild : *child )
for( const std::unique_ptr<Clipper2Lib::PolyPath64>& grandchild : *child )
importPolyPath( grandchild, aZValueBuffer, aArcBuffer );
}
@ -1148,7 +1140,7 @@ void SHAPE_POLY_SET::importTree( Clipper2Lib::PolyTree64& tree,
{
m_polys.clear();
for( Clipper2Lib::PolyPath64* n : tree )
for( const std::unique_ptr<Clipper2Lib::PolyPath64>& n : tree )
importPolyPath( n, aZValueBuffer, aArcBuffer );
}

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 26 October 2022 *
* Date : 2 March 2023 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2022 *
* Copyright : Angus Johnson 2010-2023 *
* Purpose : This is the main polygon clipping module *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -10,13 +10,16 @@
#ifndef CLIPPER_ENGINE_H
#define CLIPPER_ENGINE_H
#define CLIPPER2_VERSION "1.0.6"
constexpr auto CLIPPER2_VERSION = "1.2.1";
#include <cstdlib>
#include <iostream>
#include <queue>
#include <stdexcept>
#include <vector>
#include <functional>
#include <numeric>
#include <memory>
#include "clipper.core.h"
#ifdef None
@ -31,12 +34,13 @@ namespace Clipper2Lib {
struct Vertex;
struct LocalMinima;
struct OutRec;
struct Joiner;
struct HorzSegment;
//Note: all clipping operations except for Difference are commutative.
enum class ClipType { None, Intersection, Union, Difference, Xor };
enum class PathType { Subject, Clip };
enum class JoinWith { None, Left, Right };
enum class VertexFlags : uint32_t {
None = 0, OpenStart = 1, OpenEnd = 2, LocalMax = 4, LocalMin = 8
@ -47,7 +51,7 @@ namespace Clipper2Lib {
return (enum VertexFlags)(uint32_t(a) & uint32_t(b));
}
constexpr enum VertexFlags operator |(enum VertexFlags a, enum VertexFlags b)
constexpr enum VertexFlags operator |(enum VertexFlags a, enum VertexFlags b)
{
return (enum VertexFlags)(uint32_t(a) | uint32_t(b));
}
@ -64,7 +68,7 @@ namespace Clipper2Lib {
OutPt* next = nullptr;
OutPt* prev = nullptr;
OutRec* outrec;
Joiner* joiner = nullptr;
HorzSegment* horz = nullptr;
OutPt(const Point64& pt_, OutRec* outrec_): pt(pt_), outrec(outrec_) {
next = this;
@ -86,15 +90,20 @@ namespace Clipper2Lib {
struct OutRec {
size_t idx = 0;
OutRec* owner = nullptr;
OutRecList* splits = nullptr;
Active* front_edge = nullptr;
Active* back_edge = nullptr;
OutPt* pts = nullptr;
PolyPath* polypath = nullptr;
OutRecList* splits = nullptr;
Rect64 bounds = {};
Path64 path;
bool is_open = false;
~OutRec() { if (splits) delete splits; };
bool horz_done = false;
~OutRec() {
if (splits) delete splits;
// nb: don't delete the split pointers
// as these are owned by ClipperBase's outrec_list_
};
};
///////////////////////////////////////////////////////////////////
@ -126,6 +135,7 @@ namespace Clipper2Lib {
Vertex* vertex_top = nullptr;
LocalMinima* local_min = nullptr; // the bottom of an edge 'bound' (also Vatti)
bool is_left_bound = false;
JoinWith join_with = JoinWith::None;
};
struct LocalMinima {
@ -140,11 +150,24 @@ namespace Clipper2Lib {
Point64 pt;
Active* edge1;
Active* edge2;
IntersectNode() : pt(Point64(0, 0)), edge1(NULL), edge2(NULL) {}
IntersectNode() : pt(Point64(0,0)), edge1(NULL), edge2(NULL) {}
IntersectNode(Active* e1, Active* e2, Point64& pt_) :
pt(pt_), edge1(e1), edge2(e2)
{
}
pt(pt_), edge1(e1), edge2(e2) {}
};
struct HorzSegment {
OutPt* left_op;
OutPt* right_op = nullptr;
bool left_to_right = true;
HorzSegment() : left_op(nullptr) { }
explicit HorzSegment(OutPt* op) : left_op(op) { }
};
struct HorzJoin {
OutPt* op1 = nullptr;
OutPt* op2 = nullptr;
HorzJoin() {};
explicit HorzJoin(OutPt* ltr, OutPt* rtl) : op1(ltr), op2(rtl) { }
};
#ifdef USINGZ
@ -155,6 +178,11 @@ namespace Clipper2Lib {
const PointD& e2bot, const PointD& e2top, PointD& pt)> ZCallbackD;
#endif
typedef std::vector<HorzSegment> HorzSegmentList;
typedef std::unique_ptr<LocalMinima> LocalMinima_ptr;
typedef std::vector<LocalMinima_ptr> LocalMinimaList;
typedef std::vector<IntersectNode> IntersectNodeList;
// ClipperBase -------------------------------------------------------------
class ClipperBase {
@ -167,21 +195,21 @@ namespace Clipper2Lib {
bool using_polytree_ = false;
Active* actives_ = nullptr;
Active *sel_ = nullptr;
Joiner *horz_joiners_ = nullptr;
std::vector<LocalMinima*> minima_list_; //pointers in case of memory reallocs
std::vector<LocalMinima*>::iterator current_locmin_iter_;
LocalMinimaList minima_list_; //pointers in case of memory reallocs
LocalMinimaList::iterator current_locmin_iter_;
std::vector<Vertex*> vertex_lists_;
std::priority_queue<int64_t> scanline_list_;
std::vector<IntersectNode> intersect_nodes_;
std::vector<Joiner*> joiner_list_; //pointers in case of memory reallocs
IntersectNodeList intersect_nodes_;
HorzSegmentList horz_seg_list_;
std::vector<HorzJoin> horz_join_list_;
void Reset();
void InsertScanline(int64_t y);
bool PopScanline(int64_t &y);
bool PopLocalMinima(int64_t y, LocalMinima *&local_minima);
inline void InsertScanline(int64_t y);
inline bool PopScanline(int64_t &y);
inline bool PopLocalMinima(int64_t y, LocalMinima*& local_minima);
void DisposeAllOutRecs();
void DisposeVerticesAndLocalMinima();
void DeleteEdges(Active*& e);
void AddLocMin(Vertex &vert, PathType polytype, bool is_open);
inline void AddLocMin(Vertex &vert, PathType polytype, bool is_open);
bool IsContributingClosed(const Active &e) const;
inline bool IsContributingOpen(const Active &e) const;
void SetWindCountForClosedPathEdge(Active &edge);
@ -200,38 +228,40 @@ namespace Clipper2Lib {
bool BuildIntersectList(const int64_t top_y);
void ProcessIntersectList();
void SwapPositionsInAEL(Active& edge1, Active& edge2);
OutRec* NewOutRec();
OutPt* AddOutPt(const Active &e, const Point64& pt);
OutPt* AddLocalMinPoly(Active &e1, Active &e2,
const Point64& pt, bool is_new = false);
OutPt* AddLocalMaxPoly(Active &e1, Active &e2, const Point64& pt);
void DoHorizontal(Active &horz);
bool ResetHorzDirection(const Active &horz, const Active *max_pair,
bool ResetHorzDirection(const Active &horz, const Vertex* max_vertex,
int64_t &horz_left, int64_t &horz_right);
void DoTopOfScanbeam(const int64_t top_y);
Active *DoMaxima(Active &e);
void JoinOutrecPaths(Active &e1, Active &e2);
void CompleteSplit(OutPt* op1, OutPt* op2, OutRec& outrec);
bool ValidateClosedPathEx(OutPt*& outrec);
void CleanCollinear(OutRec* outrec);
void FixSelfIntersects(OutRec* outrec);
OutPt* DoSplitOp(OutPt* outRecOp, OutPt* splitOp);
Joiner* GetHorzTrialParent(const OutPt* op);
bool OutPtInTrialHorzList(OutPt* op);
void SafeDisposeOutPts(OutPt*& op);
void SafeDeleteOutPtJoiners(OutPt* op);
void AddTrialHorzJoin(OutPt* op);
void DeleteTrialHorzJoin(OutPt* op);
void ConvertHorzTrialsToJoins();
void AddJoin(OutPt* op1, OutPt* op2);
void DeleteJoin(Joiner* joiner);
void ProcessJoinerList();
OutRec* ProcessJoin(Joiner* joiner);
void DoSplitOp(OutRec* outRec, OutPt* splitOp);
inline void AddTrialHorzJoin(OutPt* op);
void ConvertHorzSegsToJoins();
void ProcessHorzJoins();
void Split(Active& e, const Point64& pt);
inline void CheckJoinLeft(Active& e,
const Point64& pt, bool check_curr_x = false);
inline void CheckJoinRight(Active& e,
const Point64& pt, bool check_curr_x = false);
protected:
int error_code_ = 0;
bool has_open_paths_ = false;
bool succeeded_ = true;
std::vector<OutRec*> outrec_list_; //pointers in case list memory reallocated
OutRecList outrec_list_; //pointers in case list memory reallocated
bool ExecuteInternal(ClipType ct, FillRule ft, bool use_polytrees);
bool DeepCheckOwner(OutRec* outrec, OutRec* owner);
void CleanCollinear(OutRec* outrec);
bool CheckBounds(OutRec* outrec);
void RecursiveCheckOwners(OutRec* outrec, PolyPath* polypath);
void DeepCheckOwners(OutRec* outrec, PolyPath* polypath);
#ifdef USINGZ
ZCallback64 zCallback_ = nullptr;
void SetZ(const Active& e1, const Active& e2, Point64& pt);
@ -241,9 +271,13 @@ namespace Clipper2Lib {
void AddPaths(const Paths64& paths, PathType polytype, bool is_open);
public:
virtual ~ClipperBase();
int ErrorCode() { return error_code_; };
bool PreserveCollinear = true;
bool ReverseSolution = false;
void Clear();
#ifdef USINGZ
int64_t DefaultZ = 0;
#endif
};
// PolyPath / PolyTree --------------------------------------------------------
@ -258,7 +292,7 @@ namespace Clipper2Lib {
PolyPath* parent_;
public:
PolyPath(PolyPath* parent = nullptr): parent_(parent){}
virtual ~PolyPath() { Clear(); };
virtual ~PolyPath() {};
//https://en.cppreference.com/w/cpp/language/rule_of_three
PolyPath(const PolyPath&) = delete;
PolyPath& operator=(const PolyPath&) = delete;
@ -273,145 +307,131 @@ namespace Clipper2Lib {
virtual PolyPath* AddChild(const Path64& path) = 0;
virtual void Clear() {};
virtual void Clear() = 0;
virtual size_t Count() const { return 0; }
const PolyPath* Parent() const { return parent_; }
bool IsHole() const
{
const PolyPath* pp = parent_;
bool is_hole = pp;
while (pp) {
is_hole = !is_hole;
pp = pp->parent_;
}
return is_hole;
}
unsigned lvl = Level();
//Even levels except level 0
return lvl && !(lvl & 1);
}
};
typedef typename std::vector<std::unique_ptr<PolyPath64>> PolyPath64List;
typedef typename std::vector<std::unique_ptr<PolyPathD>> PolyPathDList;
class PolyPath64 : public PolyPath {
private:
std::vector<PolyPath64*> childs_;
PolyPath64List childs_;
Path64 polygon_;
typedef typename std::vector<PolyPath64*>::const_iterator pp64_itor;
public:
PolyPath64(PolyPath64* parent = nullptr) : PolyPath(parent) {}
PolyPath64* operator [] (size_t index) { return static_cast<PolyPath64*>(childs_[index]); }
pp64_itor begin() const { return childs_.cbegin(); }
pp64_itor end() const { return childs_.cend(); }
explicit PolyPath64(PolyPath64* parent = nullptr) : PolyPath(parent) {}
~PolyPath64() {
childs_.resize(0);
}
const PolyPath64* operator [] (size_t index) const
{
return childs_[index].get();
}
const PolyPath64* Child(size_t index) const
{
return childs_[index].get();
}
PolyPath64List::const_iterator begin() const { return childs_.cbegin(); }
PolyPath64List::const_iterator end() const { return childs_.cend(); }
PolyPath64* AddChild(const Path64& path) override
{
PolyPath64* result = new PolyPath64(this);
childs_.push_back(result);
auto p = std::make_unique<PolyPath64>(this);
auto* result = childs_.emplace_back(std::move(p)).get();
result->polygon_ = path;
return result;
}
void Clear() override
{
for (PolyPath64* child : childs_)
{
child->Clear();
delete child;
}
childs_.resize(0);
}
size_t Count() const override
size_t Count() const override
{
return childs_.size();
}
const Path64 Polygon() const { return polygon_; };
const Path64& Polygon() const { return polygon_; };
double Area() const
{
double result = Clipper2Lib::Area<int64_t>(polygon_);
for (const PolyPath64* child : childs_)
result += child->Area();
return result;
}
friend std::ostream& operator << (std::ostream& outstream, const PolyPath64& polypath)
{
const size_t level_indent = 4;
const size_t coords_per_line = 4;
const size_t last_on_line = coords_per_line - 1;
unsigned level = polypath.Level();
if (level > 0)
{
std::string level_padding;
level_padding.insert(0, (level - 1) * level_indent, ' ');
std::string caption = polypath.IsHole() ? "Hole " : "Outer Polygon ";
std::string childs = polypath.Count() == 1 ? " child" : " children";
outstream << level_padding.c_str() << caption << "with " << polypath.Count() << childs << std::endl;
outstream << level_padding;
size_t i = 0, highI = polypath.Polygon().size() - 1;
for (; i < highI; ++i)
{
outstream << polypath.Polygon()[i] << ' ';
if ((i % coords_per_line) == last_on_line)
outstream << std::endl << level_padding;
}
if (highI > 0) outstream << polypath.Polygon()[i];
outstream << std::endl;
}
for (auto child : polypath)
outstream << *child;
return outstream;
return std::accumulate(childs_.cbegin(), childs_.cend(),
Clipper2Lib::Area<int64_t>(polygon_),
[](double a, const auto& child) {return a + child->Area(); });
}
};
class PolyPathD : public PolyPath {
private:
std::vector<PolyPathD*> childs_;
PolyPathDList childs_;
double inv_scale_;
PathD polygon_;
typedef typename std::vector<PolyPathD*>::const_iterator ppD_itor;
public:
PolyPathD(PolyPathD* parent = nullptr) : PolyPath(parent)
explicit PolyPathD(PolyPathD* parent = nullptr) : PolyPath(parent)
{
inv_scale_ = parent ? parent->inv_scale_ : 1.0;
}
PolyPathD* operator [] (size_t index)
{
return static_cast<PolyPathD*>(childs_[index]);
~PolyPathD() {
childs_.resize(0);
}
ppD_itor begin() const { return childs_.cbegin(); }
ppD_itor end() const { return childs_.cend(); }
const PolyPathD* operator [] (size_t index) const
{
return childs_[index].get();
}
const PolyPathD* Child(size_t index) const
{
return childs_[index].get();
}
PolyPathDList::const_iterator begin() const { return childs_.cbegin(); }
PolyPathDList::const_iterator end() const { return childs_.cend(); }
void SetInvScale(double value) { inv_scale_ = value; }
double InvScale() { return inv_scale_; }
PolyPathD* AddChild(const Path64& path) override
{
PolyPathD* result = new PolyPathD(this);
childs_.push_back(result);
result->polygon_ = ScalePath<double, int64_t>(path, inv_scale_);
int error_code = 0;
auto p = std::make_unique<PolyPathD>(this);
PolyPathD* result = childs_.emplace_back(std::move(p)).get();
result->polygon_ = ScalePath<double, int64_t>(path, inv_scale_, error_code);
return result;
}
void Clear() override
{
for (const PolyPathD* child : childs_) delete child;
childs_.resize(0);
}
size_t Count() const override
size_t Count() const override
{
return childs_.size();
}
const PathD Polygon() const { return polygon_; };
const PathD& Polygon() const { return polygon_; };
double Area() const
{
double result = Clipper2Lib::Area<double>(polygon_);
for (const PolyPathD* child : childs_)
result += child->Area();
return result;
return std::accumulate(childs_.begin(), childs_.end(),
Clipper2Lib::Area<double>(polygon_),
[](double a, const auto& child) {return a + child->Area(); });
}
};
@ -451,7 +471,7 @@ namespace Clipper2Lib {
closed_paths.clear();
open_paths.clear();
if (ExecuteInternal(clip_type, fill_rule, false))
BuildPaths64(closed_paths, &open_paths);
BuildPaths64(closed_paths, &open_paths);
CleanUp();
return succeeded_;
}
@ -480,19 +500,23 @@ namespace Clipper2Lib {
private:
double scale_ = 1.0, invScale_ = 1.0;
#ifdef USINGZ
ZCallbackD zCallback_ = nullptr;
ZCallbackD zCallbackD_ = nullptr;
#endif
void BuildPathsD(PathsD& solutionClosed, PathsD* solutionOpen);
void BuildTreeD(PolyPathD& polytree, PathsD& open_paths);
public:
explicit ClipperD(int precision = 2) : ClipperBase()
{
scale_ = std::pow(10, precision);
CheckPrecision(precision, error_code_);
// to optimize scaling / descaling precision
// set the scale to a power of double's radix (2) (#25)
scale_ = std::pow(std::numeric_limits<double>::radix,
std::ilogb(std::pow(10, precision)) + 1);
invScale_ = 1 / scale_;
}
#ifdef USINGZ
void SetZCallback(ZCallbackD cb) { zCallback_ = cb; };
void SetZCallback(ZCallbackD cb) { zCallbackD_ = cb; };
void ZCB(const Point64& e1bot, const Point64& e1top,
const Point64& e2bot, const Point64& e2top, Point64& pt)
@ -506,13 +530,13 @@ namespace Clipper2Lib {
PointD e1t = PointD(e1top) * invScale_;
PointD e2b = PointD(e2bot) * invScale_;
PointD e2t = PointD(e2top) * invScale_;
zCallback_(e1b,e1t, e2b, e2t, tmp);
zCallbackD_(e1b,e1t, e2b, e2t, tmp);
pt.z = tmp.z; // only update 'z'
};
void CheckCallback()
{
if(zCallback_)
if(zCallbackD_)
// if the user defined float point callback has been assigned
// then assign the proxy callback function
ClipperBase::zCallback_ =
@ -527,17 +551,17 @@ namespace Clipper2Lib {
void AddSubject(const PathsD& subjects)
{
AddPaths(ScalePaths<int64_t, double>(subjects, scale_), PathType::Subject, false);
AddPaths(ScalePaths<int64_t, double>(subjects, scale_, error_code_), PathType::Subject, false);
}
void AddOpenSubject(const PathsD& open_subjects)
{
AddPaths(ScalePaths<int64_t, double>(open_subjects, scale_), PathType::Subject, true);
AddPaths(ScalePaths<int64_t, double>(open_subjects, scale_, error_code_), PathType::Subject, true);
}
void AddClip(const PathsD& clips)
{
AddPaths(ScalePaths<int64_t, double>(clips, scale_), PathType::Clip, false);
AddPaths(ScalePaths<int64_t, double>(clips, scale_, error_code_), PathType::Clip, false);
}
bool Execute(ClipType clip_type, FillRule fill_rule, PathsD& closed_paths)

View File

@ -1,23 +1,23 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 28 October 2022 *
* Date : 22 March 2023 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2022 *
* Copyright : Angus Johnson 2010-2023 *
* Purpose : This module exports the Clipper2 Library (ie DLL/so) *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
// The exported functions below refer to simple structures that
// can be understood across multiple languages. Consequently
// Path64, PathD, Polytree64 etc are converted from classes
// Path64, PathD, Polytree64 etc are converted from C++ classes
// (std::vector<> etc) into the following data structures:
//
// CPath64 (int64_t*) & CPathD (double_t*):
// Path64 and PathD are converted into arrays of x,y coordinates.
// However in these arrays the first x,y coordinate pair is a
// counter with 'x' containing the number of following coordinate
// pairs. ('y' must always be 0.)
//__________________________________
// pairs. ('y' should be 0, with one exception explained below.)
// __________________________________
// |counter|coord1|coord2|...|coordN|
// |N ,0 |x1, y1|x2, y2|...|xN, yN|
// __________________________________
@ -25,19 +25,15 @@
// CPaths64 (int64_t**) & CPathsD (double_t**):
// These are arrays of pointers to CPath64 and CPathD where
// the first pointer is to a 'counter path'. This 'counter
// path' has a single x,y coord pair where 'y' contains
// the number of paths that follow (and with 'x' always 0).
// path' has a single x,y coord pair with 'y' (not 'x')
// containing the number of paths that follow. ('x' = 0).
// _______________________________
// |counter|path1|path2|...|pathN|
// |addr0 |addr1|addr2|...|addrN| (*addr0[0]=0; *addr0[1]=N)
// _______________________________
//
// The structures of CPolytree64 and CPolytreeD are defined
// below and they don't need to be repeated or explained here.
//
// Finally, the pointer structures created and exported through
// these functions can't safely be destroyed externally, so
// a number of 'dispose functions are also exported.
// below and these structures don't need to be explained here.
#ifndef CLIPPER2_EXPORT_H
#define CLIPPER2_EXPORT_H
@ -62,7 +58,7 @@ typedef struct CPolyPath64 {
uint32_t is_hole;
uint32_t child_count;
CPolyPath64* childs;
}
}
CPolyTree64;
typedef struct CPolyPathD {
@ -70,7 +66,7 @@ typedef struct CPolyPathD {
uint32_t is_hole;
uint32_t child_count;
CPolyPathD* childs;
}
}
CPolyTreeD;
template <typename T>
@ -101,6 +97,80 @@ inline Rect<T> CRectToRect(const CRect<T>& rect)
return result;
}
#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)
//////////////////////////////////////////////////////
// EXPORTED FUNCTION DEFINITIONS
//////////////////////////////////////////////////////
EXTERN_DLL_EXPORT const char* Version();
// Some of the functions below will return data in the various CPath
// and CPolyTree structures which are pointers to heap allocated
// memory. Eventually this memory will need to be released with one
// of the following 'DisposeExported' functions. (This may be the
// only safe way to release this memory since the executable
// accessing these exported functions may use a memory manager that
// allocates and releases heap memory in a different way. Also,
// CPath structures that have been constructed by the executable
// should not be destroyed using these 'DisposeExported' functions.)
EXTERN_DLL_EXPORT void DisposeExportedCPath64(CPath64 p);
EXTERN_DLL_EXPORT void DisposeExportedCPaths64(CPaths64& pp);
EXTERN_DLL_EXPORT void DisposeExportedCPathD(CPathD p);
EXTERN_DLL_EXPORT void DisposeExportedCPathsD(CPathsD& pp);
EXTERN_DLL_EXPORT void DisposeExportedCPolyTree64(CPolyTree64*& cpt);
EXTERN_DLL_EXPORT void DisposeExportedCPolyTreeD(CPolyTreeD*& cpt);
// Boolean clipping:
// cliptype: None=0, Intersection=1, Union=2, Difference=3, Xor=4
// fillrule: EvenOdd=0, NonZero=1, Positive=2, Negative=3
EXTERN_DLL_EXPORT int BooleanOp64(uint8_t cliptype,
uint8_t fillrule, const CPaths64 subjects,
const CPaths64 subjects_open, const CPaths64 clips,
CPaths64& solution, CPaths64& solution_open,
bool preserve_collinear = true, bool reverse_solution = false);
EXTERN_DLL_EXPORT int BooleanOpPt64(uint8_t cliptype,
uint8_t fillrule, const CPaths64 subjects,
const CPaths64 subjects_open, const CPaths64 clips,
CPolyTree64*& solution, CPaths64& solution_open,
bool preserve_collinear = true, bool reverse_solution = false);
EXTERN_DLL_EXPORT int BooleanOpD(uint8_t cliptype,
uint8_t fillrule, const CPathsD subjects,
const CPathsD subjects_open, const CPathsD clips,
CPathsD& solution, CPathsD& solution_open, int precision = 2,
bool preserve_collinear = true, bool reverse_solution = false);
EXTERN_DLL_EXPORT int BooleanOpPtD(uint8_t cliptype,
uint8_t fillrule, const CPathsD subjects,
const CPathsD subjects_open, const CPathsD clips,
CPolyTreeD*& solution, CPathsD& solution_open, int precision = 2,
bool preserve_collinear = true, bool reverse_solution = false);
// Polygon offsetting (inflate/deflate):
// jointype: Square=0, Round=1, Miter=2
// endtype: Polygon=0, Joined=1, Butt=2, Square=3, Round=4
EXTERN_DLL_EXPORT CPaths64 InflatePaths64(const CPaths64 paths,
double delta, uint8_t jointype, uint8_t endtype,
double miter_limit = 2.0, double arc_tolerance = 0.0,
bool reverse_solution = false);
EXTERN_DLL_EXPORT CPathsD InflatePathsD(const CPathsD paths,
double delta, uint8_t jointype, uint8_t endtype,
int precision = 2, double miter_limit = 2.0,
double arc_tolerance = 0.0, bool reverse_solution = false);
// RectClip & RectClipLines:
EXTERN_DLL_EXPORT CPaths64 RectClip64(const CRect64& rect,
const CPaths64 paths, bool convex_only = false);
EXTERN_DLL_EXPORT CPathsD RectClipD(const CRectD& rect,
const CPathsD paths, int precision = 2, bool convex_only = false);
EXTERN_DLL_EXPORT CPaths64 RectClipLines64(const CRect64& rect,
const CPaths64 paths);
EXTERN_DLL_EXPORT CPathsD RectClipLinesD(const CRectD& rect,
const CPathsD paths, int precision = 2);
//////////////////////////////////////////////////////
// INTERNAL FUNCTIONS
//////////////////////////////////////////////////////
inline CPath64 CreateCPath64(size_t cnt1, size_t cnt2);
inline CPath64 CreateCPath64(const Path64& p);
inline CPaths64 CreateCPaths64(const Paths64& pp);
@ -114,17 +184,14 @@ inline PathD ConvertCPathD(const CPathD& p);
inline PathsD ConvertCPathsD(const CPathsD& pp);
// the following function avoid multiple conversions
inline Path64 ConvertCPathD(const CPathD& p, double scale);
inline Paths64 ConvertCPathsD(const CPathsD& pp, double scale);
inline CPathD CreateCPathD(const Path64& p, double scale);
inline CPathsD CreateCPathsD(const Paths64& pp, double scale);
inline Path64 ConvertCPathD(const CPathD& p, double scale);
inline Paths64 ConvertCPathsD(const CPathsD& pp, double scale);
inline CPolyTree64* CreateCPolyTree64(const PolyTree64& pt);
inline CPolyTreeD* CreateCPolyTreeD(const PolyTree64& pt, double scale);
#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)
EXTERN_DLL_EXPORT const char* Version()
{
return CLIPPER2_VERSION;
@ -168,7 +235,7 @@ EXTERN_DLL_EXPORT int BooleanOp64(uint8_t cliptype,
uint8_t fillrule, const CPaths64 subjects,
const CPaths64 subjects_open, const CPaths64 clips,
CPaths64& solution, CPaths64& solution_open,
bool preserve_collinear = true, bool reverse_solution = false)
bool preserve_collinear, bool reverse_solution)
{
if (cliptype > static_cast<uint8_t>(ClipType::Xor)) return -4;
if (fillrule > static_cast<uint8_t>(FillRule::Negative)) return -3;
@ -195,7 +262,7 @@ EXTERN_DLL_EXPORT int BooleanOpPt64(uint8_t cliptype,
uint8_t fillrule, const CPaths64 subjects,
const CPaths64 subjects_open, const CPaths64 clips,
CPolyTree64*& solution, CPaths64& solution_open,
bool preserve_collinear = true, bool reverse_solution = false)
bool preserve_collinear, bool reverse_solution)
{
if (cliptype > static_cast<uint8_t>(ClipType::Xor)) return -4;
if (fillrule > static_cast<uint8_t>(FillRule::Negative)) return -3;
@ -222,8 +289,8 @@ EXTERN_DLL_EXPORT int BooleanOpPt64(uint8_t cliptype,
EXTERN_DLL_EXPORT int BooleanOpD(uint8_t cliptype,
uint8_t fillrule, const CPathsD subjects,
const CPathsD subjects_open, const CPathsD clips,
CPathsD& solution, CPathsD& solution_open, int precision = 2,
bool preserve_collinear = true, bool reverse_solution = false)
CPathsD& solution, CPathsD& solution_open, int precision,
bool preserve_collinear, bool reverse_solution)
{
if (precision < -8 || precision > 8) return -5;
if (cliptype > static_cast<uint8_t>(ClipType::Xor)) return -4;
@ -254,8 +321,8 @@ EXTERN_DLL_EXPORT int BooleanOpD(uint8_t cliptype,
EXTERN_DLL_EXPORT int BooleanOpPtD(uint8_t cliptype,
uint8_t fillrule, const CPathsD subjects,
const CPathsD subjects_open, const CPathsD clips,
CPolyTreeD*& solution, CPathsD& solution_open, int precision = 2,
bool preserve_collinear = true, bool reverse_solution = false)
CPolyTreeD*& solution, CPathsD& solution_open, int precision,
bool preserve_collinear, bool reverse_solution)
{
if (precision < -8 || precision > 8) return -5;
if (cliptype > static_cast<uint8_t>(ClipType::Xor)) return -4;
@ -285,84 +352,58 @@ EXTERN_DLL_EXPORT int BooleanOpPtD(uint8_t cliptype,
}
EXTERN_DLL_EXPORT CPaths64 InflatePaths64(const CPaths64 paths,
double delta, uint8_t jt, uint8_t et, double miter_limit = 2.0,
double arc_tolerance = 0.0, bool reverse_solution = false)
double delta, uint8_t jointype, uint8_t endtype, double miter_limit,
double arc_tolerance, bool reverse_solution)
{
Paths64 pp;
pp = ConvertCPaths64(paths);
ClipperOffset clip_offset( miter_limit,
arc_tolerance, reverse_solution);
clip_offset.AddPaths(pp, JoinType(jt), EndType(et));
Paths64 result = clip_offset.Execute(delta);
clip_offset.AddPaths(pp, JoinType(jointype), EndType(endtype));
Paths64 result;
clip_offset.Execute(delta, result);
return CreateCPaths64(result);
}
EXTERN_DLL_EXPORT CPathsD InflatePathsD(const CPathsD paths,
double delta, uint8_t jt, uint8_t et,
double precision = 2, double miter_limit = 2.0,
double arc_tolerance = 0.0, bool reverse_solution = false)
double delta, uint8_t jointype, uint8_t endtype,
int precision, double miter_limit,
double arc_tolerance, bool reverse_solution)
{
if (precision < -8 || precision > 8 || !paths) return nullptr;
const double scale = std::pow(10, precision);
ClipperOffset clip_offset(miter_limit, arc_tolerance, reverse_solution);
Paths64 pp = ConvertCPathsD(paths, scale);
clip_offset.AddPaths(pp, JoinType(jt), EndType(et));
Paths64 result = clip_offset.Execute(delta * scale);
clip_offset.AddPaths(pp, JoinType(jointype), EndType(endtype));
Paths64 result;
clip_offset.Execute(delta * scale, result);
return CreateCPathsD(result, 1/scale);
}
EXTERN_DLL_EXPORT CPaths64 RectClip64(const CRect64& rect,
const CPaths64 paths)
const CPaths64 paths, bool convex_only)
{
log(rect.left);
log(rect.right);
if (CRectIsEmpty(rect) || !paths) return nullptr;
Rect64 r64 = CRectToRect(rect);
class RectClip rc(r64);
Paths64 pp = ConvertCPaths64(paths);
Paths64 result;
result.reserve(pp.size());
for (const Path64& p : pp)
{
Rect64 pathRec = Bounds(p);
if (!r64.Intersects(pathRec)) continue;
if (r64.Contains(pathRec))
result.push_back(p);
else
{
Path64 p2 = rc.Execute(p);
if (!p2.empty()) result.push_back(std::move(p2));
}
}
Paths64 result = rc.Execute(pp, convex_only);
return CreateCPaths64(result);
}
EXTERN_DLL_EXPORT CPathsD RectClipD(const CRectD& rect,
const CPathsD paths, int precision = 2)
const CPathsD paths, int precision, bool convex_only)
{
if (CRectIsEmpty(rect) || !paths) return nullptr;
if (precision < -8 || precision > 8) return nullptr;
const double scale = std::pow(10, precision);
Rect64 r = ScaleRect<int64_t, double>(CRectToRect(rect), scale);
RectD r = CRectToRect(rect);
Rect64 rec = ScaleRect<int64_t, double>(r, scale);
Paths64 pp = ConvertCPathsD(paths, scale);
class RectClip rc(r);
Paths64 result;
result.reserve(pp.size());
for (const Path64& p : pp)
{
Rect64 pathRec = Bounds(p);
if (!r.Intersects(pathRec)) continue;
if (r.Contains(pathRec))
result.push_back(p);
else
{
Path64 p2 = rc.Execute(p);
if (!p2.empty()) result.push_back(std::move(p2));
}
}
class RectClip rc(rec);
Paths64 result = rc.Execute(pp, convex_only);
return CreateCPathsD(result, 1/scale);
}
@ -373,58 +414,27 @@ EXTERN_DLL_EXPORT CPaths64 RectClipLines64(const CRect64& rect,
Rect64 r = CRectToRect(rect);
class RectClipLines rcl (r);
Paths64 pp = ConvertCPaths64(paths);
Paths64 result;
result.reserve(pp.size());
for (const Path64& p : pp)
{
Rect64 pathRec = Bounds(p);
if (!r.Intersects(pathRec)) continue;
if (r.Contains(pathRec))
result.push_back(p);
else
{
Paths64 pp2 = rcl.Execute(p);
if (!pp2.empty())
result.insert(result.end(), pp2.begin(), pp2.end());
}
}
Paths64 result = rcl.Execute(pp);
return CreateCPaths64(result);
}
EXTERN_DLL_EXPORT CPathsD RectClipLinesD(const CRectD& rect,
const CPathsD paths, int precision = 2)
const CPathsD paths, int precision)
{
Paths64 result;
if (CRectIsEmpty(rect) || !paths) return nullptr;
if (precision < -8 || precision > 8) return nullptr;
const double scale = std::pow(10, precision);
Rect64 r = ScaleRect<int64_t, double>(CRectToRect(rect), scale);
class RectClipLines rcl(r);
Paths64 pp = ConvertCPathsD(paths, scale);
result.reserve(pp.size());
for (const Path64& p : pp)
{
Rect64 pathRec = Bounds(p);
if (!r.Intersects(pathRec)) continue;
if (r.Contains(pathRec))
result.push_back(p);
else
{
Paths64 pp2 = rcl.Execute(p);
if (pp2.empty()) continue;
result.insert(result.end(), pp2.begin(), pp2.end());
}
}
Paths64 result = rcl.Execute(pp);
return CreateCPathsD(result, 1/scale);
}
inline CPath64 CreateCPath64(size_t cnt1, size_t cnt2)
{
// create a dummy counter path
// allocates memory for CPath64, fills in the counter, and
// returns the structure ready to be filled with path data
CPath64 result = new int64_t[2 + cnt1 *2];
result[0] = cnt1;
result[1] = cnt2;
@ -433,6 +443,8 @@ inline CPath64 CreateCPath64(size_t cnt1, size_t cnt2)
inline CPath64 CreateCPath64(const Path64& p)
{
// allocates memory for CPath64, fills the counter
// and returns the memory filled with path data
size_t cnt = p.size();
if (!cnt) return nullptr;
CPath64 result = CreateCPath64(cnt, 0);
@ -469,6 +481,8 @@ inline Path64 ConvertCPath64(const CPath64& p)
inline CPaths64 CreateCPaths64(const Paths64& pp)
{
// allocates memory for multiple CPath64 and
// and returns this memory filled with path data
size_t cnt = pp.size(), cnt2 = cnt;
// don't allocate space for empty paths
@ -505,7 +519,8 @@ inline Paths64 ConvertCPaths64(const CPaths64& pp)
inline CPathD CreateCPathD(size_t cnt1, size_t cnt2)
{
// create a dummy path counter
// allocates memory for CPathD, fills in the counter, and
// returns the structure ready to be filled with path data
CPathD result = new double[2 + cnt1 * 2];
result[0] = static_cast<double>(cnt1);
result[1] = static_cast<double>(cnt2);
@ -514,6 +529,8 @@ inline CPathD CreateCPathD(size_t cnt1, size_t cnt2)
inline CPathD CreateCPathD(const PathD& p)
{
// allocates memory for CPath, fills the counter
// and returns the memory fills with path data
size_t cnt = p.size();
if (!cnt) return nullptr;
CPathD result = CreateCPathD(cnt, 0);
@ -621,6 +638,8 @@ inline Paths64 ConvertCPathsD(const CPathsD& pp, double scale)
inline CPathD CreateCPathD(const Path64& p, double scale)
{
// allocates memory for CPathD, fills in the counter, and
// returns the structure filled with *scaled* path data
size_t cnt = p.size();
if (!cnt) return nullptr;
CPathD result = CreateCPathD(cnt, 0);
@ -636,6 +655,8 @@ inline CPathD CreateCPathD(const Path64& p, double scale)
inline CPathsD CreateCPathsD(const Paths64& pp, double scale)
{
// allocates memory for *multiple* CPathD, and
// returns the structure filled with scaled path data
size_t cnt = pp.size(), cnt2 = cnt;
// don't allocate space for empty paths
for (size_t i = 0; i < cnt; ++i)
@ -653,17 +674,17 @@ inline CPathsD CreateCPathsD(const Paths64& pp, double scale)
}
inline void InitCPolyPath64(CPolyTree64* cpt,
bool is_hole, const PolyPath64* pp)
bool is_hole, const std::unique_ptr <PolyPath64>& pp)
{
cpt->polygon = CreateCPath64(pp->Polygon());
cpt->is_hole = is_hole;
size_t child_cnt = pp->Count();
cpt->child_count = child_cnt;
cpt->child_count = static_cast<uint32_t>(child_cnt);
cpt->childs = nullptr;
if (!child_cnt) return;
cpt->childs = new CPolyPath64[child_cnt];
CPolyPath64* child = cpt->childs;
for (const PolyPath64* pp_child : *pp)
for (const std::unique_ptr <PolyPath64>& pp_child : *pp)
InitCPolyPath64(child++, !is_hole, pp_child);
}
@ -674,11 +695,11 @@ inline CPolyTree64* CreateCPolyTree64(const PolyTree64& pt)
result->is_hole = false;
size_t child_cnt = pt.Count();
result->childs = nullptr;
result->child_count = child_cnt;
result->child_count = static_cast<uint32_t>(child_cnt);
if (!child_cnt) return result;
result->childs = new CPolyPath64[child_cnt];
CPolyPath64* child = result->childs;
for (const PolyPath64* pp : pt)
for (const std::unique_ptr <PolyPath64>& pp : pt)
InitCPolyPath64(child++, true, pp);
return result;
}
@ -701,17 +722,17 @@ EXTERN_DLL_EXPORT void DisposeExportedCPolyTree64(CPolyTree64*& cpt)
}
inline void InitCPolyPathD(CPolyTreeD* cpt,
bool is_hole, const PolyPath64* pp, double scale)
bool is_hole, const std::unique_ptr <PolyPath64>& pp, double scale)
{
cpt->polygon = CreateCPathD(pp->Polygon(), scale);
cpt->is_hole = is_hole;
size_t child_cnt = pp->Count();
cpt->child_count = child_cnt;
cpt->child_count = static_cast<uint32_t>(child_cnt);
cpt->childs = nullptr;
if (!child_cnt) return;
cpt->childs = new CPolyPathD[child_cnt];
CPolyPathD* child = cpt->childs;
for (const PolyPath64* pp_child : *pp)
for (const std::unique_ptr <PolyPath64>& pp_child : *pp)
InitCPolyPathD(child++, !is_hole, pp_child, scale);
}
@ -726,7 +747,7 @@ inline CPolyTreeD* CreateCPolyTreeD(const PolyTree64& pt, double scale)
if (!child_cnt) return result;
result->childs = new CPolyPathD[child_cnt];
CPolyPathD* child = result->childs;
for (const PolyPath64* pp : pt)
for (const std::unique_ptr <PolyPath64>& pp : pt)
InitCPolyPathD(child++, true, pp, scale);
return result;
}

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 26 October 2022 *
* Date : 9 February 2023 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2022 *
* Copyright : Angus Johnson 2010-2023 *
* Purpose : This module provides a simple interface to the Clipper Library *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -11,6 +11,7 @@
#define CLIPPER_H
#include <cstdlib>
#include <type_traits>
#include <vector>
#include "clipper.core.h"
@ -21,21 +22,6 @@
namespace Clipper2Lib {
static const char* precision_error =
"Precision exceeds the permitted range";
static const Rect64 MaxInvalidRect64 = Rect64(
(std::numeric_limits<int64_t>::max)(),
(std::numeric_limits<int64_t>::max)(),
(std::numeric_limits<int64_t>::lowest)(),
(std::numeric_limits<int64_t>::lowest)());
static const RectD MaxInvalidRectD = RectD(
(std::numeric_limits<double>::max)(),
(std::numeric_limits<double>::max)(),
(std::numeric_limits<double>::lowest)(),
(std::numeric_limits<double>::lowest)());
inline Paths64 BooleanOp(ClipType cliptype, FillRule fillrule,
const Paths64& subjects, const Paths64& clips)
{
@ -58,12 +44,13 @@ namespace Clipper2Lib {
}
inline PathsD BooleanOp(ClipType cliptype, FillRule fillrule,
const PathsD& subjects, const PathsD& clips, int decimal_prec = 2)
const PathsD& subjects, const PathsD& clips, int precision = 2)
{
if (decimal_prec > 8 || decimal_prec < -8)
throw Clipper2Exception(precision_error);
int error_code = 0;
CheckPrecision(precision, error_code);
PathsD result;
ClipperD clipper(decimal_prec);
if (error_code) return result;
ClipperD clipper(precision);
clipper.AddSubject(subjects);
clipper.AddClip(clips);
clipper.Execute(cliptype, fillrule, result);
@ -72,12 +59,13 @@ namespace Clipper2Lib {
inline void BooleanOp(ClipType cliptype, FillRule fillrule,
const PathsD& subjects, const PathsD& clips,
PolyTreeD& polytree, int decimal_prec = 2)
PolyTreeD& polytree, int precision = 2)
{
if (decimal_prec > 8 || decimal_prec < -8)
throw Clipper2Exception(precision_error);
PathsD result;
ClipperD clipper(decimal_prec);
polytree.Clear();
int error_code = 0;
CheckPrecision(precision, error_code);
if (error_code) return;
ClipperD clipper(precision);
clipper.AddSubject(subjects);
clipper.AddClip(clips);
clipper.Execute(cliptype, fillrule, polytree);
@ -112,12 +100,13 @@ namespace Clipper2Lib {
return result;
}
inline PathsD Union(const PathsD& subjects, FillRule fillrule, int decimal_prec = 2)
inline PathsD Union(const PathsD& subjects, FillRule fillrule, int precision = 2)
{
if (decimal_prec > 8 || decimal_prec < -8)
throw Clipper2Exception(precision_error);
PathsD result;
ClipperD clipper(decimal_prec);
int error_code = 0;
CheckPrecision(precision, error_code);
if (error_code) return result;
ClipperD clipper(precision);
clipper.AddSubject(subjects);
clipper.Execute(ClipType::Union, fillrule, result);
return result;
@ -144,31 +133,40 @@ namespace Clipper2Lib {
}
inline Paths64 InflatePaths(const Paths64& paths, double delta,
JoinType jt, EndType et, double miter_limit = 2.0)
JoinType jt, EndType et, double miter_limit = 2.0,
double arc_tolerance = 0.0)
{
ClipperOffset clip_offset(miter_limit);
if (!delta) return paths;
ClipperOffset clip_offset(miter_limit, arc_tolerance);
clip_offset.AddPaths(paths, jt, et);
return clip_offset.Execute(delta);
Paths64 solution;
clip_offset.Execute(delta, solution);
return solution;
}
inline PathsD InflatePaths(const PathsD& paths, double delta,
JoinType jt, EndType et, double miter_limit = 2.0, double precision = 2)
JoinType jt, EndType et, double miter_limit = 2.0,
int precision = 2, double arc_tolerance = 0.0)
{
if (precision < -8 || precision > 8)
throw Clipper2Exception(precision_error);
int error_code = 0;
CheckPrecision(precision, error_code);
if (!delta) return paths;
if (error_code) return PathsD();
const double scale = std::pow(10, precision);
ClipperOffset clip_offset(miter_limit);
clip_offset.AddPaths(ScalePaths<int64_t,double>(paths, scale), jt, et);
Paths64 tmp = clip_offset.Execute(delta * scale);
return ScalePaths<double, int64_t>(tmp, 1 / scale);
ClipperOffset clip_offset(miter_limit, arc_tolerance);
clip_offset.AddPaths(ScalePaths<int64_t,double>(paths, scale, error_code), jt, et);
if (error_code) return PathsD();
Paths64 solution;
clip_offset.Execute(delta * scale, solution);
return ScalePaths<double, int64_t>(solution, 1 / scale, error_code);
}
inline Path64 TranslatePath(const Path64& path, int64_t dx, int64_t dy)
{
Path64 result;
result.reserve(path.size());
for (const Point64& pt : path)
result.push_back(Point64(pt.x + dx, pt.y + dy));
std::transform(path.begin(), path.end(), back_inserter(result),
[dx, dy](const auto& pt) { return Point64(pt.x + dx, pt.y +dy); });
return result;
}
@ -176,8 +174,8 @@ namespace Clipper2Lib {
{
PathD result;
result.reserve(path.size());
for (const PointD& pt : path)
result.push_back(PointD(pt.x + dx, pt.y + dy));
std::transform(path.begin(), path.end(), back_inserter(result),
[dx, dy](const auto& pt) { return PointD(pt.x + dx, pt.y + dy); });
return result;
}
@ -185,8 +183,8 @@ namespace Clipper2Lib {
{
Paths64 result;
result.reserve(paths.size());
for (const Path64& path : paths)
result.push_back(TranslatePath(path, dx, dy));
std::transform(paths.begin(), paths.end(), back_inserter(result),
[dx, dy](const auto& path) { return TranslatePath(path, dx, dy); });
return result;
}
@ -194,220 +192,79 @@ namespace Clipper2Lib {
{
PathsD result;
result.reserve(paths.size());
for (const PathD& path : paths)
result.push_back(TranslatePath(path, dx, dy));
std::transform(paths.begin(), paths.end(), back_inserter(result),
[dx, dy](const auto& path) { return TranslatePath(path, dx, dy); });
return result;
}
inline Rect64 Bounds(const Path64& path)
{
Rect64 rec = MaxInvalidRect64;
for (const Point64& pt : path)
{
if (pt.x < rec.left) rec.left = pt.x;
if (pt.x > rec.right) rec.right = pt.x;
if (pt.y < rec.top) rec.top = pt.y;
if (pt.y > rec.bottom) rec.bottom = pt.y;
}
if (rec.IsEmpty()) return Rect64();
return rec;
}
inline Rect64 Bounds(const Paths64& paths)
{
Rect64 rec = MaxInvalidRect64;
for (const Path64& path : paths)
for (const Point64& pt : path)
{
if (pt.x < rec.left) rec.left = pt.x;
if (pt.x > rec.right) rec.right = pt.x;
if (pt.y < rec.top) rec.top = pt.y;
if (pt.y > rec.bottom) rec.bottom = pt.y;
}
if (rec.IsEmpty()) return Rect64();
return rec;
}
inline RectD Bounds(const PathD& path)
{
RectD rec = MaxInvalidRectD;
for (const PointD& pt : path)
{
if (pt.x < rec.left) rec.left = pt.x;
if (pt.x > rec.right) rec.right = pt.x;
if (pt.y < rec.top) rec.top = pt.y;
if (pt.y > rec.bottom) rec.bottom = pt.y;
}
if (rec.IsEmpty()) return RectD();
return rec;
}
inline RectD Bounds(const PathsD& paths)
{
RectD rec = MaxInvalidRectD;
for (const PathD& path : paths)
for (const PointD& pt : path)
{
if (pt.x < rec.left) rec.left = pt.x;
if (pt.x > rec.right) rec.right = pt.x;
if (pt.y < rec.top) rec.top = pt.y;
if (pt.y > rec.bottom) rec.bottom = pt.y;
}
if (rec.IsEmpty()) return RectD();
return rec;
}
inline Path64 ClipRect(const Rect64& rect, const Path64& path)
{
if (rect.IsEmpty() || path.empty()) return Path64();
Rect64 pathRec = Bounds(path);
if (!rect.Intersects(pathRec)) return Path64();
if (rect.Contains(pathRec)) return path;
class RectClip rc(rect);
return rc.Execute(path);
}
inline Paths64 ClipRect(const Rect64& rect, const Paths64& paths)
inline Paths64 RectClip(const Rect64& rect,
const Paths64& paths, bool convex_only = false)
{
if (rect.IsEmpty() || paths.empty()) return Paths64();
class RectClip rc(rect);
Paths64 result;
result.reserve(paths.size());
for (const Path64& p : paths)
{
Rect64 pathRec = Bounds(p);
if (!rect.Intersects(pathRec))
continue;
else if (rect.Contains(pathRec))
result.push_back(p);
else
{
Path64 p2 = rc.Execute(p);
if (!p2.empty()) result.push_back(std::move(p2));
}
}
return result;
return rc.Execute(paths, convex_only);
}
inline PathD ClipRect(const RectD& rect, const PathD& path, int precision = 2)
inline Paths64 RectClip(const Rect64& rect,
const Path64& path, bool convex_only = false)
{
if (rect.IsEmpty() || path.empty() ||
!rect.Contains(Bounds(path))) return PathD();
if (precision < -8 || precision > 8)
throw Clipper2Exception(precision_error);
const double scale = std::pow(10, precision);
Rect64 r = ScaleRect<int64_t, double>(rect, scale);
class RectClip rc(r);
Path64 p = ScalePath<int64_t, double>(path, scale);
return ScalePath<double, int64_t>(rc.Execute(p), 1 / scale);
if (rect.IsEmpty() || path.empty()) return Paths64();
class RectClip rc(rect);
return rc.Execute(Paths64{ path }, convex_only);
}
inline PathsD ClipRect(const RectD& rect, const PathsD& paths, int precision = 2)
inline PathsD RectClip(const RectD& rect,
const PathsD& paths, bool convex_only = false, int precision = 2)
{
if (rect.IsEmpty() || paths.empty()) return PathsD();
if (precision < -8 || precision > 8)
throw Clipper2Exception(precision_error);
int error_code = 0;
CheckPrecision(precision, error_code);
if (error_code) return PathsD();
const double scale = std::pow(10, precision);
Rect64 r = ScaleRect<int64_t, double>(rect, scale);
class RectClip rc(r);
PathsD result;
result.reserve(paths.size());
for (const PathD& path : paths)
{
RectD pathRec = Bounds(path);
if (!rect.Intersects(pathRec))
continue;
else if (rect.Contains(pathRec))
result.push_back(path);
else
{
Path64 p = ScalePath<int64_t, double>(path, scale);
p = rc.Execute(p);
if (!p.empty())
result.push_back(ScalePath<double, int64_t>(p, 1 / scale));
}
}
return result;
Paths64 pp = ScalePaths<int64_t, double>(paths, scale, error_code);
if (error_code) return PathsD(); // ie: error_code result is lost
return ScalePaths<double, int64_t>(
rc.Execute(pp, convex_only), 1 / scale, error_code);
}
inline Paths64 ClipLinesRect(const Rect64& rect, const Path64& path)
inline PathsD RectClip(const RectD& rect,
const PathD& path, bool convex_only = false, int precision = 2)
{
Paths64 result;
if (rect.IsEmpty() || path.empty()) return result;
Rect64 pathRec = Bounds(path);
if (!rect.Intersects(pathRec)) return result;
if (rect.Contains(pathRec))
{
result.push_back(path);
return result;
}
return RectClip(rect, PathsD{ path }, convex_only, precision);
}
inline Paths64 RectClipLines(const Rect64& rect, const Paths64& lines)
{
if (rect.IsEmpty() || lines.empty()) return Paths64();
class RectClipLines rcl(rect);
return rcl.Execute(path);
return rcl.Execute(lines);
}
inline Paths64 ClipLinesRect(const Rect64& rect, const Paths64& paths)
inline Paths64 RectClipLines(const Rect64& rect, const Path64& line)
{
Paths64 result;
if (rect.IsEmpty() || paths.empty()) return result;
class RectClipLines rcl(rect);
for (const Path64& p : paths)
{
Rect64 pathRec = Bounds(p);
if (!rect.Intersects(pathRec))
continue;
else if (rect.Contains(pathRec))
result.push_back(p);
else
{
Paths64 pp = rcl.Execute(p);
if (!pp.empty())
result.insert(result.end(), pp.begin(), pp.end());
}
}
return result;
return RectClipLines(rect, Paths64{ line });
}
inline PathsD ClipLinesRect(const RectD& rect, const PathD& path, int precision = 2)
inline PathsD RectClipLines(const RectD& rect, const PathD& line, int precision = 2)
{
if (rect.IsEmpty() || path.empty() ||
!rect.Contains(Bounds(path))) return PathsD();
if (precision < -8 || precision > 8)
throw Clipper2Exception(precision_error);
return RectClip(rect, PathsD{ line }, precision);
}
inline PathsD RectClipLines(const RectD& rect, const PathsD& lines, int precision = 2)
{
if (rect.IsEmpty() || lines.empty()) return PathsD();
int error_code = 0;
CheckPrecision(precision, error_code);
if (error_code) return PathsD();
const double scale = std::pow(10, precision);
Rect64 r = ScaleRect<int64_t, double>(rect, scale);
class RectClipLines rcl(r);
Path64 p = ScalePath<int64_t, double>(path, scale);
return ScalePaths<double, int64_t>(rcl.Execute(p), 1 / scale);
}
inline PathsD ClipLinesRect(const RectD& rect, const PathsD& paths, int precision = 2)
{
PathsD result;
if (rect.IsEmpty() || paths.empty()) return result;
if (precision < -8 || precision > 8)
throw Clipper2Exception(precision_error);
const double scale = std::pow(10, precision);
Rect64 r = ScaleRect<int64_t, double>(rect, scale);
class RectClipLines rcl(r);
result.reserve(paths.size());
for (const PathD& path : paths)
{
RectD pathRec = Bounds(path);
if (!rect.Intersects(pathRec))
continue;
else if (rect.Contains(pathRec))
result.push_back(path);
else
{
Path64 p = ScalePath<int64_t, double>(path, scale);
Paths64 pp = rcl.Execute(p);
if (pp.empty()) continue;
PathsD ppd = ScalePaths<double, int64_t>(pp, 1 / scale);
result.insert(result.end(), ppd.begin(), ppd.end());
}
}
return result;
Paths64 p = ScalePaths<int64_t, double>(lines, scale, error_code);
if (error_code) return PathsD();
p = rcl.Execute(p);
return ScalePaths<double, int64_t>(p, 1 / scale, error_code);
}
namespace details
@ -416,179 +273,219 @@ namespace Clipper2Lib {
inline void PolyPathToPaths64(const PolyPath64& polypath, Paths64& paths)
{
paths.push_back(polypath.Polygon());
for (const PolyPath* child : polypath)
PolyPathToPaths64(*(PolyPath64*)(child), paths);
for (const auto& child : polypath)
PolyPathToPaths64(*child, paths);
}
inline void PolyPathToPathsD(const PolyPathD& polypath, PathsD& paths)
{
paths.push_back(polypath.Polygon());
for (const PolyPath* child : polypath)
PolyPathToPathsD(*(PolyPathD*)(child), paths);
for (const auto& child : polypath)
PolyPathToPathsD(*child, paths);
}
inline bool PolyPath64ContainsChildren(const PolyPath64& pp)
{
for (auto ch : pp)
for (const auto& child : pp)
{
PolyPath64* child = (PolyPath64*)ch;
// return false if this child isn't fully contained by its parent
// the following algorithm is a bit too crude, and doesn't account
// for rounding errors. A better algorithm is to return false when
// consecutive vertices are found outside the parent's polygon.
//const Path64& path = pp.Polygon();
//if (std::any_of(child->Polygon().cbegin(), child->Polygon().cend(),
// [path](const auto& pt) {return (PointInPolygon(pt, path) ==
// PointInPolygonResult::IsOutside); })) return false;
int outsideCnt = 0;
for (const Point64& pt : child->Polygon())
if (PointInPolygon(pt, pp.Polygon()) == PointInPolygonResult::IsOutside)
return false;
{
PointInPolygonResult result = PointInPolygon(pt, pp.Polygon());
if (result == PointInPolygonResult::IsInside) --outsideCnt;
else if (result == PointInPolygonResult::IsOutside) ++outsideCnt;
if (outsideCnt > 1) return false;
else if (outsideCnt < -1) break;
}
// now check any nested children too
if (child->Count() > 0 && !PolyPath64ContainsChildren(*child))
return false;
}
return true;
}
inline bool GetInt(std::string::const_iterator& iter, const
std::string::const_iterator& end_iter, int64_t& val)
static void OutlinePolyPath(std::ostream& os,
bool isHole, size_t count, const std::string& preamble)
{
val = 0;
bool is_neg = *iter == '-';
if (is_neg) ++iter;
std::string::const_iterator start_iter = iter;
while (iter != end_iter &&
((*iter >= '0') && (*iter <= '9')))
std::string plural = (count == 1) ? "." : "s.";
if (isHole)
{
val = val * 10 + (static_cast<int64_t>(*iter++) - '0');
if (count)
os << preamble << "+- Hole with " << count <<
" nested polygon" << plural << std::endl;
else
os << preamble << "+- Hole" << std::endl;
}
if (is_neg) val = -val;
return (iter != start_iter);
}
inline bool GetFloat(std::string::const_iterator& iter, const
std::string::const_iterator& end_iter, double& val)
{
val = 0;
bool is_neg = *iter == '-';
if (is_neg) ++iter;
int dec_pos = 1;
const std::string::const_iterator start_iter = iter;
while (iter != end_iter && (*iter == '.' ||
((*iter >= '0') && (*iter <= '9'))))
else
{
if (*iter == '.')
{
if (dec_pos != 1) break;
dec_pos = 0;
++iter;
continue;
}
if (dec_pos != 1) --dec_pos;
val = val * 10 + ((int64_t)(*iter++) - '0');
}
if (iter == start_iter || dec_pos == 0) return false;
if (dec_pos < 0)
val *= std::pow(10, dec_pos);
if (is_neg)
val *= -1;
return true;
}
inline void SkipWhiteSpace(std::string::const_iterator& iter,
const std::string::const_iterator& end_iter)
{
while (iter != end_iter && *iter <= ' ') ++iter;
}
inline void SkipSpacesWithOptionalComma(std::string::const_iterator& iter,
const std::string::const_iterator& end_iter)
{
bool comma_seen = false;
while (iter != end_iter)
{
if (*iter == ' ') ++iter;
else if (*iter == ',')
{
if (comma_seen) return; // don't skip 2 commas!
comma_seen = true;
++iter;
}
else return;
if (count)
os << preamble << "+- Polygon with " << count <<
" hole" << plural << std::endl;
else
os << preamble << "+- Polygon" << std::endl;
}
}
inline bool has_one_match(const char c, char* chrs)
static void OutlinePolyPath64(std::ostream& os, const PolyPath64& pp,
std::string preamble, bool last_child)
{
while (*chrs > 0 && c != *chrs) ++chrs;
if (!*chrs) return false;
*chrs = ' '; // only match once per char
return true;
OutlinePolyPath(os, pp.IsHole(), pp.Count(), preamble);
preamble += (!last_child) ? "| " : " ";
if (pp.Count())
{
PolyPath64List::const_iterator it = pp.begin();
for (; it < pp.end() - 1; ++it)
OutlinePolyPath64(os, **it, preamble, false);
OutlinePolyPath64(os, **it, preamble, true);
}
}
inline void SkipUserDefinedChars(std::string::const_iterator& iter,
const std::string::const_iterator& end_iter, const std::string& skip_chars)
static void OutlinePolyPathD(std::ostream& os, const PolyPathD& pp,
std::string preamble, bool last_child)
{
const size_t MAX_CHARS = 16;
char buff[MAX_CHARS] = {0};
std::copy(skip_chars.cbegin(), skip_chars.cend(), &buff[0]);
while (iter != end_iter &&
(*iter <= ' ' || has_one_match(*iter, buff))) ++iter;
return;
OutlinePolyPath(os, pp.IsHole(), pp.Count(), preamble);
preamble += (!last_child) ? "| " : " ";
if (pp.Count())
{
PolyPathDList::const_iterator it = pp.begin();
for (; it < pp.end() - 1; ++it)
OutlinePolyPathD(os, **it, preamble, false);
OutlinePolyPathD(os, **it, preamble, true);
}
}
} // end details namespace
inline std::ostream& operator<< (std::ostream& os, const PolyTree64& pp)
{
PolyPath64List::const_iterator it = pp.begin();
for (; it < pp.end() - 1; ++it)
details::OutlinePolyPath64(os, **it, " ", false);
details::OutlinePolyPath64(os, **it, " ", true);
os << std::endl << std::endl;
if (!pp.Level()) os << std::endl;
return os;
}
inline std::ostream& operator<< (std::ostream& os, const PolyTreeD& pp)
{
PolyPathDList::const_iterator it = pp.begin();
for (; it < pp.end() - 1; ++it)
details::OutlinePolyPathD(os, **it, " ", false);
details::OutlinePolyPathD(os, **it, " ", true);
os << std::endl << std::endl;
if (!pp.Level()) os << std::endl;
return os;
}
inline Paths64 PolyTreeToPaths64(const PolyTree64& polytree)
{
Paths64 result;
for (auto child : polytree)
details::PolyPathToPaths64(*(PolyPath64*)(child), result);
for (const auto& child : polytree)
details::PolyPathToPaths64(*child, result);
return result;
}
inline PathsD PolyTreeToPathsD(const PolyTreeD& polytree)
{
PathsD result;
for (auto child : polytree)
details::PolyPathToPathsD(*(PolyPathD*)(child), result);
for (const auto& child : polytree)
details::PolyPathToPathsD(*child, result);
return result;
}
inline bool CheckPolytreeFullyContainsChildren(const PolyTree64& polytree)
{
for (auto child : polytree)
for (const auto& child : polytree)
if (child->Count() > 0 &&
!details::PolyPath64ContainsChildren(*(PolyPath64*)(child)))
!details::PolyPath64ContainsChildren(*child))
return false;
return true;
}
inline Path64 MakePath(const std::string& s)
{
const std::string skip_chars = " ,(){}[]";
Path64 result;
std::string::const_iterator s_iter = s.cbegin();
details::SkipUserDefinedChars(s_iter, s.cend(), skip_chars);
while (s_iter != s.cend())
namespace details {
template<typename T, typename U>
inline constexpr void MakePathGeneric(const T list, size_t size,
std::vector<U>& result)
{
int64_t y = 0, x = 0;
if (!details::GetInt(s_iter, s.cend(), x)) break;
details::SkipSpacesWithOptionalComma(s_iter, s.cend());
if (!details::GetInt(s_iter, s.cend(), y)) break;
result.push_back(Point64(x, y));
details::SkipUserDefinedChars(s_iter, s.cend(), skip_chars);
for (size_t i = 0; i < size; ++i)
#ifdef USINGZ
result[i / 2] = U{list[i], list[++i], 0};
#else
result[i / 2] = U{list[i], list[++i]};
#endif
}
} // end details namespace
template<typename T,
typename std::enable_if<
std::is_integral<T>::value &&
!std::is_same<char, T>::value, bool
>::type = true>
inline Path64 MakePath(const std::vector<T>& list)
{
const auto size = list.size() - list.size() % 2;
if (list.size() != size)
DoError(non_pair_error_i); // non-fatal without exception handling
Path64 result(size / 2); // else ignores unpaired value
details::MakePathGeneric(list, size, result);
return result;
}
inline PathD MakePathD(const std::string& s)
template<typename T, std::size_t N,
typename std::enable_if<
std::is_integral<T>::value &&
!std::is_same<char, T>::value, bool
>::type = true>
inline Path64 MakePath(const T(&list)[N])
{
const std::string skip_chars = " ,(){}[]";
PathD result;
std::string::const_iterator s_iter = s.cbegin();
details::SkipUserDefinedChars(s_iter, s.cend(), skip_chars);
while (s_iter != s.cend())
{
double y = 0, x = 0;
if (!details::GetFloat(s_iter, s.cend(), x)) break;
details::SkipSpacesWithOptionalComma(s_iter, s.cend());
if (!details::GetFloat(s_iter, s.cend(), y)) break;
result.push_back(PointD(x, y));
details::SkipUserDefinedChars(s_iter, s.cend(), skip_chars);
}
// Make the compiler error on unpaired value (i.e. no runtime effects).
static_assert(N % 2 == 0, "MakePath requires an even number of arguments");
Path64 result(N / 2);
details::MakePathGeneric(list, N, result);
return result;
}
template<typename T,
typename std::enable_if<
std::is_arithmetic<T>::value &&
!std::is_same<char, T>::value, bool
>::type = true>
inline PathD MakePathD(const std::vector<T>& list)
{
const auto size = list.size() - list.size() % 2;
if (list.size() != size)
DoError(non_pair_error_i); // non-fatal without exception handling
PathD result(size / 2); // else ignores unpaired value
details::MakePathGeneric(list, size, result);
return result;
}
template<typename T, std::size_t N,
typename std::enable_if<
std::is_arithmetic<T>::value &&
!std::is_same<char, T>::value, bool
>::type = true>
inline PathD MakePathD(const T(&list)[N])
{
// Make the compiler error on unpaired value (i.e. no runtime effects).
static_assert(N % 2 == 0, "MakePath requires an even number of arguments");
PathD result(N / 2);
details::MakePathGeneric(list, N, result);
return result;
}
@ -641,12 +538,14 @@ namespace Clipper2Lib {
inline PathD TrimCollinear(const PathD& path, int precision, bool is_open_path = false)
{
if (precision > 8 || precision < -8)
throw Clipper2Exception(precision_error);
int error_code = 0;
CheckPrecision(precision, error_code);
if (error_code) return PathD();
const double scale = std::pow(10, precision);
Path64 p = ScalePath<int64_t, double>(path, scale);
Path64 p = ScalePath<int64_t, double>(path, scale, error_code);
if (error_code) return PathD();
p = TrimCollinear(p, is_open_path);
return ScalePath<double, int64_t>(p, 1/scale);
return ScalePath<double, int64_t>(p, 1/scale, error_code);
}
template <typename T>
@ -721,6 +620,108 @@ namespace Clipper2Lib {
return Sqr(a * d - c * b) / (c * c + d * d);
}
inline size_t GetNext(size_t current, size_t high,
const std::vector<bool>& flags)
{
++current;
while (current <= high && flags[current]) ++current;
if (current <= high) return current;
current = 0;
while (flags[current]) ++current;
return current;
}
inline size_t GetPrior(size_t current, size_t high,
const std::vector<bool>& flags)
{
if (current == 0) current = high;
else --current;
while (current > 0 && flags[current]) --current;
if (!flags[current]) return current;
current = high;
while (flags[current]) --current;
return current;
}
template <typename T>
inline Path<T> SimplifyPath(const Path<T> path,
double epsilon, bool isOpenPath = false)
{
const size_t len = path.size(), high = len -1;
const double epsSqr = Sqr(epsilon);
if (len < 4) return Path<T>(path);
std::vector<bool> flags(len);
std::vector<double> distSqr(len);
size_t prior = high, curr = 0, start, next, prior2, next2;
if (isOpenPath)
{
distSqr[0] = MAX_DBL;
distSqr[high] = MAX_DBL;
}
else
{
distSqr[0] = PerpendicDistFromLineSqrd(path[0], path[high], path[1]);
distSqr[high] = PerpendicDistFromLineSqrd(path[high], path[0], path[high - 1]);
}
for (size_t i = 1; i < high; ++i)
distSqr[i] = PerpendicDistFromLineSqrd(path[i], path[i - 1], path[i + 1]);
for (;;)
{
if (distSqr[curr] > epsSqr)
{
start = curr;
do
{
curr = GetNext(curr, high, flags);
} while (curr != start && distSqr[curr] > epsSqr);
if (curr == start) break;
}
prior = GetPrior(curr, high, flags);
next = GetNext(curr, high, flags);
if (next == prior) break;
if (distSqr[next] < distSqr[curr])
{
flags[next] = true;
next = GetNext(next, high, flags);
next2 = GetNext(next, high, flags);
distSqr[curr] = PerpendicDistFromLineSqrd(path[curr], path[prior], path[next]);
if (next != high || !isOpenPath)
distSqr[next] = PerpendicDistFromLineSqrd(path[next], path[curr], path[next2]);
curr = next;
}
else
{
flags[curr] = true;
curr = next;
next = GetNext(next, high, flags);
prior2 = GetPrior(prior, high, flags);
distSqr[curr] = PerpendicDistFromLineSqrd(path[curr], path[prior], path[next]);
if (prior != 0 || !isOpenPath)
distSqr[prior] = PerpendicDistFromLineSqrd(path[prior], path[prior2], path[curr]);
}
}
Path<T> result;
result.reserve(len);
for (typename Path<T>::size_type i = 0; i < len; ++i)
if (!flags[i]) result.push_back(path[i]);
return result;
}
template <typename T>
inline Paths<T> SimplifyPaths(const Paths<T> paths,
double epsilon, bool isOpenPath = false)
{
Paths<T> result;
result.reserve(paths.size());
for (const auto& path : paths)
result.push_back(SimplifyPath(path, epsilon, isOpenPath));
return result;
}
template <typename T>
inline void RDP(const Path<T> path, std::size_t begin,
std::size_t end, double epsSqrd, std::vector<bool>& flags)
@ -764,8 +765,9 @@ namespace Clipper2Lib {
{
Paths<T> result;
result.reserve(paths.size());
for (const Path<T>& path : paths)
result.push_back(RamerDouglasPeucker<T>(path, epsilon));
std::transform(paths.begin(), paths.end(), back_inserter(result),
[epsilon](const auto& path)
{ return RamerDouglasPeucker<T>(path, epsilon); });
return result;
}

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 15 October 2022 *
* Date : 28 January 2023 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2022 *
* Copyright : Angus Johnson 2010-2023 *
* Purpose : Minkowski Sum and Difference *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -92,11 +92,12 @@ namespace Clipper2Lib
inline PathsD MinkowskiSum(const PathD& pattern, const PathD& path, bool isClosed, int decimalPlaces = 2)
{
int error_code = 0;
double scale = pow(10, decimalPlaces);
Path64 pat64 = ScalePath<int64_t, double>(pattern, scale);
Path64 path64 = ScalePath<int64_t, double>(path, scale);
Path64 pat64 = ScalePath<int64_t, double>(pattern, scale, error_code);
Path64 path64 = ScalePath<int64_t, double>(path, scale, error_code);
Paths64 tmp = detail::Union(detail::Minkowski(pat64, path64, true, isClosed), FillRule::NonZero);
return ScalePaths<double, int64_t>(tmp, 1 / scale);
return ScalePaths<double, int64_t>(tmp, 1 / scale, error_code);
}
inline Paths64 MinkowskiDiff(const Path64& pattern, const Path64& path, bool isClosed)
@ -106,11 +107,12 @@ namespace Clipper2Lib
inline PathsD MinkowskiDiff(const PathD& pattern, const PathD& path, bool isClosed, int decimalPlaces = 2)
{
int error_code = 0;
double scale = pow(10, decimalPlaces);
Path64 pat64 = ScalePath<int64_t, double>(pattern, scale);
Path64 path64 = ScalePath<int64_t, double>(path, scale);
Path64 pat64 = ScalePath<int64_t, double>(pattern, scale, error_code);
Path64 path64 = ScalePath<int64_t, double>(path, scale, error_code);
Paths64 tmp = detail::Union(detail::Minkowski(pat64, path64, false, isClosed), FillRule::NonZero);
return ScalePaths<double, int64_t>(tmp, 1 / scale);
return ScalePaths<double, int64_t>(tmp, 1 / scale, error_code);
}
} // Clipper2Lib namespace

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 15 October 2022 *
* Date : 22 March 2023 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2022 *
* Copyright : Angus Johnson 2010-2023 *
* Purpose : Path Offset (Inflate/Shrink) *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -11,6 +11,7 @@
#define CLIPPER_OFFSET_H_
#include "clipper.core.h"
#include "clipper.engine.h"
namespace Clipper2Lib {
@ -23,47 +24,57 @@ enum class EndType {Polygon, Joined, Butt, Square, Round};
//Joined : offsets both sides of a path, with joined ends
//Polygon: offsets only one side of a closed path
class ClipperOffset {
private:
class Group {
public:
Paths64 paths_in_;
Paths64 paths_out_;
Path64 path_;
bool is_reversed_ = false;
JoinType join_type_;
EndType end_type_;
Group(const Paths64& paths, JoinType join_type, EndType end_type) :
paths_in_(paths), join_type_(join_type), end_type_(end_type) {}
Paths64 paths_in;
Paths64 paths_out;
Path64 path;
bool is_reversed = false;
JoinType join_type;
EndType end_type;
Group(const Paths64& _paths, JoinType _join_type, EndType _end_type) :
paths_in(_paths), join_type(_join_type), end_type(_end_type) {}
};
int error_code_ = 0;
double delta_ = 0.0;
double group_delta_ = 0.0;
double abs_group_delta_ = 0.0;
double temp_lim_ = 0.0;
double steps_per_rad_ = 0.0;
double step_sin_ = 0.0;
double step_cos_ = 0.0;
PathD norms;
Paths64 solution;
std::vector<Group> groups_;
JoinType join_type_ = JoinType::Square;
EndType end_type_ = EndType::Polygon;
double miter_limit_ = 0.0;
double arc_tolerance_ = 0.0;
bool merge_groups_ = true;
bool preserve_collinear_ = false;
bool reverse_solution_ = false;
#ifdef USINGZ
ZCallback64 zCallback64_ = nullptr;
#endif
void DoSquare(Group& group, const Path64& path, size_t j, size_t k);
void DoMiter(Group& group, const Path64& path, size_t j, size_t k, double cos_a);
void DoRound(Group& group, const Path64& path, size_t j, size_t k, double angle);
void BuildNormals(const Path64& path);
void OffsetPolygon(Group& group, Path64& path);
void OffsetOpenJoined(Group& group, Path64& path);
void OffsetOpenPath(Group& group, Path64& path, EndType endType);
void OffsetOpenPath(Group& group, Path64& path);
void OffsetPoint(Group& group, Path64& path, size_t j, size_t& k);
void DoGroupOffset(Group &group, double delta);
void DoGroupOffset(Group &group);
void ExecuteInternal(double delta);
public:
ClipperOffset(double miter_limit = 2.0,
explicit ClipperOffset(double miter_limit = 2.0,
double arc_tolerance = 0.0,
bool preserve_collinear = false,
bool reverse_solution = false) :
@ -73,13 +84,13 @@ public:
~ClipperOffset() { Clear(); };
int ErrorCode() { return error_code_; };
void AddPath(const Path64& path, JoinType jt_, EndType et_);
void AddPaths(const Paths64& paths, JoinType jt_, EndType et_);
void AddPath(const PathD &p, JoinType jt_, EndType et_);
void AddPaths(const PathsD &p, JoinType jt_, EndType et_);
void Clear() { groups_.clear(); norms.clear(); };
Paths64 Execute(double delta);
void Execute(double delta, Paths64& paths);
void Execute(double delta, PolyTree64& polytree);
double MiterLimit() const { return miter_limit_; }
void MiterLimit(double miter_limit) { miter_limit_ = miter_limit; }
@ -88,19 +99,15 @@ public:
double ArcTolerance() const { return arc_tolerance_; }
void ArcTolerance(double arc_tolerance) { arc_tolerance_ = arc_tolerance; }
//MergeGroups: A path group is one or more paths added via the AddPath or
//AddPaths methods. By default these path groups will be offset
//independently of other groups and this may cause overlaps (intersections).
//However, when MergeGroups is enabled, any overlapping offsets will be
//merged (via a clipping union operation) to remove overlaps.
bool MergeGroups() const { return merge_groups_; }
void MergeGroups(bool merge_groups) { merge_groups_ = merge_groups; }
bool PreserveCollinear() const { return preserve_collinear_; }
void PreserveCollinear(bool preserve_collinear){preserve_collinear_ = preserve_collinear;}
bool ReverseSolution() const { return reverse_solution_; }
void ReverseSolution(bool reverse_solution) {reverse_solution_ = reverse_solution;}
#ifdef USINGZ
void SetZCallback(ZCallback64 cb) { zCallback64_ = cb; }
#endif
};
}

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 26 October 2022 *
* Date : 9 February 2023 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2022 *
* Copyright : Angus Johnson 2010-2023 *
* Purpose : FAST rectangular clipping *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -12,38 +12,70 @@
#include <cstdlib>
#include <vector>
#include <queue>
#include "clipper.h"
#include "clipper.core.h"
namespace Clipper2Lib
namespace Clipper2Lib
{
enum class Location { Left, Top, Right, Bottom, Inside };
class OutPt2;
typedef std::vector<OutPt2*> OutPt2List;
class OutPt2 {
public:
Point64 pt;
size_t owner_idx;
OutPt2List* edge;
OutPt2* next;
OutPt2* prev;
};
//------------------------------------------------------------------------------
// RectClip
//------------------------------------------------------------------------------
class RectClip {
private:
void ExecuteInternal(const Path64& path);
Path64 GetPath(OutPt2*& op);
protected:
const Rect64 rect_;
const Point64 mp_;
const Path64 rectPath_;
Path64 result_;
const Path64 rect_as_path_;
const Point64 rect_mp_;
Rect64 path_bounds_;
std::deque<OutPt2> op_container_;
OutPt2List results_; // each path can be broken into multiples
OutPt2List edges_[8]; // clockwise and counter-clockwise
std::vector<Location> start_locs_;
void CheckEdges();
void TidyEdges(int idx, OutPt2List& cw, OutPt2List& ccw);
void GetNextLocation(const Path64& path,
Location& loc, int& i, int highI);
OutPt2* Add(Point64 pt, bool start_new = false);
void AddCorner(Location prev, Location curr);
void AddCorner(Location& loc, bool isClockwise);
public:
RectClip(const Rect64& rect) :
explicit RectClip(const Rect64& rect) :
rect_(rect),
mp_(rect.MidPoint()),
rectPath_(rect.AsPath()) {}
Path64 Execute(const Path64& path);
rect_as_path_(rect.AsPath()),
rect_mp_(rect.MidPoint()) {}
Paths64 Execute(const Paths64& paths, bool convex_only = false);
};
//------------------------------------------------------------------------------
// RectClipLines
//------------------------------------------------------------------------------
class RectClipLines : public RectClip {
private:
void ExecuteInternal(const Path64& path);
Path64 GetPath(OutPt2*& op);
public:
RectClipLines(const Rect64& rect) : RectClip(rect) {};
Paths64 Execute(const Path64& path);
explicit RectClipLines(const Rect64& rect) : RectClip(rect) {};
Paths64 Execute(const Paths64& paths);
};
} // Clipper2Lib namespace

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 15 October 2022 *
* Date : 22 March 2023 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2022 *
* Copyright : Angus Johnson 2010-2023 *
* Purpose : Path Offset (Inflate/Shrink) *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -20,20 +20,38 @@ const double floating_point_tolerance = 1e-12;
// Miscellaneous methods
//------------------------------------------------------------------------------
Paths64::size_type GetLowestPolygonIdx(const Paths64& paths)
void GetBoundsAndLowestPolyIdx(const Paths64& paths, Rect64& r, int & idx)
{
Paths64::size_type result = 0;
Point64 lp = Point64(static_cast<int64_t>(0),
std::numeric_limits<int64_t>::min());
for (Paths64::size_type i = 0 ; i < paths.size(); ++i)
idx = -1;
r = MaxInvalidRect64;
int64_t lpx = 0;
for (int i = 0; i < static_cast<int>(paths.size()); ++i)
for (const Point64& p : paths[i])
{
if (p.y < lp.y || (p.y == lp.y && p.x >= lp.x)) continue;
result = i;
lp = p;
}
return result;
{
if (p.y >= r.bottom)
{
if (p.y > r.bottom || p.x < lpx)
{
idx = i;
lpx = p.x;
r.bottom = p.y;
}
}
else if (p.y < r.top) r.top = p.y;
if (p.x > r.right) r.right = p.x;
else if (p.x < r.left) r.left = p.x;
}
//if (idx < 0) r = Rect64(0, 0, 0, 0);
//if (r.top == INT64_MIN) r.bottom = r.top;
//if (r.left == INT64_MIN) r.left = r.right;
}
bool IsSafeOffset(const Rect64& r, double abs_delta)
{
return r.left > min_coord + abs_delta &&
r.right < max_coord - abs_delta &&
r.top > min_coord + abs_delta &&
r.bottom < max_coord - abs_delta;
}
PointD GetUnitNormal(const Point64& pt1, const Point64& pt2)
@ -80,12 +98,32 @@ inline bool IsClosedPath(EndType et)
inline Point64 GetPerpendic(const Point64& pt, const PointD& norm, double delta)
{
#ifdef USINGZ
return Point64(pt.x + norm.x * delta, pt.y + norm.y * delta, pt.z);
#else
return Point64(pt.x + norm.x * delta, pt.y + norm.y * delta);
#endif
}
inline PointD GetPerpendicD(const Point64& pt, const PointD& norm, double delta)
{
#ifdef USINGZ
return PointD(pt.x + norm.x * delta, pt.y + norm.y * delta, pt.z);
#else
return PointD(pt.x + norm.x * delta, pt.y + norm.y * delta);
#endif
}
inline void NegatePath(PathD& path)
{
for (PointD& pt : path)
{
pt.x = -pt.x;
pt.y = -pt.y;
#ifdef USINGZ
pt.z = pt.z;
#endif
}
}
//------------------------------------------------------------------------------
@ -105,19 +143,6 @@ void ClipperOffset::AddPaths(const Paths64 &paths, JoinType jt_, EndType et_)
groups_.push_back(Group(paths, jt_, et_));
}
void ClipperOffset::AddPath(const Clipper2Lib::PathD& path, JoinType jt_, EndType et_)
{
PathsD paths;
paths.push_back(path);
AddPaths(paths, jt_, et_);
}
void ClipperOffset::AddPaths(const PathsD& paths, JoinType jt_, EndType et_)
{
if (paths.size() == 0) return;
groups_.push_back(Group(PathsDToPaths64(paths), jt_, et_));
}
void ClipperOffset::BuildNormals(const Path64& path)
{
norms.clear();
@ -131,12 +156,20 @@ void ClipperOffset::BuildNormals(const Path64& path)
inline PointD TranslatePoint(const PointD& pt, double dx, double dy)
{
#ifdef USINGZ
return PointD(pt.x + dx, pt.y + dy, pt.z);
#else
return PointD(pt.x + dx, pt.y + dy);
#endif
}
inline PointD ReflectPoint(const PointD& pt, const PointD& pivot)
{
#ifdef USINGZ
return PointD(pivot.x + (pivot.x - pt.x), pivot.y + (pivot.y - pt.y), pt.z);
#else
return PointD(pivot.x + (pivot.x - pt.x), pivot.y + (pivot.y - pt.y));
#endif
}
PointD IntersectPoint(const PointD& pt1a, const PointD& pt1b,
@ -190,47 +223,68 @@ void ClipperOffset::DoSquare(Group& group, const Path64& path, size_t j, size_t
{
PointD pt4 = PointD(pt3.x + vec.x * group_delta_, pt3.y + vec.y * group_delta_);
PointD pt = IntersectPoint(pt1, pt2, pt3, pt4);
#ifdef USINGZ
pt.z = ptQ.z;
#endif
//get the second intersect point through reflecion
group.path_.push_back(Point64(ReflectPoint(pt, ptQ)));
group.path_.push_back(Point64(pt));
group.path.push_back(Point64(ReflectPoint(pt, ptQ)));
group.path.push_back(Point64(pt));
}
else
{
PointD pt4 = GetPerpendicD(path[j], norms[k], group_delta_);
PointD pt = IntersectPoint(pt1, pt2, pt3, pt4);
group.path_.push_back(Point64(pt));
#ifdef USINGZ
pt.z = ptQ.z;
#endif
group.path.push_back(Point64(pt));
//get the second intersect point through reflecion
group.path_.push_back(Point64(ReflectPoint(pt, ptQ)));
group.path.push_back(Point64(ReflectPoint(pt, ptQ)));
}
}
void ClipperOffset::DoMiter(Group& group, const Path64& path, size_t j, size_t k, double cos_a)
{
double q = group_delta_ / (cos_a + 1);
group.path_.push_back(Point64(
#ifdef USINGZ
group.path.push_back(Point64(
path[j].x + (norms[k].x + norms[j].x) * q,
path[j].y + (norms[k].y + norms[j].y) * q,
path[j].z));
#else
group.path.push_back(Point64(
path[j].x + (norms[k].x + norms[j].x) * q,
path[j].y + (norms[k].y + norms[j].y) * q));
#endif
}
void ClipperOffset::DoRound(Group& group, const Path64& path, size_t j, size_t k, double angle)
{
//even though angle may be negative this is a convex join
Point64 pt = path[j];
int steps = static_cast<int>(std::ceil(steps_per_rad_ * std::abs(angle)));
double step_sin = std::sin(angle / steps);
double step_cos = std::cos(angle / steps);
PointD pt2 = PointD(norms[k].x * group_delta_, norms[k].y * group_delta_);
if (j == k) pt2.Negate();
PointD offsetVec = PointD(norms[k].x * group_delta_, norms[k].y * group_delta_);
group.path_.push_back(Point64(pt.x + pt2.x, pt.y + pt2.y));
for (int i = 0; i < steps; i++)
if (j == k) offsetVec.Negate();
#ifdef USINGZ
group.path.push_back(Point64(pt.x + offsetVec.x, pt.y + offsetVec.y, pt.z));
#else
group.path.push_back(Point64(pt.x + offsetVec.x, pt.y + offsetVec.y));
#endif
if (angle > -PI + 0.01) // avoid 180deg concave
{
pt2 = PointD(pt2.x * step_cos - step_sin * pt2.y,
pt2.x * step_sin + pt2.y * step_cos);
group.path_.push_back(Point64(pt.x + pt2.x, pt.y + pt2.y));
int steps = static_cast<int>(std::ceil(steps_per_rad_ * std::abs(angle))); // #448, #456
for (int i = 1; i < steps; ++i) // ie 1 less than steps
{
offsetVec = PointD(offsetVec.x * step_cos_ - step_sin_ * offsetVec.y,
offsetVec.x * step_sin_ + offsetVec.y * step_cos_);
#ifdef USINGZ
group.path.push_back(Point64(pt.x + offsetVec.x, pt.y + offsetVec.y, pt.z));
#else
group.path.push_back(Point64(pt.x + offsetVec.x, pt.y + offsetVec.y));
#endif
}
}
group.path_.push_back(GetPerpendic(path[j], norms[j], group_delta_));
group.path.push_back(GetPerpendic(path[j], norms[j], group_delta_));
}
void ClipperOffset::OffsetPoint(Group& group, Path64& path, size_t j, size_t& k)
@ -248,72 +302,78 @@ void ClipperOffset::OffsetPoint(Group& group, Path64& path, size_t j, size_t& k)
if (sin_a > 1.0) sin_a = 1.0;
else if (sin_a < -1.0) sin_a = -1.0;
bool almostNoAngle = AlmostZero(sin_a) && cos_a > 0;
// when there's almost no angle of deviation or it's concave
if (almostNoAngle || (sin_a * group_delta_ < 0))
if (cos_a > 0.99) // almost straight - less than 8 degrees
{
Point64 p1 = Point64(
path[j].x + norms[k].x * group_delta_,
path[j].y + norms[k].y * group_delta_);
Point64 p2 = Point64(
path[j].x + norms[j].x * group_delta_,
path[j].y + norms[j].y * group_delta_);
group.path_.push_back(p1);
if (p1 != p2)
{
// when concave add an extra vertex to ensure neat clipping
if (!almostNoAngle) group.path_.push_back(path[j]);
group.path_.push_back(p2);
}
group.path.push_back(GetPerpendic(path[j], norms[k], group_delta_));
if (cos_a < 0.9998) // greater than 1 degree (#424)
group.path.push_back(GetPerpendic(path[j], norms[j], group_delta_)); // (#418)
}
else // it's convex
else if (cos_a > -0.99 && (sin_a * group_delta_ < 0))
{
if (join_type_ == JoinType::Round)
DoRound(group, path, j, k, std::atan2(sin_a, cos_a));
else if (join_type_ == JoinType::Miter)
{
// miter unless the angle is so acute the miter would exceeds ML
if (cos_a > temp_lim_ - 1) DoMiter(group, path, j, k, cos_a);
else DoSquare(group, path, j, k);
}
// don't bother squaring angles that deviate < ~20 degrees because
// squaring will be indistinguishable from mitering and just be a lot slower
else if (cos_a > 0.9)
DoMiter(group, path, j, k, cos_a);
else
DoSquare(group, path, j, k);
// is concave
group.path.push_back(GetPerpendic(path[j], norms[k], group_delta_));
// this extra point is the only (simple) way to ensure that
// path reversals are fully cleaned with the trailing clipper
group.path.push_back(path[j]); // (#405)
group.path.push_back(GetPerpendic(path[j], norms[j], group_delta_));
}
else if (join_type_ == JoinType::Round)
DoRound(group, path, j, k, std::atan2(sin_a, cos_a));
else if (join_type_ == JoinType::Miter)
{
// miter unless the angle is so acute the miter would exceeds ML
if (cos_a > temp_lim_ - 1) DoMiter(group, path, j, k, cos_a);
else DoSquare(group, path, j, k);
}
// don't bother squaring angles that deviate < ~20 degrees because
// squaring will be indistinguishable from mitering and just be a lot slower
else if (cos_a > 0.9)
DoMiter(group, path, j, k, cos_a);
else
DoSquare(group, path, j, k);
k = j;
}
void ClipperOffset::OffsetPolygon(Group& group, Path64& path)
{
group.path_.clear();
for (Path64::size_type i = 0, j = path.size() -1; i < path.size(); j = i, ++i)
OffsetPoint(group, path, i, j);
group.paths_out_.push_back(group.path_);
group.paths_out.push_back(group.path);
}
void ClipperOffset::OffsetOpenJoined(Group& group, Path64& path)
{
OffsetPolygon(group, path);
std::reverse(path.begin(), path.end());
BuildNormals(path);
//rebuild normals // BuildNormals(path);
std::reverse(norms.begin(), norms.end());
norms.push_back(norms[0]);
norms.erase(norms.begin());
NegatePath(norms);
group.path.clear();
OffsetPolygon(group, path);
}
void ClipperOffset::OffsetOpenPath(Group& group, Path64& path, EndType end_type)
void ClipperOffset::OffsetOpenPath(Group& group, Path64& path)
{
group.path_.clear();
// do the line start cap
switch (end_type)
switch (end_type_)
{
case EndType::Butt:
group.path_.push_back(Point64(
#ifdef USINGZ
group.path.push_back(Point64(
path[0].x - norms[0].x * group_delta_,
path[0].y - norms[0].y * group_delta_,
path[0].z));
#else
group.path.push_back(Point64(
path[0].x - norms[0].x * group_delta_,
path[0].y - norms[0].y * group_delta_));
group.path_.push_back(GetPerpendic(path[0], norms[0], group_delta_));
#endif
group.path.push_back(GetPerpendic(path[0], norms[0], group_delta_));
break;
case EndType::Round:
DoRound(group, path, 0,0, PI);
@ -335,13 +395,20 @@ void ClipperOffset::OffsetOpenPath(Group& group, Path64& path, EndType end_type)
norms[0] = norms[highI];
// do the line end cap
switch (end_type)
switch (end_type_)
{
case EndType::Butt:
group.path_.push_back(Point64(
#ifdef USINGZ
group.path.push_back(Point64(
path[highI].x - norms[highI].x * group_delta_,
path[highI].y - norms[highI].y * group_delta_,
path[highI].z));
#else
group.path.push_back(Point64(
path[highI].x - norms[highI].x * group_delta_,
path[highI].y - norms[highI].y * group_delta_));
group.path_.push_back(GetPerpendic(path[highI], norms[highI], group_delta_));
#endif
group.path.push_back(GetPerpendic(path[highI], norms[highI], group_delta_));
break;
case EndType::Round:
DoRound(group, path, highI, highI, PI);
@ -353,133 +420,199 @@ void ClipperOffset::OffsetOpenPath(Group& group, Path64& path, EndType end_type)
for (size_t i = highI, k = 0; i > 0; --i)
OffsetPoint(group, path, i, k);
group.paths_out_.push_back(group.path_);
group.paths_out.push_back(group.path);
}
void ClipperOffset::DoGroupOffset(Group& group, double delta)
void ClipperOffset::DoGroupOffset(Group& group)
{
if (group.end_type_ != EndType::Polygon) delta = std::abs(delta) * 0.5;
bool isClosedPaths = IsClosedPath(group.end_type_);
Rect64 r;
int idx = -1;
//the lowermost polygon must be an outer polygon. So we can use that as the
//designated orientation for outer polygons (needed for tidy-up clipping)
GetBoundsAndLowestPolyIdx(group.paths_in, r, idx);
if (idx < 0) return;
if (isClosedPaths)
if (group.end_type == EndType::Polygon)
{
//the lowermost polygon must be an outer polygon. So we can use that as the
//designated orientation for outer polygons (needed for tidy-up clipping)
Paths64::size_type lowestIdx = GetLowestPolygonIdx(group.paths_in_);
// nb: don't use the default orientation here ...
double area = Area(group.paths_in_[lowestIdx]);
if (area == 0) return;
group.is_reversed_ = (area < 0);
if (group.is_reversed_) delta = -delta;
double area = Area(group.paths_in[idx]);
//if (area == 0) return; // probably unhelpful (#430)
group.is_reversed = (area < 0);
if (group.is_reversed) group_delta_ = -delta_;
else group_delta_ = delta_;
}
else
group.is_reversed_ = false;
group_delta_ = delta;
abs_group_delta_ = std::abs(group_delta_);
join_type_ = group.join_type_;
double arcTol = (arc_tolerance_ > floating_point_tolerance ? arc_tolerance_
: std::log10(2 + abs_group_delta_) * default_arc_tolerance); // empirically derived
//calculate a sensible number of steps (for 360 deg for the given offset
if (group.join_type_ == JoinType::Round || group.end_type_ == EndType::Round)
{
steps_per_rad_ = PI / std::acos(1 - arcTol / abs_group_delta_) / (PI *2);
group.is_reversed = false;
group_delta_ = std::abs(delta_) * 0.5;
}
abs_group_delta_ = std::fabs(group_delta_);
// do range checking
if (!IsSafeOffset(r, abs_group_delta_))
{
DoError(range_error_i);
error_code_ |= range_error_i;
return;
}
bool is_closed_path = IsClosedPath(group.end_type_);
Paths64::const_iterator path_iter;
for(path_iter = group.paths_in_.cbegin(); path_iter != group.paths_in_.cend(); ++path_iter)
{
Path64 path = StripDuplicates(*path_iter, is_closed_path);
Path64::size_type cnt = path.size();
if (cnt == 0) continue;
join_type_ = group.join_type;
end_type_ = group.end_type;
//calculate a sensible number of steps (for 360 deg for the given offset
if (group.join_type == JoinType::Round || group.end_type == EndType::Round)
{
// arcTol - when arc_tolerance_ is undefined (0), the amount of
// curve imprecision that's allowed is based on the size of the
// offset (delta). Obviously very large offsets will almost always
// require much less precision. See also offset_triginometry2.svg
double arcTol = (arc_tolerance_ > floating_point_tolerance ?
std::min(abs_group_delta_, arc_tolerance_) :
std::log10(2 + abs_group_delta_) * default_arc_tolerance);
double steps_per_360 = PI / std::acos(1 - arcTol / abs_group_delta_);
if (steps_per_360 > abs_group_delta_ * PI)
steps_per_360 = abs_group_delta_ * PI; //ie avoids excessive precision
step_sin_ = std::sin(2 * PI / steps_per_360);
step_cos_ = std::cos(2 * PI / steps_per_360);
if (group_delta_ < 0.0) step_sin_ = -step_sin_;
steps_per_rad_ = steps_per_360 / (2 *PI);
}
bool is_joined =
(end_type_ == EndType::Polygon) ||
(end_type_ == EndType::Joined);
Paths64::const_iterator path_iter;
for(path_iter = group.paths_in.cbegin(); path_iter != group.paths_in.cend(); ++path_iter)
{
Path64 path = StripDuplicates(*path_iter, is_joined);
Path64::size_type cnt = path.size();
if (cnt == 0 || ((cnt < 3) && group.end_type == EndType::Polygon))
continue;
group.path.clear();
if (cnt == 1) // single point - only valid with open paths
{
group.path_ = Path64();
if (group_delta_ < 1) continue;
//single vertex so build a circle or square ...
if (group.join_type_ == JoinType::Round)
if (group.join_type == JoinType::Round)
{
double radius = abs_group_delta_;
group.path_ = Ellipse(path[0], radius, radius);
group.path = Ellipse(path[0], radius, radius);
#ifdef USINGZ
for (auto& p : group.path) p.z = path[0].z;
#endif
}
else
{
int d = (int)std::ceil(abs_group_delta_);
Rect64 r = Rect64(path[0].x - d, path[0].y - d, path[0].x + d, path[0].y + d);
group.path_ = r.AsPath();
r = Rect64(path[0].x - d, path[0].y - d, path[0].x + d, path[0].y + d);
group.path = r.AsPath();
#ifdef USINGZ
for (auto& p : group.path) p.z = path[0].z;
#endif
}
group.paths_out_.push_back(group.path_);
group.paths_out.push_back(group.path);
}
else
{
if ((cnt == 2) && (group.end_type == EndType::Joined))
{
if (group.join_type == JoinType::Round)
end_type_ = EndType::Round;
else
end_type_ = EndType::Square;
}
BuildNormals(path);
if (group.end_type_ == EndType::Polygon) OffsetPolygon(group, path);
else if (group.end_type_ == EndType::Joined) OffsetOpenJoined(group, path);
else OffsetOpenPath(group, path, group.end_type_);
if (end_type_ == EndType::Polygon) OffsetPolygon(group, path);
else if (end_type_ == EndType::Joined) OffsetOpenJoined(group, path);
else OffsetOpenPath(group, path);
}
}
if (!merge_groups_)
{
//clean up self-intersections ...
Clipper64 c;
c.PreserveCollinear = false;
//the solution should retain the orientation of the input
c.ReverseSolution = reverse_solution_ != group.is_reversed_;
c.AddSubject(group.paths_out_);
if (group.is_reversed_)
c.Execute(ClipType::Union, FillRule::Negative, group.paths_out_);
else
c.Execute(ClipType::Union, FillRule::Positive, group.paths_out_);
}
solution.reserve(solution.size() + group.paths_out_.size());
copy(group.paths_out_.begin(), group.paths_out_.end(), back_inserter(solution));
group.paths_out_.clear();
solution.reserve(solution.size() + group.paths_out.size());
copy(group.paths_out.begin(), group.paths_out.end(), back_inserter(solution));
group.paths_out.clear();
}
Paths64 ClipperOffset::Execute(double delta)
void ClipperOffset::ExecuteInternal(double delta)
{
error_code_ = 0;
solution.clear();
if (std::abs(delta) < default_arc_tolerance)
if (groups_.size() == 0) return;
if (std::abs(delta) < 0.5)
{
for (const Group& group : groups_)
{
solution.reserve(solution.size() + group.paths_in_.size());
copy(group.paths_in_.begin(), group.paths_in_.end(), back_inserter(solution));
solution.reserve(solution.size() + group.paths_in.size());
copy(group.paths_in.begin(), group.paths_in.end(), back_inserter(solution));
}
return solution;
}
temp_lim_ = (miter_limit_ <= 1) ?
2.0 :
2.0 / (miter_limit_ * miter_limit_);
std::vector<Group>::iterator groups_iter;
for (groups_iter = groups_.begin();
groups_iter != groups_.end(); ++groups_iter)
}
else
{
DoGroupOffset(*groups_iter, delta);
}
temp_lim_ = (miter_limit_ <= 1) ?
2.0 :
2.0 / (miter_limit_ * miter_limit_);
if (merge_groups_ && groups_.size() > 0)
{
//clean up self-intersections ...
Clipper64 c;
c.PreserveCollinear = false;
//the solution should retain the orientation of the input
c.ReverseSolution = reverse_solution_ != groups_[0].is_reversed_;
c.AddSubject(solution);
if (groups_[0].is_reversed_)
c.Execute(ClipType::Union, FillRule::Negative, solution);
else
c.Execute(ClipType::Union, FillRule::Positive, solution);
delta_ = delta;
std::vector<Group>::iterator git;
for (git = groups_.begin(); git != groups_.end(); ++git)
{
DoGroupOffset(*git);
if (!error_code_) continue; // all OK
solution.clear();
}
}
return solution;
}
void ClipperOffset::Execute(double delta, Paths64& paths)
{
paths.clear();
ExecuteInternal(delta);
if (!solution.size()) return;
paths = solution;
//clean up self-intersections ...
Clipper64 c;
c.PreserveCollinear = false;
//the solution should retain the orientation of the input
c.ReverseSolution = reverse_solution_ != groups_[0].is_reversed;
#ifdef USINGZ
if (zCallback64_) {
c.SetZCallback(zCallback64_);
}
#endif
c.AddSubject(solution);
if (groups_[0].is_reversed)
c.Execute(ClipType::Union, FillRule::Negative, paths);
else
c.Execute(ClipType::Union, FillRule::Positive, paths);
}
void ClipperOffset::Execute(double delta, PolyTree64& polytree)
{
polytree.Clear();
ExecuteInternal(delta);
if (!solution.size()) return;
//clean up self-intersections ...
Clipper64 c;
c.PreserveCollinear = false;
//the solution should retain the orientation of the input
c.ReverseSolution = reverse_solution_ != groups_[0].is_reversed;
#ifdef USINGZ
if (zCallback64_) {
c.SetZCallback(zCallback64_);
}
#endif
c.AddSubject(solution);
if (groups_[0].is_reversed)
c.Execute(ClipType::Union, FillRule::Negative, polytree);
else
c.Execute(ClipType::Union, FillRule::Positive, polytree);
}
} // namespace

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 26 October 2022 *
* Date : 14 February 2023 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2022 *
* Copyright : Angus Johnson 2010-2023 *
* Purpose : FAST rectangular clipping *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -17,15 +17,22 @@ namespace Clipper2Lib {
// Miscellaneous methods
//------------------------------------------------------------------------------
inline PointInPolygonResult Path1ContainsPath2(Path64 path1, Path64 path2)
inline bool Path1ContainsPath2(const Path64& path1, const Path64& path2)
{
PointInPolygonResult result = PointInPolygonResult::IsOn;
for(const Point64& pt : path2)
int io_count = 0;
// precondition: no (significant) overlap
for (const Point64& pt : path2)
{
result = PointInPolygon(pt, path1);
if (result != PointInPolygonResult::IsOn) break;
PointInPolygonResult pip = PointInPolygon(pt, path1);
switch (pip)
{
case PointInPolygonResult::IsOutside: ++io_count; break;
case PointInPolygonResult::IsInside: --io_count; break;
default: continue;
}
if (std::abs(io_count) > 1) break;
}
return result;
return io_count <= 0;
}
inline bool GetLocation(const Rect64& rec,
@ -59,39 +66,6 @@ namespace Clipper2Lib {
return true;
}
Point64 GetIntersectPoint64(const Point64& ln1a, const Point64& ln1b,
const Point64& ln2a, const Point64& ln2b)
{
// see http://astronomy.swin.edu.au/~pbourke/geometry/lineline2d/
if (ln1b.x == ln1a.x)
{
if (ln2b.x == ln2a.x) return Point64(); // parallel lines
double m2 = static_cast<double>(ln2b.y - ln2a.y) / (ln2b.x - ln2a.x);
double b2 = ln2a.y - m2 * ln2a.x;
return Point64(ln1a.x, static_cast<int64_t>(std::round(m2 * ln1a.x + b2)));
}
else if (ln2b.x == ln2a.x)
{
double m1 = static_cast<double>(ln1b.y - ln1a.y) / (ln1b.x - ln1a.x);
double b1 = ln1a.y - m1 * ln1a.x;
return Point64(ln2a.x, static_cast<int64_t>(std::round(m1 * ln2a.x + b1)));
}
else
{
double m1 = static_cast<double>(ln1b.y - ln1a.y) / (ln1b.x - ln1a.x);
double b1 = ln1a.y - m1 * ln1a.x;
double m2 = static_cast<double>(ln2b.y - ln2a.y) / (ln2b.x - ln2a.x);
double b2 = ln2a.y - m2 * ln2a.x;
if (std::fabs(m1 - m2) > 1.0E-15)
{
double x = (b2 - b1) / (m1 - m2);
return Point64(x, m1 * x + b1);
}
else
return Point64((ln1a.x + ln1b.x) * 0.5, (ln1a.y + ln1b.y) * 0.5);
}
}
inline bool GetIntersection(const Path64& rectPath,
const Point64& p, const Point64& p2, Location& loc, Point64& ip)
{
@ -101,16 +75,16 @@ namespace Clipper2Lib {
{
case Location::Left:
if (SegmentsIntersect(p, p2, rectPath[0], rectPath[3], true))
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[3]);
GetIntersectPoint(p, p2, rectPath[0], rectPath[3], ip);
else if (p.y < rectPath[0].y &&
SegmentsIntersect(p, p2, rectPath[0], rectPath[1], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[1]);
GetIntersectPoint(p, p2, rectPath[0], rectPath[1], ip);
loc = Location::Top;
}
else if (SegmentsIntersect(p, p2, rectPath[2], rectPath[3], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[2], rectPath[3]);
GetIntersectPoint(p, p2, rectPath[2], rectPath[3], ip);
loc = Location::Bottom;
}
else return false;
@ -118,34 +92,34 @@ namespace Clipper2Lib {
case Location::Top:
if (SegmentsIntersect(p, p2, rectPath[0], rectPath[1], true))
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[1]);
GetIntersectPoint(p, p2, rectPath[0], rectPath[1], ip);
else if (p.x < rectPath[0].x &&
SegmentsIntersect(p, p2, rectPath[0], rectPath[3], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[3]);
GetIntersectPoint(p, p2, rectPath[0], rectPath[3], ip);
loc = Location::Left;
}
else if (p.x > rectPath[1].x &&
SegmentsIntersect(p, p2, rectPath[1], rectPath[2], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[1], rectPath[2]);
GetIntersectPoint(p, p2, rectPath[1], rectPath[2], ip);
loc = Location::Right;
}
else return false;
break;
break;
case Location::Right:
if (SegmentsIntersect(p, p2, rectPath[1], rectPath[2], true))
ip = GetIntersectPoint64(p, p2, rectPath[1], rectPath[2]);
GetIntersectPoint(p, p2, rectPath[1], rectPath[2], ip);
else if (p.y < rectPath[0].y &&
SegmentsIntersect(p, p2, rectPath[0], rectPath[1], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[1]);
GetIntersectPoint(p, p2, rectPath[0], rectPath[1], ip);
loc = Location::Top;
}
else if (SegmentsIntersect(p, p2, rectPath[2], rectPath[3], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[2], rectPath[3]);
GetIntersectPoint(p, p2, rectPath[2], rectPath[3], ip);
loc = Location::Bottom;
}
else return false;
@ -153,17 +127,17 @@ namespace Clipper2Lib {
case Location::Bottom:
if (SegmentsIntersect(p, p2, rectPath[2], rectPath[3], true))
ip = GetIntersectPoint64(p, p2, rectPath[2], rectPath[3]);
GetIntersectPoint(p, p2, rectPath[2], rectPath[3], ip);
else if (p.x < rectPath[3].x &&
SegmentsIntersect(p, p2, rectPath[0], rectPath[3], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[3]);
GetIntersectPoint(p, p2, rectPath[0], rectPath[3], ip);
loc = Location::Left;
}
else if (p.x > rectPath[2].x &&
SegmentsIntersect(p, p2, rectPath[1], rectPath[2], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[1], rectPath[2]);
GetIntersectPoint(p, p2, rectPath[1], rectPath[2], ip);
loc = Location::Right;
}
else return false;
@ -172,28 +146,27 @@ namespace Clipper2Lib {
default: // loc == rInside
if (SegmentsIntersect(p, p2, rectPath[0], rectPath[3], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[3]);
GetIntersectPoint(p, p2, rectPath[0], rectPath[3], ip);
loc = Location::Left;
}
else if (SegmentsIntersect(p, p2, rectPath[0], rectPath[1], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[1]);
GetIntersectPoint(p, p2, rectPath[0], rectPath[1], ip);
loc = Location::Top;
}
else if (SegmentsIntersect(p, p2, rectPath[1], rectPath[2], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[1], rectPath[2]);
GetIntersectPoint(p, p2, rectPath[1], rectPath[2], ip);
loc = Location::Right;
}
else if (SegmentsIntersect(p, p2, rectPath[2], rectPath[3], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[2], rectPath[3]);
GetIntersectPoint(p, p2, rectPath[2], rectPath[3], ip);
loc = Location::Bottom;
}
else return false;
break;
}
return true;
}
@ -214,7 +187,7 @@ namespace Clipper2Lib {
}
inline bool IsClockwise(Location prev, Location curr,
Point64 prev_pt, Point64 curr_pt, Point64 rect_mp)
const Point64& prev_pt, const Point64& curr_pt, const Point64& rect_mp)
{
if (AreOpposites(prev, curr))
return CrossProduct(prev_pt, rect_mp, curr_pt) < 0;
@ -222,34 +195,147 @@ namespace Clipper2Lib {
return HeadingClockwise(prev, curr);
}
inline OutPt2* UnlinkOp(OutPt2* op)
{
if (op->next == op) return nullptr;
op->prev->next = op->next;
op->next->prev = op->prev;
return op->next;
}
inline OutPt2* UnlinkOpBack(OutPt2* op)
{
if (op->next == op) return nullptr;
op->prev->next = op->next;
op->next->prev = op->prev;
return op->prev;
}
inline uint32_t GetEdgesForPt(const Point64& pt, const Rect64& rec)
{
uint32_t result = 0;
if (pt.x == rec.left) result = 1;
else if (pt.x == rec.right) result = 4;
if (pt.y == rec.top) result += 2;
else if (pt.y == rec.bottom) result += 8;
return result;
}
inline bool IsHeadingClockwise(const Point64& pt1, const Point64& pt2, int edgeIdx)
{
switch (edgeIdx)
{
case 0: return pt2.y < pt1.y;
case 1: return pt2.x > pt1.x;
case 2: return pt2.y > pt1.y;
default: return pt2.x < pt1.x;
}
}
inline bool HasHorzOverlap(const Point64& left1, const Point64& right1,
const Point64& left2, const Point64& right2)
{
return (left1.x < right2.x) && (right1.x > left2.x);
}
inline bool HasVertOverlap(const Point64& top1, const Point64& bottom1,
const Point64& top2, const Point64& bottom2)
{
return (top1.y < bottom2.y) && (bottom1.y > top2.y);
}
inline void AddToEdge(OutPt2List& edge, OutPt2* op)
{
if (op->edge) return;
op->edge = &edge;
edge.push_back(op);
}
inline void UncoupleEdge(OutPt2* op)
{
if (!op->edge) return;
for (size_t i = 0; i < op->edge->size(); ++i)
{
OutPt2* op2 = (*op->edge)[i];
if (op2 == op)
{
(*op->edge)[i] = nullptr;
break;
}
}
op->edge = nullptr;
}
inline void SetNewOwner(OutPt2* op, size_t new_idx)
{
op->owner_idx = new_idx;
OutPt2* op2 = op->next;
while (op2 != op)
{
op2->owner_idx = new_idx;
op2 = op2->next;
}
}
//----------------------------------------------------------------------------
// RectClip64
//----------------------------------------------------------------------------
OutPt2* RectClip::Add(Point64 pt, bool start_new)
{
// this method is only called by InternalExecute.
// Later splitting & rejoining won't create additional op's,
// though they will change the (non-storage) results_ count.
int curr_idx = static_cast<int>(results_.size()) - 1;
OutPt2* result;
if (curr_idx < 0 || start_new)
{
result = &op_container_.emplace_back(OutPt2());
result->pt = pt;
result->next = result;
result->prev = result;
results_.push_back(result);
}
else
{
OutPt2* prevOp = results_[curr_idx];
if (prevOp->pt == pt) return prevOp;
result = &op_container_.emplace_back(OutPt2());
result->owner_idx = curr_idx;
result->pt = pt;
result->next = prevOp->next;
prevOp->next->prev = result;
prevOp->next = result;
result->prev = prevOp;
results_[curr_idx] = result;
}
return result;
}
void RectClip::AddCorner(Location prev, Location curr)
{
if (HeadingClockwise(prev, curr))
result_.push_back(rectPath_[static_cast<int>(prev)]);
Add(rect_as_path_[static_cast<int>(prev)]);
else
result_.push_back(rectPath_[static_cast<int>(curr)]);
Add(rect_as_path_[static_cast<int>(curr)]);
}
void RectClip::AddCorner(Location& loc, bool isClockwise)
{
if (isClockwise)
{
result_.push_back(rectPath_[static_cast<int>(loc)]);
Add(rect_as_path_[static_cast<int>(loc)]);
loc = GetAdjacentLocation(loc, true);
}
else
{
loc = GetAdjacentLocation(loc, false);
result_.push_back(rectPath_[static_cast<int>(loc)]);
Add(rect_as_path_[static_cast<int>(loc)]);
}
}
void RectClip::GetNextLocation(const Path64& path,
Location& loc, int& i, int highI)
Location& loc, int& i, int highI)
{
switch (loc)
{
@ -296,19 +382,15 @@ namespace Clipper2Lib {
else if (path[i].x > rect_.right) loc = Location::Right;
else if (path[i].y > rect_.bottom) loc = Location::Bottom;
else if (path[i].y < rect_.top) loc = Location::Top;
else { result_.push_back(path[i]); ++i; continue; }
else { Add(path[i]); ++i; continue; }
break; //inner loop
}
break;
} //switch
}
Path64 RectClip::Execute(const Path64& path)
void RectClip::ExecuteInternal(const Path64& path)
{
if (rect_.IsEmpty() || path.size() < 3) return Path64();
result_.clear();
start_locs_.clear();
int i = 0, highI = static_cast<int>(path.size()) - 1;
Location prev = Location::Inside, loc;
Location crossing_loc = Location::Inside;
@ -317,11 +399,16 @@ namespace Clipper2Lib {
{
i = highI - 1;
while (i >= 0 && !GetLocation(rect_, path[i], prev)) --i;
if (i < 0) return path;
if (i < 0)
{
// all of path must be inside fRect
for (const auto& pt : path) Add(pt);
return;
}
if (prev == Location::Inside) loc = Location::Inside;
i = 0;
}
Location starting_loc = loc;
Location startingLoc = loc;
///////////////////////////////////////////////////
while (i <= highI)
@ -333,16 +420,18 @@ namespace Clipper2Lib {
if (i > highI) break;
Point64 ip, ip2;
Point64 prev_pt = (i) ? path[static_cast<size_t>(i - 1)] : path[highI];
Point64 prev_pt = (i) ?
path[static_cast<size_t>(i - 1)] :
path[highI];
crossing_loc = loc;
if (!GetIntersection(rectPath_, path[i], prev_pt, crossing_loc, ip))
if (!GetIntersection(rect_as_path_,
path[i], prev_pt, crossing_loc, ip))
{
// ie remaining outside
if (crossing_prev == Location::Inside)
{
bool isClockw = IsClockwise(prev, loc, prev_pt, path[i], mp_);
bool isClockw = IsClockwise(prev, loc, prev_pt, path[i], rect_mp_);
do {
start_locs_.push_back(prev);
prev = GetAdjacentLocation(prev, isClockw);
@ -351,7 +440,7 @@ namespace Clipper2Lib {
}
else if (prev != Location::Inside && prev != loc)
{
bool isClockw = IsClockwise(prev, loc, prev_pt, path[i], mp_);
bool isClockw = IsClockwise(prev, loc, prev_pt, path[i], rect_mp_);
do {
AddCorner(prev, isClockw);
} while (prev != loc);
@ -373,7 +462,7 @@ namespace Clipper2Lib {
}
else if (prev != crossing_loc)
{
bool isClockw = IsClockwise(prev, crossing_loc, prev_pt, path[i], mp_);
bool isClockw = IsClockwise(prev, crossing_loc, prev_pt, path[i], rect_mp_);
do {
AddCorner(prev, isClockw);
} while (prev != crossing_loc);
@ -384,7 +473,7 @@ namespace Clipper2Lib {
// passing right through rect. 'ip' here will be the second
// intersect pt but we'll also need the first intersect pt (ip2)
loc = prev;
GetIntersection(rectPath_, prev_pt, path[i], loc, ip2);
GetIntersection(rect_as_path_, prev_pt, path[i], loc, ip2);
if (crossing_prev != Location::Inside)
AddCorner(crossing_prev, loc);
@ -395,7 +484,7 @@ namespace Clipper2Lib {
}
loc = crossing_loc;
result_.push_back(ip2);
Add(ip2);
if (ip == ip2)
{
// it's very likely that path[i] is on rect
@ -412,23 +501,33 @@ namespace Clipper2Lib {
first_cross_ = crossing_loc;
}
result_.push_back(ip);
Add(ip);
} //while i <= highI
///////////////////////////////////////////////////
if (first_cross_ == Location::Inside)
{
if (starting_loc == Location::Inside) return path;
Rect64 tmp_rect = Bounds(path);
if (tmp_rect.Contains(rect_) &&
Path1ContainsPath2(path, rectPath_) !=
PointInPolygonResult::IsOutside) return rectPath_;
else
return Path64();
// path never intersects
if (startingLoc != Location::Inside)
{
// path is outside rect
// but being outside, it still may not contain rect
if (path_bounds_.Contains(rect_) &&
Path1ContainsPath2(path, rect_as_path_))
{
// yep, the path does fully contain rect
// so add rect to the solution
for (size_t j = 0; j < 4; ++j)
{
Add(rect_as_path_[j]);
// we may well need to do some splitting later, so
AddToEdge(edges_[j * 2], results_[0]);
}
}
}
}
if (loc != Location::Inside &&
else if (loc != Location::Inside &&
(loc != first_cross_ || start_locs_.size() > 2))
{
if (start_locs_.size() > 0)
@ -445,54 +544,375 @@ namespace Clipper2Lib {
if (loc != first_cross_)
AddCorner(loc, HeadingClockwise(loc, first_cross_));
}
if (result_.size() < 3) return Path64();
// tidy up duplicates and collinear segments
Path64 res;
res.reserve(result_.size());
size_t k = 0; highI = static_cast<int>(result_.size()) - 1;
Point64 prev_pt = result_[highI];
res.push_back(result_[0]);
Path64::const_iterator cit;
for (cit = result_.cbegin() + 1; cit != result_.cend(); ++cit)
{
if (CrossProduct(prev_pt, res[k], *cit))
{
prev_pt = res[k++];
res.push_back(*cit);
}
else
res[k] = *cit;
}
if (k < 2) return Path64();
// and a final check for collinearity
else if (!CrossProduct(res[0], res[k - 1], res[k])) res.pop_back();
return res;
}
Paths64 RectClipLines::Execute(const Path64& path)
void RectClip::CheckEdges()
{
for (size_t i = 0; i < results_.size(); ++i)
{
OutPt2* op = results_[i];
if (!op) continue;
OutPt2* op2 = op;
do
{
if (!CrossProduct(op2->prev->pt,
op2->pt, op2->next->pt))
{
if (op2 == op)
{
op2 = UnlinkOpBack(op2);
if (!op2) break;
op = op2->prev;
}
else
{
op2 = UnlinkOpBack(op2);
if (!op2) break;
}
}
else
op2 = op2->next;
} while (op2 != op);
if (!op2)
{
results_[i] = nullptr;
continue;
}
results_[i] = op; // safety first
uint32_t edgeSet1 = GetEdgesForPt(op->prev->pt, rect_);
op2 = op;
do
{
uint32_t edgeSet2 = GetEdgesForPt(op2->pt, rect_);
if (edgeSet2 && !op2->edge)
{
uint32_t combinedSet = (edgeSet1 & edgeSet2);
for (int j = 0; j < 4; ++j)
{
if (combinedSet & (1 << j))
{
if (IsHeadingClockwise(op2->prev->pt, op2->pt, j))
AddToEdge(edges_[j * 2], op2);
else
AddToEdge(edges_[j * 2 + 1], op2);
}
}
}
edgeSet1 = edgeSet2;
op2 = op2->next;
} while (op2 != op);
}
}
void RectClip::TidyEdges(int idx, OutPt2List& cw, OutPt2List& ccw)
{
if (ccw.empty()) return;
bool isHorz = ((idx == 1) || (idx == 3));
bool cwIsTowardLarger = ((idx == 1) || (idx == 2));
size_t i = 0, j = 0;
OutPt2* p1, * p2, * p1a, * p2a, * op, * op2;
while (i < cw.size())
{
p1 = cw[i];
if (!p1 || p1->next == p1->prev)
{
cw[i++]->edge = nullptr;
j = 0;
continue;
}
size_t jLim = ccw.size();
while (j < jLim &&
(!ccw[j] || ccw[j]->next == ccw[j]->prev)) ++j;
if (j == jLim)
{
++i;
j = 0;
continue;
}
if (cwIsTowardLarger)
{
// p1 >>>> p1a;
// p2 <<<< p2a;
p1 = cw[i]->prev;
p1a = cw[i];
p2 = ccw[j];
p2a = ccw[j]->prev;
}
else
{
// p1 <<<< p1a;
// p2 >>>> p2a;
p1 = cw[i];
p1a = cw[i]->prev;
p2 = ccw[j]->prev;
p2a = ccw[j];
}
if ((isHorz && !HasHorzOverlap(p1->pt, p1a->pt, p2->pt, p2a->pt)) ||
(!isHorz && !HasVertOverlap(p1->pt, p1a->pt, p2->pt, p2a->pt)))
{
++j;
continue;
}
// to get here we're either splitting or rejoining
bool isRejoining = cw[i]->owner_idx != ccw[j]->owner_idx;
if (isRejoining)
{
results_[p2->owner_idx] = nullptr;
SetNewOwner(p2, p1->owner_idx);
}
// do the split or re-join
if (cwIsTowardLarger)
{
// p1 >> | >> p1a;
// p2 << | << p2a;
p1->next = p2;
p2->prev = p1;
p1a->prev = p2a;
p2a->next = p1a;
}
else
{
// p1 << | << p1a;
// p2 >> | >> p2a;
p1->prev = p2;
p2->next = p1;
p1a->next = p2a;
p2a->prev = p1a;
}
if (!isRejoining)
{
size_t new_idx = results_.size();
results_.push_back(p1a);
SetNewOwner(p1a, new_idx);
}
if (cwIsTowardLarger)
{
op = p2;
op2 = p1a;
}
else
{
op = p1;
op2 = p2a;
}
results_[op->owner_idx] = op;
results_[op2->owner_idx] = op2;
// and now lots of work to get ready for the next loop
bool opIsLarger, op2IsLarger;
if (isHorz) // X
{
opIsLarger = op->pt.x > op->prev->pt.x;
op2IsLarger = op2->pt.x > op2->prev->pt.x;
}
else // Y
{
opIsLarger = op->pt.y > op->prev->pt.y;
op2IsLarger = op2->pt.y > op2->prev->pt.y;
}
if ((op->next == op->prev) ||
(op->pt == op->prev->pt))
{
if (op2IsLarger == cwIsTowardLarger)
{
cw[i] = op2;
ccw[j++] = nullptr;
}
else
{
ccw[j] = op2;
cw[i++] = nullptr;
}
}
else if ((op2->next == op2->prev) ||
(op2->pt == op2->prev->pt))
{
if (opIsLarger == cwIsTowardLarger)
{
cw[i] = op;
ccw[j++] = nullptr;
}
else
{
ccw[j] = op;
cw[i++] = nullptr;
}
}
else if (opIsLarger == op2IsLarger)
{
if (opIsLarger == cwIsTowardLarger)
{
cw[i] = op;
UncoupleEdge(op2);
AddToEdge(cw, op2);
ccw[j++] = nullptr;
}
else
{
cw[i++] = nullptr;
ccw[j] = op2;
UncoupleEdge(op);
AddToEdge(ccw, op);
j = 0;
}
}
else
{
if (opIsLarger == cwIsTowardLarger)
cw[i] = op;
else
ccw[j] = op;
if (op2IsLarger == cwIsTowardLarger)
cw[i] = op2;
else
ccw[j] = op2;
}
}
}
Path64 RectClip::GetPath(OutPt2*& op)
{
if (!op || op->next == op->prev) return Path64();
OutPt2* op2 = op->next;
while (op2 && op2 != op)
{
if (CrossProduct(op2->prev->pt,
op2->pt, op2->next->pt) == 0)
{
op = op2->prev;
op2 = UnlinkOp(op2);
}
else
op2 = op2->next;
}
op = op2; // needed for op cleanup
if (!op2) return Path64();
Path64 result;
result.push_back(op->pt);
op2 = op->next;
while (op2 != op)
{
result.push_back(op2->pt);
op2 = op2->next;
}
return result;
}
Paths64 RectClip::Execute(const Paths64& paths, bool convex_only)
{
result_.clear();
Paths64 result;
if (rect_.IsEmpty() || path.size() == 0) return result;
if (rect_.IsEmpty()) return result;
for (const auto& path : paths)
{
if (path.size() < 3) continue;
path_bounds_ = GetBounds(path);
if (!rect_.Intersects(path_bounds_))
continue; // the path must be completely outside rect_
else if (rect_.Contains(path_bounds_))
{
// the path must be completely inside rect_
result.push_back(path);
continue;
}
ExecuteInternal(path);
if (!convex_only)
{
CheckEdges();
for (int i = 0; i < 4; ++i)
TidyEdges(i, edges_[i * 2], edges_[i * 2 + 1]);
}
for (OutPt2*& op : results_)
{
Path64 tmp = GetPath(op);
if (!tmp.empty())
result.emplace_back(tmp);
}
//clean up after every loop
op_container_ = std::deque<OutPt2>();
results_.clear();
for (OutPt2List edge : edges_) edge.clear();
start_locs_.clear();
}
return result;
}
//------------------------------------------------------------------------------
// RectClipLines
//------------------------------------------------------------------------------
Paths64 RectClipLines::Execute(const Paths64& paths)
{
Paths64 result;
if (rect_.IsEmpty()) return result;
for (const auto& path : paths)
{
if (path.size() < 2) continue;
Rect64 pathrec = GetBounds(path);
if (!rect_.Intersects(pathrec)) continue;
ExecuteInternal(path);
for (OutPt2*& op : results_)
{
Path64 tmp = GetPath(op);
if (!tmp.empty())
result.emplace_back(tmp);
}
results_.clear();
op_container_ = std::deque<OutPt2>();
start_locs_.clear();
}
return result;
}
void RectClipLines::ExecuteInternal(const Path64& path)
{
if (rect_.IsEmpty() || path.size() < 2) return;
results_.clear();
op_container_ = std::deque<OutPt2>();
start_locs_.clear();
int i = 1, highI = static_cast<int>(path.size()) - 1;
Location prev = Location::Inside, loc;
Location crossing_loc = Location::Inside;
Location crossing_loc;
if (!GetLocation(rect_, path[0], loc))
{
while (i <= highI && !GetLocation(rect_, path[i], prev)) ++i;
if (i > highI) {
result.push_back(path);
return result;
if (i > highI)
{
// all of path must be inside fRect
for (const auto& pt : path) Add(pt);
return;
}
if (prev == Location::Inside) loc = Location::Inside;
i = 1;
}
if (loc == Location::Inside) result_.push_back(path[0]);
if (loc == Location::Inside) Add(path[0]);
///////////////////////////////////////////////////
while (i <= highI)
@ -504,7 +924,8 @@ namespace Clipper2Lib {
Point64 prev_pt = path[static_cast<size_t>(i - 1)];
crossing_loc = loc;
if (!GetIntersection(rectPath_, path[i], prev_pt, crossing_loc, ip))
if (!GetIntersection(rect_as_path_,
path[i], prev_pt, crossing_loc, ip))
{
// ie remaining outside
++i;
@ -517,30 +938,38 @@ namespace Clipper2Lib {
if (loc == Location::Inside) // path must be entering rect
{
result_.push_back(ip);
Add(ip, true);
}
else if (prev != Location::Inside)
{
// passing right through rect. 'ip' here will be the second
// intersect pt but we'll also need the first intersect pt (ip2)
crossing_loc = prev;
GetIntersection(rectPath_, prev_pt, path[i], crossing_loc, ip2);
result_.push_back(ip2);
result_.push_back(ip);
result.push_back(result_);
result_.clear();
GetIntersection(rect_as_path_,
prev_pt, path[i], crossing_loc, ip2);
Add(ip2, true);
Add(ip);
}
else // path must be exiting rect
{
result_.push_back(ip);
result.push_back(result_);
result_.clear();
Add(ip);
}
} //while i <= highI
///////////////////////////////////////////////////
}
if (result_.size() > 1)
result.push_back(result_);
Path64 RectClipLines::GetPath(OutPt2*& op)
{
Path64 result;
if (!op || op == op->next) return result;
op = op->next; // starting at path beginning
result.push_back(op->pt);
OutPt2 *op2 = op->next;
while (op2 != op)
{
result.push_back(op2->pt);
op2 = op2->next;
}
return result;
}