File: Triangulator.cpp

package info (click to toggle)
psurface 2.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster, stretch
  • size: 1,088 kB
  • ctags: 1,113
  • sloc: cpp: 12,339; makefile: 111; awk: 38
file content (375 lines) | stat: -rw-r--r-- 13,026 bytes parent folder | download | duplicates (3)
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#include "config.h"

#include "Triangulator.h"
#include "PSurface.h"
#include "QualityRequest.h"
#include "HxParamToolBox.h"
#include "CircularPatch.h"



#ifdef _WIN32
inline int isnan(double x) {return _isnan(x);}
#endif

using namespace psurface;

signed char Triangulator::orientation(const StaticVector<float,2>& a, const StaticVector<float,2>& b, const StaticVector<float,2>& c, const float eps)
{

    float det = a[0] * (b[1]-c[1]) - b[0] * (a[1] - c[1]) + c[0] * (a[1] - b[1]);

    if (det>eps)
        return 1;
    else if (det<-eps)
        return -1;

    return 0;

}

void Triangulator::triangulateStar(const std::vector<int> &border, int center,
                                   CircularPatch<float>& resultPatch,
                                   std::vector<StaticVector<float,2> >& flatBorder,
                                   PSurface<2,float>* par)
{
    /////////////////////////////////////
    // computes the flattened coordinates
    ParamToolBox::flattenStar(center, border, flatBorder, par);

    for (size_t j=0; j<flatBorder.size(); j++)
        assert(!isnan(flatBorder[j][0]) &&!isnan(flatBorder[j][1]));

    ///////////////////////////////////////////
    // do a constrained Delaunay triangulation
    planeCDT(flatBorder, border, resultPatch, par);

}

void Triangulator::estimateStarError(const std::vector<int> &border, int center,
                                     const QualityRequest &quality, const std::vector<int> &fullStar,
                                     VertexHeap::ErrorValue& qualityValue,
                                     MultiDimOctree<Edge, EdgeIntersectionFunctor, float, 3>& edgeOctree,
                                     PSurface<2,float>* par)
{
    /////////////////////////////////////
    // computes the flattened coordinates
    std::vector<StaticVector<float,2> > flatBorder;

    ParamToolBox::flattenStar(center, border, flatBorder, par);

    for (size_t j=0; j<flatBorder.size(); j++)
        assert(!isnan(flatBorder[j][0]) &&!isnan(flatBorder[j][1]));

    ///////////////////////////////////////////
    // do a constrained Delaunay triangulation
    CircularPatch<float> resultPatch(border.size()-2, par);

    planeCDT(flatBorder, border, resultPatch, par);

    //////////////////////////////////////////
    // evaluate triangulation,
    evaluate(&resultPatch, center, quality, qualityValue, fullStar, edgeOctree, par);

    resultPatch.killAll();

}

// same thing for a half star
void Triangulator::triangulateHalfStar(const std::vector<int> &border, int center,
                                       CircularPatch<float>& resultPatch, std::vector<StaticVector<float,2> >& flatBorder,
                                       PSurface<2,float>* par)
{
    /////////////////////////////////////
    // computes the flattened coordinates
    ParamToolBox::flattenHalfStar(center, border, flatBorder, par);


    ///////////////////////////////////////////
    // do a constrained Delaunay triangulation

    planeCDT(flatBorder, border, resultPatch, par);
}


// same thing for a half star
void Triangulator::estimateHalfStarError(const std::vector<int> &border, int center,
                                         const QualityRequest &quality, const std::vector<int> &fullStar,
                                         VertexHeap::ErrorValue& qualityValue,
                                         MultiDimOctree<Edge, EdgeIntersectionFunctor, float, 3>& edgeOctree,
                                         PSurface<2,float>* par)
{
    /////////////////////////////////////
    // computes the flattened coordinates

    std::vector<StaticVector<float,2> > flatBorder;
    ParamToolBox::flattenHalfStar(center, border, flatBorder, par);


    ///////////////////////////////////////////
    // do a constrained Delaunay triangulation

    CircularPatch<float> resultPatch(border.size()-2, par);
    planeCDT(flatBorder, border, resultPatch, par);


    //////////////////////////////////////////
    // evaluate triangulation
    evaluate(&resultPatch, center, quality, qualityValue, fullStar, edgeOctree, par);

    resultPatch.killAll();

}



