Subversion Repositories gelsvn

Rev

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