Merge branch 'master' into blender2.8
[blender.git] / source / blender / modifiers / intern / MOD_skin.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): Nicholas Bishop
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  *
22  */
23
24 /** \file blender/modifiers/intern/MOD_skin.c
25  *  \ingroup modifiers
26  */
27
28 /* Implementation based in part off the paper "B-Mesh: A Fast Modeling
29  * System for Base Meshes of 3D Articulated Shapes" (Zhongping Ji,
30  * Ligang Liu, Yigang Wang)
31  * 
32  * Note that to avoid confusion with Blender's BMesh data structure,
33  * this tool is renamed as the Skin modifier.
34  *
35  * The B-Mesh paper is current available here:
36  * http://www.math.zju.edu.cn/ligangliu/CAGD/Projects/BMesh/
37  *
38  * The main missing features in this code compared to the paper are:
39  * 
40  * + No mesh evolution. The paper suggests iteratively subsurfing the
41  *   skin output and adapting the output to better conform with the
42  *   spheres of influence surrounding each vertex.
43  *
44  * + No mesh fairing. The paper suggests re-aligning output edges to
45  *   follow principal mesh curvatures.
46  *
47  * + No auxiliary balls. These would serve to influence mesh
48  *   evolution, which as noted above is not implemented.
49  *
50  * The code also adds some features not present in the paper:
51  *
52  * + Loops in the input edge graph.
53  *
54  * + Concave surfaces around branch nodes. The paper does not discuss
55  *   how to handle non-convex regions; this code adds a number of
56  *   cleanup operations to handle many (though not all) of these
57  *   cases.
58  */
59
60 #include "MEM_guardedalloc.h"
61
62 #include "DNA_mesh_types.h"
63 #include "DNA_meshdata_types.h"
64 #include "DNA_object_types.h"
65 #include "DNA_modifier_types.h"
66
67 #include "BLI_utildefines.h"
68 #include "BLI_array.h"
69 #include "BLI_heap.h"
70 #include "BLI_math.h"
71 #include "BLI_stack.h"
72 #include "BLI_bitmap.h"
73
74 #include "BKE_deform.h"
75 #include "BKE_library.h"
76 #include "BKE_mesh.h"
77 #include "BKE_mesh_mapping.h"
78 #include "BKE_modifier.h"
79
80 #include "MOD_modifiertypes.h"
81
82 #include "bmesh.h"
83
84 typedef struct {
85         float mat[3][3];
86         /* Vert that edge is pointing away from, no relation to
87          * MEdge.v1 */
88         int origin;
89 } EMat;
90
91 typedef enum {
92         CAP_START = 1,
93         CAP_END = 2,
94         SEAM_FRAME = 4,
95         ROOT = 8
96 } SkinNodeFlag;
97
98 typedef struct Frame {
99         /* Index in the MVert array */
100         BMVert *verts[4];
101         /* Location of each corner */
102         float co[4][3];
103         /* Indicates which corners have been merged with another
104          * frame's corner (so they share an MVert index) */
105         struct {
106                 /* Merge to target frame/corner (no merge if frame is null) */
107                 struct Frame *frame;
108                 int corner;
109                 /* checked to avoid chaining.
110                  * (merging when we're already been referenced), see T39775 */
111                 unsigned int is_target : 1;
112         } merge[4];
113
114         /* For hull frames, whether each vertex is detached or not */
115         bool inside_hull[4];
116         /* Whether any part of the frame (corner or edge) is detached */
117         bool detached;
118 } Frame;
119
120 #define MAX_SKIN_NODE_FRAMES 2
121 typedef struct {
122         Frame frames[MAX_SKIN_NODE_FRAMES];
123         int totframe;
124
125         SkinNodeFlag flag;
126
127         /* Used for hulling a loop seam */
128         int seam_edges[2];
129 } SkinNode;
130
131 typedef struct {
132         BMesh *bm;
133         SkinModifierData *smd;
134         int mat_nr;
135 } SkinOutput;
136
137 static void add_poly(
138         SkinOutput *so,
139         BMVert *v1,
140         BMVert *v2,
141         BMVert *v3,
142         BMVert *v4);
143
144 /***************************** Convex Hull ****************************/
145
146 static bool is_quad_symmetric(
147         BMVert *quad[4],
148         const SkinModifierData *smd)
149 {
150         const float threshold = 0.0001f;
151         const float threshold_squared = threshold * threshold;
152         int axis;
153
154         for (axis = 0; axis < 3; axis++) {
155                 if (smd->symmetry_axes & (1 << axis)) {
156                         float a[3];
157
158                         copy_v3_v3(a, quad[0]->co);
159                         a[axis] = -a[axis];
160
161                         if (len_squared_v3v3(a, quad[1]->co) < threshold_squared) {
162                                 copy_v3_v3(a, quad[2]->co);
163                                 a[axis] = -a[axis];
164                                 if (len_squared_v3v3(a, quad[3]->co) < threshold_squared)
165                                         return 1;
166                         }
167                         else if (len_squared_v3v3(a, quad[3]->co) < threshold_squared) {
168                                 copy_v3_v3(a, quad[2]->co);
169                                 a[axis] = -a[axis];
170                                 if (len_squared_v3v3(a, quad[1]->co) < threshold_squared)
171                                         return 1;
172                         }
173                 }
174         }
175
176         return 0;
177 }
178
179 /* Returns true if the quad crosses the plane of symmetry, false otherwise */
180 static bool quad_crosses_symmetry_plane(
181         BMVert *quad[4],
182         const SkinModifierData *smd)
183 {
184         int axis;
185
186         for (axis = 0; axis < 3; axis++) {
187                 if (smd->symmetry_axes & (1 << axis)) {
188                         bool left = false, right = false;
189                         int i;
190
191                         for (i = 0; i < 4; i++) {
192                                 if (quad[i]->co[axis] < 0.0f)
193                                         left = true;
194                                 else if (quad[i]->co[axis] > 0.0f)
195                                         right = true;
196
197                                 if (left && right)
198                                         return true;
199                         }
200                 }
201         }
202
203         return false;
204 }
205
206 /* Returns true if the frame is filled by precisely two faces (and
207  * outputs those faces to fill_faces), otherwise returns false. */
208 static bool skin_frame_find_contained_faces(
209         const Frame *frame,
210         BMFace *fill_faces[2])
211 {
212         BMEdge *diag;
213
214         /* See if the frame is bisected by a diagonal edge */
215         diag = BM_edge_exists(frame->verts[0], frame->verts[2]);
216         if (!diag)
217                 diag = BM_edge_exists(frame->verts[1], frame->verts[3]);
218
219         if (diag)
220                 return BM_edge_face_pair(diag, &fill_faces[0], &fill_faces[1]);
221         else
222                 return false;
223 }
224
225 /* Returns true if hull is successfully built, false otherwise */
226 static bool build_hull(SkinOutput *so, Frame **frames, int totframe)
227 {
228 #ifdef WITH_BULLET
229         BMesh *bm = so->bm;
230         BMOperator op;
231         BMIter iter;
232         BMOIter oiter;
233         BMVert *v;
234         BMFace *f;
235         BMEdge *e;
236         int i, j;
237
238         BM_mesh_elem_hflag_disable_all(bm, BM_VERT, BM_ELEM_TAG, false);
239
240         for (i = 0; i < totframe; i++) {
241                 for (j = 0; j < 4; j++) {
242                         BM_elem_flag_enable(frames[i]->verts[j], BM_ELEM_TAG);
243                 }
244         }
245
246         /* Deselect all faces so that only new hull output faces are
247          * selected after the operator is run */
248         BM_mesh_elem_hflag_disable_all(bm, BM_ALL_NOLOOP, BM_ELEM_SELECT, false);
249
250         BMO_op_initf(bm, &op, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
251                      "convex_hull input=%hv", BM_ELEM_TAG);
252         BMO_op_exec(bm, &op);
253
254         if (BMO_error_occurred(bm)) {
255                 BMO_op_finish(bm, &op);
256                 return false;
257         }
258
259         /* Apply face attributes to hull output */
260         BMO_ITER (f, &oiter, op.slots_out, "geom.out", BM_FACE) {
261                 BM_face_normal_update(f);
262                 if (so->smd->flag & MOD_SKIN_SMOOTH_SHADING)
263                         BM_elem_flag_enable(f, BM_ELEM_SMOOTH);
264                 f->mat_nr = so->mat_nr;
265         }
266
267         /* Mark interior frames */
268         BMO_ITER (v, &oiter, op.slots_out, "geom_interior.out", BM_VERT) {
269                 for (i = 0; i < totframe; i++) {
270                         Frame *frame = frames[i];
271                         
272                         if (!frame->detached) {
273                                 for (j = 0; j < 4; j++) {
274                                         if (frame->verts[j] == v) {
275                                                 frame->inside_hull[j] = true;
276                                                 frame->detached = true;
277                                                 break;
278                                         }
279                                 }
280                         }
281                 }
282         }
283
284         /* Also mark frames as interior if an edge is not in the hull */
285         for (i = 0; i < totframe; i++) {
286                 Frame *frame = frames[i];
287
288                 if (!frame->detached &&
289                     (!BM_edge_exists(frame->verts[0], frame->verts[1]) ||
290                      !BM_edge_exists(frame->verts[1], frame->verts[2]) ||
291                      !BM_edge_exists(frame->verts[2], frame->verts[3]) ||
292                      !BM_edge_exists(frame->verts[3], frame->verts[0])))
293                 {
294                         frame->detached = true;
295                 }
296         }
297         
298         /* Remove triangles that would fill the original frames -- skip if
299          * frame is partially detached */
300         BM_mesh_elem_hflag_disable_all(bm, BM_ALL_NOLOOP, BM_ELEM_TAG, false);
301         for (i = 0; i < totframe; i++) {
302                 Frame *frame = frames[i];
303                 if (!frame->detached) {
304                         BMFace *fill_faces[2];
305
306                         /* Check if the frame is filled by precisely two
307                          * triangles. If so, delete the triangles and their shared
308                          * edge. Otherwise, give up and mark the frame as
309                          * detached. */
310                         if (skin_frame_find_contained_faces(frame, fill_faces)) {
311                                 BM_elem_flag_enable(fill_faces[0], BM_ELEM_TAG);
312                                 BM_elem_flag_enable(fill_faces[1], BM_ELEM_TAG);
313                         }
314                         else
315                                 frame->detached = true;
316                 }
317         }
318
319         /* Check if removing triangles above will create wire triangles,
320          * mark them too */
321         BMO_ITER (e, &oiter, op.slots_out, "geom.out", BM_EDGE) {
322                 bool is_wire = true;
323                 BM_ITER_ELEM (f, &iter, e, BM_FACES_OF_EDGE) {
324                         if (!BM_elem_flag_test(f, BM_ELEM_TAG)) {
325                                 is_wire = false;
326                                 break;
327                         }
328                 }
329                 if (is_wire)
330                         BM_elem_flag_enable(e, BM_ELEM_TAG);
331         }
332
333         BMO_op_finish(bm, &op);
334
335         BM_mesh_delete_hflag_tagged(bm, BM_ELEM_TAG, BM_EDGE | BM_FACE);
336
337         return true;
338 #else
339         UNUSED_VARS(so, frames, totframe, skin_frame_find_contained_faces);
340         return false;
341 #endif
342 }
343
344 /* Returns the average frame side length (frames are rectangular, so
345  * just the average of two adjacent edge lengths) */
346 static float frame_len(const Frame *frame)
347 {
348         return (len_v3v3(frame->co[0], frame->co[1]) +
349                 len_v3v3(frame->co[1], frame->co[2])) * 0.5f;
350 }
351
352 static void merge_frame_corners(Frame **frames, int totframe)
353 {
354         float dist, side_a, side_b, thresh, mid[3];
355         int i, j, k, l;
356
357         for (i = 0; i < totframe; i++) {
358                 side_a = frame_len(frames[i]);
359
360                 /* For each corner of each frame... */
361                 for (j = 0; j < 4; j++) {
362
363                         /* Ensure the merge target is not itself a merge target */
364                         if (frames[i]->merge[j].frame)
365                                 continue;
366
367                         for (k = i + 1; k < totframe; k++) {
368                                 BLI_assert(frames[i] != frames[k]);
369
370                                 side_b = frame_len(frames[k]);
371                                 thresh = min_ff(side_a, side_b) / 2.0f;
372
373                                 /* Compare with each corner of all other frames... */
374                                 for (l = 0; l < 4; l++) {
375                                         if (frames[k]->merge[l].frame || frames[k]->merge[l].is_target)
376                                                 continue;
377
378                                         /* Some additional concerns that could be checked
379                                          * further:
380                                          *
381                                          * + Vertex coords are being used for the
382                                          *   edge-length test, but are also being
383                                          *   modified, might cause symmetry problems.
384                                          *
385                                          * + A frame could be merged diagonally across
386                                          *   another, would generate a weird (bad) T
387                                          *   junction
388                                          */
389
390                                         /* Check if corners are near each other, where
391                                          * 'near' is based in the frames' minimum side
392                                          * length */
393                                         dist = len_v3v3(frames[i]->co[j],
394                                                         frames[k]->co[l]);
395                                         if (dist < thresh) {
396                                                 mid_v3_v3v3(mid,
397                                                             frames[i]->co[j],
398                                                             frames[k]->co[l]);
399
400                                                 copy_v3_v3(frames[i]->co[j], mid);
401                                                 copy_v3_v3(frames[k]->co[l], mid);
402
403                                                 frames[k]->merge[l].frame = frames[i];
404                                                 frames[k]->merge[l].corner = j;
405                                                 frames[i]->merge[j].is_target = true;
406
407                                                 /* Can't merge another corner into the same
408                                                  * frame corner, so move on to frame k+1 */
409                                                 break;
410                                         }
411                                 }
412                         }
413                 }
414         }
415 }
416
417 static Frame **collect_hull_frames(
418         int v, SkinNode *frames,
419         const MeshElemMap *emap, const MEdge *medge,
420         int *tothullframe)
421 {
422         SkinNode *f;
423         Frame **hull_frames;
424         int nbr, i;
425
426         (*tothullframe) = emap[v].count;
427         hull_frames = MEM_calloc_arrayN((*tothullframe), sizeof(Frame *),
428                                   "hull_from_frames.hull_frames");
429         i = 0;
430         for (nbr = 0; nbr < emap[v].count; nbr++) {
431                 const MEdge *e = &medge[emap[v].indices[nbr]];
432                 f = &frames[BKE_mesh_edge_other_vert(e, v)];
433                 /* Can't have adjacent branch nodes yet */
434                 if (f->totframe)
435                         hull_frames[i++] = &f->frames[0];
436                 else
437                         (*tothullframe)--;
438         }
439
440         return hull_frames;
441 }
442
443
444 /**************************** Create Frames ***************************/
445
446 static void node_frames_init(SkinNode *nf, int totframe)
447 {
448         int i;
449
450         nf->totframe = totframe;
451         memset(nf->frames, 0, sizeof(nf->frames));
452         
453         nf->flag = 0;
454         for (i = 0; i < 2; i++)
455                 nf->seam_edges[i] = -1;
456 }
457
458 static void create_frame(
459         Frame *frame, const float co[3],
460         const float radius[2],
461         float mat[3][3], float offset)
462 {
463         float rx[3], ry[3], rz[3];
464         int i;
465
466         mul_v3_v3fl(ry, mat[1], radius[0]);
467         mul_v3_v3fl(rz, mat[2], radius[1]);
468         
469         add_v3_v3v3(frame->co[3], co, ry);
470         add_v3_v3v3(frame->co[3], frame->co[3], rz);
471
472         sub_v3_v3v3(frame->co[2], co, ry);
473         add_v3_v3v3(frame->co[2], frame->co[2], rz);
474
475         sub_v3_v3v3(frame->co[1], co, ry);
476         sub_v3_v3v3(frame->co[1], frame->co[1], rz);
477
478         add_v3_v3v3(frame->co[0], co, ry);
479         sub_v3_v3v3(frame->co[0], frame->co[0], rz);
480
481         mul_v3_v3fl(rx, mat[0], offset);
482         for (i = 0; i < 4; i++)
483                 add_v3_v3v3(frame->co[i], frame->co[i], rx);
484 }
485
486 static float half_v2(const float v[2])
487 {
488         return (v[0] + v[1]) * 0.5f;
489 }
490
491 static void end_node_frames(
492         int v, SkinNode *skin_nodes, const MVert *mvert,
493         const MVertSkin *nodes, const MeshElemMap *emap,
494         EMat *emat)
495 {
496         const float *rad = nodes[v].radius;
497         float mat[3][3];
498
499         if (emap[v].count == 0) {
500                 float avg = half_v2(rad);
501
502                 /* For solitary nodes, just build a box (two frames) */
503                 node_frames_init(&skin_nodes[v], 2);
504                 skin_nodes[v].flag |= (CAP_START | CAP_END);
505
506                 /* Hardcoded basis */
507                 zero_m3(mat);
508                 mat[0][2] = mat[1][0] = mat[2][1] = 1;
509
510                 /* Caps */
511                 create_frame(&skin_nodes[v].frames[0], mvert[v].co, rad, mat, avg);
512                 create_frame(&skin_nodes[v].frames[1], mvert[v].co, rad, mat, -avg);
513         }
514         else {
515                 /* For nodes with an incoming edge, create a single (capped) frame */
516                 node_frames_init(&skin_nodes[v], 1);
517                 skin_nodes[v].flag |= CAP_START;
518
519                 /* Use incoming edge for orientation */
520                 copy_m3_m3(mat, emat[emap[v].indices[0]].mat);
521                 if (emat[emap[v].indices[0]].origin != v)
522                         negate_v3(mat[0]);
523
524                 /* End frame */
525                 create_frame(&skin_nodes[v].frames[0], mvert[v].co, rad, mat, 0);
526         }
527
528         if (nodes[v].flag & MVERT_SKIN_ROOT)
529                 skin_nodes[v].flag |= ROOT;
530 }
531
532 /* Returns 1 for seam, 0 otherwise */
533 static int connection_node_mat(float mat[3][3], int v, const MeshElemMap *emap, EMat *emat)
534 {
535         float axis[3], angle, ine[3][3], oute[3][3];
536         EMat *e1, *e2;
537
538         e1 = &emat[emap[v].indices[0]];
539         e2 = &emat[emap[v].indices[1]];
540
541         if (e1->origin != v && e2->origin == v) {
542                 copy_m3_m3(ine, e1->mat);
543                 copy_m3_m3(oute, e2->mat);
544         }
545         else if (e1->origin == v && e2->origin != v) {
546                 copy_m3_m3(ine, e2->mat);
547                 copy_m3_m3(oute, e1->mat);
548         }
549         else
550                 return 1;
551
552         /* Get axis and angle to rotate frame by */
553         angle = angle_normalized_v3v3(ine[0], oute[0]) / 2.0f;
554         cross_v3_v3v3(axis, ine[0], oute[0]);
555         normalize_v3(axis);
556
557         /* Build frame matrix (don't care about X axis here) */
558         copy_v3_v3(mat[0], ine[0]);
559         rotate_normalized_v3_v3v3fl(mat[1], ine[1], axis, angle);
560         rotate_normalized_v3_v3v3fl(mat[2], ine[2], axis, angle);
561
562         return 0;
563 }
564
565 static void connection_node_frames(
566         int v, SkinNode *skin_nodes, const MVert *mvert,
567         const MVertSkin *nodes, const MeshElemMap *emap,
568         EMat *emat)
569 {
570         const float *rad = nodes[v].radius;
571         float mat[3][3];
572         EMat *e1, *e2;
573
574         if (connection_node_mat(mat, v, emap, emat)) {
575                 float avg = half_v2(rad);
576
577                 /* Get edges */
578                 e1 = &emat[emap[v].indices[0]];
579                 e2 = &emat[emap[v].indices[1]];
580
581                 /* Handle seam separately to avoid twisting */
582                 /* Create two frames, will be hulled to neighbors later */
583                 node_frames_init(&skin_nodes[v], 2);
584                 skin_nodes[v].flag |= SEAM_FRAME;
585
586                 copy_m3_m3(mat, e1->mat);
587                 if (e1->origin != v) negate_v3(mat[0]);
588                 create_frame(&skin_nodes[v].frames[0], mvert[v].co, rad, mat, avg);
589                 skin_nodes[v].seam_edges[0] = emap[v].indices[0];
590
591                 copy_m3_m3(mat, e2->mat);
592                 if (e2->origin != v) negate_v3(mat[0]);
593                 create_frame(&skin_nodes[v].frames[1], mvert[v].co, rad, mat, avg);
594                 skin_nodes[v].seam_edges[1] = emap[v].indices[1];
595
596                 return;
597         }
598
599         /* Build regular frame */
600         node_frames_init(&skin_nodes[v], 1);
601         create_frame(&skin_nodes[v].frames[0], mvert[v].co, rad, mat, 0);
602 }
603
604 static SkinNode *build_frames(
605         const MVert *mvert, int totvert,
606         const MVertSkin *nodes, const MeshElemMap *emap,
607         EMat *emat)
608 {
609         SkinNode *skin_nodes;
610         int v;
611
612         skin_nodes = MEM_calloc_arrayN(totvert, sizeof(SkinNode), "build_frames.skin_nodes");
613
614         for (v = 0; v < totvert; v++) {
615                 if (emap[v].count <= 1)
616                         end_node_frames(v, skin_nodes, mvert, nodes, emap, emat);
617                 else if (emap[v].count == 2)
618                         connection_node_frames(v, skin_nodes, mvert, nodes, emap, emat);
619                 else {
620                         /* Branch node generates no frames */
621                 }
622         }
623
624         return skin_nodes;
625 }
626
627 /**************************** Edge Matrices ***************************/
628
629 static void calc_edge_mat(float mat[3][3], const float a[3], const float b[3])
630 {
631         const float z_up[3] = {0, 0, 1};
632         float dot;
633
634         /* X = edge direction */
635         sub_v3_v3v3(mat[0], b, a);
636         normalize_v3(mat[0]);
637
638         dot = dot_v3v3(mat[0], z_up);
639         if (dot > -1 + FLT_EPSILON && dot < 1 - FLT_EPSILON) {
640                 /* Y = Z cross x */
641                 cross_v3_v3v3(mat[1], z_up, mat[0]);
642                 normalize_v3(mat[1]);
643
644                 /* Z = x cross y */
645                 cross_v3_v3v3(mat[2], mat[0], mat[1]);
646                 normalize_v3(mat[2]);
647         }
648         else {
649                 mat[1][0] = 1;
650                 mat[1][1] = 0;
651                 mat[1][2] = 0;
652                 mat[2][0] = 0;
653                 mat[2][1] = 1;
654                 mat[2][2] = 0;
655         }
656 }
657
658 typedef struct {
659         float mat[3][3];
660         int parent_v;
661         int e;
662 } EdgeStackElem;
663
664 static void build_emats_stack(
665         BLI_Stack *stack, BLI_bitmap *visited_e, EMat *emat,
666         const MeshElemMap *emap, const MEdge *medge,
667         const MVertSkin *vs, const MVert *mvert)
668 {
669         EdgeStackElem stack_elem;
670         float axis[3], angle;
671         int i, e, v, parent_v, parent_is_branch;
672
673         BLI_stack_pop(stack, &stack_elem);
674         parent_v = stack_elem.parent_v;
675         e = stack_elem.e;
676
677         /* Skip if edge already visited */
678         if (BLI_BITMAP_TEST(visited_e, e))
679                 return;
680
681         /* Mark edge as visited */
682         BLI_BITMAP_ENABLE(visited_e, e);
683         
684         /* Process edge */
685
686         parent_is_branch = ((emap[parent_v].count > 2) ||
687                             (vs[parent_v].flag & MVERT_SKIN_ROOT));
688
689         v = BKE_mesh_edge_other_vert(&medge[e], parent_v);
690         emat[e].origin = parent_v;
691
692         /* If parent is a branch node, start a new edge chain */
693         if (parent_is_branch) {
694                 calc_edge_mat(emat[e].mat, mvert[parent_v].co,
695                               mvert[v].co);
696         }
697         else {
698                 /* Build edge matrix guided by parent matrix */
699                 sub_v3_v3v3(emat[e].mat[0], mvert[v].co, mvert[parent_v].co);
700                 normalize_v3(emat[e].mat[0]);
701                 angle = angle_normalized_v3v3(stack_elem.mat[0], emat[e].mat[0]);
702                 cross_v3_v3v3(axis, stack_elem.mat[0], emat[e].mat[0]);
703                 normalize_v3(axis);
704                 rotate_normalized_v3_v3v3fl(emat[e].mat[1], stack_elem.mat[1], axis, angle);
705                 rotate_normalized_v3_v3v3fl(emat[e].mat[2], stack_elem.mat[2], axis, angle);
706         }
707
708         /* Add neighbors to stack */
709         for (i = 0; i < emap[v].count; i++) {
710                 /* Add neighbors to stack */
711                 copy_m3_m3(stack_elem.mat, emat[e].mat);
712                 stack_elem.e = emap[v].indices[i];
713                 stack_elem.parent_v = v;
714                 BLI_stack_push(stack, &stack_elem);
715         }
716 }
717
718 static EMat *build_edge_mats(
719         const MVertSkin *vs,
720         const MVert *mvert,
721         int totvert,
722         const MEdge *medge,
723         const MeshElemMap *emap,
724         int totedge,
725         bool *has_valid_root)
726 {
727         BLI_Stack *stack;
728         EMat *emat;
729         EdgeStackElem stack_elem;
730         BLI_bitmap *visited_e;
731         int i, v;
732
733         stack = BLI_stack_new(sizeof(stack_elem), "build_edge_mats.stack");
734
735         visited_e = BLI_BITMAP_NEW(totedge, "build_edge_mats.visited_e");
736         emat = MEM_calloc_arrayN(totedge, sizeof(EMat), "build_edge_mats.emat");
737
738         /* Edge matrices are built from the root nodes, add all roots with
739          * children to the stack */
740         for (v = 0; v < totvert; v++) {
741                 if (vs[v].flag & MVERT_SKIN_ROOT) {
742                         if (emap[v].count >= 1) {
743                                 const MEdge *e = &medge[emap[v].indices[0]];
744                                 calc_edge_mat(stack_elem.mat, mvert[v].co,
745                                               mvert[BKE_mesh_edge_other_vert(e, v)].co);
746                                 stack_elem.parent_v = v;
747
748                                 /* Add adjacent edges to stack */
749                                 for (i = 0; i < emap[v].count; i++) {
750                                         stack_elem.e = emap[v].indices[i];
751                                         BLI_stack_push(stack, &stack_elem);
752                                 }
753
754                                 *has_valid_root = true;
755                         }
756                 }
757         }
758
759         while (!BLI_stack_is_empty(stack)) {
760                 build_emats_stack(stack, visited_e, emat, emap, medge, vs, mvert);
761         }
762
763         MEM_freeN(visited_e);
764         BLI_stack_free(stack);
765
766         return emat;
767 }
768
769
770 /************************** Input Subdivision *************************/
771
772 /* Returns number of edge subdivisions, taking into account the radius
773  * of the endpoints and the edge length. If both endpoints are branch
774  * nodes, at least two intermediate frames are required. (This avoids
775  * having any special cases for dealing with sharing a frame between
776  * two hulls.) */
777 static int calc_edge_subdivisions(
778         const MVert *mvert, const MVertSkin *nodes,
779         const MEdge *e, const int *degree)
780 {
781         /* prevent memory errors [#38003] */
782 #define NUM_SUBDIVISIONS_MAX 128
783
784         const MVertSkin *evs[2] = {&nodes[e->v1], &nodes[e->v2]};
785         float avg_radius;
786         const bool v1_branch = degree[e->v1] > 2;
787         const bool v2_branch = degree[e->v2] > 2;
788         int num_subdivisions;
789
790         /* If either end is a branch node marked 'loose', don't subdivide
791          * the edge (or subdivide just twice if both are branches) */
792         if ((v1_branch && (evs[0]->flag & MVERT_SKIN_LOOSE)) ||
793             (v2_branch && (evs[1]->flag & MVERT_SKIN_LOOSE)))
794         {
795                 if (v1_branch && v2_branch)
796                         return 2;
797                 else
798                         return 0;
799         }
800
801         avg_radius = half_v2(evs[0]->radius) + half_v2(evs[1]->radius);
802
803         if (avg_radius != 0.0f) {
804                 /* possible (but unlikely) that we overflow INT_MAX */
805                 float num_subdivisions_fl;
806                 const float edge_len = len_v3v3(mvert[e->v1].co, mvert[e->v2].co);
807                 num_subdivisions_fl = (edge_len / avg_radius);
808                 if (num_subdivisions_fl < NUM_SUBDIVISIONS_MAX) {
809                         num_subdivisions = (int)num_subdivisions_fl;
810                 }
811                 else {
812                         num_subdivisions = NUM_SUBDIVISIONS_MAX;
813                 }
814         }
815         else {
816                 num_subdivisions = 0;
817         }
818
819         /* If both ends are branch nodes, two intermediate nodes are
820          * required */
821         if (num_subdivisions < 2 && v1_branch && v2_branch)
822                 num_subdivisions = 2;
823
824         return num_subdivisions;
825
826 #undef NUM_SUBDIVISIONS_MAX
827 }
828
829 /* Take a Mesh and subdivide its edges to keep skin nodes
830  * reasonably close. */
831 static Mesh *subdivide_base(Mesh *orig)
832 {
833         Mesh *result;
834         MVertSkin *orignode, *outnode;
835         MVert *origvert, *outvert;
836         MEdge *origedge, *outedge, *e;
837         MDeformVert *origdvert, *outdvert;
838         int totorigvert, totorigedge;
839         int totsubd, *degree, *edge_subd;
840         int i, j, k, u, v;
841         float radrat;
842
843         orignode = CustomData_get_layer(&orig->vdata, CD_MVERT_SKIN);
844         origvert = orig->mvert;
845         origedge = orig->medge;
846         origdvert = orig->dvert;
847         totorigvert = orig->totvert;
848         totorigedge = orig->totedge;
849
850         /* Get degree of all vertices */
851         degree = MEM_calloc_arrayN(totorigvert, sizeof(int), "degree");
852         for (i = 0; i < totorigedge; i++) {
853                 degree[origedge[i].v1]++;
854                 degree[origedge[i].v2]++;
855         }
856
857         /* Per edge, store how many subdivisions are needed */
858         edge_subd = MEM_calloc_arrayN(totorigedge, sizeof(int), "edge_subd");
859         for (i = 0, totsubd = 0; i < totorigedge; i++) {
860                 edge_subd[i] += calc_edge_subdivisions(origvert, orignode,
861                                                        &origedge[i], degree);
862                 totsubd += edge_subd[i];
863         }
864
865         MEM_freeN(degree);
866
867         /* Allocate output derivedmesh */
868         result = BKE_mesh_new_nomain_from_template(
869                 orig,
870                 totorigvert + totsubd,
871                 totorigedge + totsubd,
872                 0, 0, 0);
873
874         outvert = result->mvert;
875         outedge = result->medge;
876         outnode = CustomData_get_layer(&result->vdata, CD_MVERT_SKIN);
877         outdvert = result->dvert;
878
879         /* Copy original vertex data */
880         CustomData_copy_data(&orig->vdata,
881                              &result->vdata,
882                              0, 0, totorigvert);
883
884         /* Subdivide edges */
885         for (i = 0, v = totorigvert; i < totorigedge; i++) {
886                 struct {
887                         /* Vertex group number */
888                         int def_nr;
889                         float w1, w2;
890                 } *vgroups = NULL, *vg;
891                 int totvgroup = 0;
892
893                 e = &origedge[i];
894
895                 if (origdvert) {
896                         const MDeformVert *dv1 = &origdvert[e->v1];
897                         const MDeformVert *dv2 = &origdvert[e->v2];
898                         vgroups = MEM_calloc_arrayN(dv1->totweight, sizeof(*vgroups), "vgroup");
899
900                         /* Only want vertex groups used by both vertices */
901                         for (j = 0; j < dv1->totweight; j++) {
902                                 vg = NULL;
903                                 for (k = 0; k < dv2->totweight; k++) {
904                                         if (dv1->dw[j].def_nr == dv2->dw[k].def_nr) {
905                                                 vg = &vgroups[totvgroup];
906                                                 totvgroup++;
907                                                 break;
908                                         }
909                                 }
910
911                                 if (vg) {
912                                         vg->def_nr = dv1->dw[j].def_nr;
913                                         vg->w1 = dv1->dw[j].weight;
914                                         vg->w2 = dv2->dw[k].weight;
915                                 }
916                         }
917                 }
918
919                 u = e->v1;
920                 radrat = (half_v2(outnode[e->v2].radius) /
921                           half_v2(outnode[e->v1].radius));
922                 radrat = (radrat + 1) / 2;
923
924                 /* Add vertices and edge segments */
925                 for (j = 0; j < edge_subd[i]; j++, v++, outedge++) {
926                         float r = (j + 1) / (float)(edge_subd[i] + 1);
927                         float t = powf(r, radrat);
928
929                         /* Interpolate vertex coord */
930                         interp_v3_v3v3(outvert[v].co, outvert[e->v1].co,
931                                        outvert[e->v2].co, t);
932
933                         /* Interpolate skin radii */
934                         interp_v3_v3v3(outnode[v].radius,
935                                        orignode[e->v1].radius,
936                                        orignode[e->v2].radius, t);
937
938                         /* Interpolate vertex group weights */
939                         for (k = 0; k < totvgroup; k++) {
940                                 float weight;
941                                 
942                                 vg = &vgroups[k];
943                                 weight = interpf(vg->w2, vg->w1, t);
944
945                                 if (weight > 0)
946                                         defvert_add_index_notest(&outdvert[v], vg->def_nr, weight);
947                         }
948                         
949                         outedge->v1 = u;
950                         outedge->v2 = v;
951                         u = v;
952                 }
953
954                 if (vgroups)
955                         MEM_freeN(vgroups);
956                 
957                 /* Link up to final vertex */
958                 outedge->v1 = u;
959                 outedge->v2 = e->v2;
960                 outedge++;
961         }
962
963         MEM_freeN(edge_subd);
964
965         return result;
966 }
967
968 /******************************* Output *******************************/
969
970 /* Can be either quad or triangle */
971 static void add_poly(
972         SkinOutput *so,
973         BMVert *v1,
974         BMVert *v2,
975         BMVert *v3,
976         BMVert *v4)
977 {
978         BMVert *verts[4] = {v1, v2, v3, v4};
979         BMFace *f;
980         
981         BLI_assert(v1 != v2 && v1 != v3 && v1 != v4);
982         BLI_assert(v2 != v3 && v2 != v4);
983         BLI_assert(v3 != v4);
984         BLI_assert(v1 && v2 && v3);
985
986         f = BM_face_create_verts(so->bm, verts, v4 ? 4 : 3, NULL, BM_CREATE_NO_DOUBLE, true);
987         BM_face_normal_update(f);
988         if (so->smd->flag & MOD_SKIN_SMOOTH_SHADING)
989                 BM_elem_flag_enable(f, BM_ELEM_SMOOTH);
990         f->mat_nr = so->mat_nr;
991 }
992
993 static void connect_frames(
994         SkinOutput *so,
995         BMVert *frame1[4],
996         BMVert *frame2[4])
997 {
998         BMVert *q[4][4] = {{frame2[0], frame2[1], frame1[1], frame1[0]},
999                            {frame2[1], frame2[2], frame1[2], frame1[1]},
1000                            {frame2[2], frame2[3], frame1[3], frame1[2]},
1001                            {frame2[3], frame2[0], frame1[0], frame1[3]}};
1002         int i;
1003         bool swap;
1004
1005         /* Check if frame normals need swap */
1006 #if 0
1007         {
1008                 /* simple method, works mostly */
1009                 float p[3], no[3];
1010                 sub_v3_v3v3(p, q[3][0]->co, q[0][0]->co);
1011                 normal_quad_v3(no,
1012                         q[0][0]->co, q[0][1]->co,
1013                         q[0][2]->co, q[0][3]->co);
1014                 swap = dot_v3v3(no, p) > 0;
1015         }
1016 #else
1017         {
1018                 /* comprehensive method, accumulate flipping of all faces */
1019                 float cent_sides[4][3];
1020                 float cent[3];
1021                 float dot = 0.0f;
1022
1023                 for (i = 0; i < 4; i++) {
1024                         mid_v3_v3v3v3v3(cent_sides[i], UNPACK4_EX(, q[i], ->co));
1025                 }
1026                 mid_v3_v3v3v3v3(cent, UNPACK4(cent_sides));
1027
1028                 for (i = 0; i < 4; i++) {
1029                         float p[3], no[3];
1030                         normal_quad_v3(no, UNPACK4_EX(, q[i], ->co));
1031                         sub_v3_v3v3(p, cent, cent_sides[i]);
1032                         dot += dot_v3v3(no, p);
1033                 }
1034
1035                 swap = dot > 0;
1036         }
1037 #endif
1038
1039         for (i = 0; i < 4; i++) {
1040                 if (swap)
1041                         add_poly(so, q[i][3], q[i][2], q[i][1], q[i][0]);
1042                 else
1043                         add_poly(so, q[i][0], q[i][1], q[i][2], q[i][3]);
1044         }
1045 }
1046
1047 static void output_frames(
1048         BMesh *bm,
1049         SkinNode *sn,
1050         const MDeformVert *input_dvert)
1051 {
1052         Frame *f;
1053         int i, j;
1054
1055         /* Output all frame verts */
1056         for (i = 0; i < sn->totframe; i++) {
1057                 f = &sn->frames[i];
1058                 for (j = 0; j < 4; j++) {
1059                         if (!f->merge[j].frame) {
1060                                 BMVert *v = f->verts[j] = BM_vert_create(bm, f->co[j], NULL, BM_CREATE_NOP);
1061
1062                                 if (input_dvert) {
1063                                         MDeformVert *dv;
1064                                         dv = CustomData_bmesh_get(&bm->vdata,
1065                                                                   v->head.data,
1066                                                                   CD_MDEFORMVERT);
1067                                         
1068                                         BLI_assert(dv->totweight == 0);
1069                                         defvert_copy(dv, input_dvert);
1070                                 }
1071                         }
1072                 }
1073         }
1074 }
1075
1076 #define PRINT_HOLE_INFO 0
1077
1078 static void calc_frame_center(float center[3], const Frame *frame)
1079 {
1080         add_v3_v3v3(center, frame->verts[0]->co, frame->verts[1]->co);
1081         add_v3_v3(center, frame->verts[2]->co);
1082         add_v3_v3(center, frame->verts[3]->co);
1083         mul_v3_fl(center, 0.25f);
1084 }
1085
1086 /* Does crappy fan triangulation of poly, may not be so accurate for
1087  * concave faces */
1088 static int isect_ray_poly(const float ray_start[3],
1089                           const float ray_dir[3],
1090                           BMFace *f,
1091                           float *r_lambda)
1092 {
1093         BMVert *v, *v_first = NULL, *v_prev = NULL;
1094         BMIter iter;
1095         float best_dist = FLT_MAX;
1096         bool hit = false;
1097         
1098         BM_ITER_ELEM (v, &iter, f, BM_VERTS_OF_FACE) {
1099                 if (!v_first)
1100                         v_first = v;
1101                 else if (v_prev != v_first) {
1102                         float dist;
1103                         bool curhit;
1104                         
1105                         curhit = isect_ray_tri_v3(ray_start, ray_dir,
1106                                                   v_first->co, v_prev->co, v->co,
1107                                                   &dist, NULL);
1108                         if (curhit && dist < best_dist) {
1109                                 hit = true;
1110                                 best_dist = dist;
1111                         }
1112                 }
1113
1114                 v_prev = v;
1115         }
1116
1117         *r_lambda = best_dist;
1118         return hit;
1119 }
1120
1121 /* Reduce the face down to 'n' corners by collapsing the edges;
1122  * returns the new face.
1123  *
1124  * The orig_verts should contain the vertices of 'f'
1125  */
1126 static BMFace *collapse_face_corners(BMesh *bm, BMFace *f, int n,
1127                                      BMVert **orig_verts)
1128 {
1129         int orig_len = f->len;
1130
1131         BLI_assert(n >= 3);
1132         BLI_assert(f->len > n);
1133         if (f->len <= n)
1134                 return f;
1135
1136         /* Collapse shortest edge for now */
1137         while (f->len > n) {
1138                 BMFace *vf;
1139                 BMEdge *shortest_edge;
1140                 BMVert *v_safe, *v_merge;
1141                 BMOperator op;
1142                 BMIter iter;
1143                 int i;
1144                 BMOpSlot *slot_targetmap;
1145
1146                 shortest_edge = BM_face_find_shortest_loop(f)->e;
1147                 BMO_op_initf(bm, &op, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE), "weld_verts");
1148
1149                 slot_targetmap = BMO_slot_get(op.slots_in, "targetmap");
1150
1151                 /* Note: could probably calculate merges in one go to be
1152                  * faster */
1153
1154                 v_safe = shortest_edge->v1;
1155                 v_merge = shortest_edge->v2;
1156                 mid_v3_v3v3(v_safe->co, v_safe->co, v_merge->co);
1157                 BMO_slot_map_elem_insert(&op, slot_targetmap, v_merge, v_safe);
1158                 BMO_op_exec(bm, &op);
1159                 BMO_op_finish(bm, &op);
1160
1161                 /* Find the new face */
1162                 f = NULL;
1163                 BM_ITER_ELEM (vf, &iter, v_safe, BM_FACES_OF_VERT) {
1164                         bool wrong_face = false;
1165                         
1166                         for (i = 0; i < orig_len; i++) {
1167                                 if (orig_verts[i] == v_merge) {
1168                                         orig_verts[i] = NULL;
1169                                 }
1170                                 else if (orig_verts[i] &&
1171                                          !BM_vert_in_face(orig_verts[i], vf))
1172                                 {
1173                                         wrong_face = true;
1174                                         break;
1175                                 }
1176                         }
1177
1178                         if (!wrong_face) {
1179                                 f = vf;
1180                                 break;
1181                         }
1182                 }
1183
1184                 BLI_assert(f);
1185         }
1186
1187         return f;
1188 }
1189
1190 /* Choose a good face to merge the frame with, used in case the frame
1191  * is completely inside the hull. */
1192 static BMFace *skin_hole_target_face(BMesh *bm, Frame *frame)
1193 {
1194         BMFace *f, *isect_target_face, *center_target_face;
1195         BMIter iter;
1196         float frame_center[3];
1197         float frame_normal[3];
1198         float best_isect_dist = FLT_MAX;
1199         float best_center_dist = FLT_MAX;
1200
1201         calc_frame_center(frame_center, frame);
1202         normal_quad_v3(frame_normal, frame->verts[3]->co,
1203                        frame->verts[2]->co, frame->verts[1]->co,
1204                        frame->verts[0]->co);
1205
1206         /* Use a line intersection test and nearest center test against
1207          * all faces */
1208         isect_target_face = center_target_face = NULL;
1209         BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
1210                 float dist, poly_center[3];
1211                 int hit;
1212
1213                 /* Intersection test */
1214                 hit = isect_ray_poly(frame_center, frame_normal, f, &dist);
1215                 if (hit && dist < best_isect_dist) {
1216                         isect_target_face = f;
1217                         best_isect_dist = dist;
1218                 }
1219
1220                 /* Nearest test */
1221                 BM_face_calc_center_mean(f, poly_center);
1222                 dist = len_v3v3(frame_center, poly_center);
1223                 if (dist < best_center_dist) {
1224                         center_target_face = f;
1225                         best_center_dist = dist;
1226                 }
1227         }
1228
1229         f = isect_target_face;
1230         if (!f || best_center_dist < best_isect_dist / 2)
1231                 f = center_target_face;
1232
1233         /* This case is unlikely now, but could still happen. Should look
1234          * into splitting edges to make new faces. */
1235 #if PRINT_HOLE_INFO
1236         if (!f) {
1237                 printf("no good face found\n");
1238         }
1239 #endif
1240
1241         return f;
1242 }
1243
1244 /* Use edge-length heuristic to choose from eight possible polygon bridges */
1245 static void skin_choose_quad_bridge_order(BMVert *a[4], BMVert *b[4],
1246                                           int best_order[4])
1247 {
1248         int orders[8][4];
1249         float shortest_len;
1250         int i, j;
1251
1252         /* Enumerate all valid orderings */
1253         for (i = 0; i < 4; i++) {
1254                 for (j = 0; j < 4; j++) {
1255                         orders[i][j] = (j + i) % 4;
1256                         orders[i + 4][j] = 3 - ((j + i) % 4);
1257                 }
1258         }
1259
1260         shortest_len = FLT_MAX;
1261         for (i = 0; i < 8; i++) {
1262                 float len = 0;
1263                 
1264                 /* Get total edge length for this configuration */
1265                 for (j = 0; j < 4; j++)
1266                         len += len_squared_v3v3(a[j]->co, b[orders[i][j]]->co);
1267
1268                 if (len < shortest_len) {
1269                         shortest_len = len;
1270                         memcpy(best_order, orders[i], sizeof(int) * 4);
1271                 }
1272         }
1273 }
1274
1275 static void skin_fix_hole_no_good_verts(BMesh *bm, Frame *frame, BMFace *split_face)
1276 {
1277         BMFace *f;
1278         BMVert *verts[4];
1279         BMVert **vert_buf = NULL;
1280         BLI_array_declare(vert_buf);
1281         BMOIter oiter;
1282         BMOperator op;
1283         int i, best_order[4];
1284         BMOpSlot *slot_targetmap;
1285
1286         BLI_assert(split_face->len >= 3);
1287
1288         /* Extrude the split face */
1289         BM_mesh_elem_hflag_disable_all(bm, BM_FACE, BM_ELEM_TAG, false);
1290         BM_elem_flag_enable(split_face, BM_ELEM_TAG);
1291         BMO_op_initf(bm, &op, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
1292                      "extrude_discrete_faces faces=%hf", BM_ELEM_TAG);
1293         BMO_op_exec(bm, &op);
1294
1295         /* Update split face (should only be one new face created
1296          * during extrusion) */
1297         split_face = NULL;
1298         BMO_ITER (f, &oiter, op.slots_out, "faces.out", BM_FACE) {
1299                 BLI_assert(!split_face);
1300                 split_face = f;
1301         }
1302
1303         BMO_op_finish(bm, &op);
1304
1305         if (split_face->len == 3) {
1306                 BMEdge *longest_edge;
1307
1308                 /* Need at least four ring edges, so subdivide longest edge if
1309                  * face is a triangle */
1310                 longest_edge = BM_face_find_longest_loop(split_face)->e;
1311                 
1312                 BM_mesh_elem_hflag_disable_all(bm, BM_EDGE, BM_ELEM_TAG, false);
1313                 BM_elem_flag_enable(longest_edge, BM_ELEM_TAG);
1314
1315                 BMO_op_callf(bm, BMO_FLAG_DEFAULTS,
1316                              "subdivide_edges edges=%he cuts=%i quad_corner_type=%i",
1317                              BM_ELEM_TAG, 1, SUBD_CORNER_STRAIGHT_CUT);
1318         }
1319         else if (split_face->len > 4) {
1320                 /* Maintain a dynamic vert array containing the split_face's
1321                  * vertices, avoids frequent allocs in collapse_face_corners() */
1322                 if (BLI_array_len(vert_buf) < split_face->len) {
1323                         BLI_array_grow_items(vert_buf, (split_face->len -
1324                                                         BLI_array_len(vert_buf)));
1325                 }
1326
1327                 /* Get split face's verts */
1328                 BM_iter_as_array(bm, BM_VERTS_OF_FACE, split_face,
1329                                  (void **)vert_buf, split_face->len);
1330
1331                 /* Earlier edge split operations may have turned some quads
1332                  * into higher-degree faces */
1333                 split_face = collapse_face_corners(bm, split_face, 4, vert_buf);
1334         }
1335
1336         /* Done with dynamic array, split_face must now be a quad */
1337         BLI_array_free(vert_buf);
1338         BLI_assert(split_face->len == 4);
1339         if (split_face->len != 4)
1340                 return;
1341
1342         /* Get split face's verts */
1343         // BM_iter_as_array(bm, BM_VERTS_OF_FACE, split_face, (void **)verts, 4);
1344         BM_face_as_array_vert_quad(split_face, verts);
1345         skin_choose_quad_bridge_order(verts, frame->verts, best_order);
1346
1347         /* Delete split face and merge */
1348         BM_face_kill(bm, split_face);
1349         BMO_op_init(bm, &op, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
1350                     "weld_verts");
1351         slot_targetmap = BMO_slot_get(op.slots_in, "targetmap");
1352         for (i = 0; i < 4; i++) {
1353                 BMO_slot_map_elem_insert(&op, slot_targetmap, verts[i], frame->verts[best_order[i]]);
1354         }
1355         BMO_op_exec(bm, &op);
1356         BMO_op_finish(bm, &op);
1357 }
1358
1359 /* If the frame has some vertices that are inside the hull (detached)
1360  * and some attached, duplicate the attached vertices and take the
1361  * whole frame off the hull. */
1362 static void skin_hole_detach_partially_attached_frame(BMesh *bm, Frame *frame)
1363 {
1364         int i, attached[4], totattached = 0;
1365
1366         /* Get/count attached frame corners */
1367         for (i = 0; i < 4; i++) {
1368                 if (!frame->inside_hull[i])
1369                         attached[totattached++] = i;
1370         }
1371
1372         /* Detach everything */
1373         for (i = 0; i < totattached; i++) {
1374                 BMVert **av = &frame->verts[attached[i]];
1375                 (*av) = BM_vert_create(bm, (*av)->co, *av, BM_CREATE_NOP);
1376         }
1377 }
1378
1379
1380 static void quad_from_tris(BMEdge *e, BMFace *adj[2], BMVert *ndx[4])
1381 {
1382         BMVert *tri[2][3];
1383         BMVert *opp = NULL;
1384         int i, j;
1385
1386         BLI_assert(adj[0]->len == 3 && adj[1]->len == 3);
1387
1388 #if 0
1389         BM_iter_as_array(bm, BM_VERTS_OF_FACE, adj[0], (void **)tri[0], 3);
1390         BM_iter_as_array(bm, BM_VERTS_OF_FACE, adj[1], (void **)tri[1], 3);
1391 #else
1392         BM_face_as_array_vert_tri(adj[0], tri[0]);
1393         BM_face_as_array_vert_tri(adj[1], tri[1]);
1394 #endif
1395
1396         /* Find what the second tri has that the first doesn't */
1397         for (i = 0; i < 3; i++) {
1398                 if (tri[1][i] != tri[0][0] &&
1399                     tri[1][i] != tri[0][1] &&
1400                     tri[1][i] != tri[0][2])
1401                 {
1402                         opp = tri[1][i];
1403                         break;
1404                 }
1405         }
1406         BLI_assert(opp);
1407
1408         for (i = 0, j = 0; i < 3; i++, j++) {
1409                 ndx[j] = tri[0][i];
1410                 /* When the triangle edge cuts across our quad-to-be,
1411                  * throw in the second triangle's vertex */
1412                 if ((tri[0][i] == e->v1 || tri[0][i] == e->v2) &&
1413                     (tri[0][(i + 1) % 3] == e->v1 || tri[0][(i + 1) % 3] == e->v2))
1414                 {
1415                         j++;
1416                         ndx[j] = opp;
1417                 }
1418         }
1419 }
1420
1421 static void add_quad_from_tris(SkinOutput *so, BMEdge *e, BMFace *adj[2])
1422 {
1423         BMVert *quad[4];
1424
1425         quad_from_tris(e, adj, quad);
1426
1427         add_poly(so, quad[0], quad[1], quad[2], quad[3]);
1428 }
1429
1430 static void hull_merge_triangles(SkinOutput *so, const SkinModifierData *smd)
1431 {
1432         BMIter iter;
1433         BMEdge *e;
1434         Heap *heap;
1435         float score;
1436
1437         heap = BLI_heap_new();
1438
1439         BM_mesh_elem_hflag_disable_all(so->bm, BM_FACE, BM_ELEM_TAG, false);
1440
1441         /* Build heap */
1442         BM_ITER_MESH (e, &iter, so->bm, BM_EDGES_OF_MESH) {
1443                 BMFace *adj[2];
1444
1445                 /* Only care if the edge is used by exactly two triangles */
1446                 if (BM_edge_face_pair(e, &adj[0], &adj[1])) {
1447                         if (adj[0]->len == 3 && adj[1]->len == 3) {
1448                                 BMVert *quad[4];
1449
1450                                 BLI_assert(BM_face_is_normal_valid(adj[0]));
1451                                 BLI_assert(BM_face_is_normal_valid(adj[1]));
1452
1453                                 /* Construct quad using the two triangles adjacent to
1454                                  * the edge */
1455                                 quad_from_tris(e, adj, quad);
1456
1457                                 /* Calculate a score for the quad, higher score for
1458                                  * triangles being closer to coplanar */
1459                                 score = ((BM_face_calc_area(adj[0]) +
1460                                           BM_face_calc_area(adj[1])) *
1461                                          dot_v3v3(adj[0]->no, adj[1]->no));
1462
1463                                 /* Check if quad crosses the axis of symmetry */
1464                                 if (quad_crosses_symmetry_plane(quad, smd)) {
1465                                         /* Increase score if the triangles form a
1466                                          * symmetric quad, otherwise don't use it */
1467                                         if (is_quad_symmetric(quad, smd))
1468                                                 score *= 10;
1469                                         else
1470                                                 continue;
1471                                 }
1472
1473                                 /* Don't use the quad if it's concave */
1474                                 if (!is_quad_convex_v3(quad[0]->co, quad[1]->co,
1475                                                        quad[2]->co, quad[3]->co))
1476                                 {
1477                                         continue;
1478                                 }
1479
1480                                 BLI_heap_insert(heap, -score, e);
1481                         }
1482                 }
1483         }
1484
1485         while (!BLI_heap_is_empty(heap)) {
1486                 BMFace *adj[2];
1487
1488                 e = BLI_heap_pop_min(heap);
1489
1490                 if (BM_edge_face_pair(e, &adj[0], &adj[1])) {
1491                         /* If both triangles still free, and if they don't already
1492                          * share a border with another face, output as a quad */
1493                         if (!BM_elem_flag_test(adj[0], BM_ELEM_TAG) &&
1494                             !BM_elem_flag_test(adj[1], BM_ELEM_TAG) &&
1495                             !BM_face_share_face_check(adj[0], adj[1]))
1496                         {
1497                                 add_quad_from_tris(so, e, adj);
1498                                 BM_elem_flag_enable(adj[0], BM_ELEM_TAG);
1499                                 BM_elem_flag_enable(adj[1], BM_ELEM_TAG);
1500                                 BM_elem_flag_enable(e, BM_ELEM_TAG);
1501                         }
1502                 }
1503         }
1504
1505         BLI_heap_free(heap, NULL);
1506
1507         BM_mesh_delete_hflag_tagged(so->bm, BM_ELEM_TAG, BM_EDGE | BM_FACE);
1508
1509 }
1510
1511 static void skin_merge_close_frame_verts(SkinNode *skin_nodes, int totvert,
1512                                          const MeshElemMap *emap,
1513                                          const MEdge *medge)
1514 {
1515         Frame **hull_frames;
1516         int v, tothullframe;
1517         
1518         for (v = 0; v < totvert; v++) {
1519                 /* Only check branch nodes */
1520                 if (!skin_nodes[v].totframe) {
1521                         hull_frames = collect_hull_frames(v, skin_nodes,
1522                                                           emap, medge,
1523                                                           &tothullframe);
1524                         merge_frame_corners(hull_frames, tothullframe);
1525                         MEM_freeN(hull_frames);
1526                 }
1527         }
1528 }
1529
1530 static void skin_update_merged_vertices(SkinNode *skin_nodes, int totvert)
1531 {
1532         int v;
1533         
1534         for (v = 0; v < totvert; ++v) {
1535                 SkinNode *sn = &skin_nodes[v];
1536                 int i, j;
1537                 
1538                 for (i = 0; i < sn->totframe; i++) {
1539                         Frame *f = &sn->frames[i];
1540
1541                         for (j = 0; j < 4; j++) {
1542                                 if (f->merge[j].frame) {
1543                                         /* Merge chaining not allowed */
1544                                         BLI_assert(!f->merge[j].frame->merge[f->merge[j].corner].frame);
1545
1546                                         f->verts[j] = f->merge[j].frame->verts[f->merge[j].corner];
1547                                 }
1548                         }
1549                 }
1550         }
1551 }
1552
1553 static void skin_fix_hull_topology(BMesh *bm, SkinNode *skin_nodes,
1554                                    int totvert)
1555 {
1556         int v;
1557         
1558         for (v = 0; v < totvert; v++) {
1559                 SkinNode *sn = &skin_nodes[v];
1560                 int j;
1561                 
1562                 for (j = 0; j < sn->totframe; j++) {
1563                         Frame *f = &sn->frames[j];
1564
1565                         if (f->detached) {
1566                                 BMFace *target_face;
1567                                 
1568                                 skin_hole_detach_partially_attached_frame(bm, f);
1569                                 
1570                                 target_face = skin_hole_target_face(bm, f);
1571                                 if (target_face)
1572                                         skin_fix_hole_no_good_verts(bm, f, target_face);
1573                         }
1574                 }
1575         }
1576 }
1577
1578 static void skin_output_end_nodes(SkinOutput *so, SkinNode *skin_nodes,
1579                                   int totvert)
1580 {
1581         int v;
1582         
1583         for (v = 0; v < totvert; ++v) {
1584                 SkinNode *sn = &skin_nodes[v];
1585                 /* Assuming here just two frames */
1586                 if (sn->flag & SEAM_FRAME) {
1587                         BMVert *v_order[4];
1588                         int i, order[4];
1589                         
1590                         skin_choose_quad_bridge_order(sn->frames[0].verts,
1591                                                       sn->frames[1].verts,
1592                                                       order);
1593                         for (i = 0; i < 4; i++)
1594                                 v_order[i] = sn->frames[1].verts[order[i]];
1595                         connect_frames(so, sn->frames[0].verts, v_order);
1596                 }
1597                 else if (sn->totframe == 2) {
1598                         connect_frames(so,
1599                                        sn->frames[0].verts,
1600                                        sn->frames[1].verts);
1601                 }
1602
1603                 if (sn->flag & CAP_START) {
1604                         if (sn->flag & ROOT) {
1605                                 add_poly(so,
1606                                          sn->frames[0].verts[0],
1607                                          sn->frames[0].verts[1],
1608                                          sn->frames[0].verts[2],
1609                                          sn->frames[0].verts[3]);
1610                         }
1611                         else {
1612                                 add_poly(so,
1613                                          sn->frames[0].verts[3],
1614                                          sn->frames[0].verts[2],
1615                                          sn->frames[0].verts[1],
1616                                          sn->frames[0].verts[0]);
1617                         }
1618                 }
1619                 if (sn->flag & CAP_END) {
1620                         add_poly(so,
1621                                  sn->frames[1].verts[0],
1622                                 sn->frames[1].verts[1],
1623                                  sn->frames[1].verts[2],
1624                                  sn->frames[1].verts[3]);
1625                 }
1626         }
1627 }
1628
1629 static void skin_output_connections(SkinOutput *so, SkinNode *skin_nodes,
1630                                     const MEdge *medge,
1631                                     int totedge)
1632 {
1633         int e;
1634         
1635         for (e = 0; e < totedge; e++) {
1636                 SkinNode *a, *b;
1637                 a = &skin_nodes[medge[e].v1];
1638                 b = &skin_nodes[medge[e].v2];
1639
1640                 if (a->totframe && b->totframe) {
1641                         if ((a->flag & SEAM_FRAME) || (b->flag & SEAM_FRAME)) {
1642                                 Frame *fr[2] = {&a->frames[0], &b->frames[0]};
1643                                 BMVert *v_order[4];
1644                                 int i, order[4];
1645
1646                                 if ((a->flag & SEAM_FRAME) && (e != a->seam_edges[0]))
1647                                         fr[0]++;
1648                                 if ((b->flag & SEAM_FRAME) && (e != b->seam_edges[0]))
1649                                         fr[1]++;
1650                         
1651                                 skin_choose_quad_bridge_order(fr[0]->verts, fr[1]->verts, order);
1652                                 for (i = 0; i < 4; i++)
1653                                         v_order[i] = fr[1]->verts[order[i]];
1654                                 connect_frames(so, fr[0]->verts, v_order);
1655                         }
1656                         else {
1657                                 connect_frames(so,
1658                                                a->frames[0].verts,
1659                                                b->frames[0].verts);
1660                         }
1661                 }
1662         }
1663 }
1664
1665 static void skin_smooth_hulls(BMesh *bm, SkinNode *skin_nodes,
1666                               int totvert, const SkinModifierData *smd)
1667 {
1668         BMIter iter, eiter;
1669         BMVert *v;
1670         int i, j, k, skey;
1671
1672         if (smd->branch_smoothing == 0)
1673                 return;
1674
1675         /* Mark all frame vertices */
1676         BM_mesh_elem_hflag_disable_all(bm, BM_VERT, BM_ELEM_TAG, false);
1677         for (i = 0; i < totvert; i++) {
1678                 for (j = 0; j < skin_nodes[i].totframe; j++) {
1679                         Frame *frame = &skin_nodes[i].frames[j];
1680
1681                         for (k = 0; k < 4; k++)
1682                                 BM_elem_flag_enable(frame->verts[k], BM_ELEM_TAG);
1683                 }
1684         }
1685
1686         /* Add temporary shapekey layer to store original coordinates */
1687         BM_data_layer_add(bm, &bm->vdata, CD_SHAPEKEY);
1688         skey = CustomData_number_of_layers(&bm->vdata, CD_SHAPEKEY) - 1;
1689         BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
1690                 copy_v3_v3(CustomData_bmesh_get_n(&bm->vdata, v->head.data,
1691                                                   CD_SHAPEKEY, skey), v->co);
1692         }
1693
1694         /* Smooth vertices, weight unmarked vertices more strongly (helps
1695          * to smooth frame vertices, but don't want to alter them too
1696          * much) */
1697         BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
1698                 BMEdge *e;
1699                 float avg[3];
1700                 float weight = smd->branch_smoothing;
1701                 int totv = 1;
1702
1703                 if (BM_elem_flag_test(v, BM_ELEM_TAG))
1704                         weight *= 0.5f;
1705
1706                 copy_v3_v3(avg, v->co);
1707                 BM_ITER_ELEM (e, &eiter, v, BM_EDGES_OF_VERT) {
1708                         BMVert *other = BM_edge_other_vert(e, v);
1709
1710                         add_v3_v3(avg, CustomData_bmesh_get_n(&bm->vdata,
1711                                                               other->head.data,
1712                                                               CD_SHAPEKEY, skey));
1713                         totv++;
1714                 }
1715
1716                 if (totv > 1) {
1717                         mul_v3_fl(avg, 1.0f / (float)totv);
1718                         interp_v3_v3v3(v->co, v->co, avg, weight);
1719                 }
1720         }
1721
1722         /* Done with original coordinates */
1723         BM_data_layer_free_n(bm, &bm->vdata, CD_SHAPEKEY, skey);
1724 }
1725
1726 /* Returns true if all hulls are successfully built, false otherwise */
1727 static bool skin_output_branch_hulls(SkinOutput *so, SkinNode *skin_nodes,
1728                                      int totvert, const MeshElemMap *emap,
1729                                      const MEdge *medge)
1730 {
1731         bool result = true;
1732         int v;
1733         
1734         for (v = 0; v < totvert; v++) {
1735                 SkinNode *sn = &skin_nodes[v];
1736                 
1737                 /* Branch node hulls */
1738                 if (!sn->totframe) {
1739                         Frame **hull_frames;
1740                         int tothullframe;
1741                         
1742                         hull_frames = collect_hull_frames(v, skin_nodes,
1743                                                           emap, medge,
1744                                                           &tothullframe);
1745                         if (!build_hull(so, hull_frames, tothullframe))
1746                                 result = false;
1747
1748                         MEM_freeN(hull_frames);
1749                 }
1750         }
1751
1752         return result;
1753 }
1754
1755 static BMesh *build_skin(SkinNode *skin_nodes,
1756                          int totvert, const MeshElemMap *emap,
1757                          const MEdge *medge, int totedge,
1758                          const MDeformVert *input_dvert,
1759                          SkinModifierData *smd)
1760 {
1761         SkinOutput so;
1762         int v;
1763
1764         so.smd = smd;
1765         so.bm = BM_mesh_create(
1766                 &bm_mesh_allocsize_default,
1767                 &((struct BMeshCreateParams){.use_toolflags = true,}));
1768         so.mat_nr = 0;
1769         
1770         /* BMESH_TODO: bumping up the stack level (see MOD_array.c) */
1771         BM_mesh_elem_toolflags_ensure(so.bm);
1772         BMO_push(so.bm, NULL);
1773         bmesh_edit_begin(so.bm, 0);
1774
1775         if (input_dvert)
1776                 BM_data_layer_add(so.bm, &so.bm->vdata, CD_MDEFORMVERT);
1777
1778         /* Check for mergeable frame corners around hulls before
1779          * outputting vertices */
1780         skin_merge_close_frame_verts(skin_nodes, totvert, emap, medge);
1781
1782         /* Write out all frame vertices to the mesh */
1783         for (v = 0; v < totvert; ++v) {
1784                 if (skin_nodes[v].totframe)
1785                         output_frames(so.bm, &skin_nodes[v],
1786                                       input_dvert ? &input_dvert[v] : NULL);
1787         }
1788
1789         /* Update vertex pointers for merged frame corners */
1790         skin_update_merged_vertices(skin_nodes, totvert);
1791
1792         if (!skin_output_branch_hulls(&so, skin_nodes, totvert, emap, medge))
1793                 modifier_setError(&smd->modifier, "Hull error");
1794
1795         /* Merge triangles here in the hope of providing better target
1796          * faces for skin_fix_hull_topology() to connect to */
1797         hull_merge_triangles(&so, smd);
1798
1799         /* Using convex hulls may not generate a nice manifold mesh. Two
1800          * problems can occur: an input frame's edges may be inside the
1801          * hull, and/or an input frame's vertices may be inside the hull.
1802          *
1803          * General fix to produce manifold mesh: for any frame that is
1804          * partially detached, first detach it fully, then find a suitable
1805          * existing face to merge with. (Note that we do this after
1806          * creating all hull faces, but before creating any other
1807          * faces.
1808          */
1809         skin_fix_hull_topology(so.bm, skin_nodes, totvert);
1810
1811         skin_smooth_hulls(so.bm, skin_nodes, totvert, smd);
1812
1813         skin_output_end_nodes(&so, skin_nodes, totvert);
1814         skin_output_connections(&so, skin_nodes, medge, totedge);
1815         hull_merge_triangles(&so, smd);
1816
1817         bmesh_edit_end(so.bm, 0);
1818         BMO_pop(so.bm);
1819
1820         return so.bm;
1821 }
1822
1823 static void skin_set_orig_indices(Mesh *mesh)
1824 {
1825         int *orig, totpoly;
1826
1827         totpoly = mesh->totpoly;
1828         orig = CustomData_add_layer(&mesh->pdata, CD_ORIGINDEX,
1829                                     CD_CALLOC, NULL, totpoly);
1830         copy_vn_i(orig, totpoly, ORIGINDEX_NONE);
1831 }
1832
1833 /*
1834  * 0) Subdivide edges (in caller)
1835  * 1) Generate good edge matrices (uses root nodes)
1836  * 2) Generate node frames
1837  * 3) Output vertices and polygons from frames, connections, and hulls
1838  */
1839 static Mesh *base_skin(Mesh *origmesh,
1840                        SkinModifierData *smd)
1841 {
1842         Mesh *result;
1843         MVertSkin *nodes;
1844         BMesh *bm;
1845         EMat *emat;
1846         SkinNode *skin_nodes;
1847         MeshElemMap *emap;
1848         int *emapmem;
1849         MVert *mvert;
1850         MEdge *medge;
1851         MDeformVert *dvert;
1852         int totvert, totedge;
1853         bool has_valid_root = false;
1854
1855         nodes = CustomData_get_layer(&origmesh->vdata, CD_MVERT_SKIN);
1856
1857         mvert = origmesh->mvert;
1858         dvert = origmesh->dvert;
1859         medge = origmesh->medge;
1860         totvert = origmesh->totvert;
1861         totedge = origmesh->totedge;
1862
1863         BKE_mesh_vert_edge_map_create(&emap, &emapmem, medge, totvert, totedge);
1864
1865         emat = build_edge_mats(nodes, mvert, totvert, medge, emap, totedge, &has_valid_root);
1866         skin_nodes = build_frames(mvert, totvert, nodes, emap, emat);
1867         MEM_freeN(emat);
1868         emat = NULL;
1869
1870         bm = build_skin(skin_nodes, totvert, emap, medge, totedge, dvert, smd);
1871
1872         MEM_freeN(skin_nodes);
1873         MEM_freeN(emap);
1874         MEM_freeN(emapmem);
1875
1876         if (!has_valid_root) {
1877                 modifier_setError(&smd->modifier, "No valid root vertex found (you need one per mesh island you want to skin)");
1878         }
1879
1880         if (!bm)
1881                 return NULL;
1882
1883         result = BKE_bmesh_to_mesh_nomain(bm, &(struct BMeshToMeshParams){0});
1884         BM_mesh_free(bm);
1885
1886         result->runtime.cd_dirty_vert |= CD_MASK_NORMAL;
1887
1888         skin_set_orig_indices(result);
1889
1890         return result;
1891 }
1892
1893 static Mesh *final_skin(SkinModifierData *smd, Mesh *mesh)
1894 {
1895         Mesh *result;
1896
1897         /* Skin node layer is required */
1898         if (!CustomData_get_layer(&mesh->vdata, CD_MVERT_SKIN))
1899                 return mesh;
1900
1901         mesh = subdivide_base(mesh);
1902         result = base_skin(mesh, smd);
1903
1904         BKE_id_free(NULL, mesh);
1905         return result;
1906 }
1907
1908
1909 /**************************** Skin Modifier ***************************/
1910
1911 static void initData(ModifierData *md)
1912 {
1913         SkinModifierData *smd = (SkinModifierData *) md;
1914         
1915         /* Enable in editmode by default */
1916         md->mode |= eModifierMode_Editmode;
1917
1918         smd->branch_smoothing = 0;
1919         smd->flag = 0;
1920         smd->symmetry_axes = MOD_SKIN_SYMM_X;
1921 }
1922
1923 static Mesh *applyModifier(ModifierData *md,
1924                            const ModifierEvalContext *UNUSED(ctx),
1925                            Mesh *mesh)
1926 {
1927         Mesh *result;
1928
1929         if (!(result = final_skin((SkinModifierData *)md, mesh)))
1930                 return mesh;
1931         return result;
1932 }
1933
1934 static CustomDataMask requiredDataMask(Object *UNUSED(ob),
1935                                        ModifierData *UNUSED(md))
1936 {
1937         return CD_MASK_MVERT_SKIN | CD_MASK_MDEFORMVERT;
1938 }
1939
1940 ModifierTypeInfo modifierType_Skin = {
1941         /* name */              "Skin",
1942         /* structName */        "SkinModifierData",
1943         /* structSize */        sizeof(SkinModifierData),
1944         /* type */              eModifierTypeType_Constructive,
1945         /* flags */             eModifierTypeFlag_AcceptsMesh | eModifierTypeFlag_SupportsEditmode,
1946
1947         /* copyData */          modifier_copyData_generic,
1948
1949         /* deformVerts_DM */    NULL,
1950         /* deformMatrices_DM */ NULL,
1951         /* deformVertsEM_DM */  NULL,
1952         /* deformMatricesEM_DM*/NULL,
1953         /* applyModifier_DM */  NULL,
1954         /* applyModifierEM_DM */NULL,
1955
1956         /* deformVerts */       NULL,
1957         /* deformMatrices */    NULL,
1958         /* deformVertsEM */     NULL,
1959         /* deformMatricesEM */  NULL,
1960         /* applyModifier */     applyModifier,
1961         /* applyModifierEM */   NULL,
1962
1963         /* initData */          initData,
1964         /* requiredDataMask */  requiredDataMask,
1965         /* freeData */          NULL,
1966         /* isDisabled */        NULL,
1967         /* updateDepsgraph */   NULL,
1968         /* dependsOnTime */     NULL,
1969         /* dependsOnNormals */  NULL,
1970         /* foreachObjectLink */ NULL,
1971         /* foreachIDLink */     NULL,
1972 };