Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/supermerill/SuperSlicer.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to 'xs/src/libnest2d/tools')
-rw-r--r--xs/src/libnest2d/tools/benchmark.h58
-rw-r--r--xs/src/libnest2d/tools/libnfpglue.cpp157
-rw-r--r--xs/src/libnest2d/tools/libnfpglue.hpp46
-rw-r--r--xs/src/libnest2d/tools/libnfporb/LICENSE674
-rw-r--r--xs/src/libnest2d/tools/libnfporb/ORIGIN2
-rw-r--r--xs/src/libnest2d/tools/libnfporb/README.md89
-rw-r--r--xs/src/libnest2d/tools/libnfporb/libnfporb.hpp1547
-rw-r--r--xs/src/libnest2d/tools/nfp_svgnest.hpp1018
-rw-r--r--xs/src/libnest2d/tools/nfp_svgnest_glue.hpp75
-rw-r--r--xs/src/libnest2d/tools/svgtools.hpp122
10 files changed, 3788 insertions, 0 deletions
diff --git a/xs/src/libnest2d/tools/benchmark.h b/xs/src/libnest2d/tools/benchmark.h
new file mode 100644
index 000000000..19870b37b
--- /dev/null
+++ b/xs/src/libnest2d/tools/benchmark.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) Tamás Mészáros
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#ifndef INCLUDE_BENCHMARK_H_
+#define INCLUDE_BENCHMARK_H_
+
+#include <chrono>
+#include <ratio>
+
+/**
+ * A class for doing benchmarks.
+ */
+class Benchmark {
+ typedef std::chrono::high_resolution_clock Clock;
+ typedef Clock::duration Duration;
+ typedef Clock::time_point TimePoint;
+
+ TimePoint t1, t2;
+ Duration d;
+
+ inline double to_sec(Duration d) {
+ return d.count() * double(Duration::period::num) / Duration::period::den;
+ }
+
+public:
+
+ /**
+ * Measure time from the moment of this call.
+ */
+ void start() { t1 = Clock::now(); }
+
+ /**
+ * Measure time to the moment of this call.
+ */
+ void stop() { t2 = Clock::now(); }
+
+ /**
+ * Get the time elapsed between a start() end a stop() call.
+ * @return Returns the elapsed time in seconds.
+ */
+ double getElapsedSec() { d = t2 - t1; return to_sec(d); }
+};
+
+
+#endif /* INCLUDE_BENCHMARK_H_ */
diff --git a/xs/src/libnest2d/tools/libnfpglue.cpp b/xs/src/libnest2d/tools/libnfpglue.cpp
new file mode 100644
index 000000000..31733acf9
--- /dev/null
+++ b/xs/src/libnest2d/tools/libnfpglue.cpp
@@ -0,0 +1,157 @@
+//#ifndef NDEBUG
+//#define NFP_DEBUG
+//#endif
+
+#include "libnfpglue.hpp"
+#include "tools/libnfporb/libnfporb.hpp"
+
+namespace libnest2d {
+
+namespace {
+inline bool vsort(const libnfporb::point_t& v1, const libnfporb::point_t& v2)
+{
+ using Coord = libnfporb::coord_t;
+ Coord x1 = v1.x_, x2 = v2.x_, y1 = v1.y_, y2 = v2.y_;
+ auto diff = y1 - y2;
+#ifdef LIBNFP_USE_RATIONAL
+ long double diffv = diff.convert_to<long double>();
+#else
+ long double diffv = diff.val();
+#endif
+ if(std::abs(diffv) <=
+ std::numeric_limits<Coord>::epsilon())
+ return x1 < x2;
+
+ return diff < 0;
+}
+
+TCoord<PointImpl> getX(const libnfporb::point_t& p) {
+#ifdef LIBNFP_USE_RATIONAL
+ return p.x_.convert_to<TCoord<PointImpl>>();
+#else
+ return static_cast<TCoord<PointImpl>>(std::round(p.x_.val()));
+#endif
+}
+
+TCoord<PointImpl> getY(const libnfporb::point_t& p) {
+#ifdef LIBNFP_USE_RATIONAL
+ return p.y_.convert_to<TCoord<PointImpl>>();
+#else
+ return static_cast<TCoord<PointImpl>>(std::round(p.y_.val()));
+#endif
+}
+
+libnfporb::point_t scale(const libnfporb::point_t& p, long double factor) {
+#ifdef LIBNFP_USE_RATIONAL
+ auto px = p.x_.convert_to<long double>();
+ auto py = p.y_.convert_to<long double>();
+#else
+ long double px = p.x_.val();
+ long double py = p.y_.val();
+#endif
+ return {px*factor, py*factor};
+}
+
+}
+
+NfpR _nfp(const PolygonImpl &sh, const PolygonImpl &cother)
+{
+ namespace sl = shapelike;
+
+ NfpR ret;
+
+ try {
+ libnfporb::polygon_t pstat, porb;
+
+ boost::geometry::convert(sh, pstat);
+ boost::geometry::convert(cother, porb);
+
+ long double factor = 0.0000001;//libnfporb::NFP_EPSILON;
+ long double refactor = 1.0/factor;
+
+ for(auto& v : pstat.outer()) v = scale(v, factor);
+// std::string message;
+// boost::geometry::is_valid(pstat, message);
+// std::cout << message << std::endl;
+ for(auto& h : pstat.inners()) for(auto& v : h) v = scale(v, factor);
+
+ for(auto& v : porb.outer()) v = scale(v, factor);
+// message;
+// boost::geometry::is_valid(porb, message);
+// std::cout << message << std::endl;
+ for(auto& h : porb.inners()) for(auto& v : h) v = scale(v, factor);
+
+
+ // this can throw
+ auto nfp = libnfporb::generateNFP(pstat, porb, true);
+
+ auto &ct = sl::getContour(ret.first);
+ ct.reserve(nfp.front().size()+1);
+ for(auto v : nfp.front()) {
+ v = scale(v, refactor);
+ ct.emplace_back(getX(v), getY(v));
+ }
+ ct.push_back(ct.front());
+ std::reverse(ct.begin(), ct.end());
+
+ auto &rholes = sl::holes(ret.first);
+ for(size_t hidx = 1; hidx < nfp.size(); ++hidx) {
+ if(nfp[hidx].size() >= 3) {
+ rholes.emplace_back();
+ auto& h = rholes.back();
+ h.reserve(nfp[hidx].size()+1);
+
+ for(auto& v : nfp[hidx]) {
+ v = scale(v, refactor);
+ h.emplace_back(getX(v), getY(v));
+ }
+ h.push_back(h.front());
+ std::reverse(h.begin(), h.end());
+ }
+ }
+
+ ret.second = nfp::referenceVertex(ret.first);
+
+ } catch(std::exception& e) {
+ std::cout << "Error: " << e.what() << "\nTrying with convex hull..." << std::endl;
+// auto ch_stat = ShapeLike::convexHull(sh);
+// auto ch_orb = ShapeLike::convexHull(cother);
+ ret = nfp::nfpConvexOnly(sh, cother);
+ }
+
+ return ret;
+}
+
+NfpR nfp::NfpImpl<PolygonImpl, nfp::NfpLevel::CONVEX_ONLY>::operator()(
+ const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother)
+{
+ return _nfp(sh, cother);//nfpConvexOnly(sh, cother);
+}
+
+NfpR nfp::NfpImpl<PolygonImpl, nfp::NfpLevel::ONE_CONVEX>::operator()(
+ const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother)
+{
+ return _nfp(sh, cother);
+}
+
+NfpR nfp::NfpImpl<PolygonImpl, nfp::NfpLevel::BOTH_CONCAVE>::operator()(
+ const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother)
+{
+ return _nfp(sh, cother);
+}
+
+//PolygonImpl
+//Nfp::NfpImpl<PolygonImpl, NfpLevel::ONE_CONVEX_WITH_HOLES>::operator()(
+// const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother)
+//{
+// return _nfp(sh, cother);
+//}
+
+//PolygonImpl
+//Nfp::NfpImpl<PolygonImpl, NfpLevel::BOTH_CONCAVE_WITH_HOLES>::operator()(
+// const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother)
+//{
+// return _nfp(sh, cother);
+//}
+
+}
diff --git a/xs/src/libnest2d/tools/libnfpglue.hpp b/xs/src/libnest2d/tools/libnfpglue.hpp
new file mode 100644
index 000000000..1ff033cb9
--- /dev/null
+++ b/xs/src/libnest2d/tools/libnfpglue.hpp
@@ -0,0 +1,46 @@
+#ifndef LIBNFPGLUE_HPP
+#define LIBNFPGLUE_HPP
+
+#include <libnest2d/clipper_backend/clipper_backend.hpp>
+
+namespace libnest2d {
+
+using NfpR = nfp::NfpResult<PolygonImpl>;
+
+NfpR _nfp(const PolygonImpl& sh, const PolygonImpl& cother);
+
+template<>
+struct nfp::NfpImpl<PolygonImpl, nfp::NfpLevel::CONVEX_ONLY> {
+ NfpR operator()(const PolygonImpl& sh, const PolygonImpl& cother);
+};
+
+template<>
+struct nfp::NfpImpl<PolygonImpl, nfp::NfpLevel::ONE_CONVEX> {
+ NfpR operator()(const PolygonImpl& sh, const PolygonImpl& cother);
+};
+
+template<>
+struct nfp::NfpImpl<PolygonImpl, nfp::NfpLevel::BOTH_CONCAVE> {
+ NfpR operator()(const PolygonImpl& sh, const PolygonImpl& cother);
+};
+
+//template<>
+//struct Nfp::NfpImpl<PolygonImpl, NfpLevel::ONE_CONVEX_WITH_HOLES> {
+// NfpResult operator()(const PolygonImpl& sh, const PolygonImpl& cother);
+//};
+
+//template<>
+//struct Nfp::NfpImpl<PolygonImpl, NfpLevel::BOTH_CONCAVE_WITH_HOLES> {
+// NfpResult operator()(const PolygonImpl& sh, const PolygonImpl& cother);
+//};
+
+template<> struct nfp::MaxNfpLevel<PolygonImpl> {
+ static const BP2D_CONSTEXPR NfpLevel value =
+// NfpLevel::CONVEX_ONLY;
+ NfpLevel::BOTH_CONCAVE;
+};
+
+}
+
+
+#endif // LIBNFPGLUE_HPP
diff --git a/xs/src/libnest2d/tools/libnfporb/LICENSE b/xs/src/libnest2d/tools/libnfporb/LICENSE
new file mode 100644
index 000000000..94a9ed024
--- /dev/null
+++ b/xs/src/libnest2d/tools/libnfporb/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/xs/src/libnest2d/tools/libnfporb/ORIGIN b/xs/src/libnest2d/tools/libnfporb/ORIGIN
new file mode 100644
index 000000000..788bfd9af
--- /dev/null
+++ b/xs/src/libnest2d/tools/libnfporb/ORIGIN
@@ -0,0 +1,2 @@
+https://github.com/kallaballa/libnfp.git
+commit hash a5cf9f6a76ddab95567fccf629d4d099b60237d7 \ No newline at end of file
diff --git a/xs/src/libnest2d/tools/libnfporb/README.md b/xs/src/libnest2d/tools/libnfporb/README.md
new file mode 100644
index 000000000..9698972be
--- /dev/null
+++ b/xs/src/libnest2d/tools/libnfporb/README.md
@@ -0,0 +1,89 @@
+[![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0.en.html)
+##### If you give me a real good reason i might be willing to give you permission to use it under a different license for a specific application. Real good reasons include the following (non-exhausive): the greater good, educational purpose and money :)
+
+# libnfporb
+Implementation of a robust no-fit polygon generation in a C++ library using an orbiting approach.
+
+__Please note:__ The paper this implementation is based it on has several bad assumptions that required me to "improvise". That means the code doesn't reflect the paper anymore and is running way slower than expected. At the moment I'm working on implementing a new approach based on this paper (using minkowski sums): https://eprints.soton.ac.uk/36850/1/CORMSIS-05-05.pdf
+
+## Description
+
+The no-fit polygon optimization makes it possible to check for overlap (or non-overlapping touch) of two polygons with only 1 point in polygon check (by providing the set of non-overlapping placements).
+This library implements the orbiting approach to generate the no-fit polygon: Given two polygons A and B, A is the stationary one and B the orbiting one, B is slid as tightly as possibly around the edges of polygon A. During the orbiting a chosen reference point is tracked. By tracking the movement of the reference point a third polygon can be generated: the no-fit polygon.
+
+Once the no-fit polygon has been generated it can be used to test for overlap by only checking if the reference point is inside the NFP (overlap) outside the NFP (no overlap) or exactly on the edge of the NFP (touch).
+
+### Examples:
+
+The polygons:
+
+![Start of NFP](/images/start.png?raw=true)
+
+Orbiting:
+
+![State 1](/images/next0.png?raw=true)
+![State 2](/images/next1.png?raw=true)
+![State 3](/images/next2.png?raw=true)
+![State 4](/images/next3.png?raw=true)
+
+![State 5](/images/next4.png?raw=true)
+![State 6](/images/next5.png?raw=true)
+![State 7](/images/next6.png?raw=true)
+![State 8](/images/next7.png?raw=true)
+
+![State 9](/images/next8.png?raw=true)
+
+The resulting NFP is red:
+
+![nfp](/images/nfp.png?raw=true)
+
+Polygons can have concavities, holes, interlocks or might fit perfectly:
+
+![concavities](/images/concavities.png?raw=true)
+![hole](/images/hole.png?raw=true)
+![interlock](/images/interlock.png?raw=true)
+![jigsaw](/images/jigsaw.png?raw=true)
+
+## The Approach
+The approch of this library is highly inspired by the scientific paper [Complete and robust no-fit polygon generation
+for the irregular stock cutting problem](https://pdfs.semanticscholar.org/e698/0dd78306ba7d5bb349d20c6d8f2e0aa61062.pdf) and by [Svgnest](http://svgnest.com)
+
+Note that is wasn't completely possible to implement it as suggested in the paper because it had several shortcomings that prevent complete NFP generation on some of my test cases. Especially the termination criteria (reference point returns to first point of NFP) proved to be wrong (see: test-case rect). Also tracking of used edges can't be performed as suggested in the paper since there might be situations where no edge of A is traversed (see: test-case doublecon).
+
+By default the library is using floating point as coordinate type but by defining the flag "LIBNFP_USE_RATIONAL" the library can be instructed to use infinite precision.
+
+## Build
+The library has two dependencies: [Boost Geometry](http://www.boost.org/doc/libs/1_65_1/libs/geometry/doc/html/index.html) and [libgmp](https://gmplib.org). You need to install those first before building. Note that building is only required for the examples. The library itself is header-only.
+
+ git clone https://github.com/kallaballa/libnfp.git
+ cd libnfp
+ make
+ sudo make install
+
+## Code Example
+
+```c++
+//uncomment next line to use infinite precision (slow)
+//#define LIBNFP_USE_RATIONAL
+#include "../src/libnfp.hpp"
+
+int main(int argc, char** argv) {
+ using namespace libnfp;
+ polygon_t pA;
+ polygon_t pB;
+ //read polygons from wkt files
+ read_wkt_polygon(argv[1], pA);
+ read_wkt_polygon(argv[2], pB);
+
+ //generate NFP of polygon A and polygon B and check the polygons for validity.
+ //When the third parameters is false validity check is skipped for a little performance increase
+ nfp_t nfp = generateNFP(pA, pB, true);
+
+ //write a svg containing pA, pB and NFP
+ write_svg("nfp.svg",{pA,pB},nfp);
+ return 0;
+}
+```
+Run the example program:
+
+ examples/nfp data/crossing/A.wkt data/crossing/B.wkt
diff --git a/xs/src/libnest2d/tools/libnfporb/libnfporb.hpp b/xs/src/libnest2d/tools/libnfporb/libnfporb.hpp
new file mode 100644
index 000000000..8cb34567e
--- /dev/null
+++ b/xs/src/libnest2d/tools/libnfporb/libnfporb.hpp
@@ -0,0 +1,1547 @@
+#ifndef NFP_HPP_
+#define NFP_HPP_
+
+#include <iostream>
+#include <list>
+#include <string>
+#include <fstream>
+#include <streambuf>
+#include <vector>
+#include <set>
+#include <exception>
+#include <random>
+#include <limits>
+
+#if defined(_MSC_VER) && _MSC_VER <= 1800 || __cplusplus < 201103L
+ #define LIBNFP_NOEXCEPT
+ #define LIBNFP_CONSTEXPR
+#elif __cplusplus >= 201103L
+ #define LIBNFP_NOEXCEPT noexcept
+ #define LIBNFP_CONSTEXPR constexpr
+#endif
+
+#ifdef LIBNFP_USE_RATIONAL
+#include <boost/multiprecision/gmp.hpp>
+#include <boost/multiprecision/number.hpp>
+#endif
+#include <boost/geometry.hpp>
+#include <boost/geometry/util/math.hpp>
+#include <boost/geometry/geometries/point_xy.hpp>
+#include <boost/geometry/geometries/polygon.hpp>
+#include <boost/geometry/geometries/linestring.hpp>
+#include <boost/geometry/io/svg/svg_mapper.hpp>
+#include <boost/geometry/algorithms/intersects.hpp>
+#include <boost/geometry/geometries/register/point.hpp>
+
+#ifdef LIBNFP_USE_RATIONAL
+namespace bm = boost::multiprecision;
+#endif
+namespace bg = boost::geometry;
+namespace trans = boost::geometry::strategy::transform;
+
+
+namespace libnfporb {
+#ifdef NFP_DEBUG
+#define DEBUG_VAL(x) std::cerr << x << std::endl;
+#define DEBUG_MSG(title, value) std::cerr << title << ":" << value << std::endl;
+#else
+#define DEBUG_VAL(x)
+#define DEBUG_MSG(title, value)
+#endif
+
+using std::string;
+
+static LIBNFP_CONSTEXPR long double NFP_EPSILON=0.00000001;
+
+class LongDouble {
+private:
+ long double val_;
+public:
+ LongDouble() : val_(0) {
+ }
+
+ LongDouble(const long double& val) : val_(val) {
+ }
+
+ void setVal(const long double& v) {
+ val_ = v;
+ }
+
+ long double val() const {
+ return val_;
+ }
+
+ LongDouble operator/(const LongDouble& other) const {
+ return this->val_ / other.val_;
+ }
+
+ LongDouble operator*(const LongDouble& other) const {
+ return this->val_ * other.val_;
+ }
+
+ LongDouble operator-(const LongDouble& other) const {
+ return this->val_ - other.val_;
+ }
+
+ LongDouble operator-() const {
+ return this->val_ * -1;
+ }
+
+ LongDouble operator+(const LongDouble& other) const {
+ return this->val_ + other.val_;
+ }
+
+ void operator/=(const LongDouble& other) {
+ this->val_ = this->val_ / other.val_;
+ }
+
+ void operator*=(const LongDouble& other) {
+ this->val_ = this->val_ * other.val_;
+ }
+
+ void operator-=(const LongDouble& other) {
+ this->val_ = this->val_ - other.val_;
+ }
+
+ void operator+=(const LongDouble& other) {
+ this->val_ = this->val_ + other.val_;
+ }
+
+ bool operator==(const int& other) const {
+ return this->operator ==(static_cast<long double>(other));
+ }
+
+ bool operator==(const LongDouble& other) const {
+ return this->operator ==(other.val());
+ }
+
+ bool operator==(const long double& other) const {
+ return this->val() == other;
+ }
+
+ bool operator!=(const int& other) const {
+ return !this->operator ==(other);
+ }
+
+ bool operator!=(const LongDouble& other) const {
+ return !this->operator ==(other);
+ }
+
+ bool operator!=(const long double& other) const {
+ return !this->operator ==(other);
+ }
+
+ bool operator<(const int& other) const {
+ return this->operator <(static_cast<long double>(other));
+ }
+
+ bool operator<(const LongDouble& other) const {
+ return this->operator <(other.val());
+ }
+
+ bool operator<(const long double& other) const {
+ return this->val() < other;
+ }
+
+ bool operator>(const int& other) const {
+ return this->operator >(static_cast<long double>(other));
+ }
+
+ bool operator>(const LongDouble& other) const {
+ return this->operator >(other.val());
+ }
+
+ bool operator>(const long double& other) const {
+ return this->val() > other;
+ }
+
+ bool operator>=(const int& other) const {
+ return this->operator >=(static_cast<long double>(other));
+ }
+
+ bool operator>=(const LongDouble& other) const {
+ return this->operator >=(other.val());
+ }
+
+ bool operator>=(const long double& other) const {
+ return this->val() >= other;
+ }
+
+ bool operator<=(const int& other) const {
+ return this->operator <=(static_cast<long double>(other));
+ }
+
+ bool operator<=(const LongDouble& other) const {
+ return this->operator <=(other.val());
+ }
+
+ bool operator<=(const long double& other) const {
+ return this->val() <= other;
+ }
+};
+}
+
+
+namespace std {
+template<>
+ struct numeric_limits<libnfporb::LongDouble>
+ {
+ static const LIBNFP_CONSTEXPR bool is_specialized = true;
+
+ static const LIBNFP_CONSTEXPR long double
+ min() LIBNFP_NOEXCEPT { return std::numeric_limits<long double>::min(); }
+
+ static LIBNFP_CONSTEXPR long double
+ max() LIBNFP_NOEXCEPT { return std::numeric_limits<long double>::max(); }
+
+#if __cplusplus >= 201103L
+ static LIBNFP_CONSTEXPR long double
+ lowest() LIBNFP_NOEXCEPT { return -std::numeric_limits<long double>::lowest(); }
+#endif
+
+ static const LIBNFP_CONSTEXPR int digits = std::numeric_limits<long double>::digits;
+ static const LIBNFP_CONSTEXPR int digits10 = std::numeric_limits<long double>::digits10;
+#if __cplusplus >= 201103L
+ static const LIBNFP_CONSTEXPR int max_digits10
+ = std::numeric_limits<long double>::max_digits10;
+#endif
+ static const LIBNFP_CONSTEXPR bool is_signed = true;
+ static const LIBNFP_CONSTEXPR bool is_integer = false;
+ static const LIBNFP_CONSTEXPR bool is_exact = false;
+ static const LIBNFP_CONSTEXPR int radix = std::numeric_limits<long double>::radix;
+
+ static const LIBNFP_CONSTEXPR long double
+ epsilon() LIBNFP_NOEXCEPT { return libnfporb::NFP_EPSILON; }
+
+ static const LIBNFP_CONSTEXPR long double
+ round_error() LIBNFP_NOEXCEPT { return 0.5L; }
+
+ static const LIBNFP_CONSTEXPR int min_exponent = std::numeric_limits<long double>::min_exponent;
+ static const LIBNFP_CONSTEXPR int min_exponent10 = std::numeric_limits<long double>::min_exponent10;
+ static const LIBNFP_CONSTEXPR int max_exponent = std::numeric_limits<long double>::max_exponent;
+ static const LIBNFP_CONSTEXPR int max_exponent10 = std::numeric_limits<long double>::max_exponent10;
+
+
+ static const LIBNFP_CONSTEXPR bool has_infinity = std::numeric_limits<long double>::has_infinity;
+ static const LIBNFP_CONSTEXPR bool has_quiet_NaN = std::numeric_limits<long double>::has_quiet_NaN;
+ static const LIBNFP_CONSTEXPR bool has_signaling_NaN = has_quiet_NaN;
+ static const LIBNFP_CONSTEXPR float_denorm_style has_denorm
+ = std::numeric_limits<long double>::has_denorm;
+ static const LIBNFP_CONSTEXPR bool has_denorm_loss
+ = std::numeric_limits<long double>::has_denorm_loss;
+
+
+ static const LIBNFP_CONSTEXPR long double
+ infinity() LIBNFP_NOEXCEPT { return std::numeric_limits<long double>::infinity(); }
+
+ static const LIBNFP_CONSTEXPR long double
+ quiet_NaN() LIBNFP_NOEXCEPT { return std::numeric_limits<long double>::quiet_NaN(); }
+
+ static const LIBNFP_CONSTEXPR long double
+ signaling_NaN() LIBNFP_NOEXCEPT { return std::numeric_limits<long double>::signaling_NaN(); }
+
+
+ static const LIBNFP_CONSTEXPR long double
+ denorm_min() LIBNFP_NOEXCEPT { return std::numeric_limits<long double>::denorm_min(); }
+
+ static const LIBNFP_CONSTEXPR bool is_iec559
+ = has_infinity && has_quiet_NaN && has_denorm == denorm_present;
+
+ static const LIBNFP_CONSTEXPR bool is_bounded = true;
+ static const LIBNFP_CONSTEXPR bool is_modulo = false;
+
+ static const LIBNFP_CONSTEXPR bool traps = std::numeric_limits<long double>::traps;
+ static const LIBNFP_CONSTEXPR bool tinyness_before =
+ std::numeric_limits<long double>::tinyness_before;
+ static const LIBNFP_CONSTEXPR float_round_style round_style =
+ round_to_nearest;
+ };
+}
+
+namespace boost {
+namespace numeric {
+ template<>
+ struct raw_converter<boost::numeric::conversion_traits<double, libnfporb::LongDouble>>
+ {
+ typedef boost::numeric::conversion_traits<double, libnfporb::LongDouble>::result_type result_type ;
+ typedef boost::numeric::conversion_traits<double, libnfporb::LongDouble>::argument_type argument_type ;
+
+ static result_type low_level_convert ( argument_type s ) { return s.val() ; }
+ } ;
+}
+}
+
+namespace libnfporb {
+
+#ifndef LIBNFP_USE_RATIONAL
+typedef LongDouble coord_t;
+#else
+typedef bm::number<bm::gmp_rational, bm::et_off> rational_t;
+typedef rational_t coord_t;
+#endif
+
+bool equals(const LongDouble& lhs, const LongDouble& rhs);
+#ifdef LIBNFP_USE_RATIONAL
+bool equals(const rational_t& lhs, const rational_t& rhs);
+#endif
+bool equals(const long double& lhs, const long double& rhs);
+
+const coord_t MAX_COORD = 999999999999999999.0;
+const coord_t MIN_COORD = std::numeric_limits<coord_t>::min();
+
+class point_t {
+public:
+ point_t() : x_(0), y_(0) {
+ }
+ point_t(coord_t x, coord_t y) : x_(x), y_(y) {
+ }
+ bool marked_ = false;
+ coord_t x_;
+ coord_t y_;
+
+ point_t operator-(const point_t& other) const {
+ point_t result = *this;
+ bg::subtract_point(result, other);
+ return result;
+ }
+
+ point_t operator+(const point_t& other) const {
+ point_t result = *this;
+ bg::add_point(result, other);
+ return result;
+ }
+
+ bool operator==(const point_t& other) const {
+ return bg::equals(this, other);
+ }
+
+ bool operator!=(const point_t& other) const {
+ return !this->operator ==(other);
+ }
+
+ bool operator<(const point_t& other) const {
+ return boost::geometry::math::smaller(this->x_, other.x_) || (equals(this->x_, other.x_) && boost::geometry::math::smaller(this->y_, other.y_));
+ }
+};
+
+
+
+
+inline long double toLongDouble(const LongDouble& c) {
+ return c.val();
+}
+
+#ifdef LIBNFP_USE_RATIONAL
+inline long double toLongDouble(const rational_t& c) {
+ return bm::numerator(c).convert_to<long double>() / bm::denominator(c).convert_to<long double>();
+}
+#endif
+
+std::ostream& operator<<(std::ostream& os, const coord_t& p) {
+ os << toLongDouble(p);
+ return os;
+}
+
+std::istream& operator>>(std::istream& is, LongDouble& c) {
+ long double val;
+ is >> val;
+ c.setVal(val);
+ return is;
+}
+
+std::ostream& operator<<(std::ostream& os, const point_t& p) {
+ os << "{" << toLongDouble(p.x_) << "," << toLongDouble(p.y_) << "}";
+ return os;
+}
+const point_t INVALID_POINT = {MAX_COORD, MAX_COORD};
+
+typedef bg::model::segment<point_t> segment_t;
+}
+
+#ifdef LIBNFP_USE_RATIONAL
+inline long double acos(const libnfporb::rational_t& r) {
+ return acos(libnfporb::toLongDouble(r));
+}
+#endif
+
+inline long double acos(const libnfporb::LongDouble& ld) {
+ return acos(libnfporb::toLongDouble(ld));
+}
+
+#ifdef LIBNFP_USE_RATIONAL
+inline long double sqrt(const libnfporb::rational_t& r) {
+ return sqrt(libnfporb::toLongDouble(r));
+}
+#endif
+
+inline long double sqrt(const libnfporb::LongDouble& ld) {
+ return sqrt(libnfporb::toLongDouble(ld));
+}
+
+BOOST_GEOMETRY_REGISTER_POINT_2D(libnfporb::point_t, libnfporb::coord_t, cs::cartesian, x_, y_)
+
+
+namespace boost {
+namespace geometry {
+namespace math {
+namespace detail {
+
+template <>
+struct square_root<libnfporb::LongDouble>
+{
+ typedef libnfporb::LongDouble return_type;
+
+ static inline libnfporb::LongDouble apply(libnfporb::LongDouble const& a)
+ {
+ return std::sqrt(a.val());
+ }
+};
+
+#ifdef LIBNFP_USE_RATIONAL
+template <>
+struct square_root<libnfporb::rational_t>
+{
+ typedef libnfporb::rational_t return_type;
+
+ static inline libnfporb::rational_t apply(libnfporb::rational_t const& a)
+ {
+ return std::sqrt(libnfporb::toLongDouble(a));
+ }
+};
+#endif
+
+template<>
+struct abs<libnfporb::LongDouble>
+ {
+ static libnfporb::LongDouble apply(libnfporb::LongDouble const& value)
+ {
+ libnfporb::LongDouble const zero = libnfporb::LongDouble();
+ return value.val() < zero.val() ? -value.val() : value.val();
+ }
+ };
+
+template <>
+struct equals<libnfporb::LongDouble, false>
+{
+ template<typename Policy>
+ static inline bool apply(libnfporb::LongDouble const& lhs, libnfporb::LongDouble const& rhs, Policy const& policy)
+ {
+ if(lhs.val() == rhs.val())
+ return true;
+
+ return bg::math::detail::abs<libnfporb::LongDouble>::apply(lhs.val() - rhs.val()) <= policy.apply(lhs.val(), rhs.val()) * libnfporb::NFP_EPSILON;
+ }
+};
+
+template <>
+struct smaller<libnfporb::LongDouble>
+{
+ static inline bool apply(libnfporb::LongDouble const& lhs, libnfporb::LongDouble const& rhs)
+ {
+ if(lhs.val() == rhs.val() || bg::math::detail::abs<libnfporb::LongDouble>::apply(lhs.val() - rhs.val()) <= libnfporb::NFP_EPSILON * std::max(lhs.val(), rhs.val()))
+ return false;
+
+ return lhs < rhs;
+ }
+};
+}
+}
+}
+}
+
+namespace libnfporb {
+inline bool smaller(const LongDouble& lhs, const LongDouble& rhs) {
+ return boost::geometry::math::detail::smaller<LongDouble>::apply(lhs, rhs);
+}
+
+inline bool larger(const LongDouble& lhs, const LongDouble& rhs) {
+ return smaller(rhs, lhs);
+}
+
+bool equals(const LongDouble& lhs, const LongDouble& rhs) {
+ if(lhs.val() == rhs.val())
+ return true;
+
+ return bg::math::detail::abs<libnfporb::LongDouble>::apply(lhs.val() - rhs.val()) <= libnfporb::NFP_EPSILON * std::max(lhs.val(), rhs.val());
+}
+
+#ifdef LIBNFP_USE_RATIONAL
+inline bool smaller(const rational_t& lhs, const rational_t& rhs) {
+ return lhs < rhs;
+}
+
+inline bool larger(const rational_t& lhs, const rational_t& rhs) {
+ return smaller(rhs, lhs);
+}
+
+bool equals(const rational_t& lhs, const rational_t& rhs) {
+ return lhs == rhs;
+}
+#endif
+
+inline bool smaller(const long double& lhs, const long double& rhs) {
+ return lhs < rhs;
+}
+
+inline bool larger(const long double& lhs, const long double& rhs) {
+ return smaller(rhs, lhs);
+}
+
+
+bool equals(const long double& lhs, const long double& rhs) {
+ return lhs == rhs;
+}
+
+typedef bg::model::polygon<point_t, false, true> polygon_t;
+typedef std::vector<polygon_t::ring_type> nfp_t;
+typedef bg::model::linestring<point_t> linestring_t;
+
+typedef polygon_t::ring_type::size_type psize_t;
+
+typedef bg::model::d2::point_xy<long double> pointf_t;
+typedef bg::model::segment<pointf_t> segmentf_t;
+typedef bg::model::polygon<pointf_t, false, true> polygonf_t;
+
+polygonf_t::ring_type convert(const polygon_t::ring_type& r) {
+ polygonf_t::ring_type rf;
+ for(const auto& pt : r) {
+ rf.push_back(pointf_t(toLongDouble(pt.x_), toLongDouble(pt.y_)));
+ }
+ return rf;
+}
+
+polygonf_t convert(polygon_t p) {
+ polygonf_t pf;
+ pf.outer() = convert(p.outer());
+
+ for(const auto& r : p.inners()) {
+ pf.inners().push_back(convert(r));
+ }
+
+ return pf;
+}
+
+polygon_t nfpRingsToNfpPoly(const nfp_t& nfp) {
+ polygon_t nfppoly;
+ for (const auto& pt : nfp.front()) {
+ nfppoly.outer().push_back(pt);
+ }
+
+ for (size_t i = 1; i < nfp.size(); ++i) {
+ nfppoly.inners().push_back({});
+ for (const auto& pt : nfp[i]) {
+ nfppoly.inners().back().push_back(pt);
+ }
+ }
+
+ return nfppoly;
+}
+
+void write_svg(std::string const& filename,const std::vector<segment_t>& segments) {
+ std::ofstream svg(filename.c_str());
+
+ boost::geometry::svg_mapper<pointf_t> mapper(svg, 100, 100, "width=\"200mm\" height=\"200mm\" viewBox=\"-250 -250 500 500\"");
+ for(const auto& seg : segments) {
+ segmentf_t segf({toLongDouble(seg.first.x_), toLongDouble(seg.first.y_)}, {toLongDouble(seg.second.x_), toLongDouble(seg.second.y_)});
+ mapper.add(segf);
+ mapper.map(segf, "fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2");
+ }
+}
+
+void write_svg(std::string const& filename, const polygon_t& p, const polygon_t::ring_type& ring) {
+ std::ofstream svg(filename.c_str());
+
+ boost::geometry::svg_mapper<pointf_t> mapper(svg, 100, 100, "width=\"200mm\" height=\"200mm\" viewBox=\"-250 -250 500 500\"");
+ auto pf = convert(p);
+ auto rf = convert(ring);
+
+ mapper.add(pf);
+ mapper.map(pf, "fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2");
+ mapper.add(rf);
+ mapper.map(rf, "fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2");
+}
+
+void write_svg(std::string const& filename, std::vector<polygon_t> const& polygons) {
+ std::ofstream svg(filename.c_str());
+
+ boost::geometry::svg_mapper<pointf_t> mapper(svg, 100, 100, "width=\"200mm\" height=\"200mm\" viewBox=\"-250 -250 500 500\"");
+ for (auto p : polygons) {
+ auto pf = convert(p);
+ mapper.add(pf);
+ mapper.map(pf, "fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2");
+ }
+}
+
+void write_svg(std::string const& filename, std::vector<polygon_t> const& polygons, const nfp_t& nfp) {
+ polygon_t nfppoly;
+ for (const auto& pt : nfp.front()) {
+ nfppoly.outer().push_back(pt);
+ }
+
+ for (size_t i = 1; i < nfp.size(); ++i) {
+ nfppoly.inners().push_back({});
+ for (const auto& pt : nfp[i]) {
+ nfppoly.inners().back().push_back(pt);
+ }
+ }
+ std::ofstream svg(filename.c_str());
+
+ boost::geometry::svg_mapper<pointf_t> mapper(svg, 100, 100, "width=\"200mm\" height=\"200mm\" viewBox=\"-250 -250 500 500\"");
+ for (auto p : polygons) {
+ auto pf = convert(p);
+ mapper.add(pf);
+ mapper.map(pf, "fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2");
+ }
+ bg::correct(nfppoly);
+ auto nfpf = convert(nfppoly);
+ mapper.add(nfpf);
+ mapper.map(nfpf, "fill-opacity:0.5;fill:rgb(204,153,0);stroke:rgb(204,153,0);stroke-width:2");
+
+ for(auto& r: nfpf.inners()) {
+ if(r.size() == 1) {
+ mapper.add(r.front());
+ mapper.map(r.front(), "fill-opacity:0.5;fill:rgb(204,153,0);stroke:rgb(204,153,0);stroke-width:2");
+ } else if(r.size() == 2) {
+ segmentf_t seg(r.front(), *(r.begin()+1));
+ mapper.add(seg);
+ mapper.map(seg, "fill-opacity:0.5;fill:rgb(204,153,0);stroke:rgb(204,153,0);stroke-width:2");
+ }
+ }
+}
+
+std::ostream& operator<<(std::ostream& os, const segment_t& seg) {
+ os << "{" << seg.first << "," << seg.second << "}";
+ return os;
+}
+
+bool operator<(const segment_t& lhs, const segment_t& rhs) {
+ return lhs.first < rhs.first || ((lhs.first == rhs.first) && (lhs.second < rhs.second));
+}
+
+bool operator==(const segment_t& lhs, const segment_t& rhs) {
+ return (lhs.first == rhs.first && lhs.second == rhs.second) || (lhs.first == rhs.second && lhs.second == rhs.first);
+}
+
+bool operator!=(const segment_t& lhs, const segment_t& rhs) {
+ return !operator==(lhs,rhs);
+}
+
+enum Alignment {
+ LEFT,
+ RIGHT,
+ ON
+};
+
+point_t normalize(const point_t& pt) {
+ point_t norm = pt;
+ coord_t len = bg::length(segment_t{{0,0},pt});
+
+ if(len == 0.0L)
+ return {0,0};
+
+ norm.x_ /= len;
+ norm.y_ /= len;
+
+ return norm;
+}
+
+Alignment get_alignment(const segment_t& seg, const point_t& pt){
+ coord_t res = ((seg.second.x_ - seg.first.x_)*(pt.y_ - seg.first.y_)
+ - (seg.second.y_ - seg.first.y_)*(pt.x_ - seg.first.x_));
+
+ if(equals(res, 0)) {
+ return ON;
+ } else if(larger(res,0)) {
+ return LEFT;
+ } else {
+ return RIGHT;
+ }
+}
+
+long double get_inner_angle(const point_t& joint, const point_t& end1, const point_t& end2) {
+ coord_t dx21 = end1.x_-joint.x_;
+ coord_t dx31 = end2.x_-joint.x_;
+ coord_t dy21 = end1.y_-joint.y_;
+ coord_t dy31 = end2.y_-joint.y_;
+ coord_t m12 = sqrt((dx21*dx21 + dy21*dy21));
+ coord_t m13 = sqrt((dx31*dx31 + dy31*dy31));
+ if(m12 == 0.0L || m13 == 0.0L)
+ return 0;
+ return acos( (dx21*dx31 + dy21*dy31) / (m12 * m13) );
+}
+
+struct TouchingPoint {
+ enum Type {
+ VERTEX,
+ A_ON_B,
+ B_ON_A
+ };
+ Type type_;
+ psize_t A_;
+ psize_t B_;
+};
+
+struct TranslationVector {
+ point_t vector_;
+ segment_t edge_;
+ bool fromA_;
+ string name_;
+
+ bool operator<(const TranslationVector& other) const {
+ return this->vector_ < other.vector_ || ((this->vector_ == other.vector_) && (this->edge_ < other.edge_));
+ }
+};
+
+std::ostream& operator<<(std::ostream& os, const TranslationVector& tv) {
+ os << "{" << tv.edge_ << " -> " << tv.vector_ << "} = " << tv.name_;
+ return os;
+}
+
+
+void read_wkt_polygon(const string& filename, polygon_t& p) {
+ std::ifstream t(filename);
+
+ std::string str;
+ t.seekg(0, std::ios::end);
+ str.reserve(t.tellg());
+ t.seekg(0, std::ios::beg);
+
+ str.assign((std::istreambuf_iterator<char>(t)),
+ std::istreambuf_iterator<char>());
+
+ str.pop_back();
+ bg::read_wkt(str, p);
+ bg::correct(p);
+}
+
+std::vector<psize_t> find_minimum_y(const polygon_t& p) {
+ std::vector<psize_t> result;
+ coord_t min = MAX_COORD;
+ auto& po = p.outer();
+ for(psize_t i = 0; i < p.outer().size() - 1; ++i) {
+ if(smaller(po[i].y_, min)) {
+ result.clear();
+ min = po[i].y_;
+ result.push_back(i);
+ } else if (equals(po[i].y_, min)) {
+ result.push_back(i);
+ }
+ }
+ return result;
+}
+
+std::vector<psize_t> find_maximum_y(const polygon_t& p) {
+ std::vector<psize_t> result;
+ coord_t max = MIN_COORD;
+ auto& po = p.outer();
+ for(psize_t i = 0; i < p.outer().size() - 1; ++i) {
+ if(larger(po[i].y_, max)) {
+ result.clear();
+ max = po[i].y_;
+ result.push_back(i);
+ } else if (equals(po[i].y_, max)) {
+ result.push_back(i);
+ }
+ }
+ return result;
+}
+
+psize_t find_point(const polygon_t::ring_type& ring, const point_t& pt) {
+ for(psize_t i = 0; i < ring.size(); ++i) {
+ if(ring[i] == pt)
+ return i;
+ }
+ return std::numeric_limits<psize_t>::max();
+}
+
+std::vector<TouchingPoint> findTouchingPoints(const polygon_t::ring_type& ringA, const polygon_t::ring_type& ringB) {
+ std::vector<TouchingPoint> touchers;
+ for(psize_t i = 0; i < ringA.size() - 1; i++) {
+ psize_t nextI = i+1;
+ for(psize_t j = 0; j < ringB.size() - 1; j++) {
+ psize_t nextJ = j+1;
+ if(ringA[i] == ringB[j]) {
+ touchers.push_back({TouchingPoint::VERTEX, i, j});
+ } else if (ringA[nextI] != ringB[j] && bg::intersects(segment_t(ringA[i],ringA[nextI]), ringB[j])) {
+ touchers.push_back({TouchingPoint::B_ON_A, nextI, j});
+ } else if (ringB[nextJ] != ringA[i] && bg::intersects(segment_t(ringB[j],ringB[nextJ]), ringA[i])) {
+ touchers.push_back({TouchingPoint::A_ON_B, i, nextJ});
+ }
+ }
+ }
+ return touchers;
+}
+
+//TODO deduplicate code
+TranslationVector trimVector(const polygon_t::ring_type& rA, const polygon_t::ring_type& rB, const TranslationVector& tv) {
+ coord_t shortest = bg::length(tv.edge_);
+ TranslationVector trimmed = tv;
+ for(const auto& ptA : rA) {
+ point_t translated;
+ //for polygon A we invert the translation
+ trans::translate_transformer<coord_t, 2, 2> translate(-tv.vector_.x_, -tv.vector_.y_);
+ boost::geometry::transform(ptA, translated, translate);
+ linestring_t projection;
+ segment_t segproj(ptA, translated);
+ projection.push_back(ptA);
+ projection.push_back(translated);
+ std::vector<point_t> intersections;
+ bg::intersection(rB, projection, intersections);
+ if(bg::touches(projection, rB) && intersections.size() < 2) {
+ continue;
+ }
+
+ //find shortest intersection
+ coord_t len;
+ segment_t segi;
+ for(const auto& pti : intersections) {
+ segi = segment_t(ptA,pti);
+ len = bg::length(segi);
+ if(smaller(len, shortest)) {
+ trimmed.vector_ = ptA - pti;
+ trimmed.edge_ = segi;
+ shortest = len;
+ }
+ }
+ }
+
+ for(const auto& ptB : rB) {
+ point_t translated;
+
+ trans::translate_transformer<coord_t, 2, 2> translate(tv.vector_.x_, tv.vector_.y_);
+ boost::geometry::transform(ptB, translated, translate);
+ linestring_t projection;
+ segment_t segproj(ptB, translated);
+ projection.push_back(ptB);
+ projection.push_back(translated);
+ std::vector<point_t> intersections;
+ bg::intersection(rA, projection, intersections);
+ if(bg::touches(projection, rA) && intersections.size() < 2) {
+ continue;
+ }
+
+ //find shortest intersection
+ coord_t len;
+ segment_t segi;
+ for(const auto& pti : intersections) {
+
+ segi = segment_t(ptB,pti);
+ len = bg::length(segi);
+ if(smaller(len, shortest)) {
+ trimmed.vector_ = pti - ptB;
+ trimmed.edge_ = segi;
+ shortest = len;
+ }
+ }
+ }
+ return trimmed;
+}
+
+std::vector<TranslationVector> findFeasibleTranslationVectors(polygon_t::ring_type& ringA, polygon_t::ring_type& ringB, const std::vector<TouchingPoint>& touchers) {
+ //use a set to automatically filter duplicate vectors
+ std::vector<TranslationVector> potentialVectors;
+ std::vector<std::pair<segment_t,segment_t>> touchEdges;
+
+ for (psize_t i = 0; i < touchers.size(); i++) {
+ point_t& vertexA = ringA[touchers[i].A_];
+ vertexA.marked_ = true;
+
+ // adjacent A vertices
+ auto prevAindex = static_cast<signed long>(touchers[i].A_ - 1);
+ auto nextAindex = static_cast<signed long>(touchers[i].A_ + 1);
+
+ prevAindex = (prevAindex < 0) ? static_cast<signed long>(ringA.size() - 2) : prevAindex; // loop
+ nextAindex = (static_cast<psize_t>(nextAindex) >= ringA.size()) ? 1 : nextAindex; // loop
+
+ point_t& prevA = ringA[prevAindex];
+ point_t& nextA = ringA[nextAindex];
+
+ // adjacent B vertices
+ point_t& vertexB = ringB[touchers[i].B_];
+
+ auto prevBindex = static_cast<signed long>(touchers[i].B_ - 1);
+ auto nextBindex = static_cast<signed long>(touchers[i].B_ + 1);
+
+ prevBindex = (prevBindex < 0) ? static_cast<signed long>(ringB.size() - 2) : prevBindex; // loop
+ nextBindex = (static_cast<psize_t>(nextBindex) >= ringB.size()) ? 1 : nextBindex; // loop
+
+ point_t& prevB = ringB[prevBindex];
+ point_t& nextB = ringB[nextBindex];
+
+ if (touchers[i].type_ == TouchingPoint::VERTEX) {
+ segment_t a1 = { vertexA, nextA };
+ segment_t a2 = { vertexA, prevA };
+ segment_t b1 = { vertexB, nextB };
+ segment_t b2 = { vertexB, prevB };
+
+ //swap the segment elements so that always the first point is the touching point
+ //also make the second segment always a segment of ringB
+ touchEdges.push_back({a1, b1});
+ touchEdges.push_back({a1, b2});
+ touchEdges.push_back({a2, b1});
+ touchEdges.push_back({a2, b2});
+#ifdef NFP_DEBUG
+ write_svg("touchersV" + std::to_string(i) + ".svg", {a1,a2,b1,b2});
+#endif
+
+ //TODO test parallel edges for floating point stability
+ Alignment al;
+ //a1 and b1 meet at start vertex
+ al = get_alignment(a1, b1.second);
+ if(al == LEFT) {
+ potentialVectors.push_back({b1.first - b1.second, b1, false, "vertex1"});
+ } else if(al == RIGHT) {
+ potentialVectors.push_back({a1.second - a1.first, a1, true, "vertex2"});
+ } else {
+ potentialVectors.push_back({a1.second - a1.first, a1, true, "vertex3"});
+ }
+
+ //a1 and b2 meet at start and end
+ al = get_alignment(a1, b2.second);
+ if(al == LEFT) {
+ //no feasible translation
+ } else if(al == RIGHT) {
+ potentialVectors.push_back({a1.second - a1.first, a1, true, "vertex4"});
+ } else {
+ potentialVectors.push_back({a1.second - a1.first, a1, true, "vertex5"});
+ }
+
+ //a2 and b1 meet at end and start
+ al = get_alignment(a2, b1.second);
+ if(al == LEFT) {
+ //no feasible translation
+ } else if(al == RIGHT) {
+ potentialVectors.push_back({b1.first - b1.second, b1, false, "vertex6"});
+ } else {
+ potentialVectors.push_back({b1.first - b1.second, b1, false, "vertex7"});
+ }
+ } else if (touchers[i].type_ == TouchingPoint::B_ON_A) {
+ segment_t a1 = {vertexB, vertexA};
+ segment_t a2 = {vertexB, prevA};
+ segment_t b1 = {vertexB, prevB};
+ segment_t b2 = {vertexB, nextB};
+
+ touchEdges.push_back({a1, b1});
+ touchEdges.push_back({a1, b2});
+ touchEdges.push_back({a2, b1});
+ touchEdges.push_back({a2, b2});
+#ifdef NFP_DEBUG
+ write_svg("touchersB" + std::to_string(i) + ".svg", {a1,a2,b1,b2});
+#endif
+ potentialVectors.push_back({vertexA - vertexB, {vertexB, vertexA}, true, "bona"});
+ } else if (touchers[i].type_ == TouchingPoint::A_ON_B) {
+ //TODO testme
+ segment_t a1 = {vertexA, prevA};
+ segment_t a2 = {vertexA, nextA};
+ segment_t b1 = {vertexA, vertexB};
+ segment_t b2 = {vertexA, prevB};
+#ifdef NFP_DEBUG
+ write_svg("touchersA" + std::to_string(i) + ".svg", {a1,a2,b1,b2});
+#endif
+ touchEdges.push_back({a1, b1});
+ touchEdges.push_back({a2, b1});
+ touchEdges.push_back({a1, b2});
+ touchEdges.push_back({a2, b2});
+ potentialVectors.push_back({vertexA - vertexB, {vertexA, vertexB}, false, "aonb"});
+ }
+ }
+
+ //discard immediately intersecting translations
+ std::vector<TranslationVector> vectors;
+ for(const auto& v : potentialVectors) {
+ bool discarded = false;
+ for(const auto& sp : touchEdges) {
+ point_t normEdge = normalize(v.edge_.second - v.edge_.first);
+ point_t normFirst = normalize(sp.first.second - sp.first.first);
+ point_t normSecond = normalize(sp.second.second - sp.second.first);
+
+ Alignment a1 = get_alignment({{0,0},normEdge}, normFirst);
+ Alignment a2 = get_alignment({{0,0},normEdge}, normSecond);
+
+ if(a1 == a2 && a1 != ON) {
+ long double df = get_inner_angle({0,0},normEdge, normFirst);
+ long double ds = get_inner_angle({0,0},normEdge, normSecond);
+
+ point_t normIn = normalize(v.edge_.second - v.edge_.first);
+ if (equals(df, ds)) {
+ TranslationVector trimmed = trimVector(ringA,ringB, v);
+ polygon_t::ring_type translated;
+ trans::translate_transformer<coord_t, 2, 2> translate(trimmed.vector_.x_, trimmed.vector_.y_);
+ boost::geometry::transform(ringB, translated, translate);
+ if (!(bg::intersects(translated, ringA) && !bg::overlaps(translated, ringA) && !bg::covered_by(translated, ringA) && !bg::covered_by(ringA, translated))) {
+ discarded = true;
+ break;
+ }
+ } else {
+
+ if (normIn == normalize(v.vector_)) {
+ if (larger(ds, df)) {
+ discarded = true;
+ break;
+ }
+ } else {
+ if (smaller(ds, df)) {
+ discarded = true;
+ break;
+ }
+ }
+ }
+ }
+ }
+ if(!discarded)
+ vectors.push_back(v);
+ }
+ return vectors;
+}
+
+bool find(const std::vector<TranslationVector>& h, const TranslationVector& tv) {
+ for(const auto& htv : h) {
+ if(htv.vector_ == tv.vector_)
+ return true;
+ }
+ return false;
+}
+
+TranslationVector getLongest(const std::vector<TranslationVector>& tvs) {
+ coord_t len;
+ coord_t maxLen = MIN_COORD;
+ TranslationVector longest;
+ longest.vector_ = INVALID_POINT;
+
+ for(auto& tv : tvs) {
+ len = bg::length(segment_t{{0,0},tv.vector_});
+ if(larger(len, maxLen)) {
+ maxLen = len;
+ longest = tv;
+ }
+ }
+ return longest;
+}
+
+TranslationVector selectNextTranslationVector(const polygon_t& pA, const polygon_t::ring_type& rA, const polygon_t::ring_type& rB, const std::vector<TranslationVector>& tvs, const std::vector<TranslationVector>& history) {
+ if(!history.empty()) {
+ TranslationVector last = history.back();
+ std::vector<TranslationVector> historyCopy = history;
+ if(historyCopy.size() >= 2) {
+ historyCopy.erase(historyCopy.end() - 1);
+ historyCopy.erase(historyCopy.end() - 1);
+ if(historyCopy.size() > 4) {
+ historyCopy.erase(historyCopy.begin(), historyCopy.end() - 4);
+ }
+
+ } else {
+ historyCopy.clear();
+ }
+ DEBUG_MSG("last", last);
+
+ psize_t laterI = std::numeric_limits<psize_t>::max();
+ point_t previous = rA[0];
+ point_t next;
+
+ if(last.fromA_) {
+ for (psize_t i = 1; i < rA.size() + 1; ++i) {
+ if (i >= rA.size())
+ next = rA[i % rA.size()];
+ else
+ next = rA[i];
+
+ segment_t candidate( previous, next );
+ if(candidate == last.edge_) {
+ laterI = i;
+ break;
+ }
+ previous = next;
+ }
+
+ if (laterI == std::numeric_limits<psize_t>::max()) {
+ point_t later;
+ if (last.vector_ == (last.edge_.second - last.edge_.first)) {
+ later = last.edge_.second;
+ } else {
+ later = last.edge_.first;
+ }
+
+ laterI = find_point(rA, later);
+ }
+ } else {
+ point_t later;
+ if (last.vector_ == (last.edge_.second - last.edge_.first)) {
+ later = last.edge_.second;
+ } else {
+ later = last.edge_.first;
+ }
+
+ laterI = find_point(rA, later);
+ }
+
+ if (laterI == std::numeric_limits<psize_t>::max()) {
+ throw std::runtime_error(
+ "Internal error: Can't find later point of last edge");
+ }
+
+ std::vector<segment_t> viableEdges;
+ previous = rA[laterI];
+ for(psize_t i = laterI + 1; i < rA.size() + laterI + 1; ++i) {
+ if(i >= rA.size())
+ next = rA[i % rA.size()];
+ else
+ next = rA[i];
+
+ viableEdges.push_back({previous, next});
+ previous = next;
+ }
+
+// auto rng = std::default_random_engine {};
+// std::shuffle(std::begin(viableEdges), std::end(viableEdges), rng);
+
+ //search with consulting the history to prevent oscillation
+ std::vector<TranslationVector> viableTrans;
+ for(const auto& ve: viableEdges) {
+ for(const auto& tv : tvs) {
+ if((tv.fromA_ && (normalize(tv.vector_) == normalize(ve.second - ve.first))) && (tv.edge_ != last.edge_ || tv.vector_.x_ != -last.vector_.x_ || tv.vector_.y_ != -last.vector_.y_) && !find(historyCopy, tv)) {
+ viableTrans.push_back(tv);
+ }
+ }
+ for (const auto& tv : tvs) {
+ if (!tv.fromA_) {
+ point_t later;
+ if (tv.vector_ == (tv.edge_.second - tv.edge_.first) && (tv.edge_ != last.edge_ || tv.vector_.x_ != -last.vector_.x_ || tv.vector_.y_ != -last.vector_.y_) && !find(historyCopy, tv)) {
+ later = tv.edge_.second;
+ } else if (tv.vector_ == (tv.edge_.first - tv.edge_.second)) {
+ later = tv.edge_.first;
+ } else
+ continue;
+
+ if (later == ve.first || later == ve.second) {
+ viableTrans.push_back(tv);
+ }
+ }
+ }
+ }
+
+ if(!viableTrans.empty())
+ return getLongest(viableTrans);
+
+ //search again without the history
+ for(const auto& ve: viableEdges) {
+ for(const auto& tv : tvs) {
+ if((tv.fromA_ && (normalize(tv.vector_) == normalize(ve.second - ve.first))) && (tv.edge_ != last.edge_ || tv.vector_.x_ != -last.vector_.x_ || tv.vector_.y_ != -last.vector_.y_)) {
+ viableTrans.push_back(tv);
+ }
+ }
+ for (const auto& tv : tvs) {
+ if (!tv.fromA_) {
+ point_t later;
+ if (tv.vector_ == (tv.edge_.second - tv.edge_.first) && (tv.edge_ != last.edge_ || tv.vector_.x_ != -last.vector_.x_ || tv.vector_.y_ != -last.vector_.y_)) {
+ later = tv.edge_.second;
+ } else if (tv.vector_ == (tv.edge_.first - tv.edge_.second)) {
+ later = tv.edge_.first;
+ } else
+ continue;
+
+ if (later == ve.first || later == ve.second) {
+ viableTrans.push_back(tv);
+ }
+ }
+ }
+ }
+ if(!viableTrans.empty())
+ return getLongest(viableTrans);
+
+ /*
+ //search again without the history and without checking last edge
+ for(const auto& ve: viableEdges) {
+ for(const auto& tv : tvs) {
+ if((tv.fromA_ && (normalize(tv.vector_) == normalize(ve.second - ve.first)))) {
+ return tv;
+ }
+ }
+ for (const auto& tv : tvs) {
+ if (!tv.fromA_) {
+ point_t later;
+ if (tv.vector_ == (tv.edge_.second - tv.edge_.first)) {
+ later = tv.edge_.second;
+ } else if (tv.vector_ == (tv.edge_.first - tv.edge_.second)) {
+ later = tv.edge_.first;
+ } else
+ continue;
+
+ if (later == ve.first || later == ve.second) {
+ return tv;
+ }
+ }
+ }
+ }*/
+
+ if(tvs.size() == 1)
+ return *tvs.begin();
+
+ TranslationVector tv;
+ tv.vector_ = INVALID_POINT;
+ return tv;
+ } else {
+ return getLongest(tvs);
+ }
+}
+
+bool inNfp(const point_t& pt, const nfp_t& nfp) {
+ for(const auto& r : nfp) {
+ if(bg::touches(pt, r))
+ return true;
+ }
+
+ return false;
+}
+
+enum SearchStartResult {
+ FIT,
+ FOUND,
+ NOT_FOUND
+};
+
+SearchStartResult searchStartTranslation(polygon_t::ring_type& rA, const polygon_t::ring_type& rB, const nfp_t& nfp,const bool& inside, point_t& result) {
+ for(psize_t i = 0; i < rA.size() - 1; i++) {
+ psize_t index;
+ if (i >= rA.size())
+ index = i % rA.size() + 1;
+ else
+ index = i;
+
+ auto& ptA = rA[index];
+
+ if(ptA.marked_)
+ continue;
+
+ ptA.marked_ = true;
+
+ for(const auto& ptB: rB) {
+ point_t testTranslation = ptA - ptB;
+ polygon_t::ring_type translated;
+ boost::geometry::transform(rB, translated, trans::translate_transformer<coord_t, 2, 2>(testTranslation.x_, testTranslation.y_));
+
+ //check if the translated rB is identical to rA
+ bool identical = false;
+ for(const auto& ptT: translated) {
+ identical = false;
+ for(const auto& ptA: rA) {
+ if(ptT == ptA) {
+ identical = true;
+ break;
+ }
+ }
+ if(!identical)
+ break;
+ }
+
+ if(identical) {
+ result = testTranslation;
+ return FIT;
+ }
+
+ bool bInside = false;
+ for(const auto& ptT: translated) {
+ if(bg::within(ptT, rA)) {
+ bInside = true;
+ break;
+ } else if(!bg::touches(ptT, rA)) {
+ bInside = false;
+ break;
+ }
+ }
+
+ if(((bInside && inside) || (!bInside && !inside)) && (!bg::overlaps(translated, rA) && !bg::covered_by(translated, rA) && !bg::covered_by(rA, translated)) && !inNfp(translated.front(), nfp)){
+ result = testTranslation;
+ return FOUND;
+ }
+
+ point_t nextPtA = rA[index + 1];
+ TranslationVector slideVector;
+ slideVector.vector_ = nextPtA - ptA;
+ slideVector.edge_ = {ptA, nextPtA};
+ slideVector.fromA_ = true;
+ TranslationVector trimmed = trimVector(rA, translated, slideVector);
+ polygon_t::ring_type translated2;
+ trans::translate_transformer<coord_t, 2, 2> trans(trimmed.vector_.x_, trimmed.vector_.y_);
+ boost::geometry::transform(translated, translated2, trans);
+
+ //check if the translated rB is identical to rA
+ identical = false;
+ for(const auto& ptT: translated) {
+ identical = false;
+ for(const auto& ptA: rA) {
+ if(ptT == ptA) {
+ identical = true;
+ break;
+ }
+ }
+ if(!identical)
+ break;
+ }
+
+ if(identical) {
+ result = trimmed.vector_ + testTranslation;
+ return FIT;
+ }
+
+ bInside = false;
+ for(const auto& ptT: translated2) {
+ if(bg::within(ptT, rA)) {
+ bInside = true;
+ break;
+ } else if(!bg::touches(ptT, rA)) {
+ bInside = false;
+ break;
+ }
+ }
+
+ if(((bInside && inside) || (!bInside && !inside)) && (!bg::overlaps(translated2, rA) && !bg::covered_by(translated2, rA) && !bg::covered_by(rA, translated2)) && !inNfp(translated2.front(), nfp)){
+ result = trimmed.vector_ + testTranslation;
+ return FOUND;
+ }
+ }
+ }
+ return NOT_FOUND;
+}
+
+enum SlideResult {
+ LOOP,
+ NO_LOOP,
+ NO_TRANSLATION
+};
+
+SlideResult slide(polygon_t& pA, polygon_t::ring_type& rA, polygon_t::ring_type& rB, nfp_t& nfp, const point_t& transB, bool inside) {
+ polygon_t::ring_type rifsB;
+ boost::geometry::transform(rB, rifsB, trans::translate_transformer<coord_t, 2, 2>(transB.x_, transB.y_));
+ rB = std::move(rifsB);
+
+#ifdef NFP_DEBUG
+ write_svg("ifs.svg", pA, rB);
+#endif
+
+ bool startAvailable = true;
+ psize_t cnt = 0;
+ point_t referenceStart = rB.front();
+ std::vector<TranslationVector> history;
+
+ //generate the nfp for the ring
+ while(startAvailable) {
+ DEBUG_VAL(cnt);
+ //use first point of rB as reference
+ nfp.back().push_back(rB.front());
+ if(cnt == 15)
+ std::cerr << "";
+
+ std::vector<TouchingPoint> touchers = findTouchingPoints(rA, rB);
+
+#ifdef NFP_DEBUG
+ DEBUG_MSG("touchers", touchers.size());
+ for(auto t : touchers) {
+ DEBUG_VAL(t.type_);
+ }
+#endif
+ if(touchers.empty()) {
+ throw std::runtime_error("Internal error: No touching points found");
+ }
+ std::vector<TranslationVector> transVectors = findFeasibleTranslationVectors(rA, rB, touchers);
+
+#ifdef NFP_DEBUG
+ DEBUG_MSG("collected vectors", transVectors.size());
+ for(auto pt : transVectors) {
+ DEBUG_VAL(pt);
+ }
+#endif
+
+ if(transVectors.empty()) {
+ return NO_LOOP;
+ }
+
+ TranslationVector next = selectNextTranslationVector(pA, rA, rB, transVectors, history);
+
+ if(next.vector_ == INVALID_POINT)
+ return NO_TRANSLATION;
+
+ DEBUG_MSG("next", next);
+
+ TranslationVector trimmed = trimVector(rA, rB, next);
+ DEBUG_MSG("trimmed", trimmed);
+
+ history.push_back(next);
+
+ polygon_t::ring_type nextRB;
+ boost::geometry::transform(rB, nextRB, trans::translate_transformer<coord_t, 2, 2>(trimmed.vector_.x_, trimmed.vector_.y_));
+ rB = std::move(nextRB);
+
+#ifdef NFP_DEBUG
+ write_svg("next" + std::to_string(cnt) + ".svg", pA,rB);
+#endif
+
+ ++cnt;
+ if(referenceStart == rB.front() || (inside && bg::touches(rB.front(), nfp.front()))) {
+ startAvailable = false;
+ }
+ }
+ return LOOP;
+}
+
+void removeCoLinear(polygon_t::ring_type& r) {
+ assert(r.size() > 2);
+ psize_t nextI;
+ psize_t prevI = 0;
+ segment_t segment(r[r.size() - 2], r[0]);
+ polygon_t::ring_type newR;
+
+ for (psize_t i = 1; i < r.size() + 1; ++i) {
+ if (i >= r.size())
+ nextI = i % r.size() + 1;
+ else
+ nextI = i;
+
+ if (get_alignment(segment, r[nextI]) != ON) {
+ newR.push_back(r[prevI]);
+ }
+ segment = {segment.second, r[nextI]};
+ prevI = nextI;
+ }
+
+ r = newR;
+}
+
+void removeCoLinear(polygon_t& p) {
+ removeCoLinear(p.outer());
+ for (auto& r : p.inners())
+ removeCoLinear(r);
+}
+
+nfp_t generateNFP(polygon_t& pA, polygon_t& pB, const bool checkValidity = true) {
+ removeCoLinear(pA);
+ removeCoLinear(pB);
+
+ if(checkValidity) {
+ std::string reason;
+ if(!bg::is_valid(pA, reason))
+ throw std::runtime_error("Polygon A is invalid: " + reason);
+
+ if(!bg::is_valid(pB, reason))
+ throw std::runtime_error("Polygon B is invalid: " + reason);
+ }
+
+ nfp_t nfp;
+
+#ifdef NFP_DEBUG
+ write_svg("start.svg", {pA, pB});
+#endif
+
+ DEBUG_VAL(bg::wkt(pA))
+ DEBUG_VAL(bg::wkt(pB));
+
+ //prevent double vertex connections at start because we might come back the same way we go which would end the nfp prematurely
+ std::vector<psize_t> ptyaminI = find_minimum_y(pA);
+ std::vector<psize_t> ptybmaxI = find_maximum_y(pB);
+
+ point_t pAstart;
+ point_t pBstart;
+
+ if(ptyaminI.size() > 1 || ptybmaxI.size() > 1) {
+ //find right-most of A and left-most of B to prevent double connection at start
+ coord_t maxX = MIN_COORD;
+ psize_t iRightMost = 0;
+ for(psize_t& ia : ptyaminI) {
+ const point_t& candidateA = pA.outer()[ia];
+ if(larger(candidateA.x_, maxX)) {
+ maxX = candidateA.x_;
+ iRightMost = ia;
+ }
+ }
+
+ coord_t minX = MAX_COORD;
+ psize_t iLeftMost = 0;
+ for(psize_t& ib : ptybmaxI) {
+ const point_t& candidateB = pB.outer()[ib];
+ if(smaller(candidateB.x_, minX)) {
+ minX = candidateB.x_;
+ iLeftMost = ib;
+ }
+ }
+ pAstart = pA.outer()[iRightMost];
+ pBstart = pB.outer()[iLeftMost];
+ } else {
+ pAstart = pA.outer()[ptyaminI.front()];
+ pBstart = pB.outer()[ptybmaxI.front()];
+ }
+
+ nfp.push_back({});
+ point_t transB = {pAstart - pBstart};
+
+ if(slide(pA, pA.outer(), pB.outer(), nfp, transB, false) != LOOP) {
+ throw std::runtime_error("Unable to complete outer nfp loop");
+ }
+
+ DEBUG_VAL("##### outer #####");
+ point_t startTrans;
+ while(true) {
+ SearchStartResult res = searchStartTranslation(pA.outer(), pB.outer(), nfp, false, startTrans);
+ if(res == FOUND) {
+ nfp.push_back({});
+ DEBUG_VAL("##### interlock start #####")
+ polygon_t::ring_type rifsB;
+ boost::geometry::transform(pB.outer(), rifsB, trans::translate_transformer<coord_t, 2, 2>(startTrans.x_, startTrans.y_));
+ if(inNfp(rifsB.front(), nfp)) {
+ continue;
+ }
+ SlideResult sres = slide(pA, pA.outer(), pB.outer(), nfp, startTrans, true);
+ if(sres != LOOP) {
+ if(sres == NO_TRANSLATION) {
+ //no initial slide found -> jiggsaw
+ if(!inNfp(pB.outer().front(),nfp)) {
+ nfp.push_back({});
+ nfp.back().push_back(pB.outer().front());
+ }
+ }
+ }
+ DEBUG_VAL("##### interlock end #####");
+ } else if(res == FIT) {
+ point_t reference = pB.outer().front();
+ point_t translated;
+ trans::translate_transformer<coord_t, 2, 2> translate(startTrans.x_, startTrans.y_);
+ boost::geometry::transform(reference, translated, translate);
+ if(!inNfp(translated,nfp)) {
+ nfp.push_back({});
+ nfp.back().push_back(translated);
+ }
+ break;
+ } else
+ break;
+ }
+
+
+ for(auto& rA : pA.inners()) {
+ while(true) {
+ SearchStartResult res = searchStartTranslation(rA, pB.outer(), nfp, true, startTrans);
+ if(res == FOUND) {
+ nfp.push_back({});
+ DEBUG_VAL("##### hole start #####");
+ slide(pA, rA, pB.outer(), nfp, startTrans, true);
+ DEBUG_VAL("##### hole end #####");
+ } else if(res == FIT) {
+ point_t reference = pB.outer().front();
+ point_t translated;
+ trans::translate_transformer<coord_t, 2, 2> translate(startTrans.x_, startTrans.y_);
+ boost::geometry::transform(reference, translated, translate);
+ if(!inNfp(translated,nfp)) {
+ nfp.push_back({});
+ nfp.back().push_back(translated);
+ }
+ break;
+ } else
+ break;
+ }
+ }
+
+#ifdef NFP_DEBUG
+ write_svg("nfp.svg", {pA,pB}, nfp);
+#endif
+
+ return nfp;
+}
+}
+#endif
diff --git a/xs/src/libnest2d/tools/nfp_svgnest.hpp b/xs/src/libnest2d/tools/nfp_svgnest.hpp
new file mode 100644
index 000000000..ac5700c10
--- /dev/null
+++ b/xs/src/libnest2d/tools/nfp_svgnest.hpp
@@ -0,0 +1,1018 @@
+#ifndef NFP_SVGNEST_HPP
+#define NFP_SVGNEST_HPP
+
+#include <limits>
+#include <unordered_map>
+
+#include <libnest2d/geometry_traits_nfp.hpp>
+
+namespace libnest2d {
+
+namespace __svgnest {
+
+using std::sqrt;
+using std::min;
+using std::max;
+using std::abs;
+using std::isnan;
+
+//template<class Coord> struct _Scale {
+// static const BP2D_CONSTEXPR long long Value = 1000000;
+//};
+
+template<class S> struct _alg {
+ using Contour = TContour<S>;
+ using Point = TPoint<S>;
+ using iCoord = TCoord<Point>;
+ using Coord = double;
+ using Shapes = nfp::Shapes<S>;
+
+ static const Coord TOL;
+
+#define dNAN std::nan("")
+
+ struct Vector {
+ Coord x = 0.0, y = 0.0;
+ bool marked = false;
+ Vector() = default;
+ Vector(Coord X, Coord Y): x(X), y(Y) {}
+ Vector(const Point& p): x(Coord(getX(p))), y(Coord(getY(p))) {}
+ operator Point() const { return {iCoord(x), iCoord(y)}; }
+ Vector& operator=(const Point& p) {
+ x = getX(p), y = getY(p); return *this;
+ }
+ bool operator!=(const Vector& v) const {
+ return v.x != x || v.y != y;
+ }
+ Vector(std::initializer_list<Coord> il):
+ x(*il.begin()), y(*std::next(il.begin())) {}
+ };
+
+ static inline Coord x(const Point& p) { return Coord(getX(p)); }
+ static inline Coord y(const Point& p) { return Coord(getY(p)); }
+
+ static inline Coord x(const Vector& p) { return p.x; }
+ static inline Coord y(const Vector& p) { return p.y; }
+
+ class Cntr {
+ std::vector<Vector> v_;
+ public:
+ Cntr(const Contour& c) {
+ v_.reserve(c.size());
+ std::transform(c.begin(), c.end(), std::back_inserter(v_),
+ [](const Point& p) {
+ return Vector(double(x(p)) / 1e6, double(y(p)) / 1e6);
+ });
+ std::reverse(v_.begin(), v_.end());
+ v_.pop_back();
+ }
+ Cntr() = default;
+
+ Coord offsetx = 0;
+ Coord offsety = 0;
+ size_t size() const { return v_.size(); }
+ bool empty() const { return v_.empty(); }
+ typename std::vector<Vector>::const_iterator cbegin() const { return v_.cbegin(); }
+ typename std::vector<Vector>::const_iterator cend() const { return v_.cend(); }
+ typename std::vector<Vector>::iterator begin() { return v_.begin(); }
+ typename std::vector<Vector>::iterator end() { return v_.end(); }
+ Vector& operator[](size_t idx) { return v_[idx]; }
+ const Vector& operator[](size_t idx) const { return v_[idx]; }
+ template<class...Args>
+ void emplace_back(Args&&...args) {
+ v_.emplace_back(std::forward<Args>(args)...);
+ }
+ template<class...Args>
+ void push(Args&&...args) {
+ v_.emplace_back(std::forward<Args>(args)...);
+ }
+ void clear() { v_.clear(); }
+
+ operator Contour() const {
+ Contour cnt;
+ cnt.reserve(v_.size() + 1);
+ std::transform(v_.begin(), v_.end(), std::back_inserter(cnt),
+ [](const Vector& vertex) {
+ return Point(iCoord(vertex.x) * 1000000, iCoord(vertex.y) * 1000000);
+ });
+ if(!cnt.empty()) cnt.emplace_back(cnt.front());
+ S sh = shapelike::create<S>(cnt);
+
+// std::reverse(cnt.begin(), cnt.end());
+ return shapelike::getContour(sh);
+ }
+ };
+
+ inline static bool _almostEqual(Coord a, Coord b,
+ Coord tolerance = TOL)
+ {
+ return std::abs(a - b) < tolerance;
+ }
+
+ // returns true if p lies on the line segment defined by AB,
+ // but not at any endpoints may need work!
+ static bool _onSegment(const Vector& A, const Vector& B, const Vector& p) {
+
+ // vertical line
+ if(_almostEqual(A.x, B.x) && _almostEqual(p.x, A.x)) {
+ if(!_almostEqual(p.y, B.y) && !_almostEqual(p.y, A.y) &&
+ p.y < max(B.y, A.y) && p.y > min(B.y, A.y)){
+ return true;
+ }
+ else{
+ return false;
+ }
+ }
+
+ // horizontal line
+ if(_almostEqual(A.y, B.y) && _almostEqual(p.y, A.y)){
+ if(!_almostEqual(p.x, B.x) && !_almostEqual(p.x, A.x) &&
+ p.x < max(B.x, A.x) && p.x > min(B.x, A.x)){
+ return true;
+ }
+ else{
+ return false;
+ }
+ }
+
+ //range check
+ if((p.x < A.x && p.x < B.x) || (p.x > A.x && p.x > B.x) ||
+ (p.y < A.y && p.y < B.y) || (p.y > A.y && p.y > B.y))
+ return false;
+
+ // exclude end points
+ if((_almostEqual(p.x, A.x) && _almostEqual(p.y, A.y)) ||
+ (_almostEqual(p.x, B.x) && _almostEqual(p.y, B.y)))
+ return false;
+
+
+ double cross = (p.y - A.y) * (B.x - A.x) - (p.x - A.x) * (B.y - A.y);
+
+ if(abs(cross) > TOL) return false;
+
+ double dot = (p.x - A.x) * (B.x - A.x) + (p.y - A.y)*(B.y - A.y);
+
+ if(dot < 0 || _almostEqual(dot, 0)) return false;
+
+ double len2 = (B.x - A.x)*(B.x - A.x) + (B.y - A.y)*(B.y - A.y);
+
+ if(dot > len2 || _almostEqual(dot, len2)) return false;
+
+ return true;
+ }
+
+ // return true if point is in the polygon, false if outside, and null if exactly on a point or edge
+ static int pointInPolygon(const Vector& point, const Cntr& polygon) {
+ if(polygon.size() < 3){
+ return 0;
+ }
+
+ bool inside = false;
+ Coord offsetx = polygon.offsetx;
+ Coord offsety = polygon.offsety;
+
+ for (size_t i = 0, j = polygon.size() - 1; i < polygon.size(); j=i++) {
+ auto xi = polygon[i].x + offsetx;
+ auto yi = polygon[i].y + offsety;
+ auto xj = polygon[j].x + offsetx;
+ auto yj = polygon[j].y + offsety;
+
+ if(_almostEqual(xi, point.x) && _almostEqual(yi, point.y)){
+ return 0; // no result
+ }
+
+ if(_onSegment({xi, yi}, {xj, yj}, point)){
+ return 0; // exactly on the segment
+ }
+
+ if(_almostEqual(xi, xj) && _almostEqual(yi, yj)){ // ignore very small lines
+ continue;
+ }
+
+ bool intersect = ((yi > point.y) != (yj > point.y)) &&
+ (point.x < (xj - xi) * (point.y - yi) / (yj - yi) + xi);
+ if (intersect) inside = !inside;
+ }
+
+ return inside? 1 : -1;
+ }
+
+ static bool intersect(const Cntr& A, const Cntr& B){
+ Contour a = A, b = B;
+ return shapelike::intersects(shapelike::create<S>(a), shapelike::create<S>(b));
+ }
+
+ static Vector _normalizeVector(const Vector& v) {
+ if(_almostEqual(v.x*v.x + v.y*v.y, Coord(1))){
+ return Point(v); // given vector was already a unit vector
+ }
+ auto len = sqrt(v.x*v.x + v.y*v.y);
+ auto inverse = 1/len;
+
+ return { Coord(v.x*inverse), Coord(v.y*inverse) };
+ }
+
+ static double pointDistance( const Vector& p,
+ const Vector& s1,
+ const Vector& s2,
+ Vector normal,
+ bool infinite = false)
+ {
+ normal = _normalizeVector(normal);
+
+ Vector dir = {
+ normal.y,
+ -normal.x
+ };
+
+ auto pdot = p.x*dir.x + p.y*dir.y;
+ auto s1dot = s1.x*dir.x + s1.y*dir.y;
+ auto s2dot = s2.x*dir.x + s2.y*dir.y;
+
+ auto pdotnorm = p.x*normal.x + p.y*normal.y;
+ auto s1dotnorm = s1.x*normal.x + s1.y*normal.y;
+ auto s2dotnorm = s2.x*normal.x + s2.y*normal.y;
+
+ if(!infinite){
+ if (((pdot<s1dot || _almostEqual(pdot, s1dot)) &&
+ (pdot<s2dot || _almostEqual(pdot, s2dot))) ||
+ ((pdot>s1dot || _almostEqual(pdot, s1dot)) &&
+ (pdot>s2dot || _almostEqual(pdot, s2dot))))
+ {
+ // dot doesn't collide with segment,
+ // or lies directly on the vertex
+ return dNAN;
+ }
+ if ((_almostEqual(pdot, s1dot) && _almostEqual(pdot, s2dot)) &&
+ (pdotnorm>s1dotnorm && pdotnorm>s2dotnorm))
+ {
+ return min(pdotnorm - s1dotnorm, pdotnorm - s2dotnorm);
+ }
+ if ((_almostEqual(pdot, s1dot) && _almostEqual(pdot, s2dot)) &&
+ (pdotnorm<s1dotnorm && pdotnorm<s2dotnorm)){
+ return -min(s1dotnorm-pdotnorm, s2dotnorm-pdotnorm);
+ }
+ }
+
+ return -(pdotnorm - s1dotnorm + (s1dotnorm - s2dotnorm)*(s1dot - pdot)
+ / double(s1dot - s2dot));
+ }
+
+ static double segmentDistance( const Vector& A,
+ const Vector& B,
+ const Vector& E,
+ const Vector& F,
+ Vector direction)
+ {
+ Vector normal = {
+ direction.y,
+ -direction.x
+ };
+
+ Vector reverse = {
+ -direction.x,
+ -direction.y
+ };
+
+ auto dotA = A.x*normal.x + A.y*normal.y;
+ auto dotB = B.x*normal.x + B.y*normal.y;
+ auto dotE = E.x*normal.x + E.y*normal.y;
+ auto dotF = F.x*normal.x + F.y*normal.y;
+
+ auto crossA = A.x*direction.x + A.y*direction.y;
+ auto crossB = B.x*direction.x + B.y*direction.y;
+ auto crossE = E.x*direction.x + E.y*direction.y;
+ auto crossF = F.x*direction.x + F.y*direction.y;
+
+// auto crossABmin = min(crossA, crossB);
+// auto crossABmax = max(crossA, crossB);
+
+// auto crossEFmax = max(crossE, crossF);
+// auto crossEFmin = min(crossE, crossF);
+
+ auto ABmin = min(dotA, dotB);
+ auto ABmax = max(dotA, dotB);
+
+ auto EFmax = max(dotE, dotF);
+ auto EFmin = min(dotE, dotF);
+
+ // segments that will merely touch at one point
+ if(_almostEqual(ABmax, EFmin, TOL) || _almostEqual(ABmin, EFmax,TOL)) {
+ return dNAN;
+ }
+ // segments miss eachother completely
+ if(ABmax < EFmin || ABmin > EFmax){
+ return dNAN;
+ }
+
+ double overlap = 0;
+
+ if((ABmax > EFmax && ABmin < EFmin) || (EFmax > ABmax && EFmin < ABmin))
+ {
+ overlap = 1;
+ }
+ else{
+ auto minMax = min(ABmax, EFmax);
+ auto maxMin = max(ABmin, EFmin);
+
+ auto maxMax = max(ABmax, EFmax);
+ auto minMin = min(ABmin, EFmin);
+
+ overlap = (minMax-maxMin)/(maxMax-minMin);
+ }
+
+ auto crossABE = (E.y - A.y) * (B.x - A.x) - (E.x - A.x) * (B.y - A.y);
+ auto crossABF = (F.y - A.y) * (B.x - A.x) - (F.x - A.x) * (B.y - A.y);
+
+ // lines are colinear
+ if(_almostEqual(crossABE,0) && _almostEqual(crossABF,0)){
+
+ Vector ABnorm = {B.y-A.y, A.x-B.x};
+ Vector EFnorm = {F.y-E.y, E.x-F.x};
+
+ auto ABnormlength = sqrt(ABnorm.x*ABnorm.x + ABnorm.y*ABnorm.y);
+ ABnorm.x /= ABnormlength;
+ ABnorm.y /= ABnormlength;
+
+ auto EFnormlength = sqrt(EFnorm.x*EFnorm.x + EFnorm.y*EFnorm.y);
+ EFnorm.x /= EFnormlength;
+ EFnorm.y /= EFnormlength;
+
+ // segment normals must point in opposite directions
+ if(abs(ABnorm.y * EFnorm.x - ABnorm.x * EFnorm.y) < TOL &&
+ ABnorm.y * EFnorm.y + ABnorm.x * EFnorm.x < 0){
+ // normal of AB segment must point in same direction as
+ // given direction vector
+ auto normdot = ABnorm.y * direction.y + ABnorm.x * direction.x;
+ // the segments merely slide along eachother
+ if(_almostEqual(normdot,0, TOL)){
+ return dNAN;
+ }
+ if(normdot < 0){
+ return 0.0;
+ }
+ }
+ return dNAN;
+ }
+
+ std::vector<double> distances; distances.reserve(10);
+
+ // coincident points
+ if(_almostEqual(dotA, dotE)){
+ distances.emplace_back(crossA-crossE);
+ }
+ else if(_almostEqual(dotA, dotF)){
+ distances.emplace_back(crossA-crossF);
+ }
+ else if(dotA > EFmin && dotA < EFmax){
+ auto d = pointDistance(A,E,F,reverse);
+ if(!isnan(d) && _almostEqual(d, 0))
+ { // A currently touches EF, but AB is moving away from EF
+ auto dB = pointDistance(B,E,F,reverse,true);
+ if(dB < 0 || _almostEqual(dB*overlap,0)){
+ d = dNAN;
+ }
+ }
+ if(!isnan(d)){
+ distances.emplace_back(d);
+ }
+ }
+
+ if(_almostEqual(dotB, dotE)){
+ distances.emplace_back(crossB-crossE);
+ }
+ else if(_almostEqual(dotB, dotF)){
+ distances.emplace_back(crossB-crossF);
+ }
+ else if(dotB > EFmin && dotB < EFmax){
+ auto d = pointDistance(B,E,F,reverse);
+
+ if(!isnan(d) && _almostEqual(d, 0))
+ { // crossA>crossB A currently touches EF, but AB is moving away from EF
+ double dA = pointDistance(A,E,F,reverse,true);
+ if(dA < 0 || _almostEqual(dA*overlap,0)){
+ d = dNAN;
+ }
+ }
+ if(!isnan(d)){
+ distances.emplace_back(d);
+ }
+ }
+
+ if(dotE > ABmin && dotE < ABmax){
+ auto d = pointDistance(E,A,B,direction);
+ if(!isnan(d) && _almostEqual(d, 0))
+ { // crossF<crossE A currently touches EF, but AB is moving away from EF
+ double dF = pointDistance(F,A,B,direction, true);
+ if(dF < 0 || _almostEqual(dF*overlap,0)){
+ d = dNAN;
+ }
+ }
+ if(!isnan(d)){
+ distances.emplace_back(d);
+ }
+ }
+
+ if(dotF > ABmin && dotF < ABmax){
+ auto d = pointDistance(F,A,B,direction);
+ if(!isnan(d) && _almostEqual(d, 0))
+ { // && crossE<crossF A currently touches EF,
+ // but AB is moving away from EF
+ double dE = pointDistance(E,A,B,direction, true);
+ if(dE < 0 || _almostEqual(dE*overlap,0)){
+ d = dNAN;
+ }
+ }
+ if(!isnan(d)){
+ distances.emplace_back(d);
+ }
+ }
+
+ if(distances.empty()){
+ return dNAN;
+ }
+
+ return *std::min_element(distances.begin(), distances.end());
+ }
+
+ static double polygonSlideDistance( const Cntr& AA,
+ const Cntr& BB,
+ Vector direction,
+ bool ignoreNegative)
+ {
+// Vector A1, A2, B1, B2;
+ Cntr A = AA;
+ Cntr B = BB;
+
+ Coord Aoffsetx = A.offsetx;
+ Coord Boffsetx = B.offsetx;
+ Coord Aoffsety = A.offsety;
+ Coord Boffsety = B.offsety;
+
+ // close the loop for polygons
+ if(A[0] != A[A.size()-1]){
+ A.emplace_back(AA[0]);
+ }
+
+ if(B[0] != B[B.size()-1]){
+ B.emplace_back(BB[0]);
+ }
+
+ auto& edgeA = A;
+ auto& edgeB = B;
+
+ double distance = dNAN, d = dNAN;
+
+ Vector dir = _normalizeVector(direction);
+
+// Vector normal = {
+// dir.y,
+// -dir.x
+// };
+
+// Vector reverse = {
+// -dir.x,
+// -dir.y,
+// };
+
+ for(size_t i = 0; i < edgeB.size() - 1; i++){
+ for(size_t j = 0; j < edgeA.size() - 1; j++){
+ Vector A1 = {x(edgeA[j]) + Aoffsetx, y(edgeA[j]) + Aoffsety };
+ Vector A2 = {x(edgeA[j+1]) + Aoffsetx, y(edgeA[j+1]) + Aoffsety};
+ Vector B1 = {x(edgeB[i]) + Boffsetx, y(edgeB[i]) + Boffsety };
+ Vector B2 = {x(edgeB[i+1]) + Boffsetx, y(edgeB[i+1]) + Boffsety};
+
+ if((_almostEqual(A1.x, A2.x) && _almostEqual(A1.y, A2.y)) ||
+ (_almostEqual(B1.x, B2.x) && _almostEqual(B1.y, B2.y))){
+ continue; // ignore extremely small lines
+ }
+
+ d = segmentDistance(A1, A2, B1, B2, dir);
+
+ if(!isnan(d) && (isnan(distance) || d < distance)){
+ if(!ignoreNegative || d > 0 || _almostEqual(d, 0)){
+ distance = d;
+ }
+ }
+ }
+ }
+ return distance;
+ }
+
+ static double polygonProjectionDistance(const Cntr& AA,
+ const Cntr& BB,
+ Vector direction)
+ {
+ Cntr A = AA;
+ Cntr B = BB;
+
+ auto Boffsetx = B.offsetx;
+ auto Boffsety = B.offsety;
+ auto Aoffsetx = A.offsetx;
+ auto Aoffsety = A.offsety;
+
+ // close the loop for polygons
+ if(A[0] != A[A.size()-1]){
+ A.push(A[0]);
+ }
+
+ if(B[0] != B[B.size()-1]){
+ B.push(B[0]);
+ }
+
+ auto& edgeA = A;
+ auto& edgeB = B;
+
+ double distance = dNAN, d;
+// Vector p, s1, s2;
+
+ for(size_t i = 0; i < edgeB.size(); i++) {
+ // the shortest/most negative projection of B onto A
+ double minprojection = dNAN;
+ Vector minp;
+ for(size_t j = 0; j < edgeA.size() - 1; j++){
+ Vector p = {x(edgeB[i]) + Boffsetx, y(edgeB[i]) + Boffsety };
+ Vector s1 = {x(edgeA[j]) + Aoffsetx, y(edgeA[j]) + Aoffsety };
+ Vector s2 = {x(edgeA[j+1]) + Aoffsetx, y(edgeA[j+1]) + Aoffsety };
+
+ if(abs((s2.y-s1.y) * direction.x -
+ (s2.x-s1.x) * direction.y) < TOL) continue;
+
+ // project point, ignore edge boundaries
+ d = pointDistance(p, s1, s2, direction);
+
+ if(!isnan(d) && (isnan(minprojection) || d < minprojection)) {
+ minprojection = d;
+ minp = p;
+ }
+ }
+
+ if(!isnan(minprojection) && (isnan(distance) ||
+ minprojection > distance)){
+ distance = minprojection;
+ }
+ }
+
+ return distance;
+ }
+
+ static std::pair<bool, Vector> searchStartPoint(
+ const Cntr& AA, const Cntr& BB, bool inside, const std::vector<Cntr>& NFP = {})
+ {
+ // clone arrays
+ auto A = AA;
+ auto B = BB;
+
+// // close the loop for polygons
+// if(A[0] != A[A.size()-1]){
+// A.push(A[0]);
+// }
+
+// if(B[0] != B[B.size()-1]){
+// B.push(B[0]);
+// }
+
+ // returns true if point already exists in the given nfp
+ auto inNfp = [](const Vector& p, const std::vector<Cntr>& nfp){
+ if(nfp.empty()){
+ return false;
+ }
+
+ for(size_t i=0; i < nfp.size(); i++){
+ for(size_t j = 0; j< nfp[i].size(); j++){
+ if(_almostEqual(p.x, nfp[i][j].x) &&
+ _almostEqual(p.y, nfp[i][j].y)){
+ return true;
+ }
+ }
+ }
+
+ return false;
+ };
+
+ for(size_t i = 0; i < A.size() - 1; i++){
+ if(!A[i].marked) {
+ A[i].marked = true;
+ for(size_t j = 0; j < B.size(); j++){
+ B.offsetx = A[i].x - B[j].x;
+ B.offsety = A[i].y - B[j].y;
+
+ int Binside = 0;
+ for(size_t k = 0; k < B.size(); k++){
+ int inpoly = pointInPolygon({B[k].x + B.offsetx, B[k].y + B.offsety}, A);
+ if(inpoly != 0){
+ Binside = inpoly;
+ break;
+ }
+ }
+
+ if(Binside == 0){ // A and B are the same
+ return {false, {}};
+ }
+
+ auto startPoint = std::make_pair(true, Vector(B.offsetx, B.offsety));
+ if(((Binside && inside) || (!Binside && !inside)) &&
+ !intersect(A,B) && !inNfp(startPoint.second, NFP)){
+ return startPoint;
+ }
+
+ // slide B along vector
+ auto vx = A[i+1].x - A[i].x;
+ auto vy = A[i+1].y - A[i].y;
+
+ double d1 = polygonProjectionDistance(A,B,{vx, vy});
+ double d2 = polygonProjectionDistance(B,A,{-vx, -vy});
+
+ double d = dNAN;
+
+ // todo: clean this up
+ if(isnan(d1) && isnan(d2)){
+ // nothin
+ }
+ else if(isnan(d1)){
+ d = d2;
+ }
+ else if(isnan(d2)){
+ d = d1;
+ }
+ else{
+ d = min(d1,d2);
+ }
+
+ // only slide until no longer negative
+ // todo: clean this up
+ if(!isnan(d) && !_almostEqual(d,0) && d > 0){
+
+ }
+ else{
+ continue;
+ }
+
+ auto vd2 = vx*vx + vy*vy;
+
+ if(d*d < vd2 && !_almostEqual(d*d, vd2)){
+ auto vd = sqrt(vx*vx + vy*vy);
+ vx *= d/vd;
+ vy *= d/vd;
+ }
+
+ B.offsetx += vx;
+ B.offsety += vy;
+
+ for(size_t k = 0; k < B.size(); k++){
+ int inpoly = pointInPolygon({B[k].x + B.offsetx, B[k].y + B.offsety}, A);
+ if(inpoly != 0){
+ Binside = inpoly;
+ break;
+ }
+ }
+ startPoint = std::make_pair(true, Vector{B.offsetx, B.offsety});
+ if(((Binside && inside) || (!Binside && !inside)) &&
+ !intersect(A,B) && !inNfp(startPoint.second, NFP)){
+ return startPoint;
+ }
+ }
+ }
+ }
+
+ return {false, Vector(0, 0)};
+ }
+
+ static std::vector<Cntr> noFitPolygon(Cntr A,
+ Cntr B,
+ bool inside,
+ bool searchEdges)
+ {
+ if(A.size() < 3 || B.size() < 3) {
+ throw GeometryException(GeomErr::NFP);
+ return {};
+ }
+
+ A.offsetx = 0;
+ A.offsety = 0;
+
+ long i = 0, j = 0;
+
+ auto minA = y(A[0]);
+ long minAindex = 0;
+
+ auto maxB = y(B[0]);
+ long maxBindex = 0;
+
+ for(i = 1; i < A.size(); i++){
+ A[i].marked = false;
+ if(y(A[i]) < minA){
+ minA = y(A[i]);
+ minAindex = i;
+ }
+ }
+
+ for(i = 1; i < B.size(); i++){
+ B[i].marked = false;
+ if(y(B[i]) > maxB){
+ maxB = y(B[i]);
+ maxBindex = i;
+ }
+ }
+
+ std::pair<bool, Vector> startpoint;
+
+ if(!inside){
+ // shift B such that the bottom-most point of B is at the top-most
+ // point of A. This guarantees an initial placement with no
+ // intersections
+ startpoint = { true,
+ { x(A[minAindex]) - x(B[maxBindex]),
+ y(A[minAindex]) - y(B[maxBindex]) }
+ };
+ }
+ else {
+ // no reliable heuristic for inside
+ startpoint = searchStartPoint(A, B, true);
+ }
+
+ std::vector<Cntr> NFPlist;
+
+ struct Touch {
+ int type;
+ long A;
+ long B;
+ Touch(int t, long a, long b): type(t), A(a), B(b) {}
+ };
+
+ while(startpoint.first) {
+
+ B.offsetx = startpoint.second.x;
+ B.offsety = startpoint.second.y;
+
+ // maintain a list of touching points/edges
+ std::vector<Touch> touching;
+
+ struct V {
+ Coord x, y;
+ Vector *start, *end;
+ operator bool() {
+ return start != nullptr && end != nullptr;
+ }
+ operator Vector() const { return {x, y}; }
+ } prevvector = {0, 0, nullptr, nullptr};
+
+ Cntr NFP;
+ NFP.emplace_back(x(B[0]) + B.offsetx, y(B[0]) + B.offsety);
+
+ auto referencex = x(B[0]) + B.offsetx;
+ auto referencey = y(B[0]) + B.offsety;
+ auto startx = referencex;
+ auto starty = referencey;
+ unsigned counter = 0;
+
+ // sanity check, prevent infinite loop
+ while(counter < 10*(A.size() + B.size())){
+ touching.clear();
+
+ // find touching vertices/edges
+ for(i = 0; i < A.size(); i++){
+ long nexti = (i == A.size() - 1) ? 0 : i + 1;
+ for(j = 0; j < B.size(); j++){
+
+ long nextj = (j == B.size() - 1) ? 0 : j + 1;
+
+ if( _almostEqual(A[i].x, B[j].x+B.offsetx) &&
+ _almostEqual(A[i].y, B[j].y+B.offsety))
+ {
+ touching.emplace_back(0, i, j);
+ }
+ else if( _onSegment(
+ A[i], A[nexti],
+ { B[j].x+B.offsetx, B[j].y + B.offsety}) )
+ {
+ touching.emplace_back(1, nexti, j);
+ }
+ else if( _onSegment(
+ {B[j].x+B.offsetx, B[j].y + B.offsety},
+ {B[nextj].x+B.offsetx, B[nextj].y + B.offsety},
+ A[i]) )
+ {
+ touching.emplace_back(2, i, nextj);
+ }
+ }
+ }
+
+ // generate translation vectors from touching vertices/edges
+ std::vector<V> vectors;
+ for(i=0; i < touching.size(); i++){
+ auto& vertexA = A[touching[i].A];
+ vertexA.marked = true;
+
+ // adjacent A vertices
+ auto prevAindex = touching[i].A - 1;
+ auto nextAindex = touching[i].A + 1;
+
+ prevAindex = (prevAindex < 0) ? A.size() - 1 : prevAindex; // loop
+ nextAindex = (nextAindex >= A.size()) ? 0 : nextAindex; // loop
+
+ auto& prevA = A[prevAindex];
+ auto& nextA = A[nextAindex];
+
+ // adjacent B vertices
+ auto& vertexB = B[touching[i].B];
+
+ auto prevBindex = touching[i].B-1;
+ auto nextBindex = touching[i].B+1;
+
+ prevBindex = (prevBindex < 0) ? B.size() - 1 : prevBindex; // loop
+ nextBindex = (nextBindex >= B.size()) ? 0 : nextBindex; // loop
+
+ auto& prevB = B[prevBindex];
+ auto& nextB = B[nextBindex];
+
+ if(touching[i].type == 0){
+
+ V vA1 = {
+ prevA.x - vertexA.x,
+ prevA.y - vertexA.y,
+ &vertexA,
+ &prevA
+ };
+
+ V vA2 = {
+ nextA.x - vertexA.x,
+ nextA.y - vertexA.y,
+ &vertexA,
+ &nextA
+ };
+
+ // B vectors need to be inverted
+ V vB1 = {
+ vertexB.x - prevB.x,
+ vertexB.y - prevB.y,
+ &prevB,
+ &vertexB
+ };
+
+ V vB2 = {
+ vertexB.x - nextB.x,
+ vertexB.y - nextB.y,
+ &nextB,
+ &vertexB
+ };
+
+ vectors.emplace_back(vA1);
+ vectors.emplace_back(vA2);
+ vectors.emplace_back(vB1);
+ vectors.emplace_back(vB2);
+ }
+ else if(touching[i].type == 1){
+ vectors.emplace_back(V{
+ vertexA.x-(vertexB.x+B.offsetx),
+ vertexA.y-(vertexB.y+B.offsety),
+ &prevA,
+ &vertexA
+ });
+
+ vectors.emplace_back(V{
+ prevA.x-(vertexB.x+B.offsetx),
+ prevA.y-(vertexB.y+B.offsety),
+ &vertexA,
+ &prevA
+ });
+ }
+ else if(touching[i].type == 2){
+ vectors.emplace_back(V{
+ vertexA.x-(vertexB.x+B.offsetx),
+ vertexA.y-(vertexB.y+B.offsety),
+ &prevB,
+ &vertexB
+ });
+
+ vectors.emplace_back(V{
+ vertexA.x-(prevB.x+B.offsetx),
+ vertexA.y-(prevB.y+B.offsety),
+ &vertexB,
+ &prevB
+ });
+ }
+ }
+
+ // TODO: there should be a faster way to reject vectors that
+ // will cause immediate intersection. For now just check them all
+
+ V translate = {0, 0, nullptr, nullptr};
+ double maxd = 0;
+
+ for(i = 0; i < vectors.size(); i++) {
+ if(vectors[i].x == 0 && vectors[i].y == 0){
+ continue;
+ }
+
+ // if this vector points us back to where we came from, ignore it.
+ // ie cross product = 0, dot product < 0
+ if(prevvector && vectors[i].y * prevvector.y + vectors[i].x * prevvector.x < 0){
+
+ // compare magnitude with unit vectors
+ double vectorlength = sqrt(vectors[i].x*vectors[i].x+vectors[i].y*vectors[i].y);
+ Vector unitv = {Coord(vectors[i].x/vectorlength),
+ Coord(vectors[i].y/vectorlength)};
+
+ double prevlength = sqrt(prevvector.x*prevvector.x+prevvector.y*prevvector.y);
+ Vector prevunit = { prevvector.x/prevlength, prevvector.y/prevlength};
+
+ // we need to scale down to unit vectors to normalize vector length. Could also just do a tan here
+ if(abs(unitv.y * prevunit.x - unitv.x * prevunit.y) < 0.0001){
+ continue;
+ }
+ }
+
+ V vi = vectors[i];
+ double d = polygonSlideDistance(A, B, vi, true);
+ double vecd2 = vectors[i].x*vectors[i].x + vectors[i].y*vectors[i].y;
+
+ if(isnan(d) || d*d > vecd2){
+ double vecd = sqrt(vectors[i].x*vectors[i].x + vectors[i].y*vectors[i].y);
+ d = vecd;
+ }
+
+ if(!isnan(d) && d > maxd){
+ maxd = d;
+ translate = vectors[i];
+ }
+ }
+
+ if(!translate || _almostEqual(maxd, 0))
+ {
+ // didn't close the loop, something went wrong here
+ NFP.clear();
+ break;
+ }
+
+ translate.start->marked = true;
+ translate.end->marked = true;
+
+ prevvector = translate;
+
+ // trim
+ double vlength2 = translate.x*translate.x + translate.y*translate.y;
+ if(maxd*maxd < vlength2 && !_almostEqual(maxd*maxd, vlength2)){
+ double scale = sqrt((maxd*maxd)/vlength2);
+ translate.x *= scale;
+ translate.y *= scale;
+ }
+
+ referencex += translate.x;
+ referencey += translate.y;
+
+ if(_almostEqual(referencex, startx) &&
+ _almostEqual(referencey, starty)) {
+ // we've made a full loop
+ break;
+ }
+
+ // if A and B start on a touching horizontal line,
+ // the end point may not be the start point
+ bool looped = false;
+ if(NFP.size() > 0) {
+ for(i = 0; i < NFP.size() - 1; i++) {
+ if(_almostEqual(referencex, NFP[i].x) &&
+ _almostEqual(referencey, NFP[i].y)){
+ looped = true;
+ }
+ }
+ }
+
+ if(looped){
+ // we've made a full loop
+ break;
+ }
+
+ NFP.emplace_back(referencex, referencey);
+
+ B.offsetx += translate.x;
+ B.offsety += translate.y;
+
+ counter++;
+ }
+
+ if(NFP.size() > 0){
+ NFPlist.emplace_back(NFP);
+ }
+
+ if(!searchEdges){
+ // only get outer NFP or first inner NFP
+ break;
+ }
+
+ startpoint =
+ searchStartPoint(A, B, inside, NFPlist);
+
+ }
+
+ return NFPlist;
+ }
+};
+
+template<class S> const double _alg<S>::TOL = std::pow(10, -9);
+
+}
+}
+
+#endif // NFP_SVGNEST_HPP
diff --git a/xs/src/libnest2d/tools/nfp_svgnest_glue.hpp b/xs/src/libnest2d/tools/nfp_svgnest_glue.hpp
new file mode 100644
index 000000000..ea1fb4d07
--- /dev/null
+++ b/xs/src/libnest2d/tools/nfp_svgnest_glue.hpp
@@ -0,0 +1,75 @@
+#ifndef NFP_SVGNEST_GLUE_HPP
+#define NFP_SVGNEST_GLUE_HPP
+
+#include "nfp_svgnest.hpp"
+
+#include <libnest2d/clipper_backend/clipper_backend.hpp>
+
+namespace libnest2d {
+
+namespace __svgnest {
+
+//template<> struct _Tol<double> {
+// static const BP2D_CONSTEXPR TCoord<PointImpl> Value = 1000000;
+//};
+
+}
+
+namespace nfp {
+
+using NfpR = NfpResult<PolygonImpl>;
+
+template<> struct NfpImpl<PolygonImpl, NfpLevel::CONVEX_ONLY> {
+ NfpR operator()(const PolygonImpl& sh, const PolygonImpl& cother) {
+// return nfpConvexOnly(sh, cother);
+ namespace sl = shapelike;
+ using alg = __svgnest::_alg<PolygonImpl>;
+
+ auto nfp_p = alg::noFitPolygon(sl::getContour(sh),
+ sl::getContour(cother), false, false);
+
+ PolygonImpl nfp_cntr;
+ if(!nfp_p.empty()) nfp_cntr.Contour = nfp_p.front();
+ return {nfp_cntr, referenceVertex(nfp_cntr)};
+ }
+};
+
+template<> struct NfpImpl<PolygonImpl, NfpLevel::ONE_CONVEX> {
+ NfpR operator()(const PolygonImpl& sh, const PolygonImpl& cother) {
+// return nfpConvexOnly(sh, cother);
+ namespace sl = shapelike;
+ using alg = __svgnest::_alg<PolygonImpl>;
+
+ std::cout << "Itt vagyok" << std::endl;
+ auto nfp_p = alg::noFitPolygon(sl::getContour(sh),
+ sl::getContour(cother), false, false);
+
+ PolygonImpl nfp_cntr;
+ nfp_cntr.Contour = nfp_p.front();
+ return {nfp_cntr, referenceVertex(nfp_cntr)};
+ }
+};
+
+template<>
+struct NfpImpl<PolygonImpl, NfpLevel::BOTH_CONCAVE> {
+ NfpR operator()(const PolygonImpl& sh, const PolygonImpl& cother) {
+ namespace sl = shapelike;
+ using alg = __svgnest::_alg<PolygonImpl>;
+
+ auto nfp_p = alg::noFitPolygon(sl::getContour(sh),
+ sl::getContour(cother), true, false);
+
+ PolygonImpl nfp_cntr;
+ nfp_cntr.Contour = nfp_p.front();
+ return {nfp_cntr, referenceVertex(nfp_cntr)};
+ }
+};
+
+template<> struct MaxNfpLevel<PolygonImpl> {
+// static const BP2D_CONSTEXPR NfpLevel value = NfpLevel::BOTH_CONCAVE;
+ static const BP2D_CONSTEXPR NfpLevel value = NfpLevel::CONVEX_ONLY;
+};
+
+}}
+
+#endif // NFP_SVGNEST_GLUE_HPP
diff --git a/xs/src/libnest2d/tools/svgtools.hpp b/xs/src/libnest2d/tools/svgtools.hpp
new file mode 100644
index 000000000..776dd5a1a
--- /dev/null
+++ b/xs/src/libnest2d/tools/svgtools.hpp
@@ -0,0 +1,122 @@
+#ifndef SVGTOOLS_HPP
+#define SVGTOOLS_HPP
+
+#include <iostream>
+#include <fstream>
+#include <string>
+
+#include <libnest2d/libnest2d.hpp>
+
+namespace libnest2d { namespace svg {
+
+template<class RawShape>
+class SVGWriter {
+ using Item = _Item<RawShape>;
+ using Coord = TCoord<TPoint<RawShape>>;
+ using Box = _Box<TPoint<RawShape>>;
+ using PackGroup = _PackGroup<RawShape>;
+
+public:
+
+ enum OrigoLocation {
+ TOPLEFT,
+ BOTTOMLEFT
+ };
+
+ struct Config {
+ OrigoLocation origo_location;
+ Coord mm_in_coord_units;
+ double width, height;
+ Config():
+ origo_location(BOTTOMLEFT), mm_in_coord_units(1000000),
+ width(500), height(500) {}
+
+ };
+
+private:
+ Config conf_;
+ std::vector<std::string> svg_layers_;
+ bool finished_ = false;
+public:
+
+ SVGWriter(const Config& conf = Config()):
+ conf_(conf) {}
+
+ void setSize(const Box& box) {
+ conf_.height = static_cast<double>(box.height()) /
+ conf_.mm_in_coord_units;
+ conf_.width = static_cast<double>(box.width()) /
+ conf_.mm_in_coord_units;
+ }
+
+ void writeItem(const Item& item) {
+ if(svg_layers_.empty()) addLayer();
+ auto tsh = item.transformedShape();
+ if(conf_.origo_location == BOTTOMLEFT) {
+ auto d = static_cast<Coord>(
+ std::round(conf_.height*conf_.mm_in_coord_units) );
+
+ auto& contour = shapelike::getContour(tsh);
+ for(auto& v : contour) setY(v, -getY(v) + d);
+
+ auto& holes = shapelike::holes(tsh);
+ for(auto& h : holes) for(auto& v : h) setY(v, -getY(v) + d);
+
+ }
+ currentLayer() += shapelike::serialize<Formats::SVG>(tsh,
+ 1.0/conf_.mm_in_coord_units) + "\n";
+ }
+
+ void writePackGroup(const PackGroup& result) {
+ for(auto r : result) {
+ addLayer();
+ for(Item& sh : r) {
+ writeItem(sh);
+ }
+ finishLayer();
+ }
+ }
+
+ void addLayer() {
+ svg_layers_.emplace_back(header());
+ finished_ = false;
+ }
+
+ void finishLayer() {
+ currentLayer() += "\n</svg>\n";
+ finished_ = true;
+ }
+
+ void save(const std::string& filepath) {
+ size_t lyrc = svg_layers_.size() > 1? 1 : 0;
+ size_t last = svg_layers_.size() > 1? svg_layers_.size() : 0;
+
+ for(auto& lyr : svg_layers_) {
+ std::fstream out(filepath + (lyrc > 0? std::to_string(lyrc) : "") +
+ ".svg", std::fstream::out);
+ if(out.is_open()) out << lyr;
+ if(lyrc == last && !finished_) out << "\n</svg>\n";
+ out.flush(); out.close(); lyrc++;
+ };
+ }
+
+private:
+
+ std::string& currentLayer() { return svg_layers_.back(); }
+
+ const std::string header() const {
+ std::string svg_header =
+R"raw(<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
+<svg height=")raw";
+ svg_header += std::to_string(conf_.height) + "\" width=\"" + std::to_string(conf_.width) + "\" ";
+ svg_header += R"raw(xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">)raw";
+ return svg_header;
+ }
+
+};
+
+}
+}
+
+#endif // SVGTOOLS_HPP