////////////////////////////////////////////////////////////////////////////
// the plane Delaunay triangulation of a plane star-shaped polygon
void Triangulator::planeCDT(const std::vector<StaticVector<float,2> >& flatBorder, const std::vector<int>& border,
                            CircularPatch<float>& result, PSurface<2,float>* par)
{

    int K = border.size();

    if (K==3){
        result[0] = par->createSpaceForTriangle(border[0], border[1], border[2]);
        return;
    }

    const signed char counterclockwise = 1;

    int k = 0;
    int idx = 0;
    int edgeIdx = 0;

    std::vector<int> tmpVertices   = border;
    std::vector<StaticVector<float,2> > tmpCoords   = flatBorder;

    while (K>4){

        int bestEdge = -1;
        int bestDelaunayEdge = -1;

        float bestAspectRatio = std::numeric_limits<float>::max();
        float bestDelaunayAspectRatio = std::numeric_limits<float>::max();

        ////////////////////////////////////////
        // look for best edge
        for (k=0; k<K; k++) {

            if (orientation(tmpCoords[k%K], tmpCoords[(k+1)%K], tmpCoords[(k+2)%K])==counterclockwise) {

                const float aspectRatio = computeAspectRatio(par->vertices(tmpVertices[k%K]),
                                                             par->vertices(tmpVertices[(k+1)%K]),
                                                             par->vertices(tmpVertices[(k+2)%K]));

                if (aspectRatio<bestAspectRatio) {
                    bestAspectRatio = aspectRatio;
                    bestEdge = k;
                }

                if (isLegalEdge(tmpCoords[k%K], tmpCoords[(k+1)%K], tmpCoords[(k+2)%K], flatBorder) &&
                    aspectRatio<bestDelaunayAspectRatio) {
                    bestDelaunayAspectRatio = aspectRatio;
                    bestDelaunayEdge = k;
                }
            }
        }

        assert(bestEdge!=-1);


        // /////////////////////////////////////
        // cut off that edge

        const int chosenEdge = (bestDelaunayEdge!=-1) ? bestDelaunayEdge : bestEdge;

        result[idx++] = par->createSpaceForTriangle(tmpVertices[chosenEdge%K],
                                                    tmpVertices[(chosenEdge+1)%K],
                                                    tmpVertices[(chosenEdge+2)%K]);

        result.innerEdges[edgeIdx][0] = tmpVertices[chosenEdge%K];
        result.innerEdges[edgeIdx][1] = tmpVertices[(chosenEdge+2)%K];
        edgeIdx++;
        tmpVertices.erase(tmpVertices.begin()+((chosenEdge+1)%K));
        tmpCoords.erase(tmpCoords.begin()+((chosenEdge+1)%K));
        K--;

    }

    // /////////////////////////////////////
    // the case K=4
    // choose the triangulation which yields the lowest max aspect ratio
    const float aRa1 = computeAspectRatio(par->vertices(tmpVertices[0]),
                                          par->vertices(tmpVertices[1]),
                                          par->vertices(tmpVertices[2]));
    const float aRa2 = computeAspectRatio(par->vertices(tmpVertices[2]),
                                          par->vertices(tmpVertices[3]),
                                          par->vertices(tmpVertices[0]));

    const float aRb1 = computeAspectRatio(par->vertices(tmpVertices[1]),
                                          par->vertices(tmpVertices[2]),
                                          par->vertices(tmpVertices[3]));
    const float aRb2 = computeAspectRatio(par->vertices(tmpVertices[3]),
                                          par->vertices(tmpVertices[0]),
                                          par->vertices(tmpVertices[1]));

    const float maxA = (aRa1>aRa2) ? aRa1 : aRa2;
    const float maxB = (aRb1>aRb2) ? aRb1 : aRb2;

    if (maxA<maxB)  {
        result[idx++] = par->createSpaceForTriangle(tmpVertices[0], tmpVertices[1], tmpVertices[2]);
        result[idx++] = par->createSpaceForTriangle(tmpVertices[2], tmpVertices[3], tmpVertices[0]);
        result.innerEdges[edgeIdx][0] = tmpVertices[0];
        result.innerEdges[edgeIdx][1] = tmpVertices[2];
    } else {
        result[idx++] = par->createSpaceForTriangle(tmpVertices[1], tmpVertices[2], tmpVertices[3]);
        result[idx++] = par->createSpaceForTriangle(tmpVertices[3], tmpVertices[0], tmpVertices[1]);
        result.innerEdges[edgeIdx][0] = tmpVertices[1];
        result.innerEdges[edgeIdx][1] = tmpVertices[3];
    }

}


