correct typos in comments.
[blender.git] / source / blender / bmesh / tools / bmesh_decimate_collapse.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Campbell Barton
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/bmesh/tools/bmesh_decimate_collapse.c
24  *  \ingroup bmesh
25  *
26  * BMesh decimator that uses an edge collapse method.
27  */
28
29 #include <stddef.h>
30
31 #include "MEM_guardedalloc.h"
32
33 #include "DNA_scene_types.h"
34
35 #include "BLI_math.h"
36 #include "BLI_quadric.h"
37 #include "BLI_heap.h"
38
39 #include "BKE_customdata.h"
40
41 #include "bmesh.h"
42 #include "bmesh_decimate.h"  /* own include */
43
44 #include "../intern/bmesh_structure.h"
45
46 /* defines for testing */
47 #define USE_CUSTOMDATA
48 #define USE_TRIANGULATE
49 #define USE_VERT_NORMAL_INTERP  /* has the advantage that flipped faces don't mess up vertex normals */
50
51 /* these checks are for rare cases that we can't avoid since they are valid meshes still */
52 #define USE_SAFETY_CHECKS
53
54 #define BOUNDARY_PRESERVE_WEIGHT 100.0f
55 #define OPTIMIZE_EPS 0.01f  /* FLT_EPSILON is too small, see [#33106] */
56 #define COST_INVALID FLT_MAX
57
58 typedef enum CD_UseFlag {
59         CD_DO_VERT = (1 << 0),
60         CD_DO_EDGE = (1 << 1),
61         CD_DO_LOOP = (1 << 2)
62 } CD_UseFlag;
63
64
65 /* BMesh Helper Functions
66  * ********************** */
67
68 /**
69  * \param vquadrics must be calloc'd
70  */
71 static void bm_decim_build_quadrics(BMesh *bm, Quadric *vquadrics)
72 {
73         BMIter iter;
74         BMFace *f;
75         BMEdge *e;
76
77         BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
78                 BMLoop *l_first;
79                 BMLoop *l_iter;
80
81                 const float *co = BM_FACE_FIRST_LOOP(f)->v->co;
82                 const float *no = f->no;
83                 const float offset = -dot_v3v3(no, co);
84                 Quadric q;
85
86                 BLI_quadric_from_v3_dist(&q, no, offset);
87
88                 l_iter = l_first = BM_FACE_FIRST_LOOP(f);
89                 do {
90                         BLI_quadric_add_qu_qu(&vquadrics[BM_elem_index_get(l_iter->v)], &q);
91                 } while ((l_iter = l_iter->next) != l_first);
92         }
93
94         /* boundary edges */
95         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
96                 if (UNLIKELY(BM_edge_is_boundary(e))) {
97                         float edge_vector[3];
98                         float edge_cross[3];
99                         sub_v3_v3v3(edge_vector, e->v2->co, e->v1->co);
100                         f = e->l->f;
101                         cross_v3_v3v3(edge_cross, edge_vector, f->no);
102
103                         if (normalize_v3(edge_cross) > FLT_EPSILON) {
104                                 Quadric q;
105                                 BLI_quadric_from_v3_dist(&q, edge_cross, -dot_v3v3(edge_cross, e->v1->co));
106                                 BLI_quadric_mul(&q, BOUNDARY_PRESERVE_WEIGHT);
107
108                                 BLI_quadric_add_qu_qu(&vquadrics[BM_elem_index_get(e->v1)], &q);
109                                 BLI_quadric_add_qu_qu(&vquadrics[BM_elem_index_get(e->v2)], &q);
110                         }
111                 }
112         }
113 }
114
115
116 static void bm_decim_calc_target_co(BMEdge *e, float optimize_co[3],
117                                     const Quadric *vquadrics)
118 {
119         /* compute an edge contraction target for edge 'e'
120          * this is computed by summing it's vertices quadrics and
121          * optimizing the result. */
122         Quadric q;
123
124         BLI_quadric_add_qu_ququ(&q,
125                                 &vquadrics[BM_elem_index_get(e->v1)],
126                                 &vquadrics[BM_elem_index_get(e->v2)]);
127
128
129         if (BLI_quadric_optimize(&q, optimize_co, OPTIMIZE_EPS)) {
130                 return;  /* all is good */
131         }
132         else {
133                 mid_v3_v3v3(optimize_co, e->v1->co, e->v2->co);
134         }
135 }
136
137 static bool bm_edge_collapse_is_degenerate_flip(BMEdge *e, const float optimize_co[3])
138 {
139         BMIter liter;
140         BMLoop *l;
141         unsigned int i;
142
143         for (i = 0; i < 2; i++) {
144                 /* loop over both verts */
145                 BMVert *v = *((&e->v1) + i);
146
147                 BM_ITER_ELEM (l, &liter, v, BM_LOOPS_OF_VERT) {
148                         if (l->e != e && l->prev->e != e) {
149                                 float *co_prev = l->prev->v->co;
150                                 float *co_next = l->next->v->co;
151                                 float cross_exist[3];
152                                 float cross_optim[3];
153
154 #if 1
155                                 float vec_other[3];  /* line between the two outer verts, re-use for both cross products */
156                                 float vec_exist[3];  /* before collapse */
157                                 float vec_optim[3];  /* after collapse */
158
159                                 sub_v3_v3v3(vec_other, co_prev, co_next);
160                                 sub_v3_v3v3(vec_exist, co_prev, v->co);
161                                 sub_v3_v3v3(vec_optim, co_prev, optimize_co);
162
163                                 cross_v3_v3v3(cross_exist, vec_other, vec_exist);
164                                 cross_v3_v3v3(cross_optim, vec_other, vec_optim);
165
166                                 /* normalize isn't really needed, but ensures the value at a unit we can compare against */
167                                 normalize_v3(cross_exist);
168                                 normalize_v3(cross_optim);
169 #else
170                                 normal_tri_v3(cross_exist, v->co,       co_prev, co_next);
171                                 normal_tri_v3(cross_optim, optimize_co, co_prev, co_next);
172 #endif
173
174                                 /* use a small value rather then zero so we don't flip a face in multiple steps
175                                  * (first making it zero area, then flipping again) */
176                                 if (dot_v3v3(cross_exist, cross_optim) <= FLT_EPSILON) {
177                                         //printf("no flip\n");
178                                         return true;
179                                 }
180                         }
181                 }
182         }
183
184         return false;
185 }
186
187 static void bm_decim_build_edge_cost_single(BMEdge *e,
188                                             const Quadric *vquadrics, const float *vweights,
189                                             Heap *eheap, HeapNode **eheap_table)
190 {
191         const Quadric *q1, *q2;
192         float optimize_co[3];
193         float cost;
194
195         if (eheap_table[BM_elem_index_get(e)]) {
196                 BLI_heap_remove(eheap, eheap_table[BM_elem_index_get(e)]);
197         }
198
199         /* check we can collapse, some edges we better not touch */
200         if (BM_edge_is_boundary(e)) {
201                 if (e->l->f->len == 3) {
202                         /* pass */
203                 }
204                 else {
205                         /* only collapse tri's */
206                         eheap_table[BM_elem_index_get(e)] = NULL;
207                         return;
208                 }
209         }
210         else if (BM_edge_is_manifold(e)) {
211                 if ((e->l->f->len == 3) && (e->l->radial_next->f->len == 3)) {
212                         /* pass */
213                 }
214                 else {
215                         /* only collapse tri's */
216                         eheap_table[BM_elem_index_get(e)] = NULL;
217                         return;
218                 }
219         }
220         else {
221                 eheap_table[BM_elem_index_get(e)] = NULL;
222                 return;
223         }
224
225         if (vweights) {
226                 if ((vweights[BM_elem_index_get(e->v1)] >= BM_MESH_DECIM_WEIGHT_MAX) &&
227                     (vweights[BM_elem_index_get(e->v2)] >= BM_MESH_DECIM_WEIGHT_MAX))
228                 {
229                         /* skip collapsing this edge */
230                         eheap_table[BM_elem_index_get(e)] = NULL;
231                         return;
232                 }
233         }
234         /* end sanity check */
235
236
237         bm_decim_calc_target_co(e, optimize_co, vquadrics);
238
239         q1 = &vquadrics[BM_elem_index_get(e->v1)];
240         q2 = &vquadrics[BM_elem_index_get(e->v2)];
241
242         if (vweights == NULL) {
243                 cost = (BLI_quadric_evaluate(q1, optimize_co) +
244                         BLI_quadric_evaluate(q2, optimize_co));
245         }
246         else {
247                 /* add 1.0 so planar edges are still weighted against */
248                 cost = (((BLI_quadric_evaluate(q1, optimize_co) + 1.0f) * vweights[BM_elem_index_get(e->v1)]) +
249                         ((BLI_quadric_evaluate(q2, optimize_co) + 1.0f) * vweights[BM_elem_index_get(e->v2)]));
250         }
251         // print("COST %.12f\n");
252
253         eheap_table[BM_elem_index_get(e)] = BLI_heap_insert(eheap, cost, e);
254 }
255
256
257 /* use this for degenerate cases - add back to the heap with an invalid cost,
258  * this way it may be calculated again if surrounding geometry changes */
259 static void bm_decim_invalid_edge_cost_single(BMEdge *e,
260                                               Heap *eheap, HeapNode **eheap_table)
261 {
262         BLI_assert(eheap_table[BM_elem_index_get(e)] == NULL);
263         eheap_table[BM_elem_index_get(e)] = BLI_heap_insert(eheap, COST_INVALID, e);
264 }
265
266 static void bm_decim_build_edge_cost(BMesh *bm,
267                                      const Quadric *vquadrics, const float *vweights,
268                                      Heap *eheap, HeapNode **eheap_table)
269 {
270         BMIter iter;
271         BMEdge *e;
272         unsigned int i;
273
274         BM_ITER_MESH_INDEX (e, &iter, bm, BM_EDGES_OF_MESH, i) {
275                 eheap_table[i] = NULL;  /* keep sanity check happy */
276                 bm_decim_build_edge_cost_single(e, vquadrics, vweights, eheap, eheap_table);
277         }
278 }
279
280 #ifdef USE_TRIANGULATE
281 /* Temp Triangulation
282  * ****************** */
283
284 /**
285  * To keep things simple we can only collapse edges on triangulated data
286  * (limitation with edge collapse and error calculation functions).
287  *
288  * But to avoid annoying users by only giving triangle results, we can
289  * triangulate, keeping a reference between the faces, then join after
290  * if the edges don't collapse, this will also allow more choices when
291  * collapsing edges so even has some advantage over decimating quads
292  * directly.
293  *
294  * \return true if any faces were triangulated.
295  */
296
297 static bool bm_decim_triangulate_begin(BMesh *bm)
298 {
299         BMIter iter;
300         BMFace *f;
301         // bool has_quad;  // could optimize this a little
302         bool has_cut = false;
303
304         BLI_assert((bm->elem_index_dirty & BM_VERT) == 0);
305
306         /* first clear loop index values */
307         BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
308                 BMLoop *l_iter;
309                 BMLoop *l_first;
310
311                 l_iter = l_first = BM_FACE_FIRST_LOOP(f);
312                 do {
313                         BM_elem_index_set(l_iter, -1);
314                 } while ((l_iter = l_iter->next) != l_first);
315
316                 // has_quad |= (f->len == 4)
317         }
318
319         /* adding new faces as we loop over faces
320          * is normally best avoided, however in this case its not so bad because any face touched twice
321          * will already be triangulated*/
322         BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
323                 if (f->len == 4) {
324                         BMLoop *f_l[4];
325                         BMLoop *l_a, *l_b;
326
327                         {
328                                 BMLoop *l_iter = BM_FACE_FIRST_LOOP(f);
329
330                                 f_l[0] = l_iter; l_iter = l_iter->next;
331                                 f_l[1] = l_iter; l_iter = l_iter->next;
332                                 f_l[2] = l_iter; l_iter = l_iter->next;
333                                 f_l[3] = l_iter;
334                         }
335
336                         if (len_squared_v3v3(f_l[0]->v->co, f_l[2]->v->co) <
337                             len_squared_v3v3(f_l[1]->v->co, f_l[3]->v->co))
338                         {
339                                 l_a = f_l[0];
340                                 l_b = f_l[2];
341                         }
342                         else {
343                                 l_a = f_l[1];
344                                 l_b = f_l[3];
345                         }
346
347 #ifdef USE_SAFETY_CHECKS
348                         if (BM_edge_exists(l_a->v, l_b->v) == false)
349 #endif
350                         {
351                                 BMFace *f_new;
352                                 BMLoop *l_new;
353
354                                 /* warning, NO_DOUBLE option here isn't handled as nice as it could be
355                                  * - if there is a quad that has a free standing edge joining it along
356                                  * where we want to split the face, there isnt a good way we can handle this.
357                                  * currently that edge will get removed when joining the tris back into a quad. */
358                                 f_new = BM_face_split(bm, f, l_a->v, l_b->v, &l_new, NULL, false);
359
360                                 if (f_new) {
361                                         /* the value of this doesn't matter, only that the 2 loops match and have unique values */
362                                         const int f_index = BM_elem_index_get(f);
363
364                                         /* since we just split theres only ever 2 loops */
365                                         BLI_assert(BM_edge_is_manifold(l_new->e));
366
367                                         BM_elem_index_set(l_new, f_index);
368                                         BM_elem_index_set(l_new->radial_next, f_index);
369
370                                         BM_face_normal_update(f);
371                                         BM_face_normal_update(f_new);
372
373                                         has_cut = true;
374                                 }
375                         }
376                 }
377         }
378
379         BLI_assert((bm->elem_index_dirty & BM_VERT) == 0);
380
381         if (has_cut) {
382                 /* now triangulation is done we need to correct index values */
383                 BM_mesh_elem_index_ensure(bm, BM_EDGE | BM_FACE);
384         }
385
386         return has_cut;
387 }
388
389 static void bm_decim_triangulate_end(BMesh *bm)
390 {
391         /* decimation finished, now re-join */
392         BMIter iter;
393         BMEdge *e;
394
395         /* boundary edges */
396         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
397                 BMLoop *l_a, *l_b;
398                 if (BM_edge_loop_pair(e, &l_a, &l_b)) {
399                         const int l_a_index = BM_elem_index_get(l_a);
400                         if (l_a_index != -1) {
401                                 const int l_b_index = BM_elem_index_get(l_b);
402                                 if (l_a_index == l_b_index) {
403                                         if (LIKELY(l_a->f->len == 3 && l_b->f->len == 3)) {
404                                                 if (l_a->v != l_b->v) {  /* if this is the case, faces have become flipped */
405                                                         /* check we are not making a degenerate quad */
406                                                         BMVert *vquad[4] = {
407                                                                 e->v1,
408                                                                 BM_vert_in_edge(e, l_a->next->v) ? l_a->prev->v : l_a->next->v,
409                                                                 e->v2,
410                                                                 BM_vert_in_edge(e, l_b->next->v) ? l_b->prev->v : l_b->next->v,
411                                                         };
412
413                                                         BLI_assert(ELEM3(vquad[0], vquad[1], vquad[2], vquad[3]) == false);
414                                                         BLI_assert(ELEM3(vquad[1], vquad[0], vquad[2], vquad[3]) == false);
415                                                         BLI_assert(ELEM3(vquad[2], vquad[1], vquad[0], vquad[3]) == false);
416                                                         BLI_assert(ELEM3(vquad[3], vquad[1], vquad[2], vquad[0]) == false);
417
418                                                         if (is_quad_convex_v3(vquad[0]->co, vquad[1]->co, vquad[2]->co, vquad[3]->co)) {
419                                                                 /* highly unlikely to fail, but prevents possible double-ups */
420                                                                 BMFace *f[2] = {l_a->f, l_b->f};
421                                                                 BM_faces_join(bm, f, 2, true);
422                                                         }
423                                                 }
424                                         }
425                                 }
426                         }
427                 }
428         }
429 }
430
431 #endif  /* USE_TRIANGULATE */
432
433 /* Edge Collapse Functions
434  * *********************** */
435
436 #ifdef USE_CUSTOMDATA
437
438 /**
439  * \param v is the target to merge into.
440  */
441 static void bm_edge_collapse_loop_customdata(BMesh *bm, BMLoop *l, BMVert *v_clear, BMVert *v_other,
442                                              const float customdata_fac)
443 {
444         /* disable seam check - the seam check would have to be done per layer, its not really that important */
445 //#define USE_SEAM
446         /* these don't need to be updated, since they will get removed when the edge collapses */
447         BMLoop *l_clear, *l_other;
448         const bool is_manifold = BM_edge_is_manifold(l->e);
449         int side;
450
451         /* l defines the vert to collapse into  */
452
453         /* first find the loop of 'v_other' thats attached to the face of 'l' */
454         if (l->v == v_clear) {
455                 l_clear = l;
456                 l_other = l->next;
457         }
458         else {
459                 l_clear = l->next;
460                 l_other = l;
461         }
462
463         BLI_assert(l_clear->v == v_clear);
464         BLI_assert(l_other->v == v_other);
465         (void)v_other;  /* quiet warnings for release */
466
467         /* now we have both corners of the face 'l->f' */
468         for (side = 0; side < 2; side++) {
469 #ifdef USE_SEAM
470                 bool is_seam = false;
471 #endif
472                 void *src[2];
473                 BMFace *f_exit = is_manifold ? l->radial_next->f : NULL;
474                 BMEdge *e_prev = l->e;
475                 BMLoop *l_first;
476                 BMLoop *l_iter;
477                 float w[2];
478
479                 if (side == 0) {
480                         l_iter = l_first = l_clear;
481                         src[0] = l_clear->head.data;
482                         src[1] = l_other->head.data;
483
484                         w[0] = customdata_fac;
485                         w[1] = 1.0f - customdata_fac;
486                 }
487                 else {
488                         l_iter = l_first = l_other;
489                         src[0] = l_other->head.data;
490                         src[1] = l_clear->head.data;
491
492                         w[0] = 1.0f - customdata_fac;
493                         w[1] = customdata_fac;
494                 }
495
496                 // print_v2("weights", w);
497
498                 /* WATCH IT! - should NOT reference (_clear or _other) vars for this while loop */
499
500                 /* walk around the fan using 'e_prev' */
501                 while (((l_iter = BM_vert_step_fan_loop(l_iter, &e_prev)) != l_first) && (l_iter != NULL)) {
502                         int i;
503                         /* quit once we hit the opposite face, if we have one */
504                         if (f_exit && UNLIKELY(f_exit == l_iter->f)) {
505                                 break;
506                         }
507
508 #ifdef USE_SEAM
509                         /* break out unless we find a match */
510                         is_seam = true;
511 #endif
512
513                         /* ok. we have a loop. now be smart with it! */
514                         for (i = 0; i < bm->ldata.totlayer; i++) {
515                                 if (CustomData_layer_has_math(&bm->ldata, i)) {
516                                         const int offset = bm->ldata.layers[i].offset;
517                                         const int type = bm->ldata.layers[i].type;
518                                         void *cd_src[2] = {(char *)src[0] + offset,
519                                                            (char *)src[1] + offset};
520                                         void *cd_iter = (char *)l_iter->head.data + offset;
521
522                                         /* detect seams */
523                                         if (CustomData_data_equals(type, cd_src[0], cd_iter)) {
524                                                 CustomData_bmesh_interp_n(&bm->ldata, cd_src, w, NULL, 2, l_iter->head.data, i);
525 #ifdef USE_SEAM
526                                                 is_seam = false;
527 #endif
528                                         }
529                                 }
530                         }
531
532 #ifdef USE_SEAM
533                         if (is_seam) {
534                                 break;
535                         }
536 #endif
537                 }
538         }
539
540 //#undef USE_SEAM
541
542 }
543 #endif  /* USE_CUSTOMDATA */
544
545 /**
546  * Check if the collapse will result in a degenerate mesh,
547  * that is - duplicate edges or faces.
548  *
549  * This situation could be checked for when calculating collapse cost
550  * however its quite slow and a degenerate collapse could eventuate
551  * after the cost is calculated, so instead, check just before collapsing.
552  */
553
554 static void bm_edge_tag_enable(BMEdge *e)
555 {
556         BM_elem_flag_enable(e->v1, BM_ELEM_TAG);
557         BM_elem_flag_enable(e->v2, BM_ELEM_TAG);
558         if (e->l) {
559                 BM_elem_flag_enable(e->l->f, BM_ELEM_TAG);
560                 if (e->l != e->l->radial_next) {
561                         BM_elem_flag_enable(e->l->radial_next->f, BM_ELEM_TAG);
562                 }
563         }
564 }
565
566 static void bm_edge_tag_disable(BMEdge *e)
567 {
568         BM_elem_flag_disable(e->v1, BM_ELEM_TAG);
569         BM_elem_flag_disable(e->v2, BM_ELEM_TAG);
570         if (e->l) {
571                 BM_elem_flag_disable(e->l->f, BM_ELEM_TAG);
572                 if (e->l != e->l->radial_next) {
573                         BM_elem_flag_disable(e->l->radial_next->f, BM_ELEM_TAG);
574                 }
575         }
576 }
577
578 static int bm_edge_tag_test(BMEdge *e)
579 {
580         /* is the edge or one of its faces tagged? */
581         return (BM_elem_flag_test(e->v1, BM_ELEM_TAG) ||
582                 BM_elem_flag_test(e->v2, BM_ELEM_TAG) ||
583                 (e->l && (BM_elem_flag_test(e->l->f, BM_ELEM_TAG) ||
584                           (e->l != e->l->radial_next &&
585                           BM_elem_flag_test(e->l->radial_next->f, BM_ELEM_TAG))))
586                 );
587 }
588
589 /* takes the edges loop */
590 BLI_INLINE int bm_edge_is_manifold_or_boundary(BMLoop *l)
591 {
592 #if 0
593         /* less optimized version of check below */
594         return (BM_edge_is_manifold(l->e) || BM_edge_is_boundary(l->e);
595 #else
596         /* if the edge is a boundary it points to its self, else this must be a manifold */
597         return LIKELY(l) && LIKELY(l->radial_next->radial_next == l);
598 #endif
599 }
600
601 static bool bm_edge_collapse_is_degenerate_topology(BMEdge *e_first)
602 {
603         /* simply check that there is no overlap between faces and edges of each vert,
604          * (excluding the 2 faces attached to 'e' and 'e' its self) */
605
606         BMEdge *e_iter;
607
608         /* clear flags on both disks */
609         e_iter = e_first;
610         do {
611                 if (!bm_edge_is_manifold_or_boundary(e_iter->l)) {
612                         return true;
613                 }
614                 bm_edge_tag_disable(e_iter);
615         } while ((e_iter = bmesh_disk_edge_next(e_iter, e_first->v1)) != e_first);
616
617         e_iter = e_first;
618         do {
619                 if (!bm_edge_is_manifold_or_boundary(e_iter->l)) {
620                         return true;
621                 }
622                 bm_edge_tag_disable(e_iter);
623         } while ((e_iter = bmesh_disk_edge_next(e_iter, e_first->v2)) != e_first);
624
625         /* now enable one side... */
626         e_iter = e_first;
627         do {
628                 bm_edge_tag_enable(e_iter);
629         } while ((e_iter = bmesh_disk_edge_next(e_iter, e_first->v1)) != e_first);
630
631         /* ... except for the edge we will collapse, we know thats shared,
632          * disable this to avoid false positive. We could be smart and never enable these
633          * face/edge tags in the first place but easier to do this */
634         // bm_edge_tag_disable(e_first);
635         /* do inline... */
636         {
637 #if 0
638                 BMIter iter;
639                 BMIter liter;
640                 BMLoop *l;
641                 BMVert *v;
642                 BM_ITER_ELEM (l, &liter, e_first, BM_LOOPS_OF_EDGE) {
643                         BM_elem_flag_disable(l->f, BM_ELEM_TAG);
644                         BM_ITER_ELEM (v, &iter, l->f, BM_VERTS_OF_FACE) {
645                                 BM_elem_flag_disable(v, BM_ELEM_TAG);
646                         }
647                 }
648 #else
649                 /* we know each face is a triangle, no looping/iterators needed here */
650
651                 BMLoop *l_radial;
652                 BMLoop *l_face;
653
654                 l_radial = e_first->l;
655                 l_face = l_radial;
656                 BLI_assert(l_face->f->len == 3);
657                 BM_elem_flag_disable(l_face->f, BM_ELEM_TAG);
658                 BM_elem_flag_disable((l_face = l_radial)->v,     BM_ELEM_TAG);
659                 BM_elem_flag_disable((l_face = l_face->next)->v, BM_ELEM_TAG);
660                 BM_elem_flag_disable((         l_face->next)->v, BM_ELEM_TAG);
661                 l_face = l_radial->radial_next;
662                 if (l_radial != l_face) {
663                         BLI_assert(l_face->f->len == 3);
664                         BM_elem_flag_disable(l_face->f, BM_ELEM_TAG);
665                         BM_elem_flag_disable((l_face = l_radial->radial_next)->v, BM_ELEM_TAG);
666                         BM_elem_flag_disable((l_face = l_face->next)->v,          BM_ELEM_TAG);
667                         BM_elem_flag_disable((         l_face->next)->v,          BM_ELEM_TAG);
668                 }
669 #endif
670         }
671
672         /* and check for overlap */
673         e_iter = e_first;
674         do {
675                 if (bm_edge_tag_test(e_iter)) {
676                         return true;
677                 }
678         } while ((e_iter = bmesh_disk_edge_next(e_iter, e_first->v2)) != e_first);
679
680         return false;
681 }
682
683 /**
684  * special, highly limited edge collapse function
685  * intended for speed over flexibility.
686  * can only collapse edges connected to (1, 2) tris.
687  *
688  * Important - dont add vert/edge/face data on collapsing!
689  *
690  * \param e_clear_other let caller know what edges we remove besides \a e_clear
691  * \param customdata_flag merge factor, scales from 0 - 1 ('v_clear' -> 'v_other')
692  */
693 static bool bm_edge_collapse(BMesh *bm, BMEdge *e_clear, BMVert *v_clear, int r_e_clear_other[2],
694 #ifdef USE_CUSTOMDATA
695                              const CD_UseFlag customdata_flag,
696                              const float customdata_fac
697 #else
698                              const CD_UseFlag UNUSED(customdata_flag),
699                              const float UNUSED(customdata_fac)
700 #endif
701                             )
702 {
703         BMVert *v_other;
704
705         v_other = BM_edge_other_vert(e_clear, v_clear);
706         BLI_assert(v_other != NULL);
707
708         if (BM_edge_is_manifold(e_clear)) {
709                 BMLoop *l_a, *l_b;
710                 BMEdge *e_a_other[2], *e_b_other[2];
711                 bool ok;
712
713                 ok = BM_edge_loop_pair(e_clear, &l_a, &l_b);
714
715                 BLI_assert(ok == true);
716                 BLI_assert(l_a->f->len == 3);
717                 BLI_assert(l_b->f->len == 3);
718
719                 /* keep 'v_clear' 0th */
720                 if (BM_vert_in_edge(l_a->prev->e, v_clear)) {
721                         e_a_other[0] = l_a->prev->e;
722                         e_a_other[1] = l_a->next->e;
723                 }
724                 else {
725                         e_a_other[1] = l_a->prev->e;
726                         e_a_other[0] = l_a->next->e;
727                 }
728
729                 if (BM_vert_in_edge(l_b->prev->e, v_clear)) {
730                         e_b_other[0] = l_b->prev->e;
731                         e_b_other[1] = l_b->next->e;
732                 }
733                 else {
734                         e_b_other[1] = l_b->prev->e;
735                         e_b_other[0] = l_b->next->e;
736                 }
737
738                 /* we could assert this case, but better just bail out */
739 #if 0
740                 BLI_assert(e_a_other[0] != e_b_other[0]);
741                 BLI_assert(e_a_other[0] != e_b_other[1]);
742                 BLI_assert(e_b_other[0] != e_a_other[0]);
743                 BLI_assert(e_b_other[0] != e_a_other[1]);
744 #endif
745                 /* not totally common but we want to avoid */
746                 if (ELEM(e_a_other[0], e_b_other[0], e_b_other[1]) ||
747                     ELEM(e_a_other[1], e_b_other[0], e_b_other[1]))
748                 {
749                         return false;
750                 }
751
752                 BLI_assert(BM_edge_share_vert(e_a_other[0], e_b_other[0]));
753                 BLI_assert(BM_edge_share_vert(e_a_other[1], e_b_other[1]));
754
755                 r_e_clear_other[0] = BM_elem_index_get(e_a_other[0]);
756                 r_e_clear_other[1] = BM_elem_index_get(e_b_other[0]);
757
758 #ifdef USE_CUSTOMDATA
759                 /* before killing, do customdata */
760                 if (customdata_flag & CD_DO_VERT) {
761                         BM_data_interp_from_verts(bm, v_other, v_clear, v_other, customdata_fac);
762                 }
763                 if (customdata_flag & CD_DO_EDGE) {
764                         BM_data_interp_from_edges(bm, e_a_other[1], e_a_other[0], e_a_other[1], customdata_fac);
765                         BM_data_interp_from_edges(bm, e_b_other[1], e_b_other[0], e_b_other[1], customdata_fac);
766                 }
767                 if (customdata_flag & CD_DO_LOOP) {
768                         bm_edge_collapse_loop_customdata(bm, e_clear->l,              v_clear, v_other, customdata_fac);
769                         bm_edge_collapse_loop_customdata(bm, e_clear->l->radial_next, v_clear, v_other, customdata_fac);
770                 }
771 #endif
772
773                 BM_edge_kill(bm, e_clear);
774
775                 v_other->head.hflag |= v_clear->head.hflag;
776                 BM_vert_splice(bm, v_clear, v_other);
777
778                 e_a_other[1]->head.hflag |= e_a_other[0]->head.hflag;
779                 e_b_other[1]->head.hflag |= e_b_other[0]->head.hflag;
780                 BM_edge_splice(bm, e_a_other[0], e_a_other[1]);
781                 BM_edge_splice(bm, e_b_other[0], e_b_other[1]);
782
783                 // BM_mesh_validate(bm);
784
785                 return true;
786         }
787         else if (BM_edge_is_boundary(e_clear)) {
788                 /* same as above but only one triangle */
789                 BMLoop *l_a;
790                 BMEdge *e_a_other[2];
791
792                 l_a = e_clear->l;
793
794                 BLI_assert(l_a->f->len == 3);
795
796                 /* keep 'v_clear' 0th */
797                 if (BM_vert_in_edge(l_a->prev->e, v_clear)) {
798                         e_a_other[0] = l_a->prev->e;
799                         e_a_other[1] = l_a->next->e;
800                 }
801                 else {
802                         e_a_other[1] = l_a->prev->e;
803                         e_a_other[0] = l_a->next->e;
804                 }
805
806                 r_e_clear_other[0] = BM_elem_index_get(e_a_other[0]);
807                 r_e_clear_other[1] = -1;
808
809 #ifdef USE_CUSTOMDATA
810                 /* before killing, do customdata */
811                 if (customdata_flag & CD_DO_VERT) {
812                         BM_data_interp_from_verts(bm, v_other, v_clear, v_other, customdata_fac);
813                 }
814                 if (customdata_flag & CD_DO_EDGE) {
815                         BM_data_interp_from_edges(bm, e_a_other[1], e_a_other[0], e_a_other[1], customdata_fac);
816                 }
817                 if (customdata_flag & CD_DO_LOOP) {
818                         bm_edge_collapse_loop_customdata(bm, e_clear->l, v_clear, v_other, customdata_fac);
819                 }
820 #endif
821
822                 BM_edge_kill(bm, e_clear);
823
824                 v_other->head.hflag |= v_clear->head.hflag;
825                 BM_vert_splice(bm, v_clear, v_other);
826
827                 e_a_other[1]->head.hflag |= e_a_other[0]->head.hflag;
828                 BM_edge_splice(bm, e_a_other[0], e_a_other[1]);
829
830                 // BM_mesh_validate(bm);
831
832                 return true;
833         }
834         else {
835                 return false;
836         }
837 }
838
839
840 /* collapse e the edge, removing e->v2 */
841 static void bm_decim_edge_collapse(BMesh *bm, BMEdge *e,
842                                    Quadric *vquadrics, float *vweights,
843                                    Heap *eheap, HeapNode **eheap_table,
844                                    const CD_UseFlag customdata_flag)
845 {
846         int e_clear_other[2];
847         BMVert *v_other = e->v1;
848         int v_clear_index = BM_elem_index_get(e->v2);  /* the vert is removed so only store the index */
849         float optimize_co[3];
850         float customdata_fac;
851
852 #ifdef USE_VERT_NORMAL_INTERP
853         float v_clear_no[3];
854         copy_v3_v3(v_clear_no, e->v2->no);
855 #endif
856
857         /* disallow collapsing which results in degenerate cases */
858         if (UNLIKELY(bm_edge_collapse_is_degenerate_topology(e))) {
859                 bm_decim_invalid_edge_cost_single(e, eheap, eheap_table);  /* add back with a high cost */
860                 return;
861         }
862
863         bm_decim_calc_target_co(e, optimize_co, vquadrics);
864
865         /* check if this would result in an overlapping face */
866         if (UNLIKELY(bm_edge_collapse_is_degenerate_flip(e, optimize_co))) {
867                 bm_decim_invalid_edge_cost_single(e, eheap, eheap_table);  /* add back with a high cost */
868                 return;
869         }
870
871         /* use for customdata merging */
872         if (LIKELY(compare_v3v3(e->v1->co, e->v2->co, FLT_EPSILON) == false)) {
873                 customdata_fac = line_point_factor_v3(optimize_co, e->v1->co, e->v2->co);
874 #if 0
875                 /* simple test for stupid collapse */
876                 if (customdata_fac < 0.0 - FLT_EPSILON || customdata_fac > 1.0f + FLT_EPSILON) {
877                         return;
878                 }
879 #endif
880         }
881         else {
882                 /* avoid divide by zero */
883                 customdata_fac = 0.5f;
884         }
885
886         if (bm_edge_collapse(bm, e, e->v2, e_clear_other, customdata_flag, customdata_fac)) {
887                 /* update collapse info */
888                 int i;
889
890                 if (vweights) {
891                         vweights[BM_elem_index_get(v_other)] += vweights[v_clear_index];
892                 }
893
894                 e = NULL;  /* paranoid safety check */
895
896                 copy_v3_v3(v_other->co, optimize_co);
897
898                 /* remove eheap */
899                 for (i = 0; i < 2; i++) {
900                         /* highly unlikely 'eheap_table[ke_other[i]]' would be NULL, but do for sanity sake */
901                         if ((e_clear_other[i] != -1) && (eheap_table[e_clear_other[i]] != NULL)) {
902                                 BLI_heap_remove(eheap, eheap_table[e_clear_other[i]]);
903                                 eheap_table[e_clear_other[i]] = NULL;
904                         }
905                 }
906
907                 /* update vertex quadric, add kept vertex from killed vertex */
908                 BLI_quadric_add_qu_qu(&vquadrics[BM_elem_index_get(v_other)], &vquadrics[v_clear_index]);
909
910                 /* update connected normals */
911
912                 /* in fact face normals are not used for progressive updates, no need to update them */
913                 // BM_vert_normal_update_all(v);
914 #ifdef USE_VERT_NORMAL_INTERP
915                 interp_v3_v3v3(v_other->no, v_other->no, v_clear_no, customdata_fac);
916                 normalize_v3(v_other->no);
917 #else
918                 BM_vert_normal_update(v_other);
919 #endif
920
921
922                 /* update error costs and the eheap */
923                 if (LIKELY(v_other->e)) {
924                         BMEdge *e_iter;
925                         BMEdge *e_first;
926                         e_iter = e_first = v_other->e;
927                         do {
928                                 BLI_assert(BM_edge_find_double(e_iter) == NULL);
929                                 bm_decim_build_edge_cost_single(e_iter, vquadrics, vweights, eheap, eheap_table);
930                         } while ((e_iter = bmesh_disk_edge_next(e_iter, v_other)) != e_first);
931                 }
932
933                 /* this block used to be disabled,
934                  * but enable now since surrounding faces may have been
935                  * set to COST_INVALID because of a face overlap that no longer occurs */
936 #if 1
937                 /* optional, update edges around the vertex face fan */
938                 {
939                         BMIter liter;
940                         BMLoop *l;
941                         BM_ITER_ELEM (l, &liter, v_other, BM_LOOPS_OF_VERT) {
942                                 if (l->f->len == 3) {
943                                         BMEdge *e_outer;
944                                         if (BM_vert_in_edge(l->prev->e, l->v))
945                                                 e_outer = l->next->e;
946                                         else
947                                                 e_outer = l->prev->e;
948
949                                         BLI_assert(BM_vert_in_edge(e_outer, l->v) == false);
950
951                                         bm_decim_build_edge_cost_single(e_outer, vquadrics, vweights, eheap, eheap_table);
952                                 }
953                         }
954                 }
955                 /* end optional update */
956 #endif
957         }
958         else {
959                 /* add back with a high cost */
960                 bm_decim_invalid_edge_cost_single(e, eheap, eheap_table);
961         }
962 }
963
964
965 /* Main Decimate Function
966  * ********************** */
967
968 /**
969  * \brief BM_mesh_decimate
970  * \param bm The mesh
971  * \param factor face count multiplier [0 - 1]
972  * \param vweights Optional array of vertex  aligned weights [0 - 1],
973  *        a vertex group is the usual source for this.
974  */
975 void BM_mesh_decimate_collapse(BMesh *bm, const float factor, float *vweights, const bool do_triangulate)
976 {
977         Heap *eheap;             /* edge heap */
978         HeapNode **eheap_table;  /* edge index aligned table pointing to the eheap */
979         Quadric *vquadrics;      /* vert index aligned quadrics */
980         int tot_edge_orig;
981         int face_tot_target;
982         bool use_triangulate;
983
984         CD_UseFlag customdata_flag = 0;
985
986 #ifdef USE_TRIANGULATE
987         /* temp convert quads to triangles */
988         use_triangulate = bm_decim_triangulate_begin(bm);
989 #endif
990
991
992         /* alloc vars */
993         vquadrics = MEM_callocN(sizeof(Quadric) * bm->totvert, __func__);
994         /* since some edges may be degenerate, we might be over allocing a little here */
995         eheap = BLI_heap_new_ex(bm->totedge);
996         eheap_table = MEM_mallocN(sizeof(HeapNode *) * bm->totedge, __func__);
997         tot_edge_orig = bm->totedge;
998
999
1000         /* build initial edge collapse cost data */
1001         bm_decim_build_quadrics(bm, vquadrics);
1002
1003         bm_decim_build_edge_cost(bm, vquadrics, vweights, eheap, eheap_table);
1004
1005         face_tot_target = bm->totface * factor;
1006         bm->elem_index_dirty |= BM_FACE | BM_EDGE | BM_VERT;
1007
1008
1009 #ifdef USE_CUSTOMDATA
1010         /* initialize customdata flag, we only need math for loops */
1011         if (CustomData_has_interp(&bm->vdata))  customdata_flag |= CD_DO_VERT;
1012         if (CustomData_has_interp(&bm->edata))  customdata_flag |= CD_DO_EDGE;
1013         if (CustomData_has_math(&bm->ldata))    customdata_flag |= CD_DO_LOOP;
1014 #endif
1015
1016         /* iterative edge collapse and maintain the eheap */
1017         while ((bm->totface > face_tot_target) &&
1018                (BLI_heap_is_empty(eheap) == false) &&
1019                (BLI_heap_node_value(BLI_heap_top(eheap)) != COST_INVALID))
1020         {
1021                 // const float value = BLI_heap_node_value(BLI_heap_top(eheap));
1022                 BMEdge *e = BLI_heap_popmin(eheap);
1023                 BLI_assert(BM_elem_index_get(e) < tot_edge_orig);  /* handy to detect corruptions elsewhere */
1024
1025                 // printf("COST %.10f\n", value);
1026
1027                 /* under normal conditions wont be accessed again,
1028                  * but NULL just incase so we don't use freed node */
1029                 eheap_table[BM_elem_index_get(e)] = NULL;
1030
1031                 bm_decim_edge_collapse(bm, e, vquadrics, vweights, eheap, eheap_table, customdata_flag);
1032         }
1033
1034
1035 #ifdef USE_TRIANGULATE
1036         if (do_triangulate == false) {
1037                 /* its possible we only had triangles, skip this step in that case */
1038                 if (LIKELY(use_triangulate)) {
1039                         /* temp convert quads to triangles */
1040                         bm_decim_triangulate_end(bm);
1041                 }
1042         }
1043 #endif
1044
1045         /* free vars */
1046         MEM_freeN(vquadrics);
1047         MEM_freeN(eheap_table);
1048         BLI_heap_free(eheap, NULL);
1049
1050         /* testing only */
1051         // BM_mesh_validate(bm);
1052
1053         (void)tot_edge_orig;  /* quiet release build warning */
1054 }