Subversion Repositories gelsvn

Rev

Rev 631 | Rev 636 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
595 jab 1
/* ----------------------------------------------------------------------- *
2
 * This file is part of GEL, http://www.imm.dtu.dk/GEL
3
 * Copyright (C) the authors and DTU Informatics
4
 * For license and list of authors, see ../../doc/intro.pdf
5
 * ----------------------------------------------------------------------- */
561 awk 6
#include <iterator>
39 bj 7
#include "Manifold.h"
8
 
595 jab 9
#include <iostream>
10
#include <vector>
11
#include <map>
12
#include <iterator>
39 bj 13
 
601 jab 14
#include "../Geometry/TriMesh.h"
595 jab 15
 
39 bj 16
namespace HMesh
17
{
336 jab 18
 
595 jab 19
    using namespace std;
20
    using namespace Geometry;
21
    using namespace CGLA;
178 bj 22
 
595 jab 23
    namespace
24
    {
25
        /************************************************************
26
		 * Edgekeys and Edges for halfedge identification during build
27
		 ************************************************************/
28
        class EdgeKey
29
        {
30
        public:
31
            EdgeKey(VertexID va, VertexID vb)
32
            {
33
                if(va < vb){
34
                    v0 = va;
35
                    v1 = vb;
36
                }
37
                else{
38
                    v0 = vb;
39
                    v1 = va;
40
                }
41
            }
42
 
43
            bool operator<(const EdgeKey& k2) const
44
            {
45
                if(v0 < k2.v0){
46
                    return true;
47
                }
48
                else if( k2.v0 < v0){
49
                    return false;
50
                }
51
                else{
52
                    return v1 < k2.v1;
53
                }
54
            }
55
        private:
56
            VertexID v0;
57
            VertexID v1;
58
        };
336 jab 59
 
595 jab 60
        struct Edge
61
        {
62
            HalfEdgeID h0;
63
            HalfEdgeID h1;
64
            int count;
65
            Edge() : count(0){}
66
        };
67
    }
336 jab 68
 
595 jab 69
    /*********************************************
70
	 * Public functions
71
	 *********************************************/
72
    void Manifold::build(const TriMesh& mesh)
73
    {
74
        // A vector of 3's - used to tell build how many indices each face consists of
75
        vector<int> faces(mesh.geometry.no_faces(), 3);
336 jab 76
 
595 jab 77
        build_template( static_cast<size_t>(mesh.geometry.no_vertices()),
78
					   reinterpret_cast<const float*>(&mesh.geometry.vertex(0)),
79
					   static_cast<size_t>(faces.size()),
80
					   static_cast<const int*>(&faces[0]),
81
					   reinterpret_cast<const int*>(&mesh.geometry.face(0)));
82
    }
83
 
84
    void Manifold::build(   size_t no_vertices,
85
						 const float* vertvec,
86
						 size_t no_faces,
87
						 const int* facevec,
88
						 const int* indices)
89
    {
90
        build_template(no_vertices, vertvec, no_faces, facevec, indices);
91
    }
92
 
93
    void Manifold::build(   size_t no_vertices,
94
						 const double* vertvec,
95
						 size_t no_faces,
96
						 const int* facevec,
97
						 const int* indices)
98
    {
99
        build_template(no_vertices, vertvec, no_faces, facevec, indices);
100
    }
101
 
102
    FaceID Manifold::add_face(std::vector<Manifold::Vec> points)
103
    {
104
        int F = points.size();
105
        vector<int> indices;
605 jab 106
        for(size_t i=0;i<points.size(); ++i)
595 jab 107
            indices.push_back(i);
108
        FaceID fid = *faces_end();
109
        build(points.size(), reinterpret_cast<double*>(&points[0]), 1, &F, &indices[0]);
110
        return fid;
111
    }
112
 
600 jab 113
    bool Manifold::remove_face(FaceID fid)
114
    {
115
        if(!in_use(fid))
116
            return false;
117
 
118
        HalfEdgeID he = kernel.last(fid);
119
        HalfEdgeID last = he;
120
 
121
        vector<HalfEdgeID> halfedges;
122
        do
123
        {
124
            halfedges.push_back(he);
125
            kernel.set_face(he, InvalidFaceID);
126
            he = kernel.next(he);
127
        }
128
        while(he != last);
129
 
130
        vector<HalfEdgeID> halfedges_garbage;
131
        vector<VertexID> vertices_garbage;
605 jab 132
        for(size_t i=0;i<halfedges.size(); ++i)
600 jab 133
        {
134
            HalfEdgeID h = halfedges[i];
135
            HalfEdgeID hopp = kernel.opp(h);
136
            if(kernel.face(hopp) == InvalidFaceID)
137
            {
138
                halfedges_garbage.push_back(h);
139
                VertexID v0 = kernel.vert(hopp);
140
                if(valency(*this, v0) <= 2 )
141
                    vertices_garbage.push_back(v0);
142
                else {
143
                    link(kernel.prev(h), kernel.next(hopp));
144
                    kernel.set_out(v0, kernel.opp(kernel.prev(h)));
145
                }
146
                VertexID v1 = kernel.vert(h);
147
                if(valency(*this, v1)>2)
148
                {
149
                    link(kernel.prev(hopp),kernel.next(h));
150
                    kernel.set_out(v1, kernel.opp(kernel.prev(hopp)));
151
                }
152
 
153
            }
154
        }
605 jab 155
        for(size_t i=0;i<halfedges_garbage.size();++i){
600 jab 156
            kernel.remove_halfedge(kernel.opp(halfedges_garbage[i]));
157
            kernel.remove_halfedge(halfedges_garbage[i]);
158
        }
605 jab 159
        for(size_t i=0;i<vertices_garbage.size(); ++i)
600 jab 160
            kernel.remove_vertex(vertices_garbage[i]);
161
 
162
        kernel.remove_face(fid);
163
        return true;
164
    }
165
 
595 jab 166
 
600 jab 167
    bool Manifold::remove_edge(HalfEdgeID hid)
168
    {
169
        if(!in_use(hid))
170
            return false;
171
 
172
        FaceID f0 = kernel.face(hid);
173
        FaceID f1 = kernel.face(kernel.opp(hid));
174
 
175
        remove_face(f0);
176
        remove_face(f1);
177
 
178
        return true;
179
    }
180
 
595 jab 181
 
600 jab 182
 
183
    bool Manifold::remove_vertex(VertexID vid)
184
    {
185
        if(!in_use(vid))
186
            return false;
187
 
188
        vector<FaceID> faces;
189
 
633 janba 190
        int N = circulate_vertex_ccw(*this, vid, [&](FaceID f) {
191
            faces.push_back(f);
192
        });
193
        for(size_t i=0;i<N;++i)
600 jab 194
            remove_face(faces[i]);
195
 
196
        return true;
197
    }
198
 
199
 
336 jab 200
 
595 jab 201
    void Manifold::collapse_edge(HalfEdgeID h, bool avg_vertices)
202
    {
203
        HalfEdgeID ho = kernel.opp(h);
204
        VertexID hv = kernel.vert(h);
205
        VertexID hov = kernel.vert(ho);
206
        HalfEdgeID hn = kernel.next(h);
207
        HalfEdgeID hp = kernel.prev(h);
208
        HalfEdgeID hon = kernel.next(ho);
209
        HalfEdgeID hop = kernel.prev(ho);
210
		FaceID f = kernel.face(h);
211
		FaceID fo = kernel.face(ho);
336 jab 212
 
595 jab 213
        // average the vertex positions
214
        pos(hv) = avg_vertices ? (0.5f * (pos(hov) + pos(hv))) : pos(hv);
336 jab 215
 
595 jab 216
        // update all halfedges pointing to hov to point to hv, effectively removing hov from all loops
217
        HalfEdgeID he = kernel.out(hov);
218
        HalfEdgeID last = he;
219
		do {
220
			assert(kernel.vert(kernel.opp(he)) == hov);
221
            kernel.set_vert(kernel.opp(he), hv);
222
            he = kernel.next(kernel.opp(he));
223
        }
224
		while(he != last);
225
        kernel.set_out(hv, hn);
336 jab 226
 
595 jab 227
        // link hp and hn, effectively removing h from opposite loop
228
        link(hp, hn);
229
        // make face owning h own hn instead
230
        if(kernel.face(h) != InvalidFaceID)
231
            kernel.set_last(f, hn);
336 jab 232
 
595 jab 233
        // link hop and hon, effectively removing h from opposite face loop
234
        link(hop, hon);
235
        // make opposite face owning h own hon instead
236
        if(kernel.face(ho) != InvalidFaceID)
237
            kernel.set_last(fo, hon);
336 jab 238
 
595 jab 239
        // remove the obsolete entities
240
        kernel.remove_vertex(hov);
241
        kernel.remove_halfedge(h);
242
        kernel.remove_halfedge(ho);
336 jab 243
 
595 jab 244
        // verify that remaining faces haven't become degenerate because of collapse
245
        remove_face_if_degenerate(hn);
246
        remove_face_if_degenerate(hon);
336 jab 247
 
595 jab 248
        // verify that v is sane after collapse
249
        ensure_boundary_consistency(hv);
250
    }
336 jab 251
 
595 jab 252
    FaceID Manifold::split_face_by_edge(FaceID f, VertexID v0, VertexID v1)
253
    {
254
		assert(!connected(*this, v0, v1));
255
        HalfEdgeID he = kernel.last(f);
256
        HalfEdgeID last = he;
257
        int steps = 0;
258
        while(he != last || steps == 0){
259
            ++steps;
260
            he = kernel.next(he);
261
        }
336 jab 262
 
595 jab 263
        // make sure this is not a triangle
264
        assert(steps > 3);
265
        // make sure we are not trying to connect a vertex to itself
266
        assert(v0 != v1);
336 jab 267
 
595 jab 268
		HalfEdgeID h0 = kernel.out(v0);
269
		for(Walker w = walker(v0); !w.full_circle(); w = w.circulate_vertex_cw()){
270
			if(w.face() == f){
271
				h0 = w.halfedge();
272
				break;
39 bj 273
			}
336 jab 274
		}
595 jab 275
		assert(kernel.face(h0) != InvalidFaceID);
276
        assert(kernel.face(h0) == f);
336 jab 277
 
595 jab 278
        // the halfedge belonging to f, going out from v0, is denoted h. Move along h until we hit v1.
279
        // now we have the halfedge which belongs to f and points to v1.
280
        HalfEdgeID h = h0;
281
        while(kernel.vert(h) != v1){
282
            h = kernel.next(h);
283
        }
284
        assert(h != h0);
336 jab 285
 
595 jab 286
        // create a new halfedge ha which connects v1 and v0 closing the first loop.
287
        HalfEdgeID h1 = kernel.next(h);
288
        HalfEdgeID ha = kernel.add_halfedge();
289
        link(h, ha);
290
        link(ha, h0);
291
        kernel.set_face(ha, f);
292
        kernel.set_vert(ha, v0);
293
        kernel.set_last(f, ha);
336 jab 294
 
595 jab 295
        // create a new face, f2, and set all halfedges in the remaining part of the polygon to point to this face.
296
        h = h1;
297
        FaceID f2 = kernel.add_face();
298
        while(kernel.vert(h) != v0){
299
            kernel.set_face(h, f2);
300
            h = kernel.next(h);
301
        }
302
        kernel.set_face(h, f2);
303
        assert(h != h1);
336 jab 304
 
595 jab 305
        // create a new halfedge hb to connect v0 and v1.
306
        HalfEdgeID hb = kernel.add_halfedge();
307
        link(h, hb);
308
        link(hb, h1);
309
        kernel.set_face(hb, f2);
310
        kernel.set_vert(hb, v1);
311
        kernel.set_last(f2, hb);
336 jab 312
 
595 jab 313
        // complete the operation by gluing the two new halfedges
314
        glue(ha, hb);
336 jab 315
 
595 jab 316
        // assert sanity of operation
317
        assert(kernel.next(kernel.opp(kernel.prev(h1))) == h0);
318
        assert(kernel.next(kernel.opp(kernel.prev(h0))) == h1);
319
        assert(kernel.face(kernel.next(hb)) == f2);
320
        assert(kernel.face(kernel.next(kernel.next(hb))) == f2);
321
        assert(kernel.face(hb) == f2);
336 jab 322
 
595 jab 323
        // return handle to newly created face
324
        return f2;
325
    }
336 jab 326
 
595 jab 327
    VertexID Manifold::split_face_by_vertex(FaceID f)
328
    {
329
        //create the new vertex, with the barycenter of the face as position
330
        Manifold::Vec p(0.0f);
331
        HalfEdgeID last_he = kernel.last(f);
332
        HalfEdgeID he = last_he;
333
        int steps = 0;
336 jab 334
 
595 jab 335
        while(he != last_he || steps == 0){
336
            p += positions[kernel.vert(he)];
337
            ++steps;
338
            he = kernel.next(he);
339
        }
336 jab 340
 
595 jab 341
        p /= steps;
336 jab 342
 
595 jab 343
        VertexID v = kernel.add_vertex();
344
        positions[v]  = p;
336 jab 345
 
595 jab 346
        //circulate the face, create halfedges and connect to vertex
347
        vector<HalfEdgeID> eout;
348
        vector<HalfEdgeID> ein;
349
        last_he = kernel.last(f);
350
        he = last_he;
336 jab 351
 
595 jab 352
        do{
353
            HalfEdgeID hn = kernel.next(he);
354
 
355
            HalfEdgeID ho = kernel.add_halfedge();
356
            HalfEdgeID hi = kernel.add_halfedge();
357
 
358
            FaceID fn = kernel.add_face();
359
            kernel.set_face(hi, fn);
360
            kernel.set_vert(hi, v);
361
            kernel.set_face(ho, fn);
362
            kernel.set_vert(ho, kernel.vert(kernel.opp(he)));
363
            kernel.set_face(he, fn);
364
            kernel.set_last(fn, ho);
365
 
366
            link(hi, ho);
367
            link(ho, he);
368
            link(he, hi);
369
 
370
            eout.push_back(ho);
371
            ein.push_back(hi);
372
 
373
            he = hn;
374
        }
375
        while(he != last_he);
336 jab 376
 
595 jab 377
        // glue new halfedges together
378
        size_t N = eout.size();
379
        for(size_t i = 0; i < N; ++i){
380
            glue(ein[i], eout[(i+1)%N]);
381
        }
382
        kernel.set_out(v, eout[0]);
336 jab 383
 
595 jab 384
        //remove the now replaced face
385
        kernel.remove_face(f);
336 jab 386
 
595 jab 387
        return v;
388
    }
389
    VertexID Manifold::split_edge(HalfEdgeID h)
390
    {
391
        HalfEdgeID ho = kernel.opp(h);
392
        VertexID v = kernel.vert(h);
393
        VertexID vo = kernel.vert(ho);
336 jab 394
 
595 jab 395
        //create the new vertex with middle of edge as position and update connectivity
396
        VertexID vn = kernel.add_vertex();
397
        positions[vn] = .5f * (positions[v] + positions[vo]);
398
        kernel.set_out(vn, h);
336 jab 399
 
595 jab 400
        //create two necessary halfedges, and update connectivity
401
        HalfEdgeID hn = kernel.add_halfedge();
402
        HalfEdgeID hno = kernel.add_halfedge();
336 jab 403
 
595 jab 404
        kernel.set_out(vo, hn);
631 janba 405
        kernel.set_out(v, hno);
336 jab 406
 
631 janba 407
        glue(h, hno);
408
        glue(hn, ho);
336 jab 409
 
595 jab 410
        link(kernel.prev(h), hn);
411
        link(hn, h);
412
        kernel.set_vert(hn, vn);
336 jab 413
 
631 janba 414
        link(kernel.prev(ho), hno);
415
        link(hno, ho);
416
        kernel.set_vert(hno, vn);
336 jab 417
 
595 jab 418
        // update faces in case of non boundary edge
419
        if(kernel.face(h) != InvalidFaceID)
420
            kernel.set_last(kernel.face(h), hn);
336 jab 421
 
595 jab 422
        if(kernel.face(ho) != InvalidFaceID)
423
            kernel.set_last(kernel.face(ho), ho);
336 jab 424
 
595 jab 425
        // update new edge with faces from existing edge
426
        kernel.set_face(hn, kernel.face(h));
427
        kernel.set_face(hno, kernel.face(ho));
336 jab 428
 
595 jab 429
        //if split occurs on a boundary, consistency must be ensured.
430
        ensure_boundary_consistency(vn);
431
        ensure_boundary_consistency(v);
432
        ensure_boundary_consistency(vo);
336 jab 433
 
595 jab 434
        return vn;
435
    }
436
 
437
    size_t link_intersection(const Manifold& m, VertexID v0, VertexID v1, vector<VertexID>& lisect)
438
    {
439
        // get the one-ring of v0
440
        vector<VertexID> link0;
633 janba 441
        circulate_vertex_ccw(m, v0, [&](VertexID vn) {
442
            link0.push_back(vn);
443
        });
336 jab 444
 
595 jab 445
        // get the one-ring of v1
446
        vector<VertexID> link1;
633 janba 447
        circulate_vertex_ccw(m, v1, [&](VertexID vn) {
448
            link1.push_back(vn);
449
        });
336 jab 450
 
595 jab 451
        // sort the vertices of the two rings
452
        sort(link0.begin(), link0.end());
453
        sort(link1.begin(), link1.end());
336 jab 454
 
595 jab 455
        // get the intersection of the shared vertices from both rings
456
        std::back_insert_iterator<vector<VertexID> > lii(lisect);
457
        set_intersection(link0.begin(), link0.end(),
458
						 link1.begin(), link1.end(),
459
						 lii);
460
 
461
        return lisect.size();
462
    }
463
 
464
    bool Manifold::stitch_boundary_edges(HalfEdgeID h0, HalfEdgeID h1)
465
    {
466
        // Cannot stitch an edge with itself
467
        if(h0 == h1)
468
            return false;
469
 
470
        // Only stitch a pair of boundary edges.
471
        if(kernel.face(h0) == InvalidFaceID && kernel.face(h1) == InvalidFaceID)
472
        {
473
            HalfEdgeID h0o = kernel.opp(h0);
474
            HalfEdgeID h1o = kernel.opp(h1);
475
            VertexID v0a = kernel.vert(h0);
476
            VertexID v0b = kernel.vert(kernel.opp(h1));
477
            VertexID v1b = kernel.vert(h1);
478
            VertexID v1a = kernel.vert(kernel.opp(h0));
479
 
480
            // Case below implies that h0 and h1 are the same edge with different ID
481
            // That should not happen.
482
            assert(!(v0a == v0b && v1a == v1b));
483
 
484
            if(connected(*this, v0a, v0b))
485
                return false;
486
            if(connected(*this, v1a, v1b))
487
                return false;
488
 
489
 
490
            if(v0b != v0a)
491
            {
492
 
493
                // Check the link intersection v0a and v0b are welded together
494
                // if they share a neighbouring vertex, it will appear twice in the combined
495
                // one ring unless it v1a and v1a==v1b
496
                vector<VertexID> lisect;
497
                if(link_intersection(*this, v0a, v0b, lisect))
498
                {
499
                    vector<VertexID>::iterator iter;
500
 
501
                    if(v1a == v1b)
502
                    {
503
                        iter = find(lisect.begin(), lisect.end(), v1a);
504
                        if(iter != lisect.end())
505
                            lisect.erase(iter);
506
                    }
507
                    iter = find(lisect.begin(), lisect.end(), kernel.vert(kernel.next(h0)));
508
                    if(iter != lisect.end())
509
                        lisect.erase(iter);
510
                    if(lisect.size() > 0)
511
                        return false;
512
                }
513
            }
514
 
515
            if(v1a != v1b)
516
            {
517
                // Check the same for the other endpoints.
518
                vector<VertexID> lisect;
519
                if(link_intersection(*this, v1a, v1b, lisect))
520
                {
521
                    vector<VertexID>::iterator iter;
522
 
523
                    if(v0a == v0b)
524
                    {
525
                        iter = find(lisect.begin(), lisect.end(), v1a);
526
                        if(iter != lisect.end())
527
                            lisect.erase(iter);
528
                    }
529
                    iter = find(lisect.begin(), lisect.end(), kernel.vert(kernel.next(h1)));
530
                    if(iter != lisect.end())
531
                        lisect.erase(iter);
532
                    if(lisect.size() > 0)
533
                        return false;
534
                }
535
            }
536
 
537
 
538
            if(v0b != v0a)
633 janba 539
                circulate_vertex_ccw(*this, v0b, [&](Walker hew) {
595 jab 540
                    kernel.set_vert(hew.opp().halfedge(), v0a);
633 janba 541
                });
595 jab 542
 
543
            if(v1b != v1a)
633 janba 544
                circulate_vertex_ccw(*this, v1b, [&](Walker hew) {
595 jab 545
                    kernel.set_vert(hew.opp().halfedge(), v1a);
633 janba 546
                });
595 jab 547
 
548
            if(v0a != v0b)
549
            {
550
                HalfEdgeID h1p = kernel.prev(h1);
551
                HalfEdgeID h0n = kernel.next(h0);
552
 
553
                if(kernel.next(h0n) == h1p)
554
                {
555
                    glue(kernel.opp(h0n), kernel.opp(h1p));
556
                    kernel.set_out(kernel.vert(h0n),kernel.opp(h0n));
557
                    kernel.remove_halfedge(h0n);
558
                    kernel.remove_halfedge(h1p);
559
                }
560
                else
561
                    link(h1p, h0n);
562
                kernel.remove_vertex(v0b);
563
            }
564
 
565
            if(v1a != v1b)
566
            {
567
                HalfEdgeID h0p = kernel.prev(h0);
568
                HalfEdgeID h1n = kernel.next(h1);
569
                if(kernel.next(h1n) == h0p)
570
                {
571
                    glue(kernel.opp(h0p), kernel.opp(h1n));
572
                    kernel.set_out(kernel.vert(h1n), kernel.opp(h1n));
573
                    kernel.remove_halfedge(h0p);
574
                    kernel.remove_halfedge(h1n);
575
                }
576
                else
577
                    link(h0p, h1n);
578
                kernel.remove_vertex(v1b);
579
            }
580
            glue(h0o, h1o);
581
 
582
            kernel.remove_halfedge(h0);
583
            kernel.remove_halfedge(h1);
584
 
585
            kernel.set_out(v1a, h1o);
586
            kernel.set_out(v0a, h0o);
587
 
588
            ensure_boundary_consistency(v1a);
589
            ensure_boundary_consistency(v0a);
590
 
591
            return true;
592
        }
593
        return false;
594
    }
595
 
596
 
597
 
598
    FaceID Manifold::merge_one_ring(VertexID v, float max_loop_length)
599
    {
600
        // If the vertex is either not in use or has just
601
        // one incident edge (or less), bail out.
602
        int val = valency(*this,v);
603
        if(!in_use(v) || val<2)
604
            return InvalidFaceID;
605
 
606
        // If the vertex is  a boundary vertex, we preparte the walker so that the
607
        // first face visited is not the invalid face outside the boundary. If the boundary
608
        // vertex is adjacent to only one vertex, there is little to do and we bail out.
609
        bool vertex_is_boundary = false;
610
        Walker hew = walker(v);
611
        if(boundary(*this, v))
612
        {
613
            if(val==2) return InvalidFaceID;
614
            vertex_is_boundary = true;
615
            hew = hew.circulate_vertex_ccw();
616
        }
617
 
618
        // Prepare some vectors for taking out the trash: We remove all old faces and all orphaned edges
619
        // and vertices
620
        vector<HalfEdgeID> garbage_halfedges;
621
        vector<FaceID> garbage_faces;
622
        vector<VertexID> garbage_vertices;
623
 
624
        vector<HalfEdgeID> loop; // The halfedges which form the outer loop of the merged one ring.
625
 
626
        // Below we loop over all faces adjacent to the vertex and add their halfedges to a big loop
627
        // which will form the loop of the new merged face. Below we remove from the loop edges
628
        // that appear twice (as each other's opposite).
629
        for(;!hew.full_circle(); hew = hew.circulate_vertex_ccw())
630
        {
631
            garbage_faces.push_back(hew.face());
632
            for(Walker hew2 = walker(hew.halfedge());
633
                !hew2.full_circle(); hew2 = hew2.circulate_face_ccw())
634
                loop.push_back(hew2.halfedge());
635
        }
636
 
637
 
638
        // Now merge the loops. We iteratively remove pairs of adjacent halfedges from the loop
639
        // if we find that the second is the opposite of the first since this is a degenerate
640
        // situation. However, we stop at four remaining halfedges since otherwise the loop degenerates
641
        // to zero after the next step if these four are also pairwise each other's opposites.
642
        int did_work;
643
        do
644
        {
645
            did_work = 0;
646
            vector<HalfEdgeID> loop_tmp(0);
605 jab 647
            for(size_t i=0;i<loop.size();++i)
595 jab 648
                if(walker(loop[i]).opp().halfedge() == loop[(i+1)%loop.size()])
649
                {
650
                    VertexID vid = walker(loop[i]).vertex();
651
                    if(vid != v)
652
                        garbage_vertices.push_back(walker(loop[i]).vertex());
653
                    garbage_halfedges.push_back(loop[i]);
654
                    garbage_halfedges.push_back(loop[(i+1)%loop.size()]);
655
                    loop[i] = InvalidHalfEdgeID;
656
                    loop[(i+1)%loop.size()] = InvalidHalfEdgeID;
657
                    ++did_work;
658
                    ++i;
659
                }
605 jab 660
            for(size_t i=0;i<loop.size();++i)
595 jab 661
                if(loop[i] != InvalidHalfEdgeID)
662
                    loop_tmp.push_back(loop[i]);
663
            loop = loop_tmp;
664
        } while(did_work > 0 && loop.size() > 4);
665
 
666
        // Check whether the loop is too long
667
        float loop_len=0.0;
605 jab 668
        for(size_t i=0;i<loop.size();++i)
595 jab 669
            loop_len += length(*this, loop[i]);
670
        if(loop_len > max_loop_length)
671
            return InvalidFaceID;
672
 
673
        // The following block checks wheteher the same halfedge appears twice. In this
674
        // case we fail since it means that the one ring contains the same face twice.
675
        vector<HalfEdgeID> loop_tmp = loop;
676
        sort(loop_tmp.begin(), loop_tmp.end());
677
        vector<HalfEdgeID>::iterator end_iter = unique(loop_tmp.begin(), loop_tmp.end());
678
        if(end_iter != loop_tmp.end())
679
            return InvalidFaceID;
680
 
681
        // Remove all faces and connected halfedges and the original vertex v.
605 jab 682
        for(size_t i=0;i<garbage_vertices.size(); ++i)
595 jab 683
            kernel.remove_vertex(garbage_vertices[i]);
605 jab 684
        for(size_t i=0;i<garbage_faces.size(); ++i)
595 jab 685
            kernel.remove_face(garbage_faces[i]);
605 jab 686
        for(size_t i=0;i<garbage_halfedges.size(); ++i)
595 jab 687
            kernel.remove_halfedge(garbage_halfedges[i]);
688
        if(!vertex_is_boundary)
689
            kernel.remove_vertex(v);
690
 
691
        // Create a new face for the merged one ring and link up all the halfedges
692
        // in the loop
693
        FaceID f = kernel.add_face();
694
        kernel.set_last(f,loop[0]);
605 jab 695
        for(size_t i=0;i<loop.size(); ++i)
595 jab 696
        {
697
            kernel.set_face(loop[i], f);
698
            Walker hw = walker(loop[i]);
699
            kernel.set_out(hw.vertex(),hw.opp().halfedge());
700
            link(loop[i],loop[(i+1)%loop.size()]);
701
            assert(hw.vertex() == walker(loop[(i+1)%loop.size()]).opp().vertex());
702
        }
703
 
704
        // Finally, we ensure boundary consitency for all vertices in the loop.
605 jab 705
        for(size_t i=0;i<loop.size(); ++i)
595 jab 706
        {
707
            Walker hw = walker(loop[i]);
708
            ensure_boundary_consistency(hw.vertex());
709
        }
710
 
711
        // Return the brand new merged face.
712
        return f;
713
    }
714
 
715
 
716
 
717
    bool Manifold::merge_faces(FaceID f, HalfEdgeID h)
718
    {
719
        //assert that we're merging a valid face with the corresponding halfedge
720
        assert(kernel.face(h) == f);
721
 
722
        HalfEdgeID ho = kernel.opp(h);
723
        FaceID fo = kernel.face(ho);
724
        HalfEdgeID hn = kernel.next(h);
725
        HalfEdgeID hon = kernel.next(ho);
726
 
727
        if(fo == f)
728
            return false;
729
 
730
        //boundary case
731
        if(kernel.vert(hn) == kernel.vert(hon))
732
            return false;
733
 
734
        HalfEdgeID hp = kernel.prev(h);
735
        HalfEdgeID hop = kernel.prev(ho);
736
        VertexID v = kernel.vert(h);
737
        VertexID vo = kernel.vert(ho);
738
 
739
        if(valency(*this, v) < 3 || valency(*this, vo) < 3)
740
            return false;
741
 
742
        link(hop, hn);
743
        link(hp, hon);
744
        kernel.set_out(vo, hon);
745
        kernel.set_out(v, hn);
746
        kernel.set_last(f, hn);
747
 
748
        HalfEdgeID hx = hon;
749
 
750
        assert(kernel.face(hx) == fo);
751
        while(kernel.face(hx) != f){
752
            kernel.set_face(hx, f);
753
            hx = kernel.next(hx);
754
        }
755
 
756
        ensure_boundary_consistency(v);
757
        ensure_boundary_consistency(vo);
758
 
759
        kernel.remove_halfedge(h);
760
        kernel.remove_halfedge(ho);
761
        kernel.remove_face(fo);
762
 
763
        return true;
764
    }
765
 
766
    FaceID Manifold::close_hole(HalfEdgeID h)
767
    {
768
        // invalid face is a hole
769
        if(kernel.face(h) == InvalidFaceID){
770
            FaceID f = kernel.add_face();
771
            kernel.set_last(f, h);
772
            do{
773
                kernel.set_face(h, f);
774
                h = kernel.next(h);
775
            }
776
            while(kernel.face(h) != f);
777
            return f;
778
        }
779
        return kernel.face(h);
780
    }
781
    void Manifold::flip_edge(HalfEdgeID h)
782
    {
783
        HalfEdgeID hn = kernel.next(h);
784
        HalfEdgeID hp = kernel.prev(h);
785
        HalfEdgeID ho = kernel.opp(h);
786
        HalfEdgeID hon = kernel.next(ho);
787
        HalfEdgeID hop = kernel.prev(ho);
788
 
789
        FaceID hf = kernel.face(h);
790
        FaceID hof = kernel.face(ho);
791
 
792
        VertexID hv = kernel.vert(h);
793
        VertexID hnv = kernel.vert(hn);
794
        VertexID hov = kernel.vert(ho);
795
        VertexID honv = kernel.vert(hon);
796
 
797
        // update face connectivity of halfedges changing face
798
        kernel.set_face(hop, hf);
799
        kernel.set_face(hp, hof);
800
 
801
        // connectivity of faces with halfedges of flipped edge
802
        kernel.set_last(hf, h);
803
        kernel.set_last(hof, ho);
804
 
805
        // connectivity of halfedges of first face after flip
806
        link(hn, h);
807
        link(h, hop);
808
        link(hop, hn);
809
 
810
        // connectivity of halfedges of second face after flip
811
        link(hon, ho);
812
        link(ho, hp);
813
        link(hp, hon);
814
 
815
        // connectivity of flipped edge and corresponding vertices
816
        kernel.set_vert(h, honv);
817
        kernel.set_vert(ho, hnv);
818
 
819
        if(kernel.out(hv) == ho)
820
            kernel.set_out(hv, hn);
821
        if(kernel.out(hov) == h)
822
            kernel.set_out(hov, hon);
823
 
824
        //
825
        //        // if the flip occurs next to a boundary, ensure the boundary consistency
826
        //        ensure_boundary_consistency(hv);
827
        //        ensure_boundary_consistency(hov);
828
    }
829
 
830
 
831
    /**********************************************
832
     * Private functions
833
     **********************************************/
834
 
835
    template<typename size_type, typename float_type, typename int_type>
836
    void Manifold::build_template(  size_type no_vertices,
837
                                  const float_type* vertvec,
838
                                  size_type no_faces,
839
                                  const int_type* facevec,
840
                                  const int_type* indices)
841
    {
842
        vector<VertexID> vids(no_vertices);
843
 
844
        // create vertices corresponding to positions stored in vertvec
605 jab 845
        for(size_t i=0;i<no_vertices;++i)
595 jab 846
        {
847
            const float_type* v0 = &vertvec[i*3];
848
            pos(vids[i] = kernel.add_vertex()) = Manifold::Vec(v0[0], v0[1], v0[2]);
849
        }
850
 
851
        //map over the created edges - needed to preserve edge uniqueness
852
        typedef map<EdgeKey, Edge> EdgeMap;
853
        EdgeMap edge_map;
854
 
855
        // counter that jumps between faces in indices vector
856
        int_type n  = 0;
857
 
858
        // create faces correspponding to faces stored in facevec
859
        for(size_type i = 0; i < no_faces; ++i){
860
            //amount of vertices in current face
861
            size_type N = facevec[i];
862
            vector<HalfEdgeID> fh;
863
 
864
            //each face indice results corresponds to 1 edge, 2 halfedges
865
            for(size_type j = 0; j < N; ++j){
866
                // ensure indice integrity
867
 
868
                assert(static_cast<size_type>(indices[j + n]) < no_vertices);
869
                assert(static_cast<size_type>(indices[(j + 1) % N + n]) < no_vertices);
870
 
871
 
872
                // each iteration uses two indices from the face
873
                VertexID v0 = vids[static_cast<size_type>(indices[j + n])];
874
                VertexID v1 = vids[static_cast<size_type>(indices[(j + 1) % N + n])];
875
 
876
                // create key and search map for edge
877
                EdgeKey ek(v0, v1);
878
                EdgeMap::iterator em_iter = edge_map.find(ek);
879
 
880
                // current edge has not been created
881
                if(em_iter == edge_map.end()){
882
                    // create edge for map
883
                    Edge e;
884
                    e.h0 = kernel.add_halfedge();
885
                    e.h1 = kernel.add_halfedge();
886
                    e.count = 1;
887
 
888
                    // glue operation: 1 edge = 2 glued halfedges
889
                    glue(e.h0, e.h1);
890
 
891
                    // update vertices with their outgoing halfedges
892
                    kernel.set_out(v0, e.h0);
893
                    kernel.set_out(v1, e.h1);
894
 
895
                    // update halfedges with the vertices they point to
896
                    kernel.set_vert(e.h0, v1);
897
                    kernel.set_vert(e.h1, v0);
898
 
899
                    // update map
900
                    edge_map[ek] = e;
901
 
902
                    // update vector of halfedges belonging to current face
903
                    fh.push_back(e.h0);
904
                }
905
                else{
906
                    // update current face with halfedge from edge
907
                    fh.push_back(em_iter->second.h1);
908
 
909
                    // asserting that a halfedge is visited exactly twice;
910
                    // once for each face on either side of the edge.
911
                    em_iter->second.count++;
912
                    assert(em_iter->second.count == 2);
913
                }
914
            }
915
 
916
            FaceID fid = kernel.add_face();
917
            for(size_type j = 0; j < N; ++j){
918
                // update halfedge with face
919
                kernel.set_face(fh[j], fid);
920
 
921
                // link operation: link two halfedges in the same face
922
                link(fh[j], fh[(j + 1) % N]);
923
            }
924
            //update face with the first halfedge created
925
            kernel.set_last(fid, fh[0]);
926
 
927
            // step to first index of next face
928
            n += N;
929
        }
930
 
931
        // test for unused vertices
932
        for(VertexIDIterator v = vertices_begin(); v != vertices_end(); ++v){
933
            assert( (*v) != InvalidVertexID);
934
            if(kernel.out(*v) == InvalidHalfEdgeID)
935
                kernel.remove_vertex(*v);
936
        }
937
 
938
        // boundary check while avoiding unused vertices
939
        for(VertexIDIterator v = vertices_begin(); v != vertices_end(); ++v){
940
            if((*v) != InvalidVertexID)
941
                ensure_boundary_consistency(*v);
942
        }
943
    }
944
    void Manifold::link(HalfEdgeID h0, HalfEdgeID h1)
945
    {
946
        kernel.set_next(h0, h1);
947
        kernel.set_prev(h1, h0);
948
    }
949
    void Manifold::glue(HalfEdgeID h0, HalfEdgeID h1)
950
    {
951
        kernel.set_opp(h0, h1);
952
        kernel.set_opp(h1, h0);
953
    }
954
    void Manifold::ensure_boundary_consistency(VertexID v)
955
    {
956
        // boundary consistency check by performing two vertex circulations
957
        HalfEdgeID h = kernel.out(v);
958
        HalfEdgeID last = h;
959
 
960
        // step 1: circle through edges pointing away from vertex until reaching a null face
961
        while(kernel.face(h) != InvalidFaceID){
962
            h = kernel.opp(kernel.prev(h));
963
            if(h == last) // We came full circle - vertex not boundary - return.
964
                return;
965
        }
966
        // null face encountered, we update our vertex with half edge index and prepare for step 2
967
        kernel.set_out(v, h);
968
        HalfEdgeID ho = kernel.opp(h);
969
 
970
        // step 2: circle through edges pointing towards vertex until reaching a null face
971
        while(kernel.face(ho) != InvalidFaceID){
972
            ho = kernel.opp(kernel.next(ho));
973
        }
974
        // null face encountered again, we update our edge with vertex index
975
        kernel.set_vert(ho, v);
976
 
977
        // remaining step is to make the in and out going edges link to each other
978
        link(ho, h);
979
    }
980
    void Manifold::remove_face_if_degenerate(HalfEdgeID h)
981
    {
982
        // face is degenerate if there is only two halfedges in face loop
983
        if(kernel.next(kernel.next(h)) == h)
984
        {
985
            HalfEdgeID hn = kernel.next(h);
986
            HalfEdgeID ho = kernel.opp(h);
987
            HalfEdgeID hno = kernel.opp(hn);
988
            VertexID hv = kernel.vert(h);
989
            VertexID hnv = kernel.vert(hn);
990
            FaceID f = kernel.face(h);
991
 
992
            assert(ho != hn);
993
            assert(h != hno);
994
            assert(hv != hnv);
995
 
996
            // glue opposite halfedge to halfedge opposite next halfedge, obsoleting h and hn from loop
997
            glue(ho, hno);
998
 
999
            // make v and vn point to opposite and next opposite halfedge, obsoleting h and hn from loop
1000
            kernel.set_out(hnv, hno);
1001
            kernel.set_out(hv, ho);
1002
 
1003
            // if face owning h is valid, remove face
1004
            if(f != InvalidFaceID)
1005
                kernel.remove_face(f);
1006
            // remove the two invalid halfedges and the invalid face loop
1007
            kernel.remove_halfedge(h);
1008
            kernel.remove_halfedge(hn);
1009
 
1010
            // verify that v and vn is sane after removing the degenerate face
1011
            ensure_boundary_consistency(hv);
1012
            ensure_boundary_consistency(hnv);
1013
        }
1014
    }
1015
 
1016
    vector<HalfEdgeID> Manifold::bridge_faces(FaceID f0, FaceID f1, const vector<pair<VertexID, VertexID> >& pairs)
1017
    {
1018
        // Let N be the number of vertex pairs to connect by edges
1019
        size_t N = pairs.size();
1020
 
1021
        // We now create N pairs of edges, glue each pair and let them point to the appropriate
1022
        // vertices.
1023
        vector<HalfEdgeID> new_halfedges(N);
1024
        vector<HalfEdgeID> new_halfedges_opp(N);
605 jab 1025
        for(size_t i=0;i<N; ++i)
595 jab 1026
        {
1027
            new_halfedges[i] = kernel.add_halfedge();
1028
            new_halfedges_opp[i] = kernel.add_halfedge();
1029
            glue(new_halfedges[i], new_halfedges_opp[i]);
1030
            kernel.set_vert(new_halfedges[i], pairs[i].second);
1031
            kernel.set_vert(new_halfedges_opp[i], pairs[i].first);
1032
        }
1033
 
1034
        // We now maintain some halfedge indices to right before
1035
        // and right after the point we are trying to connect on
1036
        // each of the two loops.
1037
        HalfEdgeID h0p = kernel.last(f0);
1038
        HalfEdgeID h1n = kernel.last(f1);
1039
 
1040
        // loop over all connections and link the new halfedges with the old
1041
        // ones.
605 jab 1042
        for(size_t i=0;i<N; ++i)
595 jab 1043
        {
1044
            while(kernel.vert(h0p) != pairs[i].first)
1045
                h0p = kernel.next(h0p);
1046
            while(kernel.vert(kernel.prev(h1n)) != pairs[i].second)
1047
                h1n = kernel.prev(h1n);
1048
 
1049
            HalfEdgeID h0n = kernel.next(h0p);
1050
            HalfEdgeID h1p = kernel.prev(h1n);
1051
 
1052
            link(h0p, new_halfedges[i]);
1053
            link(new_halfedges[i],h1n);
1054
            link(h1p, new_halfedges_opp[i]);
1055
            link(new_halfedges_opp[i],h0n);
1056
 
1057
            h0p = new_halfedges_opp[i];
1058
            h1n = new_halfedges_opp[i];
1059
        }
1060
 
1061
        // Create the faces and their connections
605 jab 1062
        for(size_t i=0;i<N; ++i)
595 jab 1063
        {
1064
            HalfEdgeID last = new_halfedges[i];
1065
            FaceID f = kernel.add_face();
1066
            kernel.set_last(f, last);
1067
            HalfEdgeID h = last;
1068
            do
1069
            {
1070
                kernel.set_face(h, f);
1071
                h = kernel.next(h);
1072
            } while(h != last);
1073
        }
1074
 
1075
        // Delete the old faces that were bridged.
1076
        kernel.remove_face(f0);
1077
        kernel.remove_face(f1);
1078
 
1079
        new_halfedges.insert(new_halfedges.end(), new_halfedges_opp.begin(), new_halfedges_opp.end());
1080
        return new_halfedges;
1081
    }
1082
 
1083
    /***************************************************
1084
     * Namespace functions
1085
     ***************************************************/
1086
    bool valid(const Manifold& m)
1087
    {
1088
        // Verify components of halfedges
1089
        for(HalfEdgeIDIterator h = m.halfedges_begin(); h != m.halfedges_end(); ++h){
1090
            Walker j = m.walker(*h);
1091
 
1092
            if(j.vertex() == InvalidVertexID){
1093
                cout << "Halfedge lacks vert" << endl;
1094
                return false;
1095
            }
1096
            if(j.next().halfedge() == InvalidHalfEdgeID){
1097
                cout << "Halfedge lacks next" << endl;
1098
                return false;
1099
            }
1100
            if(j.prev().halfedge() == InvalidHalfEdgeID){
1101
                cout << "Halfedge lacks prev" << endl;
1102
                return false;
1103
            }
1104
            if(j.opp().halfedge() == InvalidHalfEdgeID){
1105
                cout << "Halfedge lacks opp" << endl;
1106
                return false;
1107
            }
1108
 
1109
        }
1110
        // Verify components of vertices
1111
        for(VertexIDIterator v = m.vertices_begin(); v != m.vertices_end(); ++v){
1112
            vector<VertexID> link;
1113
 
1114
            // circulate the halfedges of vertex
1115
            for(Walker j = m.walker(*v); !j.full_circle(); j = j.circulate_vertex_cw()){
1116
                // test halfedges around v
1117
                if(j.halfedge() == InvalidHalfEdgeID){
1118
                    cout << "Vertex circulation produced invalid halfedge" << endl;
1119
                    return false;
1120
                }
1121
                VertexID ring_v = j.vertex();
1122
 
1123
                // test one-ring for multiple occurences of vertex
1124
                if(find(link.begin(), link.end(), ring_v) != link.end()){
1125
                    cout << "Vertex appears two times in one-ring of vertex" << endl;
1126
                    return false;
1127
                }
1128
                link.push_back(ring_v);
1129
 
1130
                // test for infinite loop around vertex
1131
                if(static_cast<size_t>(j.no_steps()) > m.no_vertices()){
1132
                    cout << "Vertex loop contains more vertices than manifold" << endl;
1133
                    return false;
1134
                }
1135
            }
1136
 
1137
            // test one_ring size for boundary consistency
1138
            if(link.size() <= 2){
1139
                Walker j = m.walker(*v);
1140
 
1141
                if(j.face() != InvalidFaceID && j.opp().face() != InvalidFaceID)
1142
                {
1143
                    if(link.size()==1)
1144
                        cout << "Vertex contains only a single incident edge" << endl;
1145
                    //
1146
                    //                    cout << "Vertex contains only " << link.size() <<" incident edges" << endl;
1147
                }
1148
                else
1149
                    cout << "Boundary vertex contains only " << link.size() <<" incident edges" << endl;
1150
            }
1151
        }
1152
        // verify components of faces
1153
        for(FaceIDIterator f = m.faces_begin(); f != m.faces_end(); ++f){
1154
            // count edges on face
1155
            Walker j = m.walker(*f);
1156
 
1157
            for(; !j.full_circle(); j = j.circulate_face_cw()){
1158
                // test that all halfedges in faces bind properly to their face
1159
                if(j.face() != *f){
1160
                    cout << "Face is inconsistent, halfedge is not bound to face" << endl;
1161
                    return false;
1162
                }
1163
            }
1164
            // test faces for valid geometrical properties
1165
            if(j.no_steps() < 3){
1166
                cout << "Face contains less than 3 edges" << endl;
1167
                return false;
1168
            }
1169
            // test for infinite loop around face
1170
            if(j.no_steps() > m.no_halfedges() * 0.5f){
1171
                cout << "Face loop contains more halfedges than manifold" << endl;
1172
                return false;
1173
            }
1174
        }
1175
        return true;
1176
    }
1177
 
1178
    void bbox(const Manifold& m, Manifold::Vec& pmin, Manifold::Vec& pmax)
1179
    {
1180
 
1181
        VertexIDIterator v = m.vertices_begin();
1182
        pmin = pmax = m.pos(*v);
1183
        ++v;
1184
        for(; v != m.vertices_end(); ++v){
1185
            pmin = v_min(m.pos(*v), pmin);
1186
            pmax = v_max(m.pos(*v), pmax);
1187
        }
1188
    }
1189
 
1190
    void bsphere(const Manifold& m, Manifold::Vec& c, float& r)
1191
    {
1192
        Manifold::Vec p0, p7;
1193
        bbox(m, p0, p7);
1194
        Manifold::Vec rad = (p7 - p0) * 0.5f;
1195
        c = p0 + rad;
1196
        r = rad.length();
1197
    }
1198
 
1199
 
1200
 
1201
    bool precond_collapse_edge(const Manifold& m, HalfEdgeID h)
1202
    {
1203
        Walker hew = m.walker(h);
1204
        HalfEdgeID ho = hew.opp().halfedge();
1205
        VertexID v0 = hew.opp().vertex();
1206
        VertexID v1 = hew.vertex();
1207
 
1208
        // get the one-ring of v0
1209
        vector<VertexID> link0;
1210
        vector<FaceID> faces0;
1211
        for(Walker vj = m.walker(h);
1212
            !vj.full_circle(); vj = vj.circulate_vertex_ccw()){
1213
            link0.push_back(vj.vertex());
1214
            if(vj.halfedge() != h)
1215
                faces0.push_back(vj.face());
1216
        }
1217
        assert(link0.size() > 1);
1218
 
1219
        // get the one-ring of v1
1220
        vector<VertexID> link1;
1221
        vector<FaceID> faces1;
1222
        for(Walker vj = m.walker(ho);
1223
            !vj.full_circle(); vj = vj.circulate_vertex_ccw()){
1224
            link1.push_back(vj.vertex());
1225
            if(vj.halfedge() != ho)
1226
                faces1.push_back(vj.face());
1227
        }
1228
        assert(link1.size() > 1);
1229
 
1230
        // sort the vertices of the two rings
1231
        sort(link0.begin(), link0.end());
1232
        sort(link1.begin(), link1.end());
1233
 
1234
        // get the intersection of the shared vertices from both rings
1235
        vector<VertexID> lisect;
1236
        std::back_insert_iterator<vector<VertexID> > lii(lisect);
1237
        set_intersection(link0.begin(), link0.end(),
1238
                         link1.begin(), link1.end(),
1239
                         lii);
1240
 
1241
        // sort the faces of the two rings
1242
        sort(faces0.begin(), faces0.end());
1243
        sort(faces1.begin(), faces1.end());
1244
 
1245
        // get the intersection of the shared faces from both rings
1246
        vector<FaceID> fisect;
1247
        std::back_insert_iterator<vector<FaceID> > fii(fisect);
1248
        set_intersection(faces0.begin(), faces0.end(),
1249
                         faces1.begin(), faces1.end(),
1250
                         fii);
1251
        if(fisect.size() > 0)
1252
            return false;
1253
 
1254
        int k = 0;
1255
        // if the adjacent face is a triangle (see 2)
1256
        if(hew.next().next().next().halfedge() == h){
1257
            VertexID v = hew.next().vertex();
1258
 
1259
            // valency test (see 5)
1260
            if(valency(m, v) < 3)
1261
                return false;
1262
 
1263
            // remove the vertex shared by the two rings from the intersection
1264
            vector<VertexID>::iterator iter;
1265
            iter = find(lisect.begin(), lisect.end(), v);
1266
            assert(iter != lisect.end());
1267
            lisect.erase(iter);
1268
            ++k;
1269
        }
1270
        // if the adjacent face is a triangle (see 2)
1271
        if(hew.opp().next().next().next().halfedge() == hew.opp().halfedge()){
1272
            VertexID v = hew.opp().next().vertex();
1273
 
1274
            // valency test (see 5)
1275
            if(valency(m, v) < 3)
1276
                return false;
1277
 
1278
            // remove the vertex shared by the two rings from the intersection
1279
            vector<VertexID>::iterator iter;
1280
            iter = find(lisect.begin(), lisect.end(), v);
1281
            assert(iter != lisect.end());
1282
            lisect.erase(iter);
1283
            ++k;
1284
        }
1285
        // double edge test (see 3)
1286
        if(lisect.size() != 0)
1287
            return false;
1288
 
1289
        // tetrahedon test (see 4)
1290
        if(k == 2 && (link0.size() + link1.size() == 6))
1291
            return false;
1292
 
1293
        // test that we do not merge holes (see 6)
1294
        if(boundary(m, v0) && boundary(m, v1) && hew.face() != InvalidFaceID && hew.opp().face() != InvalidFaceID)
1295
            return false;
1296
 
1297
        return true;
1298
    }
1299
 
1300
    bool precond_flip_edge(const Manifold& m, HalfEdgeID h)
1301
    {
1302
        Walker j = m.walker(h);
1303
 
1304
        FaceID hf = j.face();
1305
        //        HalfEdgeID ho = j.opp().halfedge();
1306
        FaceID hof = j.opp().face();
1307
 
1308
        // boundary case
1309
        if(hf == InvalidFaceID || hof == InvalidFaceID)
1310
            return false;
1311
 
1312
        // We can only flip an edge if both incident polygons are triangles.
1313
        if(no_edges(m, hf) != 3 || no_edges(m, hof) !=3)
1314
            return false;
1315
 
1316
        // non boundary vertices with a valency of less than 4(less than 3 after operation) degenerates mesh.
1317
        VertexID hv = j.vertex();
1318
        VertexID hov = j.opp().vertex();
1319
        if((valency(m, hv) < 4 && !boundary(m, hv)) || (valency(m, hov) < 4 && !boundary(m, hov)))
1320
            return false;
1321
 
1322
        // Disallow flip if vertices being connected already are.
1323
        VertexID hnv = j.next().vertex();
1324
        VertexID honv = j.opp().next().vertex();
1325
        if(connected(m, hnv, honv))
1326
            return false;
1327
 
1328
        return true;
1329
    }
1330
 
1331
    bool boundary(const Manifold& m, VertexID v)
1332
    {
1333
        Walker j  = m.walker(v);
1334
        return boundary(m, j.halfedge());
1335
    }
1336
    int valency(const Manifold& m, VertexID v)
1337
    {
633 janba 1338
        return circulate_vertex_ccw(m,v, [](Walker){});
595 jab 1339
    }
1340
 
1341
    Manifold::Vec normal(const Manifold& m, VertexID v)
1342
    {
1343
        Manifold::Vec p0 = m.pos(v);
1344
        vector<Manifold::Vec> one_ring;
1345
 
1346
        // run through outgoing edges, and store them normalized
633 janba 1347
        int N = circulate_vertex_ccw(m, v, [&](VertexID vn) {
1348
            Manifold::Vec edge = m.pos(vn) - p0;
1349
            double l = length(edge);
1350
            if(l > 0.0)
1351
                one_ring.push_back(edge/l);
1352
        });
595 jab 1353
 
1354
        if(N<2)
1355
            return Manifold::Vec(0);
1356
 
1357
        size_t N_count = N;
631 janba 1358
        size_t N_start = 0;
595 jab 1359
        if(boundary(m, v))
631 janba 1360
            N_start = 1;
595 jab 1361
 
1362
        // sum up the normals of each face surrounding the vertex
633 janba 1363
        Manifold::Vec n(0);
631 janba 1364
        for(size_t i = N_start; i < N_count; ++i){
595 jab 1365
            Manifold::Vec e0 = one_ring[i];
1366
            Manifold::Vec e1 = one_ring[(i+1) % N];
1367
 
1368
            Manifold::Vec n_part = normalize(cross(e0, e1));
1369
            n += n_part * acos(max(-1.0, min(1.0, dot(e0, e1))));
1370
        }
1371
 
1372
        // normalize and return the normal
1373
        float sqr_l = sqr_length(n);
1374
        if(sqr_l > 0.0f) return n / sqrt(sqr_l);
1375
 
1376
        return n;
1377
    }
1378
 
1379
    bool connected(const Manifold& m, VertexID v0, VertexID v1)
1380
    {
633 janba 1381
        bool c=false;
1382
        circulate_vertex_ccw(m, v0, [&](VertexID v){ c |= (v==v1);});
1383
        return c;
595 jab 1384
    }
1385
 
1386
    int no_edges(const Manifold& m, FaceID f)
1387
    {
633 janba 1388
        return circulate_face_ccw(m, f, [](Walker w){});
595 jab 1389
    }
633 janba 1390
 
595 jab 1391
    Manifold::Vec normal(const Manifold& m, FaceID f)
1392
    {
1393
        vector<Manifold::Vec> v;
1394
 
633 janba 1395
        int k= circulate_face_ccw(m, f, [&](VertexID vid) {
1396
            v.push_back(m.pos(vid));
1397
        });
595 jab 1398
 
1399
        Manifold::Vec norm(0);
1400
        for(int i=0;i<k;++i)
1401
        {
1402
            norm[0] += (v[i][1]-v[(i+1)%k][1])*(v[i][2]+v[(i+1)%k][2]);
1403
            norm[1] += (v[i][2]-v[(i+1)%k][2])*(v[i][0]+v[(i+1)%k][0]);
1404
            norm[2] += (v[i][0]-v[(i+1)%k][0])*(v[i][1]+v[(i+1)%k][1]);
1405
        }
1406
        float l = sqr_length(norm);
1407
        if(l>0.0f)
1408
            norm /= sqrt(l);
1409
        return norm;
1410
    }
1411
 
1412
 
633 janba 1413
    double area(const Manifold& m, FaceID fid)
595 jab 1414
    {
1415
        // Get all projected vertices
1416
        vector<Manifold::Vec> vertices;
633 janba 1417
        int N = circulate_face_ccw(m, fid, [&](VertexID vid) {
1418
            vertices.push_back(m.pos(vid));
1419
        });
1420
 
1421
 
1422
        double area = 0;
631 janba 1423
        Manifold::Vec norm = normal(m,fid);
1424
        for(int i = 1; i < N-1; ++i)
1425
            area += 0.5 * dot(norm,cross(vertices[i]-vertices[0], vertices[(i+1 )]-vertices[0]));
1426
        return area;
595 jab 1427
    }
1428
 
1429
    Manifold::Vec centre(const Manifold& m, FaceID f)
1430
    {
1431
        Manifold::Vec c(0);
633 janba 1432
        int n = circulate_face_ccw(m, f, [&](VertexID v) {c+=m.pos(v);});
1433
        return c / n;
595 jab 1434
    }
1435
 
633 janba 1436
    double perimeter(const Manifold& m, FaceID f)
595 jab 1437
    {
633 janba 1438
        double l=0.0;
1439
        circulate_face_ccw(m, f, [&](HalfEdgeID h) { l+= length(m, h);});
1440
        return l;
595 jab 1441
    }
1442
 
1443
    bool boundary(const Manifold& m, HalfEdgeID h)
1444
    {
1445
        Walker w = m.walker(h);
1446
        return w.face() == InvalidFaceID || w.opp().face() == InvalidFaceID;
1447
    }
1448
 
633 janba 1449
    double length(const Manifold& m, HalfEdgeID h)
595 jab 1450
    {
1451
        Walker w = m.walker(h);
1452
        return (m.pos(w.vertex()) - m.pos(w.opp().vertex())).length();
1453
    }
39 bj 1454
}