bool Triangulator::isLegalEdge(const StaticVector<float,2>& a, const StaticVector<float,2>& b, const StaticVector<float,2>& c,
                               const std::vector<StaticVector<float,2> > &polygon)
{
    //compute the circumcirle of the points a, b, c
    // code taken from 'GraphicsGems I'
    double d1 = (c - a).dot(b - a);
    double d2 = (c - b).dot(a - b);
    double d3 = (a - c).dot(b - c);
    double c1 = d2*d3, c2 = d3*d1, c3 = d1*d2;
    double c123 = c1 + c2 + c3;

    // test for degeneracy

    if (c123==0) return false;

    float radius = 0.5*sqrt((d1+d2) * (d2+d3) * (d3+d1)/c123);

    if (std::isnan(radius))
        return false;

    StaticVector<float,2> center = ((c2+c3)*a + (c3+c1)*b + (c1+c2)*c)/(2*c123);

    for (size_t i=0; i<polygon.size(); i++)
        if (polygon[i]!=a && polygon[i]!=b && polygon[i]!=c &&
            (polygon[i]-center).length()<radius)
            return false;

    return true;
}


void Triangulator::evaluate(const CircularPatch<float>* cP, int removedVertex,
                            const QualityRequest &quality, VertexHeap::ErrorValue& error,
                            const std::vector<int> &fullStar,
                            MultiDimOctree<Edge, EdgeIntersectionFunctor, float, 3>& edgeOctree,
                            const PSurface<2,float>* par)
{
    error.unblock();

    for (int i=0; i<cP->size(); i++)
        for (int j=0; j<3; j++)
            assert( par->triangles((*cP)[i]).vertices[j] != -1);

    std::vector<int> closeEdges(0);

    if (quality.intersections){

        // get close edges that might intersect the new patch
        Box<float,3> resultBox;
        cP->getBoundingBox(resultBox);

        std::vector<Edge*> tmpCloseEdges;
        edgeOctree.lookup(resultBox, tmpCloseEdges);

        for (size_t i=0; i<tmpCloseEdges.size(); i++) {

            if (tmpCloseEdges[i]->isConnectedTo(removedVertex))
                continue;

            int newEdge = tmpCloseEdges[i] - &par->edges(0);

            if (std::find(closeEdges.begin(), closeEdges.end(), newEdge)==closeEdges.end())
                closeEdges.push_back(newEdge);

        }

        if (cP->intersectsParametrization(closeEdges) || cP->hasSelfintersections()){
            error.block();
            return;
        }

    }

    if (quality.maxEdgeLength>=0) {

        for (size_t i=0; i<cP->innerEdges.size(); i++)
            if ( (par->vertices(cP->innerEdges[i][0]) - par->vertices(cP->innerEdges[i][1])).length() > quality.maxEdgeLength){
                error.block();
                return;
            }

    }

    if (cP->inducesTopologyChange()){
        //printf("Induces TopChange\n");
        error.block();
        return;
    }

    // compute the Hausdorff distance
    float HausdorffDistance=0;
    if (quality.hausdorffDistance > 0.01) {
        //printf("ev 13\n");
        int nNodes = 0;

        for (size_t i=0; i<fullStar.size(); i++){

            const DomainTriangle<float>& cT = par->triangles(fullStar[i]);

            for (size_t cN=0; cN<cT.nodes.size(); cN++) {
                //printf("ev 13.3\n");
                if (cT.nodes[cN].isINTERIOR_NODE() ||
                    cT.nodes[cN].isTOUCHING_NODE()){
                    //printf("ev 13.4\n");
                    nNodes++;

                    HausdorffDistance += cP->distanceTo(par->imagePos(fullStar[i], cN));
                    //printf("ev 13.5\n");
                }
            }
        }

        HausdorffDistance += cP->distanceTo(par->vertices(removedVertex));
        HausdorffDistance /= nNodes+1;
    }
    //printf("ev 14\n");
    float aspectRatioImprovement =  0;

    if (quality.aspectRatio > 0.01) {
        //printf("ev 15\n");
        // compute max aspect ratio of the star at the vertex
        float oldMaxAspectRatio = 0;
        for (size_t i=0; i<fullStar.size(); i++){
            const float thisAspectRatio = par->aspectRatio(fullStar[i]);
            if (thisAspectRatio>oldMaxAspectRatio)
                oldMaxAspectRatio = thisAspectRatio;
        }

        // compute max aspect ratio of retriangulation
        const float newMaxAspectRatio = cP->maxAspectRatio();
        aspectRatioImprovement = newMaxAspectRatio - oldMaxAspectRatio;
    }

    error.unblock();
    error.value   = HausdorffDistance*quality.hausdorffDistance + (aspectRatioImprovement)*quality.aspectRatio;
    //printf("ev 16\n");
    return;
}