Style Cleanup: whitespace and some formatting.
[blender.git] / source / blender / bmesh / operators / subdivideop.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): Joseph Eagar.
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 #include "MEM_guardedalloc.h"
24
25 #include "BKE_utildefines.h"
26 #include "BKE_tessmesh.h"
27
28 #include "BLI_math.h"
29 #include "BLI_rand.h"
30 #include "BLI_ghash.h"
31 #include "BLI_array.h"
32 #include "BLI_noise.h"
33 #include "BLI_utildefines.h"
34
35 #include "DNA_object_types.h"
36
37 #include "ED_mesh.h"
38
39 #include "bmesh.h"
40 #include "bmesh_private.h"
41
42 #include "mesh_intern.h"
43 #include "subdivideop.h"
44
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <math.h>
49
50 /* flags for all elements share a common bitfield space */
51 #define SUBD_SPLIT      1
52
53 #define EDGE_PERCENT    2
54
55 /* I don't think new faces are flagged, currently, but
56  * better safe than sorry. */
57 #define FACE_NEW        4
58 #define FACE_CUSTOMFILL 8
59 #define ELE_INNER       16
60 #define ELE_SPLIT       32
61 #define ELE_CONNECT     64
62
63 /* stuff for the flag paramter.  note that
64  * what used to live in "beauty" and
65  * in "seltype" live here.  still have to
66  * convert the beauty flags over, which
67  * is why it starts at 128 (to avoid
68  * collision). */
69 #define SELTYPE_INNER   128
70
71 /*
72  * NOTE: beauty has been renamed to flag!
73  */
74
75 /* generic subdivision rules:
76  *
77  * - two selected edges in a face should make a link
78  *   between them.
79  *
80  * - one edge should do, what? make pretty topology, or just
81  *   split the edge only?
82  */
83
84 #if 0 //misc. code, maps a parametric coordinate to a fractal line
85         float lastrnd[3], vec2[3] = {0.0f, 0.0f, 0.0f};
86         int seed = BLI_rand();
87         int d, i, j, dp, lvl, wid;
88         float df;
89
90         BLI_srandom(seed);
91
92         wid = (params->numcuts + 2);
93         dp = perc * wid;
94         wid /= 2;
95         d = lvl = 0;
96         while (1) {
97                 if (d > dp) {
98                         d -= wid;
99                 }
100                 else if (d < dp) {
101                         d += wid;
102                 }
103                 else {
104                         break;
105                 }
106
107
108                 wid = MAX2((wid / 2), 1);
109                 lvl++;
110         }
111
112         zero_v3(vec1);
113         df = 1.0f;
114         for (i = 0; i < lvl; i++, df /= 4.0f) {
115                 int tot = (1 << i);
116
117                 lastrnd[0] = BLI_drand() - 0.5f;
118                 lastrnd[1] = BLI_drand() - 0.5f;
119                 lastrnd[2] = BLI_drand() - 0.5f;
120                 for (j = 0; j < tot; j++) {
121                         float a, b, rnd[3], rnd2[3];
122
123                         rnd[0] = BLI_drand() - 0.5f;
124                         rnd[1] = BLI_drand() - 0.5f;
125                         rnd[2] = BLI_drand() - 0.5f;
126
127                         a = (float)j * (float)((float)params->numcuts / (float)tot);
128                         b = (float)(j + 1) * (float)((float)params->numcuts / (float)tot);
129                         if (d >= a && d <= b) {
130                                 interp_v3_v3v3(rnd2, lastrnd, rnd, (((float)d) - a) / (b - a));
131                                 mul_v3_fl(rnd2, df);
132                                 add_v3_v3(vec1, rnd2);
133                         }
134
135                         copy_v3_v3(lastrnd, rnd);
136                 }
137         }
138 #endif
139 /* connects face with smallest len, which I think should always be correct for
140  * edge subdivision */
141 static BMEdge *connect_smallest_face(BMesh *bm, BMVert *v1, BMVert *v2, BMFace **r_nf)
142 {
143         BMIter iter, iter2;
144         BMVert *v;
145         BMLoop *nl;
146         BMFace *face, *curf = NULL;
147
148         /* this isn't the best thing in the world.  it doesn't handle cases where there's
149          * multiple faces yet.  that might require a convexity test to figure out which
150          * face is "best," and who knows what for non-manifold conditions. */
151         for (face = BMIter_New(&iter, bm, BM_FACES_OF_VERT, v1); face; face = BMIter_Step(&iter)) {
152                 for (v = BMIter_New(&iter2, bm, BM_VERTS_OF_FACE, face); v; v = BMIter_Step(&iter2)) {
153                         if (v == v2) {
154                                 if (!curf || face->len < curf->len) curf = face;
155                         }
156                 }
157         }
158
159         if (curf) {
160                 face = BM_Split_Face(bm, curf, v1, v2, &nl, NULL);
161                 
162                 if (r_nf) *r_nf = face;
163                 return nl ? nl->e : NULL;
164         }
165
166         return NULL;
167 }
168 /* calculates offset for co, based on fractal, sphere or smooth settings  */
169 static void alter_co(BMesh *bm, BMVert *v, BMEdge *UNUSED(origed), const subdparams *params, float perc,
170                      BMVert *vsta, BMVert *vend)
171 {
172         float tvec[3], prev_co[3], fac;
173         float *co = NULL;
174         int i, totlayer = CustomData_number_of_layers(&bm->vdata, CD_SHAPEKEY);
175         
176         BM_Vert_UpdateAllNormals(bm, v);
177
178         co = CustomData_bmesh_get_n(&bm->vdata, v->head.data, CD_SHAPEKEY, params->origkey);
179         copy_v3_v3(prev_co, co);
180
181         if (params->beauty & B_SMOOTH) {
182                 /* we calculate an offset vector vec1[], to be added to *co */
183                 float len, nor[3], nor1[3], nor2[3], smooth = params->smooth;
184
185                 sub_v3_v3v3(nor, vsta->co, vend->co);
186                 len = 0.5f * normalize_v3(nor);
187
188                 copy_v3_v3(nor1, vsta->no);
189                 copy_v3_v3(nor2, vend->no);
190
191                 /* cosine angle */
192                 fac=  dot_v3v3(nor, nor1);
193                 mul_v3_v3fl(tvec, nor1, fac);
194
195                 /* cosine angle */
196                 fac = -dot_v3v3(nor, nor2);
197                 madd_v3_v3fl(tvec, nor2, fac);
198
199                 /* falloff for multi subdivide */
200                 smooth *= sqrtf(fabsf(1.0f - 2.0f * fabsf(0.5f-perc)));
201
202                 mul_v3_fl(tvec, smooth * len);
203
204                 add_v3_v3(co, tvec);
205         }
206         else if (params->beauty & B_SPHERE) { /* subdivide sphere */
207                 normalize_v3(co);
208                 mul_v3_fl(co, params->smooth);
209         }
210
211         if (params->beauty & B_FRACTAL) {
212                 float len = len_v3v3(vsta->co, vend->co);
213                 float vec2[3] = {0.0f, 0.0f, 0.0f}, co2[3];
214
215                 fac = params->fractal * len;
216
217                 add_v3_v3(vec2, vsta->no);
218                 add_v3_v3(vec2, vend->no);
219                 mul_v3_fl(vec2, 0.5f);
220
221                 add_v3_v3v3(co2, v->co, params->off);
222                 tvec[0] = fac * (BLI_gTurbulence(1.0, co2[0], co2[1], co2[2], 15, 0, 1) - 0.5f);
223                 tvec[1] = fac * (BLI_gTurbulence(1.0, co2[0], co2[1], co2[2], 15, 0, 1) - 0.5f);
224                 tvec[2] = fac * (BLI_gTurbulence(1.0, co2[0], co2[1], co2[2], 15, 0, 1) - 0.5f);
225
226                 mul_v3_v3(vec2, tvec);
227
228                 /* add displacemen */
229                 add_v3_v3v3(co, co, vec2);
230         }
231
232         /* apply the new difference to the rest of the shape keys,
233          * note that this doent take rotations into account, we _could_ support
234          * this by getting the normals and coords for each shape key and
235          * re-calculate the smooth value for each but this is quite involved.
236          * for now its ok to simply apply the difference IMHO - campbell */
237         sub_v3_v3v3(tvec, prev_co, co);
238
239         for (i = 0; i < totlayer; i++) {
240                 if (params->origkey != i) {
241                         co = CustomData_bmesh_get_n(&bm->vdata, v->head.data, CD_SHAPEKEY, i);
242                         sub_v3_v3(co, tvec);
243                 }
244         }
245
246 }
247
248 /* assumes in the edge is the correct interpolated vertices already */
249 /* percent defines the interpolation, rad and flag are for special options */
250 /* results in new vertex with correct coordinate, vertex normal and weight group info */
251 static BMVert *bm_subdivide_edge_addvert(BMesh *bm, BMEdge *edge, BMEdge *oedge,
252                                          const subdparams *params, float percent,
253                                          float percent2,
254                                          BMEdge **out, BMVert *vsta, BMVert *vend)
255 {
256         BMVert *ev;
257         
258         ev = BM_Split_Edge(bm, edge->v1, edge, out, percent);
259
260         BMO_SetFlag(bm, ev, ELE_INNER);
261
262         /* offset for smooth or sphere or fractal */
263         alter_co(bm, ev, oedge, params, percent2, vsta, vend);
264
265 #if 0 //BMESH_TODO
266         /* clip if needed by mirror modifier */
267         if (edge->v1->f2) {
268                 if (edge->v1->f2 & edge->v2->f2 & 1) {
269                         co[0] = 0.0f;
270                 }
271                 if (edge->v1->f2 & edge->v2->f2 & 2) {
272                         co[1] = 0.0f;
273                 }
274                 if (edge->v1->f2 & edge->v2->f2 & 4) {
275                         co[2] = 0.0f;
276                 }
277         }
278 #endif
279         
280         return ev;
281 }
282
283 static BMVert *subdivideedgenum(BMesh *bm, BMEdge *edge, BMEdge *oedge,
284                                 int curpoint, int totpoint, const subdparams *params,
285                                 BMEdge **newe, BMVert *vsta, BMVert *vend)
286 {
287         BMVert *ev;
288         float percent, percent2 = 0.0f;
289          
290         if (BMO_TestFlag(bm, edge, EDGE_PERCENT) && totpoint == 1)
291                 percent = BMO_Get_MapFloat(bm, params->op, "edgepercents", edge);
292         else {
293                 percent = 1.0f / (float)(totpoint + 1-curpoint);
294                 percent2 = (float)(curpoint + 1) / (float)(totpoint + 1);
295
296         }
297         
298         ev = bm_subdivide_edge_addvert(bm, edge, oedge, params, percent,
299                                       percent2, newe, vsta, vend);
300         return ev;
301 }
302
303 static void bm_subdivide_multicut(BMesh *bm, BMEdge *edge, const subdparams *params,
304                                   BMVert *vsta, BMVert *vend)
305 {
306         BMEdge *eed = edge, *newe, temp = *edge;
307         BMVert *v, ov1 = *edge->v1, ov2 = *edge->v2, *v1 = edge->v1, *v2 = edge->v2;
308         int i, numcuts = params->numcuts;
309
310         temp.v1 = &ov1;
311         temp.v2 = &ov2;
312         
313         for (i = 0; i < numcuts; i++) {
314                 v = subdivideedgenum(bm, eed, &temp, i, params->numcuts, params, &newe, vsta, vend);
315
316                 BMO_SetFlag(bm, v, SUBD_SPLIT);
317                 BMO_SetFlag(bm, eed, SUBD_SPLIT);
318                 BMO_SetFlag(bm, newe, SUBD_SPLIT);
319
320                 BMO_SetFlag(bm, v, ELE_SPLIT);
321                 BMO_SetFlag(bm, eed, ELE_SPLIT);
322                 BMO_SetFlag(bm, newe, SUBD_SPLIT);
323
324                 BM_CHECK_ELEMENT(bm, v);
325                 if (v->e) BM_CHECK_ELEMENT(bm, v->e);
326                 if (v->e && v->e->l) BM_CHECK_ELEMENT(bm, v->e->l->f);
327         }
328         
329         alter_co(bm, v1, &temp, params, 0, &ov1, &ov2);
330         alter_co(bm, v2, &temp, params, 1.0, &ov1, &ov2);
331 }
332
333 /* note: the patterns are rotated as necassary to
334  * match the input geometry.  they're based on the
335  * pre-split state of the  face */
336
337 /*
338  *  v3---------v2
339  *  |          |
340  *  |          |
341  *  |          |
342  *  |          |
343  *  v4---v0---v1
344  */
345 static void quad_1edge_split(BMesh *bm, BMFace *UNUSED(face),
346                              BMVert **verts, const subdparams *params)
347 {
348         BMFace *nf;
349         int i, add, numcuts = params->numcuts;
350
351         /* if it's odd, the middle face is a quad, otherwise it's a triangl */
352         if ((numcuts % 2) == 0) {
353                 add = 2;
354                 for (i = 0; i < numcuts; i++) {
355                         if (i == numcuts / 2) {
356                                 add -= 1;
357                         }
358                         connect_smallest_face(bm, verts[i], verts[numcuts + add], &nf);
359                 }
360         }
361         else {
362                 add = 2;
363                 for (i = 0; i < numcuts; i++) {
364                         connect_smallest_face(bm, verts[i], verts[numcuts + add], &nf);
365                         if (i == numcuts/2) {
366                                 add -= 1;
367                                 connect_smallest_face(bm, verts[i], verts[numcuts + add], &nf);
368                         }
369                 }
370
371         }
372 }
373
374 static SubDPattern quad_1edge = {
375         {1, 0, 0, 0},
376         quad_1edge_split,
377         4,
378 };
379
380
381 /*
382  *  v6--------v5
383  *  |          |
384  *  |          |v4s
385  *  |          |v3s
386  *  |   s  s   |
387  *  v7-v0--v1-v2
388  */
389 static void quad_2edge_split_path(BMesh *bm, BMFace *UNUSED(face), BMVert **verts,
390                                   const subdparams *params)
391 {
392         BMFace *nf;
393         int i, numcuts = params->numcuts;
394         
395         for (i = 0; i < numcuts; i++) {
396                 connect_smallest_face(bm, verts[i], verts[numcuts + (numcuts - i)], &nf);
397         }
398         connect_smallest_face(bm, verts[numcuts * 2 + 3], verts[numcuts * 2 + 1], &nf);
399 }
400
401 static SubDPattern quad_2edge_path = {
402         {1, 1, 0, 0},
403         quad_2edge_split_path,
404         4,
405 };
406
407 /*
408  *  v6--------v5
409  *  |          |
410  *  |          |v4s
411  *  |          |v3s
412  *  |   s  s   |
413  *  v7-v0--v1-v2
414  */
415 static void quad_2edge_split_innervert(BMesh *bm, BMFace *UNUSED(face), BMVert **verts,
416                                        const subdparams *params)
417 {
418         BMFace *nf;
419         BMVert *v, *lastv;
420         BMEdge *e, *ne, olde;
421         int i, numcuts = params->numcuts;
422         
423         lastv = verts[numcuts];
424
425         for (i = numcuts - 1; i >= 0; i--) {
426                 e = connect_smallest_face(bm, verts[i], verts[numcuts + (numcuts - i)], &nf);
427
428                 olde = *e;
429                 v = bm_subdivide_edge_addvert(bm, e, &olde, params, 0.5f, 0.5f, &ne, e->v1, e->v2);
430
431                 if (i != numcuts - 1) {
432                         connect_smallest_face(bm, lastv, v, &nf);
433                 }
434
435                 lastv = v;
436         }
437
438         connect_smallest_face(bm, lastv, verts[numcuts * 2 + 2], &nf);
439 }
440
441 static SubDPattern quad_2edge_innervert = {
442         {1, 1, 0, 0},
443         quad_2edge_split_innervert,
444         4,
445 };
446
447 /*
448  *  v6--------v5
449  *  |          |
450  *  |          |v4s
451  *  |          |v3s
452  *  |   s  s   |
453  *  v7-v0--v1-v2
454  *
455  */
456 static void quad_2edge_split_fan(BMesh *bm, BMFace *UNUSED(face), BMVert **verts,
457                                  const subdparams *params)
458 {
459         BMFace *nf;
460         /* BMVert *v; */               /* UNUSED */
461         /* BMVert *lastv = verts[2]; */ /* UNUSED */
462         /* BMEdge *e, *ne; */          /* UNUSED */
463         int i, numcuts = params->numcuts;
464
465         for (i = 0; i < numcuts; i++) {
466                 connect_smallest_face(bm, verts[i], verts[numcuts * 2 + 2], &nf);
467                 connect_smallest_face(bm, verts[numcuts + (numcuts - i)], verts[numcuts * 2 + 2], &nf);
468         }
469 }
470
471 static SubDPattern quad_2edge_fan = {
472         {1, 1, 0, 0},
473         quad_2edge_split_fan,
474         4,
475 };
476
477 /*
478  *      s   s
479  *  v8--v7--v6-v5
480  *  |          |
481  *  |          v4 s
482  *  |          |
483  *  |          v3 s
484  *  |   s  s   |
485  *  v9-v0--v1-v2
486  */
487 static void quad_3edge_split(BMesh *bm, BMFace *UNUSED(face), BMVert **verts,
488                              const subdparams *params)
489 {
490         BMFace *nf;
491         int i, add = 0, numcuts = params->numcuts;
492         
493         for (i = 0; i < numcuts; i++) {
494                 if (i == numcuts / 2) {
495                         if (numcuts % 2 != 0) {
496                                 connect_smallest_face(bm, verts[numcuts - i - 1 + add], verts[i + numcuts + 1], &nf);
497                         }
498                         add = numcuts * 2 + 2;
499                 }
500                 connect_smallest_face(bm, verts[numcuts - i - 1 + add], verts[i + numcuts + 1], &nf);
501         }
502
503         for (i = 0; i < numcuts / 2 + 1; i++) {
504                 connect_smallest_face(bm, verts[i], verts[(numcuts - i) + numcuts * 2 + 1], &nf);
505         }
506 }
507
508 static SubDPattern quad_3edge = {
509         {1, 1, 1, 0},
510         quad_3edge_split,
511         4,
512 };
513
514 /*
515  *            v8--v7-v6--v5
516  *            |     s    |
517  *            |v9 s     s|v4
518  * first line |          |   last line
519  *            |v10s s   s|v3
520  *            v11-v0--v1-v2
521  *
522  *            it goes from bottom up
523  */
524 static void quad_4edge_subdivide(BMesh *bm, BMFace *UNUSED(face), BMVert **verts,
525                                  const subdparams *params)
526 {
527         BMFace *nf;
528         BMVert *v, *v1, *v2;
529         BMEdge *e, *ne, temp;
530         BMVert **lines;
531         int numcuts = params->numcuts;
532         int i, j, a, b, s = numcuts + 2 /* , totv = numcuts * 4 + 4 */;
533
534         lines = MEM_callocN(sizeof(BMVert *)*(numcuts + 2)*(numcuts + 2), "q_4edge_split");
535         /* build a 2-dimensional array of verts,
536          * containing every vert (and all new ones)
537          * in the face */
538
539         /* first line */
540         for (i = 0; i < numcuts + 2; i++) {
541                 lines[i] = verts[numcuts * 3 + 2 + (numcuts - i + 1)];
542         }
543
544         /* last line */
545         for (i = 0; i < numcuts + 2; i++) {
546                 lines[(s - 1) * s + i] = verts[numcuts + i];
547         }
548         
549         /* first and last members of middle lines */
550         for (i = 0; i < numcuts; i++) {
551                 a = i;
552                 b = numcuts + 1 + numcuts + 1 + (numcuts - i - 1);
553                 
554                 e = connect_smallest_face(bm, verts[a], verts[b], &nf);
555                 if (!e)
556                         continue;
557
558                 BMO_SetFlag(bm, e, ELE_INNER);
559                 BMO_SetFlag(bm, nf, ELE_INNER);
560
561                 
562                 v1 = lines[(i + 1)*s] = verts[a];
563                 v2 = lines[(i + 1)*s + s - 1] = verts[b];
564                 
565                 temp = *e;
566                 for (a = 0; a < numcuts; a++) {
567                         v = subdivideedgenum(bm, e, &temp, a, numcuts, params, &ne,
568                                             v1, v2);
569                         if (!v)
570                                 bmesh_error();
571
572                         BMO_SetFlag(bm, ne, ELE_INNER);
573                         lines[(i + 1) * s + a + 1] = v;
574                 }
575         }
576
577         for (i = 1; i < numcuts + 2; i++) {
578                 for (j = 1; j < numcuts + 1; j++) {
579                         a = i * s + j;
580                         b = (i - 1) * s + j;
581                         e = connect_smallest_face(bm, lines[a], lines[b], &nf);
582                         if (!e)
583                                 continue;
584
585                         BMO_SetFlag(bm, e, ELE_INNER);
586                         BMO_SetFlag(bm, nf, ELE_INNER);
587                 }
588         }
589
590         MEM_freeN(lines);
591 }
592
593 /*
594  *        v3
595  *       / \
596  *      /   \
597  *     /     \
598  *    /       \
599  *   /         \
600  *  v4--v0--v1--v2
601  *      s    s
602  */
603 static void tri_1edge_split(BMesh *bm, BMFace *UNUSED(face), BMVert **verts,
604                             const subdparams *params)
605 {
606         BMFace *nf;
607         int i, numcuts = params->numcuts;
608         
609         for (i = 0; i < numcuts; i++) {
610                 connect_smallest_face(bm, verts[i], verts[numcuts + 1], &nf);
611         }
612 }
613
614 static SubDPattern tri_1edge = {
615         {1, 0, 0},
616         tri_1edge_split,
617         3,
618 };
619
620 /*         v5
621  *        / \
622  *   s v6/---\ v4 s
623  *      / \ / \
624  *  sv7/---v---\ v3 s
625  *    /  \/  \/ \
626  *   v8--v0--v1--v2
627  *      s    s
628  */
629 static void tri_3edge_subdivide(BMesh *bm, BMFace *UNUSED(face), BMVert **verts,
630                                 const subdparams *params)
631 {
632         BMFace *nf;
633         BMEdge *e, *ne, temp;
634         BMVert ***lines, *v, ov1, ov2;
635         void *stackarr[1];
636         int i, j, a, b, numcuts = params->numcuts;
637         
638         /* number of verts in each lin */
639         lines = MEM_callocN(sizeof(void *)*(numcuts + 2), "triangle vert table");
640         
641         lines[0] = (BMVert **) stackarr;
642         lines[0][0] = verts[numcuts * 2 + 1];
643         
644         lines[numcuts + 1] = MEM_callocN(sizeof(void *) * (numcuts + 2), "triangle vert table 2");
645         for (i = 0; i < numcuts; i++) {
646                 lines[numcuts + 1][i + 1] = verts[i];
647         }
648         lines[numcuts + 1][0] = verts[numcuts * 3 + 2];
649         lines[numcuts + 1][numcuts + 1] = verts[numcuts];
650
651         for (i = 0; i < numcuts; i++) {
652                 lines[i + 1] = MEM_callocN(sizeof(void *)*(2 + i), "triangle vert table row");
653                 a = numcuts * 2 + 2 + i;
654                 b = numcuts + numcuts - i;
655                 e = connect_smallest_face(bm, verts[a], verts[b], &nf);
656                 if (!e) goto cleanup;
657
658                 BMO_SetFlag(bm, e, ELE_INNER);
659                 BMO_SetFlag(bm, nf, ELE_INNER);
660
661                 lines[i + 1][0] = verts[a];
662                 lines[i + 1][i + 1] = verts[b];
663                 
664                 temp = *e;
665                 ov1 = *verts[a];
666                 ov2 = *verts[b];
667                 temp.v1 = &ov1;
668                 temp.v2 = &ov2;
669                 for (j = 0; j < i; j++) {
670                         v = subdivideedgenum(bm, e, &temp, j, i, params, &ne,
671                                              verts[a], verts[b]);
672                         lines[i + 1][j + 1] = v;
673
674                         BMO_SetFlag(bm, ne, ELE_INNER);
675                 }
676         }
677         
678         /*
679          *         v5
680          *        / \
681          *   s v6/---\ v4 s
682          *      / \ / \
683          *  sv7/---v---\ v3 s
684          *    /  \/  \/ \
685          *   v8--v0--v1--v2
686          *      s    s
687          */
688         for (i = 1; i < numcuts + 1; i++) {
689                 for (j = 0; j < i; j++) {
690                         e = connect_smallest_face(bm, lines[i][j], lines[i + 1][j + 1], &nf);
691
692                         BMO_SetFlag(bm, e, ELE_INNER);
693                         BMO_SetFlag(bm, nf, ELE_INNER);
694
695                         e = connect_smallest_face(bm, lines[i][j + 1], lines[i + 1][j + 1], &nf);
696
697                         BMO_SetFlag(bm, e, ELE_INNER);
698                         BMO_SetFlag(bm, nf, ELE_INNER);
699                 }
700         }
701
702 cleanup:
703         for (i = 1; i < numcuts + 2; i++) {
704                 if (lines[i]) MEM_freeN(lines[i]);
705         }
706
707         MEM_freeN(lines);
708 }
709
710 static SubDPattern tri_3edge = {
711         {1, 1, 1},
712         tri_3edge_subdivide,
713         3,
714 };
715
716
717 static SubDPattern quad_4edge = {
718         {1, 1, 1, 1},
719         quad_4edge_subdivide,
720         4,
721 };
722
723 static SubDPattern *patterns[] = {
724         NULL, //quad single edge pattern is inserted here
725         NULL, //quad corner vert pattern is inserted here
726         NULL, //tri single edge pattern is inserted here
727         NULL,
728         &quad_3edge,
729         NULL,
730 };
731
732 #define PLEN    (sizeof(patterns) / sizeof(void *))
733
734 typedef struct subd_facedata {
735         BMVert *start; SubDPattern *pat;
736         int totedgesel; //only used if pat was NULL, e.g. no pattern was found
737         BMFace *face;
738 } subd_facedata;
739
740 void esubdivide_exec(BMesh *bmesh, BMOperator *op)
741 {
742         BMOpSlot *einput;
743         SubDPattern *pat;
744         subdparams params;
745         subd_facedata *facedata = NULL;
746         BMIter viter, fiter, liter;
747         BMVert *v, **verts = NULL;
748         BMEdge *edge, **edges = NULL;
749         BMLoop *nl, *l, **splits = NULL, **loops = NULL;
750         BMFace *face;
751         BLI_array_declare(splits);
752         BLI_array_declare(loops);
753         BLI_array_declare(facedata);
754         BLI_array_declare(edges);
755         BLI_array_declare(verts);
756         float smooth, fractal;
757         int beauty, cornertype, singleedge, gridfill;
758         int skey, seed, i, j, matched, a, b, numcuts, totesel;
759         
760         BMO_Flag_Buffer(bmesh, op, "edges", SUBD_SPLIT, BM_EDGE);
761         
762         numcuts = BMO_Get_Int(op, "numcuts");
763         seed = BMO_Get_Int(op, "seed");
764         smooth = BMO_Get_Float(op, "smooth");
765         fractal = BMO_Get_Float(op, "fractal");
766         beauty = BMO_Get_Int(op, "beauty");
767         cornertype = BMO_Get_Int(op, "quadcornertype");
768         singleedge = BMO_Get_Int(op, "singleedge");
769         gridfill = BMO_Get_Int(op, "gridfill");
770         
771         BLI_srandom(seed);
772         
773         patterns[1] = NULL;
774         //straight cut is patterns[1] == NULL
775         switch (cornertype) {
776                 case SUBD_PATH:
777                         patterns[1] = &quad_2edge_path;
778                         break;
779                 case SUBD_INNERVERT:
780                         patterns[1] = &quad_2edge_innervert;
781                         break;
782                 case SUBD_FAN:
783                         patterns[1] = &quad_2edge_fan;
784                         break;
785         }
786         
787         if (singleedge) {
788                 patterns[0] = &quad_1edge;
789                 patterns[2] = &tri_1edge;
790         }
791         else {
792                 patterns[0] = NULL;
793                 patterns[2] = NULL;
794         }
795
796         if (gridfill) {
797                 patterns[3] = &quad_4edge;
798                 patterns[5] = &tri_3edge;
799         }
800         else {
801                 patterns[3] = NULL;
802                 patterns[5] = NULL;
803         }
804         
805         /* add a temporary shapekey layer to store displacements on current geometr */
806         BM_add_data_layer(bmesh, &bmesh->vdata, CD_SHAPEKEY);
807         skey = CustomData_number_of_layers(&bmesh->vdata, CD_SHAPEKEY) - 1;
808         
809         BM_ITER(v, &viter, bmesh, BM_VERTS_OF_MESH, NULL) {
810                 float *co = CustomData_bmesh_get_n(&bmesh->vdata, v->head.data, CD_SHAPEKEY, skey);
811                 copy_v3_v3(co, v->co);
812         }
813
814         /* first go through and tag edge */
815         BMO_Flag_To_Slot(bmesh, op, "edges",
816                          SUBD_SPLIT, BM_EDGE);
817
818         params.numcuts = numcuts;
819         params.op = op;
820         params.smooth = smooth;
821         params.seed = seed;
822         params.fractal = fractal;
823         params.beauty = beauty;
824         params.origkey = skey;
825         params.off[0] = (float)BLI_drand() * 200.0f;
826         params.off[1] = (float)BLI_drand() * 200.0f;
827         params.off[2] = (float)BLI_drand() * 200.0f;
828         
829         BMO_Mapping_To_Flag(bmesh, op, "custompatterns",
830                             FACE_CUSTOMFILL);
831
832         BMO_Mapping_To_Flag(bmesh, op, "edgepercents",
833                             EDGE_PERCENT);
834
835         for (face = BMIter_New(&fiter, bmesh, BM_FACES_OF_MESH, NULL);
836              face; face = BMIter_Step(&fiter)) {
837                 BMEdge *e1 = NULL, *e2 = NULL;
838                 float vec1[3], vec2[3];
839
840                 /* figure out which pattern to us */
841
842                 BLI_array_empty(edges);
843                 BLI_array_empty(verts);
844                 matched = 0;
845
846                 i = 0;
847                 totesel = 0;
848                 for (nl = BMIter_New(&liter, bmesh, BM_LOOPS_OF_FACE, face); nl; nl = BMIter_Step(&liter)) {
849                         BLI_array_growone(edges);
850                         BLI_array_growone(verts);
851                         edges[i] = nl->e;
852                         verts[i] = nl->v;
853
854                         if (BMO_TestFlag(bmesh, edges[i], SUBD_SPLIT)) {
855                                 if (!e1) e1 = edges[i];
856                                 else e2 = edges[i];
857
858                                 totesel++;
859                         }
860
861                         i++;
862                 }
863
864                 /* make sure the two edges have a valid angle to each othe */
865                 if (totesel == 2 && BM_Edge_Share_Vert(e1, e2)) {
866                         float angle;
867
868                         sub_v3_v3v3(vec1, e1->v2->co, e1->v1->co);
869                         sub_v3_v3v3(vec2, e2->v2->co, e2->v1->co);
870                         normalize_v3(vec1);
871                         normalize_v3(vec2);
872
873                         angle = dot_v3v3(vec1, vec2);
874                         angle = fabsf(angle);
875                         if (fabsf(angle - 1.0f) < 0.01f) {
876                                 totesel = 0;
877                         }
878                 }
879
880                 if (BMO_TestFlag(bmesh, face, FACE_CUSTOMFILL)) {
881                         pat = BMO_Get_MapData(bmesh, op,
882                                               "custompatterns", face);
883                         for (i = 0; i < pat->len; i++) {
884                                 matched = 1;
885                                 for (j = 0; j < pat->len; j++) {
886                                         a = (j + i) % pat->len;
887                                         if ((!!BMO_TestFlag(bmesh, edges[a], SUBD_SPLIT)) != (!!pat->seledges[j])) {
888                                                 matched = 0;
889                                                 break;
890                                         }
891                                 }
892                                 if (matched) {
893                                         BLI_array_growone(facedata);
894                                         b = BLI_array_count(facedata) - 1;
895                                         facedata[b].pat = pat;
896                                         facedata[b].start = verts[i];
897                                         facedata[b].face = face;
898                                         facedata[b].totedgesel = totesel;
899                                         BMO_SetFlag(bmesh, face, SUBD_SPLIT);
900                                         break;
901                                 }
902                         }
903
904                         /* obvously don't test for other patterns matchin */
905                         continue;
906                 }
907
908                 for (i = 0; i < PLEN; i++) {
909                         pat = patterns[i];
910                         if (!pat) continue;
911
912                         if (pat->len == face->len) {
913                                 for (a = 0; a < pat->len; a++) {
914                                         matched = 1;
915                                         for (b = 0; b < pat->len; b++) {
916                                                 j = (b + a) % pat->len;
917                                                 if ((!!BMO_TestFlag(bmesh, edges[j], SUBD_SPLIT)) != (!!pat->seledges[b])) {
918                                                         matched = 0;
919                                                         break;
920                                                 }
921                                         }
922                                         if (matched) {
923                                                 break;
924                                         }
925                                 }
926                                 if (matched) {
927                                         BLI_array_growone(facedata);
928                                         j = BLI_array_count(facedata) - 1;
929
930                                         BMO_SetFlag(bmesh, face, SUBD_SPLIT);
931
932                                         facedata[j].pat = pat;
933                                         facedata[j].start = verts[a];
934                                         facedata[j].face = face;
935                                         facedata[j].totedgesel = totesel;
936                                         break;
937                                 }
938                         }
939
940                 }
941                 
942                 if (!matched && totesel) {
943                         BLI_array_growone(facedata);
944                         j = BLI_array_count(facedata) - 1;
945                         
946                         BMO_SetFlag(bmesh, face, SUBD_SPLIT);
947                         facedata[j].totedgesel = totesel;
948                         facedata[j].face = face;
949                 }
950         }
951
952         einput = BMO_GetSlot(op, "edges");
953
954         /* go through and split edge */
955         for (i = 0; i < einput->len; i++) {
956                 edge = ((BMEdge **)einput->data.p)[i];
957                 bm_subdivide_multicut(bmesh, edge, &params, edge->v1, edge->v2);
958         }
959
960         i = 0;
961         for (i = 0; i < BLI_array_count(facedata); i++) {
962                 face = facedata[i].face;
963
964                 /* figure out which pattern to us */
965                 BLI_array_empty(verts);
966
967                 pat = facedata[i].pat;
968
969                 if (!pat && facedata[i].totedgesel == 2) {
970                         int vlen;
971                         
972                         /* ok, no pattern.  we still may be able to do something */
973                         BLI_array_empty(loops);
974                         BLI_array_empty(splits);
975
976                         /* for case of two edges, connecting them shouldn't be too har */
977                         BM_ITER(l, &liter, bmesh, BM_LOOPS_OF_FACE, face) {
978                                 BLI_array_growone(loops);
979                                 loops[BLI_array_count(loops) - 1] = l;
980                         }
981                         
982                         vlen = BLI_array_count(loops);
983
984                         /* find the boundary of one of the split edge */
985                         for (a = 1; a < vlen; a++) {
986                                 if ( !BMO_TestFlag(bmesh, loops[a - 1]->v, ELE_INNER) &&
987                                      BMO_TestFlag(bmesh, loops[a]->v, ELE_INNER))
988                                 {
989                                         break;
990                                 }
991                         }
992                         
993                         if (BMO_TestFlag(bmesh, loops[(a + numcuts + 1) % vlen]->v, ELE_INNER)) {
994                                 b = (a + numcuts + 1) % vlen;
995                         }
996                         else {
997                                 /* find the boundary of the other edge. */
998                                 for (j = 0; j < vlen; j++) {
999                                         b = (j + a + numcuts + 1) % vlen;
1000                                         if ( !BMO_TestFlag(bmesh, loops[b == 0 ? vlen - 1 : b - 1]->v, ELE_INNER) &&
1001                                              BMO_TestFlag(bmesh, loops[b]->v, ELE_INNER))
1002                                         {
1003                                                 break;
1004                                         }
1005                                 }
1006                         }
1007                         
1008                         b += numcuts - 1;
1009
1010                         for (j = 0; j < numcuts; j++) {
1011                                 BLI_array_growone(splits);
1012                                 splits[BLI_array_count(splits) - 1] = loops[a];
1013                                 
1014                                 BLI_array_growone(splits);
1015                                 splits[BLI_array_count(splits) - 1] = loops[b];
1016
1017                                 b = (b - 1) % vlen;
1018                                 a = (a + 1) % vlen;
1019                         }
1020                         
1021                         //BM_LegalSplits(bmesh, face, splits, BLI_array_count(splits)/2);
1022
1023                         for (j = 0; j < BLI_array_count(splits) / 2; j++) {
1024                                 if (splits[j * 2]) {
1025                                         /* BMFace *nf = */ /* UNUSED */
1026                                         BM_Split_Face(bmesh, face, splits[j * 2]->v, splits[j * 2 + 1]->v, &nl, NULL);
1027                                 }
1028                         }
1029
1030                         continue;
1031                 }
1032                 else if (!pat) {
1033                         continue;
1034                 }
1035
1036                 j = a = 0;
1037                 for (nl = BMIter_New(&liter, bmesh, BM_LOOPS_OF_FACE, face);
1038                      nl;
1039                      nl = BMIter_Step(&liter))
1040                 {
1041                         if (nl->v == facedata[i].start) {
1042                                 a = j + 1;
1043                                 break;
1044                         }
1045                         j++;
1046                 }
1047
1048                 for (j = 0; j < face->len; j++) {
1049                         BLI_array_growone(verts);
1050                 }
1051                 
1052                 j = 0;
1053                 for (nl = BMIter_New(&liter, bmesh, BM_LOOPS_OF_FACE, face); nl; nl = BMIter_Step(&liter)) {
1054                         b = (j - a + face->len) % face->len;
1055                         verts[b] = nl->v;
1056                         j += 1;
1057                 }
1058
1059                 BM_CHECK_ELEMENT(bmesh, face);
1060                 pat->connectexec(bmesh, face, verts, &params);
1061         }
1062
1063         /* copy original-geometry displacements to current coordinate */
1064         BM_ITER(v, &viter, bmesh, BM_VERTS_OF_MESH, NULL) {
1065                 float *co = CustomData_bmesh_get_n(&bmesh->vdata, v->head.data, CD_SHAPEKEY, skey);
1066                 copy_v3_v3(v->co, co);
1067         }
1068
1069         BM_free_data_layer_n(bmesh, &bmesh->vdata, CD_SHAPEKEY, skey);
1070         
1071         if (facedata) BLI_array_free(facedata);
1072         if (edges) BLI_array_free(edges);
1073         if (verts) BLI_array_free(verts);
1074         BLI_array_free(splits);
1075         BLI_array_free(loops);
1076
1077         BMO_Flag_To_Slot(bmesh, op, "outinner",
1078                          ELE_INNER, BM_ALL);
1079         BMO_Flag_To_Slot(bmesh, op, "outsplit",
1080                          ELE_SPLIT, BM_ALL);
1081         
1082         BMO_Flag_To_Slot(bmesh, op, "geomout",
1083                          ELE_INNER|ELE_SPLIT|SUBD_SPLIT, BM_ALL);
1084 }
1085
1086 /* editmesh-emulating functio */
1087 void BM_esubdivideflag(Object *UNUSED(obedit), BMesh *bm, int flag, float smooth,
1088                        float fractal, int beauty, int numcuts,
1089                        int seltype, int cornertype, int singleedge,
1090                        int gridfill, int seed)
1091 {
1092         BMOperator op;
1093         
1094         BMO_InitOpf(bm, &op, "esubd edges=%he smooth=%f fractal=%f "
1095                     "beauty=%d numcuts=%d quadcornertype=%d singleedge=%d "
1096                     "gridfill=%d seed=%d",
1097                     flag, smooth, fractal, beauty, numcuts,
1098                     cornertype, singleedge, gridfill, seed);
1099         
1100         BMO_Exec_Op(bm, &op);
1101         
1102         if (seltype == SUBDIV_SELECT_INNER) {
1103                 BMOIter iter;
1104                 BMHeader *ele;
1105                 // int i;
1106                 
1107                 ele = BMO_IterNew(&iter, bm, &op, "outinner", BM_EDGE|BM_VERT);
1108                 for ( ; ele; ele = BMO_IterStep(&iter)) {
1109                         BM_Select(bm, ele, TRUE);
1110                 }
1111         }
1112         else if (seltype == SUBDIV_SELECT_LOOPCUT) {
1113                 BMOIter iter;
1114                 BMHeader *ele;
1115                 // int i;
1116                 
1117                 /* deselect inpu */
1118                 BM_clear_flag_all(bm, BM_SELECT);
1119
1120                 ele = BMO_IterNew(&iter, bm, &op, "outinner", BM_EDGE|BM_VERT);
1121                 for ( ; ele; ele = BMO_IterStep(&iter)) {
1122                         BM_Select(bm, ele, TRUE);
1123
1124                         if (ele->htype == BM_VERT) {
1125                                 BMEdge *e;
1126                                 BMIter eiter;
1127
1128                                 BM_ITER(e, &eiter, bm, BM_EDGES_OF_VERT, ele) {
1129                                         if ( !BM_TestHFlag(e, BM_SELECT) &&
1130                                              BM_TestHFlag(e->v1, BM_SELECT) &&
1131                                              BM_TestHFlag(e->v2, BM_SELECT))
1132                                         {
1133                                                 BM_Select(bm, e, TRUE);
1134                                                 bm->totedgesel += 1;
1135                                         }
1136                                         else if (BM_TestHFlag(e, BM_SELECT) &&
1137                                                  (!BM_TestHFlag(e->v1, BM_SELECT) ||
1138                                                   !BM_TestHFlag(e->v2, BM_SELECT)))
1139                                         {
1140                                                 BM_Select(bm, e, FALSE);
1141                                                 bm->totedgesel -= 1;
1142                                         }
1143                                 }
1144                         }
1145                 }
1146         }
1147
1148         BMO_Finish_Op(bm, &op);
1149 }
1150
1151 void esplit_exec(BMesh *bm, BMOperator *op)
1152 {
1153         BMOIter siter;
1154         BMEdge *e;
1155         subdparams params;
1156         int skey;
1157         
1158         params.numcuts = BMO_GetSlot(op, "numcuts")->data.i;
1159         params.op = op;
1160         
1161         BM_add_data_layer(bm, &bm->vdata, CD_SHAPEKEY);
1162         skey = CustomData_number_of_layers(&bm->vdata, CD_SHAPEKEY) - 1;
1163         
1164         params.origkey = skey;
1165
1166         /* go through and split edge */
1167         BMO_ITER(e, &siter, bm, op, "edges", BM_EDGE) {
1168                 bm_subdivide_multicut(bm, e, &params, e->v1, e->v2);
1169         }
1170
1171         BMO_Flag_To_Slot(bm, op, "outsplit",
1172                          ELE_SPLIT, BM_ALL);
1173
1174         BM_free_data_layer_n(bm, &bm->vdata, CD_SHAPEKEY, skey);
1175 }