aboutsummaryrefslogtreecommitdiff
path: root/svg-flatten/src/svg_geom.cpp
blob: da9d78dcfb40a7e58b7a780c10b434cd31d37066 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/*
 * This file is part of gerbolyze, a vector image preprocessing toolchain 
 * Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include "svg_geom.h"

#include <cmath>
#include <string>
#include <iostream>
#include <sstream>
#include <queue>
#include <assert.h>
#include "svg_import_defs.h"

using namespace ClipperLib;
using namespace std;

/* Get bounding box of a Clipper Paths */
IntRect gerbolyze::get_paths_bounds(const Paths &paths) {
    if (paths.empty()) {
        return {0, 0, 0, 0};
    }

    if (paths[0].empty()) {
        return {0, 0, 0, 0};
    }

    IntPoint p0 = paths[0][0];
    cInt x0=p0.X, y0=p0.Y, x1=p0.X, y1=p0.Y;

    for (const Path &p : paths) {
        for (const IntPoint ip : p) {
            if (ip.X < x0)
                x0 = ip.X;

            if (ip.Y < y0)
                y0 = ip.Y;

            if (ip.X > x1)
                x1 = ip.X;

            if (ip.Y > y1)
                y1 = ip.Y;
        }
    }

    return {x0, y0, x1, y1};
}

enum ClipperLib::PolyFillType gerbolyze::clipper_fill_rule(const pugi::xml_node &node) {
    string val(node.attribute("fill-rule").value());
    if (val == "evenodd")
        return ClipperLib::pftEvenOdd;
    else
        return ClipperLib::pftNonZero; /* default */
}

enum ClipperLib::EndType gerbolyze::clipper_end_type(const pugi::xml_node &node) {
    string val(node.attribute("stroke-linecap").value());
    if (val == "round")
        return ClipperLib::etOpenRound;

    if (val == "square")
        return ClipperLib::etOpenSquare;

    return ClipperLib::etOpenButt;
}

enum ClipperLib::JoinType gerbolyze::clipper_join_type(const pugi::xml_node &node) {
    string val(node.attribute("stroke-linejoin").value());
    if (val == "round")
        return ClipperLib::jtRound;

    if (val == "bevel")
        return ClipperLib::jtSquare;

    return ClipperLib::jtMiter;
}

/* Some debugging helpers */
static double toplevel_winding_direction(PolyNode &ptree) {
    double sum = 0.0;
    size_t sz = ptree.Contour.size();
    for (size_t i=0; i<sz; i++) {
        size_t j = (i+1) % sz;
        double x1 = ptree.Contour[i].X, y1 = ptree.Contour[i].Y;
        double x2 = ptree.Contour[j].X, y2 = ptree.Contour[j].Y;
        sum += (x2-x1)*(y2+y1);
    }
    return sum;
}

static void dump_ptree(PolyNode &ptree) {
    /* dumps node count, winding direction and tree structure */
    double sum = toplevel_winding_direction(ptree);
    char sign = '.';
    if (sum > 0) {
        sign = '+';
    } else if (sum < 0) {
        sign = '-';
    }

    cerr << sign << ptree.Contour.size() <<  "[";
    for (size_t i=0; i<ptree.ChildCount(); i++) {
        if (i > 0) {
            cerr << ",";
        }
        dump_ptree(*ptree.Childs[i]);
    }
    cerr << "]";
}

static void dump_clipper2svg(Path &path, string stroke) {
    /* dumps the ptree to SVG */
    /* use together with
            cerr << "<svg width=\"200\" height=\"200\" xmlns=\"http://www.w3.org/2000/svg\">" << endl;
            ...
            dump_clipper2svg(...); // can be used multiple times
            ...
            cerr << "</svg>" << endl;
    */

    size_t sz = path.size();
    if (sz == 0) {
        return;
    }

    cerr << "<path fill=\"" << stroke << "\" d=\"M ";
    for (size_t i=0; i<sz; i++) {
        if (i>0) {
            cerr << " L ";
        }
        cerr << (path[i].X / 1e7) << ", " << (path[i].Y / 1e7);
    }
    cerr << " Z\"/>" << endl;
}

static void dehole_polytree_worker(PolyNode &ptree, Paths &out, queue<PolyTree> &todo) {
    for (int i=0; i<ptree.ChildCount(); i++) {
        PolyNode *nod = ptree.Childs[i];
        assert(nod);
        assert(!nod->IsHole());

        /* First, recursively process inner polygons. */
        for (int j=0; j<nod->ChildCount(); j++) {
            PolyNode *child = nod->Childs[j];
            assert(child);
            assert(child->IsHole());

            if (child->ChildCount() > 0) {
                dehole_polytree_worker(*child, out, todo);
            }
        }

        if (nod->ChildCount() == 0) {
            out.push_back(nod->Contour);

        } else {
            /* Do not add children's children, those were handled in the recursive call above */
            Clipper c;
            c.AddPath(nod->Contour, ptSubject, /* closed= */ true);
            for (int k=0; k<nod->ChildCount(); k++) {
                c.AddPath(nod->Childs[k]->Contour, ptSubject, /* closed= */ true);
            }

            /* Find a viable cut: Cut from top-left bounding box corner, through two subsequent points on the hole
             * outline and to top-right bbox corner. */
            IntRect bbox = c.GetBounds();

            /* Clipper might return a polygon with a zero-length, or an exactly vertical outline segment. We iterate
             * until we find a point that has a different X coordinate than our starting point. If we can't find one
             * because the polygon only consists only of points on a vertical line, we can safely discard it and do
             * nothing since it has zero area anyway. */
            for (size_t i=1; i<nod->Childs[0]->Contour.size(); i++) {
                if (nod->Childs[0]->Contour[i].X == nod->Childs[0]->Contour[i-1].X) {
                    continue;
                }

                /* We now have found that Contour[i-1] - Contour[i] has a non-zero horizontal component, and is a
                 * candidate for our cut. However, we have to make sure that the first point is left (lower X
                 * coordinate) of the second point, or the cutting polygon we create here would have a
                 * self-intersection, which with high likelihood would lead to a new hole being created when cutting.
                 */
                int a=i-1, b=i;
                if (nod->Childs[0]->Contour[i].X < nod->Childs[0]->Contour[i-1].X) {
                    /* Swap points */
                    a = i;
                    b = i-1;
                }
                Path tri = { { bbox.left, bbox.top }, nod->Childs[0]->Contour[a], nod->Childs[0]->Contour[b], { bbox.right, bbox.top } };
                c.AddPath(tri, ptClip, true);

                /* Execute twice, once for intersection fragment and once for difference fragment. Note that this will yield
                 * at least two, but possibly more polygons. */
                c.StrictlySimple(true);
                c.Execute(ctDifference, todo.emplace(), pftNonZero);
                c.Execute(ctIntersection, todo.emplace(), pftNonZero);
                break;
            }
        }
    }
}

/* Take a Clipper polytree, i.e. a description of a set of polygons, their holes and their inner polygons, and remove
 * all holes from it. We remove holes by splitting each polygon that has a hole into two or more pieces so that the hole
 * is no more. These pieces perfectly fit each other so there is no visual or functional difference.
 */
void gerbolyze::dehole_polytree(PolyTree &ptree, Paths &out) {
    queue<PolyTree> todo;
    dehole_polytree_worker(ptree, out, todo);
    while (!todo.empty()) {
        dehole_polytree_worker(todo.front(), out, todo);
        todo.pop();
    }
}