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