Subversion Repositories gelsvn

Rev

Rev 636 | Rev 646 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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