doxygen: add newline after \file
[blender.git] / source / blender / bmesh / operators / bmo_normals.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  */
16
17 /** \file
18  * \ingroup bmesh
19  *
20  * normal recalculation.
21  */
22
23 #include "MEM_guardedalloc.h"
24
25 #include "BLI_math.h"
26 #include "BLI_linklist_stack.h"
27
28 #include "bmesh.h"
29
30 #include "intern/bmesh_operators_private.h" /* own include */
31
32 /********* righthand faces implementation ****** */
33
34 #define FACE_FLAG       (1 << 0)
35 #define FACE_FLIP       (1 << 1)
36 #define FACE_TEMP       (1 << 2)
37
38 static bool bmo_recalc_normal_loop_filter_cb(const BMLoop *l, void *UNUSED(user_data))
39 {
40         return BM_edge_is_manifold(l->e);
41 }
42
43 /**
44  * This uses a more comprehensive test to see if the furthest face from the center
45  * is pointing towards the center or not.
46  *
47  * A simple test could just check the dot product of the faces-normal and the direction from the center,
48  * however this can fail for faces which make a sharp spike. eg:
49  *
50  * <pre>
51  * +
52  * |\ <- face
53  * + +
54  * \ \
55  *   \ \
56  *    \ +--------------+
57  *     \               |
58  *      \ center -> +  |
59  *       \             |
60  *        +------------+
61  * </pre>
62  *
63  * In the example above, the a\ face can point towards the \a center
64  * which would end up flipping the normals inwards.
65  *
66  * To take these spikes into account, find the furthest face-loop-vertex.
67  */
68
69 /**
70  * \return a face index in \a faces and set \a r_is_flip if the face is flipped away from the center.
71  */
72 static int recalc_face_normals_find_index(BMesh *bm, BMFace **faces, const int faces_len, bool *r_is_flip)
73 {
74         const float eps = FLT_EPSILON;
75         float cent_area_accum = 0.0f;
76         float cent[3];
77         const float cent_fac = 1.0f / (float)faces_len;
78
79         bool is_flip = false;
80         int f_start_index;
81         int i;
82
83         /* Search for the best loop. Members are compared in-order defined here. */
84         struct {
85                 /* Squared distance from the center to the loops vertex 'l->v'.
86                  * The normalized direction between the center and this vertex is also used for the dot-products below. */
87                 float dist_sq;
88                 /* Signed dot product using the normalized edge vector,
89                  * (best of 'l->prev->v' or 'l->next->v'). */
90                 float edge_dot;
91                 /* Unsigned dot product using the loop-normal
92                  * (sign is used to check if we need to flip) */
93                 float loop_dot;
94         } best, test;
95
96         UNUSED_VARS_NDEBUG(bm);
97
98         zero_v3(cent);
99
100         /* first calculate the center */
101         for (i = 0; i < faces_len; i++) {
102                 float f_cent[3];
103                 const float f_area = BM_face_calc_area(faces[i]);
104                 BM_face_calc_center_median_weighted(faces[i], f_cent);
105                 madd_v3_v3fl(cent, f_cent, cent_fac * f_area);
106                 cent_area_accum += f_area;
107
108                 BLI_assert(BMO_face_flag_test(bm, faces[i], FACE_TEMP) == 0);
109                 BLI_assert(BM_face_is_normal_valid(faces[i]));
110         }
111
112         if (cent_area_accum != 0.0f) {
113                 mul_v3_fl(cent, 1.0f / cent_area_accum);
114         }
115
116         /* Distances must start above zero,
117          * or we can't do meaningful calculations based on the direction to the center */
118         best.dist_sq = eps;
119         best.edge_dot = best.loop_dot = -FLT_MAX;
120
121         /* used in degenerate cases only */
122         f_start_index = 0;
123
124         /**
125          * Find the outer-most vertex, comparing distance to the center,
126          * then the outer-most loop attached to that vertex.
127          *
128          * Important this is correctly detected,
129          * where casting a ray from the center wont hit any loops past this one.
130          * Otherwise the result may be incorrect.
131          */
132         for (i = 0; i < faces_len; i++) {
133                 BMLoop *l_iter, *l_first;
134
135                 l_iter = l_first = BM_FACE_FIRST_LOOP(faces[i]);
136                 do {
137                         bool is_best_dist_sq;
138                         float dir[3];
139                         sub_v3_v3v3(dir, l_iter->v->co, cent);
140                         test.dist_sq = len_squared_v3(dir);
141                         is_best_dist_sq =      (test.dist_sq  > best.dist_sq);
142                         if (is_best_dist_sq || (test.dist_sq == best.dist_sq)) {
143                                 float edge_dir_pair[2][3];
144                                 mul_v3_fl(dir, 1.0f / sqrtf(test.dist_sq));
145
146                                 sub_v3_v3v3(edge_dir_pair[0], l_iter->next->v->co, l_iter->v->co);
147                                 sub_v3_v3v3(edge_dir_pair[1], l_iter->prev->v->co, l_iter->v->co);
148
149                                 if ((normalize_v3(edge_dir_pair[0]) > eps) &&
150                                     (normalize_v3(edge_dir_pair[1]) > eps))
151                                 {
152                                         bool is_best_edge_dot;
153                                         test.edge_dot = max_ff(dot_v3v3(dir, edge_dir_pair[0]),
154                                                                dot_v3v3(dir, edge_dir_pair[1]));
155                                         is_best_edge_dot =                         (test.edge_dot  > best.edge_dot);
156                                         if (is_best_dist_sq || is_best_edge_dot || (test.edge_dot == best.edge_dot)) {
157                                                 float loop_dir[3];
158                                                 cross_v3_v3v3(loop_dir, edge_dir_pair[0], edge_dir_pair[1]);
159                                                 if (normalize_v3(loop_dir) > eps) {
160                                                         float loop_dir_dot;
161                                                         /* Highly unlikely the furthest loop is also the concave part of an ngon,
162                                                          * but it can be contrived with _very_ non-planar faces - so better check. */
163                                                         if (UNLIKELY(dot_v3v3(loop_dir, l_iter->f->no) < 0.0f)) {
164                                                                 negate_v3(loop_dir);
165                                                         }
166                                                         loop_dir_dot = dot_v3v3(dir, loop_dir);
167                                                         test.loop_dot = fabsf(loop_dir_dot);
168                                                         if (is_best_dist_sq || is_best_edge_dot || (test.loop_dot > best.loop_dot)) {
169                                                                 best = test;
170                                                                 f_start_index = i;
171                                                                 is_flip = (loop_dir_dot < 0.0f);
172                                                         }
173                                                 }
174                                         }
175                                 }
176                         }
177                 } while ((l_iter = l_iter->next) != l_first);
178         }
179
180         *r_is_flip = is_flip;
181         return f_start_index;
182 }
183
184 /**
185  * Given an array of faces, recalculate their normals.
186  * this functions assumes all faces in the array are connected by edges.
187  *
188  * \param bm:
189  * \param faces: Array of connected faces.
190  * \param faces_len: Length of \a faces
191  * \param oflag: Flag to check before doing the actual face flipping.
192  */
193 static void bmo_recalc_face_normals_array(BMesh *bm, BMFace **faces, const int faces_len, const short oflag)
194 {
195         int i, f_start_index;
196         const short oflag_flip = oflag | FACE_FLIP;
197         bool is_flip;
198
199         BMFace *f;
200
201         BLI_LINKSTACK_DECLARE(fstack, BMFace *);
202
203         f_start_index = recalc_face_normals_find_index(bm, faces, faces_len, &is_flip);
204
205         if (is_flip) {
206                 BMO_face_flag_enable(bm, faces[f_start_index], FACE_FLIP);
207         }
208
209         /* now that we've found our starting face, make all connected faces
210          * have the same winding.  this is done recursively, using a manual
211          * stack (if we use simple function recursion, we'd end up overloading
212          * the stack on large meshes). */
213         BLI_LINKSTACK_INIT(fstack);
214
215         BLI_LINKSTACK_PUSH(fstack, faces[f_start_index]);
216         BMO_face_flag_enable(bm, faces[f_start_index], FACE_TEMP);
217
218         while ((f = BLI_LINKSTACK_POP(fstack))) {
219                 const bool flip_state = BMO_face_flag_test_bool(bm, f, FACE_FLIP);
220                 BMLoop *l_iter, *l_first;
221
222                 l_iter = l_first = BM_FACE_FIRST_LOOP(f);
223                 do {
224                         BMLoop *l_other = l_iter->radial_next;
225
226                         if ((l_other != l_iter) && bmo_recalc_normal_loop_filter_cb(l_iter, NULL)) {
227                                 if (!BMO_face_flag_test(bm, l_other->f, FACE_TEMP)) {
228                                         BMO_face_flag_enable(bm, l_other->f, FACE_TEMP);
229                                         BMO_face_flag_set(bm, l_other->f, FACE_FLIP, (l_other->v == l_iter->v) != flip_state);
230                                         BLI_LINKSTACK_PUSH(fstack, l_other->f);
231                                 }
232                         }
233                 } while ((l_iter = l_iter->next) != l_first);
234         }
235
236         BLI_LINKSTACK_FREE(fstack);
237
238         /* apply flipping to oflag'd faces */
239         for (i = 0; i < faces_len; i++) {
240                 if (BMO_face_flag_test(bm, faces[i], oflag_flip) == oflag_flip) {
241                         BM_face_normal_flip(bm, faces[i]);
242                 }
243                 BMO_face_flag_disable(bm, faces[i], FACE_TEMP);
244         }
245 }
246
247 /*
248  * put normal to the outside, and set the first direction flags in edges
249  *
250  * then check the object, and set directions / direction-flags: but only for edges with 1 or 2 faces
251  * this is in fact the 'select connected'
252  *
253  * in case all faces were not done: start over with 'find the ultimate ...' */
254
255 void bmo_recalc_face_normals_exec(BMesh *bm, BMOperator *op)
256 {
257         int *groups_array = MEM_mallocN(sizeof(*groups_array) * bm->totface, __func__);
258         BMFace **faces_grp = MEM_mallocN(sizeof(*faces_grp) * bm->totface, __func__);
259
260         int (*group_index)[2];
261         const int group_tot = BM_mesh_calc_face_groups(
262                 bm, groups_array, &group_index,
263                 bmo_recalc_normal_loop_filter_cb, NULL,
264                 0, BM_EDGE);
265         int i;
266
267         BMO_slot_buffer_flag_enable(bm, op->slots_in, "faces", BM_FACE, FACE_FLAG);
268
269         BM_mesh_elem_table_ensure(bm, BM_FACE);
270
271         for (i = 0; i < group_tot; i++) {
272                 const int fg_sta = group_index[i][0];
273                 const int fg_len = group_index[i][1];
274                 int j;
275                 bool is_calc = false;
276
277                 for (j = 0; j < fg_len; j++) {
278                         faces_grp[j] = BM_face_at_index(bm, groups_array[fg_sta + j]);
279
280                         if (is_calc == false) {
281                                 is_calc = BMO_face_flag_test_bool(bm, faces_grp[j], FACE_FLAG);
282                         }
283                 }
284
285                 if (is_calc) {
286                         bmo_recalc_face_normals_array(bm, faces_grp, fg_len, FACE_FLAG);
287                 }
288         }
289
290         MEM_freeN(faces_grp);
291
292         MEM_freeN(groups_array);
293         MEM_freeN(group_index);
294 }