Fix #30952: uv unwrapper not working as well as 2.62 on some topologies, let the
[blender.git] / source / blender / editors / uvedit / uvedit_smart_stitch.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  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Antony Riakiotakis.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/uvedit/uvedit_smart_stitch.c
29  *  \ingroup eduv
30  */
31
32
33 #include <stdlib.h>
34 #include <string.h>
35 #include <math.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_object_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_meshdata_types.h"
42 #include "DNA_scene_types.h"
43
44 #include "BLI_ghash.h"
45 #include "BLI_math.h"
46 #include "BLI_math_vector.h"
47 #include "BLI_string.h"
48
49 #include "BKE_context.h"
50 #include "BKE_customdata.h"
51 #include "BKE_depsgraph.h"
52 #include "BKE_mesh.h"
53 #include "BKE_tessmesh.h"
54
55 #include "ED_mesh.h"
56 #include "ED_uvedit.h"
57 #include "ED_screen.h"
58
59 #include "RNA_access.h"
60 #include "RNA_define.h"
61
62 #include "WM_api.h"
63 #include "WM_types.h"
64
65 #include "UI_view2d.h"
66
67 #include "uvedit_intern.h"
68
69 /* ********************** smart stitch operator *********************** */
70
71
72 struct IslandStitchData;
73
74 /* This is a straightforward implementation, count the uv's in the island that will move and take the mean displacement/rotation and apply it to all
75  * elements of the island except from the stitchable */
76 typedef struct IslandStitchData {
77         /* rotation can be used only for edges, for vertices there is no such notion */
78         float rotation;
79         float translation[2];
80         /* Used for rotation, the island will rotate around this point */
81         float medianPoint[2];
82         int numOfElements;
83         int num_rot_elements;
84         /* flag to remember if island has been added for preview */
85         char addedForPreview;
86         /* flag an island to be considered for determining static island */
87         char stitchableCandidate;
88         /* if edge rotation is used, flag so that vertex rotation is not used */
89         char use_edge_rotation;
90 }IslandStitchData;
91
92 /* just for averaging UVs */
93 typedef struct UVVertAverage {
94         float uv[2];
95         unsigned short count;
96 } UVVertAverage;
97
98 typedef struct UvEdge {
99         /* index to uv buffer */
100         unsigned int uv1;
101         unsigned int uv2;
102         /* general use flag (Used to check if edge is boundary here, and propagates to adjacency elements) */
103         char flag;
104         /* element that guarantees element->face has the face on element->tfindex and element->tfindex+1 is the second uv */
105         UvElement *element;
106 }UvEdge;
107
108
109 /* stitch state object */
110 typedef struct StitchState {
111         /* use limit flag */
112         char use_limit;
113         /* limit to operator, same as original operator */
114         float limit_dist;
115         /* snap uv islands together during stitching */
116         char snap_islands;
117         /* stich at midpoints or at islands */
118         char midpoints;
119         /* editmesh, cached for use in modal handler */
120         BMEditMesh *em;
121         /* element map for getting info about uv connectivity */
122         UvElementMap *element_map;
123         /* edge container */
124         UvEdge *uvedges;
125         /* container of first of a group of coincident uvs, these will be operated upon */
126         UvElement **uvs;
127         /* maps uvelements to their first coincident uv */
128         int *map;
129         /* 2D normals per uv to calculate rotation for snapping */
130         float *normals;
131         /* edge storage */
132         UvEdge *edges;
133
134         /* count of separate uvs and edges */
135         int total_boundary_edges;
136         int total_separate_uvs;
137         /* hold selection related information */
138         UvElement **selection_stack;
139         int selection_size;
140         /* island that stays in place */
141         int static_island;
142         /* store number of primitives per face so that we can allocate the active island buffer later */
143         unsigned int *tris_per_island;
144 } StitchState;
145
146 typedef struct PreviewPosition {
147         int data_position;
148         int polycount_position;
149 }PreviewPosition;
150 /*
151  * defines for UvElement flags
152  */
153 #define STITCH_SELECTED 1
154 #define STITCH_STITCHABLE 2
155 #define STITCH_PROCESSED 4
156 #define STITCH_BOUNDARY 8
157 #define STITCH_STITCHABLE_CANDIDATE 16
158
159 #define STITCH_NO_PREVIEW -1
160
161 /* previewer stuff (see uvedit_intern.h for more info) */
162 static StitchPreviewer *_stitch_preview;
163
164 /* constructor */
165 static StitchPreviewer *stitch_preview_init(void)
166 {
167         _stitch_preview = MEM_mallocN(sizeof(StitchPreviewer), "stitch_previewer");
168         _stitch_preview->preview_polys = NULL;
169         _stitch_preview->preview_stitchable = NULL;
170         _stitch_preview->preview_unstitchable = NULL;
171         _stitch_preview->uvs_per_polygon = NULL;
172
173         _stitch_preview->preview_uvs = 0;
174         _stitch_preview->num_polys = 0;
175         _stitch_preview->num_stitchable = 0;
176         _stitch_preview->num_unstitchable = 0;
177
178         _stitch_preview->static_tris = NULL;
179
180         _stitch_preview->num_static_tris = 0;
181
182         return _stitch_preview;
183 }
184
185 /* destructor...yeah this should be C++ :) */
186 static void stitch_preview_delete(void)
187 {
188         if (_stitch_preview) {
189                 if (_stitch_preview->preview_polys) {
190                         MEM_freeN(_stitch_preview->preview_polys);
191                         _stitch_preview->preview_polys = NULL;
192                 }
193                 if (_stitch_preview->uvs_per_polygon) {
194                         MEM_freeN(_stitch_preview->uvs_per_polygon);
195                         _stitch_preview->uvs_per_polygon = NULL;
196                 }
197                 if (_stitch_preview->preview_stitchable) {
198                         MEM_freeN(_stitch_preview->preview_stitchable);
199                         _stitch_preview->preview_stitchable = NULL;
200                 }
201                 if (_stitch_preview->preview_unstitchable) {
202                         MEM_freeN(_stitch_preview->preview_unstitchable);
203                         _stitch_preview->preview_unstitchable = NULL;
204                 }
205                 if (_stitch_preview->static_tris) {
206                         MEM_freeN(_stitch_preview->static_tris);
207                         _stitch_preview->static_tris = NULL;
208                 }
209
210                 MEM_freeN(_stitch_preview);
211                 _stitch_preview = NULL;
212         }
213 }
214
215
216 /* "getter method" */
217 StitchPreviewer *uv_get_stitch_previewer(void)
218 {
219         return _stitch_preview;
220 }
221
222 #define HEADER_LENGTH 256
223
224 /* This function updates the header of the UV editor when the stitch tool updates its settings */
225 static void stitch_update_header(StitchState *stitch_state, bContext *C)
226 {
227         static char str[] = "(S)nap %s, (M)idpoints %s, (L)imit %.2f (Alt Wheel adjust) %s, Switch (I)sland, shift select vertices";
228
229         char msg[HEADER_LENGTH];
230         ScrArea *sa = CTX_wm_area(C);
231
232         if (sa) {
233                 BLI_snprintf(msg, HEADER_LENGTH, str,
234                              stitch_state->snap_islands ? "On" : "Off",
235                              stitch_state->midpoints    ? "On" : "Off",
236                              stitch_state->limit_dist,
237                              stitch_state->use_limit    ? "On" : "Off");
238
239                 ED_area_headerprint(sa, msg);
240         }
241 }
242
243 static int getNumOfIslandUvs(UvElementMap *elementMap, int island)
244 {
245         if (island == elementMap->totalIslands - 1) {
246                 return elementMap->totalUVs - elementMap->islandIndices[island];
247         }
248         else {
249                 return elementMap->islandIndices[island + 1] - elementMap->islandIndices[island];
250         }
251 }
252
253 static void stitch_uv_rotate(float rotation, float medianPoint[2], float uv[2])
254 {
255         float uv_rotation_result[2];
256
257         uv[0] -= medianPoint[0];
258         uv[1] -= medianPoint[1];
259
260         uv_rotation_result[0] = cos(rotation) * uv[0] - sin(rotation) * uv[1];
261         uv_rotation_result[1] = sin(rotation) * uv[0] + cos(rotation) * uv[1];
262
263         uv[0] = uv_rotation_result[0] + medianPoint[0];
264         uv[1] = uv_rotation_result[1] + medianPoint[1];
265 }
266
267 static int stitch_check_uvs_stitchable(UvElement *element, UvElement *element_iter, StitchState *state)
268 {
269         float limit;
270         int do_limit;
271
272         if (element_iter == element) {
273                 return 0;
274         }
275
276         limit = state->limit_dist;
277         do_limit = state->use_limit;
278
279         if (do_limit) {
280                 MLoopUV *luv_orig, *luv_iter;
281                 BMLoop *l_orig, *l_iter;
282
283
284                 l_orig = element->l;
285                 luv_orig = CustomData_bmesh_get(&state->em->bm->ldata, l_orig->head.data, CD_MLOOPUV);
286                 l_iter = element_iter->l;
287                 luv_iter = CustomData_bmesh_get(&state->em->bm->ldata, l_iter->head.data, CD_MLOOPUV);
288
289                 if (fabs(luv_orig->uv[0] - luv_iter->uv[0]) < limit &&
290                     fabs(luv_orig->uv[1] - luv_iter->uv[1]) < limit)
291                 {
292                         return 1;
293                 }
294                 else {
295                         return 0;
296                 }
297         }
298         else {
299                 return 1;
300         }
301 }
302
303
304 static int stitch_check_uvs_state_stitchable(UvElement *element, UvElement *element_iter, StitchState *state)
305 {
306         if ((state->snap_islands && element->island == element_iter->island) ||
307             (!state->midpoints && element->island == element_iter->island))
308         {
309                 return 0;
310         }
311
312         return stitch_check_uvs_stitchable(element, element_iter, state);
313 }
314
315
316 /* calculate snapping for islands */
317 static void stitch_calculate_island_snapping(StitchState *state, PreviewPosition *preview_position, StitchPreviewer *preview, IslandStitchData *island_stitch_data, int final)
318 {
319         int i;
320         UvElement *element;
321
322         for (i = 0; i <  state->element_map->totalIslands; i++) {
323                 if (island_stitch_data[i].addedForPreview) {
324                         int numOfIslandUVs = 0, j;
325
326                         /* check to avoid divide by 0 */
327                         if (island_stitch_data[i].num_rot_elements > 0) {
328                                 island_stitch_data[i].rotation /= island_stitch_data[i].num_rot_elements;
329                                 island_stitch_data[i].medianPoint[0] /= island_stitch_data[i].numOfElements;
330                                 island_stitch_data[i].medianPoint[1] /= island_stitch_data[i].numOfElements;
331                         }
332                         island_stitch_data[i].translation[0] /= island_stitch_data[i].numOfElements;
333                         island_stitch_data[i].translation[1] /= island_stitch_data[i].numOfElements;
334                         numOfIslandUVs = getNumOfIslandUvs(state->element_map, i);
335                         element = &state->element_map->buf[state->element_map->islandIndices[i]];
336                         for (j = 0; j < numOfIslandUVs; j++, element++) {
337                                 /* stitchable uvs have already been processed, don't process */
338                                 if (!(element->flag & STITCH_PROCESSED)) {
339                                         MLoopUV *luv;
340                                         BMLoop *l;
341
342                                         l = element->l;
343                                         luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
344
345                                         if (final) {
346
347                                                 stitch_uv_rotate(island_stitch_data[i].rotation, island_stitch_data[i].medianPoint, luv->uv);
348
349                                                 add_v2_v2(luv->uv, island_stitch_data[i].translation);
350                                         }
351
352                                         else {
353                                                 int face_preview_pos = preview_position[BM_elem_index_get(element->face)].data_position;
354
355                                                 stitch_uv_rotate(island_stitch_data[i].rotation, island_stitch_data[i].medianPoint,
356                                                                  preview->preview_polys + face_preview_pos + 2 * element->tfindex);
357
358                                                 add_v2_v2(preview->preview_polys + face_preview_pos + 2 * element->tfindex,
359                                                           island_stitch_data[i].translation);
360                                         }
361                                 }
362                                 /* cleanup */
363                                 element->flag &= STITCH_SELECTED;
364                         }
365                 }
366         }
367 }
368
369
370
371 static void stitch_island_calculate_edge_rotation(UvEdge *edge, StitchState *state, UVVertAverage *uv_average, unsigned int *uvfinal_map, IslandStitchData *island_stitch_data)
372 {
373         UvElement *element1, *element2;
374         float uv1[2], uv2[2];
375         float edgecos, edgesin;
376         int index1, index2;
377         float rotation;
378         MLoopUV *luv1, *luv2;
379         BMLoop *l1, *l2;
380
381         element1 = state->uvs[edge->uv1];
382         element2 = state->uvs[edge->uv2];
383
384         l1 = element1->l;
385         luv1 = CustomData_bmesh_get(&state->em->bm->ldata, l1->head.data, CD_MLOOPUV);
386         l2 = element2->l;
387         luv2 = CustomData_bmesh_get(&state->em->bm->ldata, l2->head.data, CD_MLOOPUV);
388
389         index1 = uvfinal_map[element1 - state->element_map->buf];
390         index2 = uvfinal_map[element2 - state->element_map->buf];
391
392         /* the idea here is to take the directions of the edges and find the rotation between final and initial
393          * direction. This, using inner and outer vector products, gives the angle. Directions are differences so... */
394         uv1[0] = luv2->uv[0] - luv1->uv[0];
395         uv1[1] = luv2->uv[1] - luv1->uv[1];
396
397         uv2[0] = uv_average[index2].uv[0] - uv_average[index1].uv[0];
398         uv2[1] = uv_average[index2].uv[1] - uv_average[index1].uv[1];
399
400         normalize_v2(uv1);
401         normalize_v2(uv2);
402
403         edgecos = uv1[0] * uv2[0] + uv1[1] * uv2[1];
404         edgesin = uv1[0] * uv2[1] - uv2[0] * uv1[1];
405
406         rotation = (edgesin > 0) ? acos(MAX2(-1.0, MIN2(1.0, edgecos))) : -acos(MAX2(-1.0, MIN2(1.0, edgecos)));
407
408         island_stitch_data[element1->island].num_rot_elements++;
409         island_stitch_data[element1->island].rotation += rotation;
410 }
411
412
413 static void stitch_island_calculate_vert_rotation(UvElement *element, StitchState *state, IslandStitchData *island_stitch_data)
414 {
415         float edgecos = 1, edgesin = 0;
416         int index;
417         UvElement *element_iter;
418         float rotation = 0;
419         BMLoop *l;
420
421         if (element->island == state->static_island && !state->midpoints)
422                 return;
423
424         l = element->l;
425
426         index = BM_elem_index_get(l->v);
427
428         element_iter = state->element_map->vert[index];
429
430         for (; element_iter; element_iter = element_iter->next) {
431                 if (element_iter->separate && stitch_check_uvs_state_stitchable(element, element_iter, state)) {
432                         int index_tmp1, index_tmp2;
433                         float normal[2];
434                         /* easily possible*/
435
436                         index_tmp1 = element_iter - state->element_map->buf;
437                         index_tmp1 = state->map[index_tmp1];
438                         index_tmp2 = element - state->element_map->buf;
439                         index_tmp2 = state->map[index_tmp2];
440
441                         negate_v2_v2(normal, state->normals + index_tmp2 * 2);
442                         edgecos = dot_v2v2(normal, state->normals + index_tmp1 * 2);
443                         edgesin = cross_v2v2(normal, state->normals + index_tmp1 * 2);
444                         rotation += (edgesin > 0) ? acos(edgecos) : -acos(edgecos);
445                 }
446         }
447
448         if (state->midpoints)
449                 rotation /= 2.0;
450         island_stitch_data[element->island].num_rot_elements++;
451         island_stitch_data[element->island].rotation += rotation;
452 }
453
454
455 static void stitch_state_delete(StitchState *stitch_state)
456 {
457         if (stitch_state) {
458                 if (stitch_state->element_map) {
459                         EDBM_uv_element_map_free(stitch_state->element_map);
460                 }
461                 if (stitch_state->uvs) {
462                         MEM_freeN(stitch_state->uvs);
463                 }
464                 if (stitch_state->selection_stack) {
465                         MEM_freeN(stitch_state->selection_stack);
466                 }
467                 if (stitch_state->tris_per_island) {
468                         MEM_freeN(stitch_state->tris_per_island);
469                 }
470                 if (stitch_state->map) {
471                         MEM_freeN(stitch_state->map);
472                 }
473                 if (stitch_state->normals) {
474                         MEM_freeN(stitch_state->normals);
475                 }
476                 if (stitch_state->edges) {
477                         MEM_freeN(stitch_state->edges);
478                 }
479                 MEM_freeN(stitch_state);
480         }
481 }
482
483
484
485 /* checks for remote uvs that may be stitched with a certain uv, flags them if stitchable. */
486 static void determine_uv_stitchability(UvElement *element, StitchState *state, IslandStitchData *island_stitch_data)
487 {
488         int vert_index;
489         UvElement *element_iter;
490         BMLoop *l;
491
492         l = element->l;
493
494         vert_index = BM_elem_index_get(l->v);
495         element_iter = state->element_map->vert[vert_index];
496
497         for (; element_iter; element_iter = element_iter->next) {
498                 if (element_iter->separate) {
499                         if (element_iter == element) {
500                                 continue;
501                         }
502                         if (stitch_check_uvs_stitchable(element, element_iter, state)) {
503                                 island_stitch_data[element_iter->island].stitchableCandidate = 1;
504                                 island_stitch_data[element->island].stitchableCandidate = 1;
505                                 element->flag |= STITCH_STITCHABLE_CANDIDATE;
506                         }
507                 }
508         }
509 }
510
511
512 /* set preview buffer position of UV face in editface->tmp.l */
513 static void stitch_set_face_preview_buffer_position(BMFace *efa, StitchPreviewer *preview, PreviewPosition *preview_position)
514 {
515         int index = BM_elem_index_get(efa);
516
517         if (preview_position[index].data_position == STITCH_NO_PREVIEW) {
518                 preview_position[index].data_position = preview->preview_uvs * 2;
519                 preview_position[index].polycount_position = preview->num_polys++;
520                 preview->preview_uvs += efa->len;
521         }
522 }
523
524
525 /* setup face preview for all coincident uvs and their faces */
526 static void stitch_setup_face_preview_for_uv_group(UvElement *element, StitchState *state, IslandStitchData *island_stitch_data,
527                                                    PreviewPosition *preview_position) {
528         StitchPreviewer *preview = uv_get_stitch_previewer();
529
530         /* static island does not change so returning immediately */
531         if (state->snap_islands && !state->midpoints && state->static_island == element->island)
532                 return;
533
534         if (state->snap_islands) {
535                 island_stitch_data[element->island].addedForPreview = 1;
536         }
537
538         do {
539                 stitch_set_face_preview_buffer_position(element->face, preview, preview_position);
540                 element = element->next;
541         } while (element && !element->separate);
542 }
543
544
545 /* checks if uvs are indeed stitchable and registers so that they can be shown in preview */
546 static void stitch_validate_stichability(UvElement *element, StitchState *state, IslandStitchData *island_stitch_data,
547                                          PreviewPosition *preview_position) {
548         UvElement *element_iter;
549         StitchPreviewer *preview;
550         int vert_index;
551         BMLoop *l;
552
553         l = element->l;
554
555         vert_index = BM_elem_index_get(l->v);
556
557         preview = uv_get_stitch_previewer();
558         element_iter = state->element_map->vert[vert_index];
559
560         for (; element_iter; element_iter = element_iter->next) {
561                 if (element_iter->separate) {
562                         if (element_iter == element)
563                                 continue;
564                         if (stitch_check_uvs_state_stitchable(element, element_iter, state)) {
565                                 if ((element_iter->island == state->static_island) || (element->island == state->static_island)) {
566                                         element->flag |= STITCH_STITCHABLE;
567                                         preview->num_stitchable++;
568                                         stitch_setup_face_preview_for_uv_group(element, state, island_stitch_data, preview_position);
569                                         return;
570                                 }
571                         }
572                 }
573         }
574
575         /* this can happen if the uvs to be stitched are not on a stitchable island */
576         if (!(element->flag & STITCH_STITCHABLE)) {
577                 preview->num_unstitchable++;
578         }
579 }
580
581 /* main processing function. It calculates preview and final positions. */
582 static int stitch_process_data(StitchState *state, Scene *scene, int final)
583 {
584         int i;
585         StitchPreviewer *preview;
586         IslandStitchData *island_stitch_data = NULL;
587         int previous_island = state->static_island;
588         BMFace *efa;
589         BMIter iter;
590         UVVertAverage *final_position;
591         char stitch_midpoints = state->midpoints;
592         /* used to map uv indices to uvaverage indices for selection */
593         unsigned int *uvfinal_map;
594         /* per face preview position in preview buffer */
595         PreviewPosition *preview_position;
596
597         /* cleanup previous preview */
598         stitch_preview_delete();
599         preview = stitch_preview_init();
600         if (preview == NULL)
601                 return 0;
602
603         preview_position = MEM_mallocN(state->em->bm->totface * sizeof(*preview_position), "stitch_face_preview_position");
604         /* each face holds its position in the preview buffer in tmp. -1 is uninitialized */
605         for (i = 0; i < state->em->bm->totface; i++) {
606                 preview_position[i].data_position = STITCH_NO_PREVIEW;
607         }
608
609         island_stitch_data = MEM_callocN(sizeof(*island_stitch_data) * state->element_map->totalIslands, "stitch_island_data");
610         if (!island_stitch_data) {
611                 return 0;
612         }
613
614         /* store indices to editVerts and Faces. May be unneeded but ensuring anyway */
615         BM_mesh_elem_index_ensure(state->em->bm, BM_VERT | BM_FACE);
616
617         /*****************************************
618          *  First determine stitchability of uvs *
619          *****************************************/
620
621         for (i = 0; i < state->selection_size; i++) {
622                 UvElement *element = state->selection_stack[i];
623                 determine_uv_stitchability(element, state, island_stitch_data);
624         }
625
626         /* set static island to one that is added for preview */
627         state->static_island %= state->element_map->totalIslands;
628         while (!(island_stitch_data[state->static_island].stitchableCandidate)) {
629                 state->static_island++;
630                 state->static_island %= state->element_map->totalIslands;
631                 /* this is entirely possible if for example limit stitching with no stitchable verts or no selection */
632                 if (state->static_island == previous_island)
633                         break;
634         }
635
636         for (i = 0; i < state->selection_size; i++) {
637                 UvElement *element = state->selection_stack[i];
638                 if (element->flag & STITCH_STITCHABLE_CANDIDATE) {
639                         element->flag &= ~STITCH_STITCHABLE_CANDIDATE;
640                         stitch_validate_stichability(element, state, island_stitch_data, preview_position);
641                 }
642                 else {
643                         /* add to preview for unstitchable */
644                         preview->num_unstitchable++;
645                 }
646         }
647
648         /*****************************************
649          *  Setup preview for stitchable islands *
650          *****************************************/
651         if (state->snap_islands) {
652                 for (i = 0; i <  state->element_map->totalIslands; i++) {
653                         if (island_stitch_data[i].addedForPreview) {
654                                 int numOfIslandUVs = 0, j;
655                                 UvElement *element;
656                                 numOfIslandUVs = getNumOfIslandUvs(state->element_map, i);
657                                 element = &state->element_map->buf[state->element_map->islandIndices[i]];
658                                 for (j = 0; j < numOfIslandUVs; j++, element++) {
659                                         stitch_set_face_preview_buffer_position(element->face, preview, preview_position);
660                                 }
661                         }
662                 }
663         }
664
665         /*********************************************************************
666          * Setup the preview buffers and fill them with the appropriate data *
667          *********************************************************************/
668         if (!final) {
669                 BMIter liter;
670                 BMLoop *l;
671                 MLoopUV *luv;
672                 unsigned int buffer_index = 0;
673                 int stitchBufferIndex = 0, unstitchBufferIndex = 0;
674                 /* initialize the preview buffers */
675                 preview->preview_polys = (float *)MEM_mallocN(preview->preview_uvs * sizeof(float) * 2, "tri_uv_stitch_prev");
676                 preview->uvs_per_polygon = MEM_mallocN(preview->num_polys * sizeof(*preview->uvs_per_polygon), "tri_uv_stitch_prev");
677                 preview->preview_stitchable = (float *)MEM_mallocN(preview->num_stitchable * sizeof(float) * 2, "stitch_preview_stichable_data");
678                 preview->preview_unstitchable = (float *)MEM_mallocN(preview->num_unstitchable * sizeof(float) * 2, "stitch_preview_unstichable_data");
679
680                 preview->static_tris = (float *)MEM_mallocN(state->tris_per_island[state->static_island] * sizeof(float) * 6, "static_island_preview_tris");
681
682                 preview->num_static_tris = state->tris_per_island[state->static_island];
683                 /* will cause cancel and freeing of all data structures so OK */
684                 if (!preview->preview_polys || !preview->preview_stitchable || !preview->preview_unstitchable) {
685                         return 0;
686                 }
687
688                 /* copy data from MTFaces to the preview display buffers */
689                 BM_ITER(efa, &iter, state->em->bm, BM_FACES_OF_MESH, NULL) {
690                         /* just to test if face was added for processing. uvs of inselected vertices will return NULL */
691                         UvElement *element = ED_uv_element_get(state->element_map, efa, BM_FACE_FIRST_LOOP(efa));
692
693                         if (element) {
694                                 int numoftris = efa->len - 2;
695                                 int index = BM_elem_index_get(efa);
696                                 int face_preview_pos = preview_position[index].data_position;
697                                 if (face_preview_pos != STITCH_NO_PREVIEW) {
698                                         preview->uvs_per_polygon[preview_position[index].polycount_position] = efa->len;
699                                         BM_ITER_INDEX(l, &liter, state->em->bm, BM_LOOPS_OF_FACE, efa, i) {
700                                                 luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
701                                                 copy_v2_v2(preview->preview_polys + face_preview_pos + i * 2, luv->uv);
702                                         }
703                                 }
704
705                                 if (element->island == state->static_island) {
706                                         BMLoop *fl = BM_FACE_FIRST_LOOP(efa);
707                                         MLoopUV *fuv = CustomData_bmesh_get(&state->em->bm->ldata, fl->head.data, CD_MLOOPUV);
708
709                                         BM_ITER_INDEX(l, &liter, state->em->bm, BM_LOOPS_OF_FACE, efa, i) {
710                                                 if (i < numoftris) {
711                                                         /* using next since the first uv is already accounted for */
712                                                         BMLoop *lnext = l->next;
713                                                         MLoopUV *luvnext = CustomData_bmesh_get(&state->em->bm->ldata, lnext->next->head.data, CD_MLOOPUV);
714                                                         luv = CustomData_bmesh_get(&state->em->bm->ldata, lnext->head.data, CD_MLOOPUV);
715
716                                                         memcpy(preview->static_tris + buffer_index, fuv->uv, 2 * sizeof(float));
717                                                         memcpy(preview->static_tris + buffer_index + 2, luv->uv, 2 * sizeof(float));
718                                                         memcpy(preview->static_tris + buffer_index + 4, luvnext->uv, 2 * sizeof(float));
719                                                         buffer_index += 6;
720                                                 }
721                                                 else {
722                                                         break;
723                                                 }
724                                         }
725                                 }
726                         }
727                 }
728
729                 /* fill the appropriate preview buffers */
730                 for (i = 0; i < state->total_separate_uvs; i++) {
731                         UvElement *element = (UvElement *)state->uvs[i];
732                         if (element->flag & STITCH_STITCHABLE) {
733                                 l = element->l;
734                                 luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
735
736                                 copy_v2_v2(&preview->preview_stitchable[stitchBufferIndex * 2], luv->uv);
737
738                                 stitchBufferIndex++;
739                         }
740                         else if (element->flag & STITCH_SELECTED) {
741                                 l = element->l;
742                                 luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
743
744                                 copy_v2_v2(&preview->preview_unstitchable[unstitchBufferIndex * 2], luv->uv);
745                                 unstitchBufferIndex++;
746                         }
747                 }
748         }
749
750         /******************************************************
751          * Here we calculate the final coordinates of the uvs *
752          ******************************************************/
753
754         final_position = MEM_callocN(state->selection_size * sizeof(*final_position), "stitch_uv_average");
755         uvfinal_map = MEM_mallocN(state->element_map->totalUVs * sizeof(*uvfinal_map), "stitch_uv_final_map");
756
757         /* first pass, calculate final position for stitchable uvs of the static island */
758         for (i = 0; i < state->selection_size; i++) {
759                 UvElement *element = state->selection_stack[i];
760                 if (element->flag & STITCH_STITCHABLE) {
761                         BMLoop *l;
762                         MLoopUV *luv;
763                         UvElement *element_iter;
764
765                         l = element->l;
766                         luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
767
768
769                         uvfinal_map[element - state->element_map->buf] = i;
770
771                         copy_v2_v2(final_position[i].uv, luv->uv);
772                         final_position[i].count = 1;
773
774                         if (state->snap_islands && element->island == state->static_island && !stitch_midpoints)
775                                 continue;
776
777                         element_iter = state->element_map->vert[BM_elem_index_get(l->v)];
778
779                         for ( ; element_iter; element_iter = element_iter->next) {
780                                 if (element_iter->separate) {
781                                         if (stitch_check_uvs_state_stitchable(element, element_iter, state)) {
782                                                 l = element_iter->l;
783                                                 luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
784                                                 if (stitch_midpoints) {
785                                                         add_v2_v2(final_position[i].uv, luv->uv);
786                                                         final_position[i].count++;
787                                                 }
788                                                 else if (element_iter->island == state->static_island) {
789                                                         /* if multiple uvs on the static island exist,
790                                                          * last checked remains. to disambiguate we need to limit or use
791                                                          * edge stitch */
792                                                         copy_v2_v2(final_position[i].uv, luv->uv);
793                                                 }
794                                         }
795                                 }
796                         }
797                 }
798                 if (stitch_midpoints) {
799                         final_position[i].uv[0] /= final_position[i].count;
800                         final_position[i].uv[1] /= final_position[i].count;
801                 }
802         }
803
804         /* second pass, calculate island rotation and translation before modifying any uvs */
805         if (state->snap_islands) {
806                 for (i = 0; i < state->selection_size; i++) {
807                         UvElement *element = state->selection_stack[i];
808                         if (element->flag & STITCH_STITCHABLE) {
809                                 BMLoop *l;
810                                 MLoopUV *luv;
811
812                                 l = element->l;
813                                 luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
814
815                                 /* accumulate each islands' translation from stitchable elements. it is important to do here
816                                  * because in final pass MTFaces get modified and result is zero. */
817                                 island_stitch_data[element->island].translation[0] += final_position[i].uv[0] - luv->uv[0];
818                                 island_stitch_data[element->island].translation[1] += final_position[i].uv[1] - luv->uv[1];
819                                 island_stitch_data[element->island].medianPoint[0] += luv->uv[0];
820                                 island_stitch_data[element->island].medianPoint[1] += luv->uv[1];
821                                 island_stitch_data[element->island].numOfElements++;
822                         }
823                 }
824
825                 /* only calculate rotation when an edge has been fully selected */
826                 for (i = 0; i < state->total_boundary_edges; i++) {
827                         UvEdge *edge = state->edges + i;
828                         if ((state->uvs[edge->uv1]->flag & STITCH_STITCHABLE) && (state->uvs[edge->uv2]->flag & STITCH_STITCHABLE)) {
829                                 stitch_island_calculate_edge_rotation(edge, state, final_position, uvfinal_map, island_stitch_data);
830                                 island_stitch_data[state->uvs[edge->uv1]->island].use_edge_rotation = 1;
831                         }
832                 }
833
834                 for (i = 0; i < state->selection_size; i++) {
835                         UvElement *element = state->selection_stack[i];
836                         if (!island_stitch_data[element->island].use_edge_rotation) {
837                                 if (element->flag & STITCH_STITCHABLE) {
838                                         stitch_island_calculate_vert_rotation(element, state, island_stitch_data);
839                                 }
840                         }
841                 }
842
843         }
844
845         /* third pass, propagate changes to coincident uvs */
846         for (i = 0; i < state->selection_size; i++) {
847                 UvElement *element = state->selection_stack[i];
848                 if (element->flag & STITCH_STITCHABLE) {
849                         UvElement *element_iter = element;
850                         /* propagate to coincident uvs */
851                         do {
852                                 BMLoop *l;
853                                 MLoopUV *luv;
854
855                                 l = element_iter->l;
856                                 luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
857
858                                 element_iter->flag |= STITCH_PROCESSED;
859                                 /* either flush to preview or to the MTFace, if final */
860                                 if (final) {
861                                         copy_v2_v2(luv->uv, final_position[i].uv);
862
863                                         uvedit_uv_select(state->em, scene, l);
864                                 }
865                                 else {
866                                         int face_preview_pos = preview_position[BM_elem_index_get(element_iter->face)].data_position;
867                                         if (face_preview_pos != STITCH_NO_PREVIEW) {
868                                                 copy_v2_v2(preview->preview_polys + face_preview_pos + 2 * element_iter->tfindex,
869                                                            final_position[i].uv);
870                                         }
871                                 }
872
873                                 /* end of calculations, keep only the selection flag */
874                                 if ( (!state->snap_islands) || ((!stitch_midpoints) && (element_iter->island == state->static_island))) {
875                                         element_iter->flag &= STITCH_SELECTED;
876                                 }
877
878                                 element_iter = element_iter->next;
879                         } while (element_iter && !element_iter->separate);
880                 }
881         }
882
883         /* final pass, calculate Island translation/rotation if needed */
884         if (state->snap_islands) {
885                 stitch_calculate_island_snapping(state, preview_position, preview, island_stitch_data, final);
886         }
887
888         MEM_freeN(final_position);
889         MEM_freeN(uvfinal_map);
890         MEM_freeN(island_stitch_data);
891         MEM_freeN(preview_position);
892
893         return 1;
894 }
895
896 /* Stitch hash initialization functions */
897 static unsigned int uv_edge_hash(const void *key)
898 {
899         UvEdge *edge = (UvEdge *)key;
900         return
901             BLI_ghashutil_inthash(SET_INT_IN_POINTER(edge->uv2)) +
902             BLI_ghashutil_inthash(SET_INT_IN_POINTER(edge->uv1));
903 }
904
905 static int uv_edge_compare(const void *a, const void *b)
906 {
907         UvEdge *edge1 = (UvEdge *)a;
908         UvEdge *edge2 = (UvEdge *)b;
909
910         if ((edge1->uv1 == edge2->uv1) && (edge1->uv2 == edge2->uv2)) {
911                 return 0;
912         }
913         return 1;
914 }
915
916
917 /* Select all common uvs */
918 static void stitch_select_uv(UvElement *element, StitchState *state, int always_select)
919 {
920         BMLoop *l;
921         UvElement *element_iter;
922         UvElement **selection_stack = state->selection_stack;
923
924         l = element->l;
925
926         element_iter = state->element_map->vert[BM_elem_index_get(l->v)];
927         /* first deselect all common uvs */
928         for (; element_iter; element_iter = element_iter->next) {
929                 if (element_iter->separate) {
930                         /* only separators go to selection */
931                         if (element_iter->flag & STITCH_SELECTED) {
932                                 int i;
933                                 if (always_select)
934                                         continue;
935
936                                 element_iter->flag &= ~STITCH_SELECTED;
937                                 for (i = 0; i < state->selection_size; i++) {
938                                         if (selection_stack[i] == element_iter) {
939                                                 (state->selection_size)--;
940                                                 selection_stack[i] = selection_stack[state->selection_size];
941                                                 break;
942                                         }
943                                 }
944                         }
945                         else {
946                                 element_iter->flag |= STITCH_SELECTED;
947                                 selection_stack[state->selection_size++] = element_iter;
948                         }
949                 }
950         }
951 }
952
953 static void stitch_calculate_edge_normal(BMEditMesh *em, UvEdge *edge, float *normal)
954 {
955         BMLoop *l1 = edge->element->l;
956         BMLoop *l2 = l1->next;
957         MLoopUV *luv1, *luv2;
958         float tangent[2];
959
960         luv1 = CustomData_bmesh_get(&em->bm->ldata, l1->head.data, CD_MLOOPUV);
961         luv2 = CustomData_bmesh_get(&em->bm->ldata, l2->head.data, CD_MLOOPUV);
962
963         sub_v2_v2v2(tangent, luv2->uv,  luv1->uv);
964
965         normal[0] = tangent[1];
966         normal[1] = -tangent[0];
967
968         normalize_v2(normal);
969 }
970
971 static int stitch_init(bContext *C, wmOperator *op)
972 {
973         /* for fast edge lookup... */
974         GHash *edgeHash;
975         /* ...and actual edge storage */
976         UvEdge *edges;
977         int total_edges;
978         /* maps uvelements to their first coincident uv */
979         int *map;
980         int counter = 0, i;
981         BMFace *efa;
982         BMLoop *l;
983         BMIter iter, liter;
984         BMEditMesh *em;
985         GHashIterator *ghi;
986         UvEdge *all_edges;
987         StitchState *state = MEM_mallocN(sizeof(StitchState), "stitch state");
988         Scene *scene = CTX_data_scene(C);
989         ToolSettings *ts = scene->toolsettings;
990
991         Object *obedit = CTX_data_edit_object(C);
992
993         op->customdata = state;
994
995         if (!state)
996                 return 0;
997
998         /* initialize state */
999         state->use_limit = RNA_boolean_get(op->ptr, "use_limit");
1000         state->limit_dist = RNA_float_get(op->ptr, "limit");
1001         state->em = em = BMEdit_FromObject(obedit);
1002         state->snap_islands = RNA_boolean_get(op->ptr, "snap_islands");
1003         state->static_island = RNA_int_get(op->ptr, "static_island");
1004         state->midpoints = RNA_boolean_get(op->ptr, "midpoint_snap");
1005         /* in uv synch selection, all uv's are visible */
1006         if (ts->uv_flag & UV_SYNC_SELECTION) {
1007                 state->element_map = EDBM_uv_element_map_create(state->em, 0, 1);
1008         }
1009         else {
1010                 state->element_map = EDBM_uv_element_map_create(state->em, 1, 1);
1011         }
1012         if (!state->element_map) {
1013                 stitch_state_delete(state);
1014                 return 0;
1015         }
1016
1017         /* Entirely possible if redoing last operator that static island is bigger than total number of islands.
1018          * This ensures we get no hang in the island checking code in stitch_process_data. */
1019         state->static_island %= state->element_map->totalIslands;
1020
1021         /* Count 'unique' uvs */
1022         for (i = 0; i < state->element_map->totalUVs; i++) {
1023                 if (state->element_map->buf[i].separate) {
1024                         counter++;
1025                 }
1026         }
1027
1028         /* Allocate the unique uv buffers */
1029         state->uvs = MEM_mallocN(sizeof(*state->uvs) * counter, "uv_stitch_unique_uvs");
1030         /* internal uvs need no normals but it is hard and slow to keep a map of
1031          * normals only for boundary uvs, so allocating for all uvs */
1032         state->normals = MEM_callocN(sizeof(*state->normals) * counter * 2, "uv_stitch_normals");
1033         state->total_separate_uvs = counter;
1034         /* we can at most have totalUVs edges or uvs selected. Actually they are less, considering we store only
1035          * unique uvs for processing but I am accounting for all bizarre cases, especially for edges, this way */
1036         state->selection_stack = MEM_mallocN(sizeof(*state->selection_stack) * counter, "uv_stitch_selection_stack");
1037         state->map = map = MEM_mallocN(sizeof(*map) * state->element_map->totalUVs, "uv_stitch_unique_map");
1038         /* Allocate the edge stack */
1039         edgeHash = BLI_ghash_new(uv_edge_hash, uv_edge_compare, "stitch_edge_hash");
1040         all_edges = MEM_mallocN(sizeof(*all_edges) * state->element_map->totalUVs, "stitch_all_edges");
1041
1042         if (!state->selection_stack || !state->uvs || !map || !edgeHash || !all_edges) {
1043                 stitch_state_delete(state);
1044                 return 0;
1045         }
1046
1047         /* So that we can use this as index for the UvElements */
1048         counter = -1;
1049         /* initialize the unique UVs and map */
1050         for (i = 0; i < em->bm->totvert; i++) {
1051                 UvElement *element = state->element_map->vert[i];
1052                 for (; element; element = element->next) {
1053                         if (element->separate) {
1054                                 counter++;
1055                                 state->uvs[counter] = element;
1056                         }
1057                         /* pointer arithmetic to the rescue, as always :)*/
1058                         map[element - state->element_map->buf] = counter;
1059                 }
1060         }
1061
1062         counter = 0;
1063         /* Now, on to generate our uv connectivity data */
1064         BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1065                 if (!(ts->uv_flag & UV_SYNC_SELECTION) && ((BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) || !BM_elem_flag_test(efa, BM_ELEM_SELECT)))
1066                         continue;
1067
1068                 BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
1069                         UvElement *element = ED_uv_element_get(state->element_map, efa, l);
1070                         int offset1, itmp1 = element - state->element_map->buf;
1071                         int offset2, itmp2 = ED_uv_element_get(state->element_map, efa, l->next) - state->element_map->buf;
1072
1073                         offset1 = map[itmp1];
1074                         offset2 = map[itmp2];
1075
1076                         all_edges[counter].flag = 0;
1077                         all_edges[counter].element = element;
1078                         /* using an order policy, sort uvs according to address space. This avoids
1079                          * Having two different UvEdges with the same uvs on different positions  */
1080                         if (offset1 < offset2) {
1081                                 all_edges[counter].uv1 = offset1;
1082                                 all_edges[counter].uv2 = offset2;
1083                         }
1084                         else {
1085                                 all_edges[counter].uv1 = offset2;
1086                                 all_edges[counter].uv2 = offset1;
1087                         }
1088
1089                         if (BLI_ghash_haskey(edgeHash, &all_edges[counter])) {
1090                                 char *flag = BLI_ghash_lookup(edgeHash, &all_edges[counter]);
1091                                 *flag = 0;
1092                         }
1093                         else {
1094                                 BLI_ghash_insert(edgeHash, &all_edges[counter], &(all_edges[counter].flag));
1095                                 all_edges[counter].flag = STITCH_BOUNDARY;
1096                         }
1097                         counter++;
1098                 }
1099         }
1100
1101
1102         ghi = BLI_ghashIterator_new(edgeHash);
1103         total_edges = 0;
1104         /* fill the edges with data */
1105         for (; !BLI_ghashIterator_isDone(ghi); BLI_ghashIterator_step(ghi)) {
1106                 UvEdge *edge = ((UvEdge *)BLI_ghashIterator_getKey(ghi));
1107                 if (edge->flag & STITCH_BOUNDARY) {
1108                         total_edges++;
1109                 }
1110         }
1111         state->edges = edges = MEM_mallocN(sizeof(*edges) * total_edges, "stitch_edges");
1112         if (!ghi || !edges) {
1113                 MEM_freeN(all_edges);
1114                 stitch_state_delete(state);
1115                 return 0;
1116         }
1117
1118         state->total_boundary_edges = total_edges;
1119
1120         /* fill the edges with data */
1121         for (i = 0, BLI_ghashIterator_init(ghi, edgeHash); !BLI_ghashIterator_isDone(ghi); BLI_ghashIterator_step(ghi)) {
1122                 UvEdge *edge = ((UvEdge *)BLI_ghashIterator_getKey(ghi));
1123                 if (edge->flag & STITCH_BOUNDARY) {
1124                         edges[i++] = *((UvEdge *)BLI_ghashIterator_getKey(ghi));
1125                 }
1126         }
1127
1128         /* cleanup temporary stuff */
1129         BLI_ghashIterator_free(ghi);
1130         MEM_freeN(all_edges);
1131
1132         /* refill hash with new pointers to cleanup duplicates */
1133         BLI_ghash_free(edgeHash, NULL, NULL);
1134
1135         /***** calculate 2D normals for boundary uvs *****/
1136
1137         /* we use boundary edges to calculate 2D normals.
1138          * to disambiguate the direction of the normal, we also need
1139          * a point "inside" the island, that can be provided by
1140          * the opposite uv for a quad, or the next uv for a triangle. */
1141
1142         for (i = 0; i < total_edges; i++) {
1143                 float normal[2];
1144                 stitch_calculate_edge_normal(em, edges + i, normal);
1145
1146                 add_v2_v2(state->normals + edges[i].uv1 * 2, normal);
1147                 add_v2_v2(state->normals + edges[i].uv2 * 2, normal);
1148
1149                 normalize_v2(state->normals + edges[i].uv1 * 2);
1150                 normalize_v2(state->normals + edges[i].uv2 * 2);
1151         }
1152
1153
1154         /***** fill selection stack *******/
1155
1156         state->selection_size = 0;
1157
1158         /* Load old selection if redoing operator with different settings */
1159         if (RNA_struct_property_is_set(op->ptr, "selection")) {
1160                 int faceIndex, elementIndex;
1161                 UvElement *element;
1162
1163                 EDBM_index_arrays_init(em, 0, 0, 1);
1164
1165                 RNA_BEGIN(op->ptr, itemptr, "selection") {
1166                         faceIndex = RNA_int_get(&itemptr, "face_index");
1167                         elementIndex = RNA_int_get(&itemptr, "element_index");
1168                         efa = EDBM_face_at_index(em, faceIndex);
1169                         element = ED_uv_element_get(state->element_map, efa, BM_iter_at_index(NULL, BM_LOOPS_OF_FACE, efa, elementIndex));
1170                         stitch_select_uv(element, state, 1);
1171                 }
1172                 RNA_END;
1173
1174                 EDBM_index_arrays_free(em);
1175                 /* Clear the selection */
1176                 RNA_collection_clear(op->ptr, "selection");
1177
1178         }
1179         else {
1180                 BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1181                         i = 0;
1182                         BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
1183                                 if (uvedit_uv_selected(em, scene, l)) {
1184                                         UvElement *element = ED_uv_element_get(state->element_map, efa, l);
1185                                         stitch_select_uv(element, state, 1);
1186                                 }
1187                                 i++;
1188                         }
1189                 }
1190         }
1191
1192         /***** initialize static island preview data *****/
1193
1194         state->tris_per_island = MEM_mallocN(sizeof(*state->tris_per_island) * state->element_map->totalIslands,
1195                                              "stitch island tris");
1196         for (i = 0; i < state->element_map->totalIslands; i++) {
1197                 state->tris_per_island[i] = 0;
1198         }
1199
1200         BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1201                 UvElement *element = ED_uv_element_get(state->element_map, efa, BM_FACE_FIRST_LOOP(efa));
1202
1203                 if (element) {
1204                         state->tris_per_island[element->island] += (efa->len > 2) ? efa->len - 2 : 0;
1205                 }
1206         }
1207
1208         if (!stitch_process_data(state, scene, 0)) {
1209                 stitch_state_delete(state);
1210                 return 0;
1211         }
1212
1213         stitch_update_header(state, C);
1214         return 1;
1215 }
1216
1217 static int stitch_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1218 {
1219         Object *obedit = CTX_data_edit_object(C);
1220         if (!stitch_init(C, op))
1221                 return OPERATOR_CANCELLED;
1222
1223         WM_event_add_modal_handler(C, op);
1224         WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
1225         return OPERATOR_RUNNING_MODAL;
1226 }
1227
1228 static void stitch_exit(bContext *C, wmOperator *op, int finished)
1229 {
1230         StitchState *stitch_state;
1231         Scene *scene;
1232         SpaceImage *sima;
1233         ScrArea *sa = CTX_wm_area(C);
1234         Object *obedit;
1235
1236         scene = CTX_data_scene(C);
1237         obedit = CTX_data_edit_object(C);
1238         sima = CTX_wm_space_image(C);
1239
1240         stitch_state = (StitchState *)op->customdata;
1241
1242         if (finished) {
1243                 int i;
1244
1245                 RNA_float_set(op->ptr, "limit", stitch_state->limit_dist);
1246                 RNA_boolean_set(op->ptr, "use_limit", stitch_state->use_limit);
1247                 RNA_boolean_set(op->ptr, "snap_islands", stitch_state->snap_islands);
1248                 RNA_int_set(op->ptr, "static_island", stitch_state->static_island);
1249                 RNA_boolean_set(op->ptr, "midpoint_snap", stitch_state->midpoints);
1250
1251                 /* Store selection for re-execution of stitch */
1252                 for (i = 0; i < stitch_state->selection_size; i++) {
1253                         PointerRNA itemptr;
1254                         UvElement *element = stitch_state->selection_stack[i];
1255
1256                         RNA_collection_add(op->ptr, "selection", &itemptr);
1257
1258                         RNA_int_set(&itemptr, "face_index", BM_elem_index_get(element->face));
1259
1260                         RNA_int_set(&itemptr, "element_index", element->tfindex);
1261                 }
1262
1263
1264                 uvedit_live_unwrap_update(sima, scene, obedit);
1265         }
1266
1267         if (sa)
1268                 ED_area_headerprint(sa, NULL);
1269
1270         DAG_id_tag_update(obedit->data, 0);
1271         WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
1272
1273         stitch_state_delete(stitch_state);
1274         op->customdata = NULL;
1275
1276         stitch_preview_delete();
1277 }
1278
1279
1280 static int stitch_cancel(bContext *C, wmOperator *op)
1281 {
1282         stitch_exit(C, op, 0);
1283         return OPERATOR_CANCELLED;
1284 }
1285
1286
1287 static int stitch_exec(bContext *C, wmOperator *op)
1288 {
1289         Scene *scene = CTX_data_scene(C);
1290
1291         if (!stitch_init(C, op))
1292                 return OPERATOR_CANCELLED;
1293         if (stitch_process_data((StitchState *)op->customdata, scene, 1)) {
1294                 stitch_exit(C, op, 1);
1295                 return OPERATOR_FINISHED;
1296         }
1297         else {
1298                 return stitch_cancel(C, op);
1299         }
1300 }
1301
1302 static void stitch_select(bContext *C, Scene *scene, wmEvent *event, StitchState *stitch_state)
1303 {
1304         /* add uv under mouse to processed uv's */
1305         float co[2];
1306         NearestHit hit;
1307         ARegion *ar = CTX_wm_region(C);
1308         Image *ima = CTX_data_edit_image(C);
1309
1310         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &co[0], &co[1]);
1311         uv_find_nearest_vert(scene, ima, stitch_state->em, co, NULL, &hit);
1312
1313         if (hit.efa) {
1314                 /* Add vertex to selection, deselect all common uv's of vert other
1315                  * than selected and update the preview. This behavior was decided so that
1316                  * you can do stuff like deselect the opposite stitchable vertex and the initial still gets deselected */
1317
1318                 /* This works due to setting of tmp in find nearest uv vert */
1319                 UvElement *element = ED_uv_element_get(stitch_state->element_map, hit.efa, hit.l);
1320                 stitch_select_uv(element, stitch_state, 0);
1321
1322         }
1323 }
1324
1325 static int stitch_modal(bContext *C, wmOperator *op, wmEvent *event)
1326 {
1327         StitchState *stitch_state;
1328         Scene *scene = CTX_data_scene(C);
1329
1330         stitch_state = (StitchState *)op->customdata;
1331
1332         switch (event->type) {
1333                 case MIDDLEMOUSE:
1334                         return OPERATOR_PASS_THROUGH;
1335
1336                 /* Cancel */
1337                 case ESCKEY:
1338                         return stitch_cancel(C, op);
1339
1340
1341                 case LEFTMOUSE:
1342                         if (event->shift && (U.flag & USER_LMOUSESELECT)) {
1343                                 if (event->val == KM_RELEASE) {
1344                                         stitch_select(C, scene, event, stitch_state);
1345
1346                                         if (!stitch_process_data(stitch_state, scene, 0)) {
1347                                                 return stitch_cancel(C, op);
1348                                         }
1349                                 }
1350                                 break;
1351                         }
1352                 case PADENTER:
1353                 case RETKEY:
1354                         if (stitch_process_data(stitch_state, scene, 1)) {
1355                                 stitch_exit(C, op, 1);
1356                                 return OPERATOR_FINISHED;
1357                         }
1358                         else {
1359                                 return stitch_cancel(C, op);
1360                         }
1361
1362                 /* Increase limit */
1363                 case PADPLUSKEY:
1364                 case WHEELUPMOUSE:
1365                         if (event->alt) {
1366                                 stitch_state->limit_dist += 0.01;
1367                                 if (!stitch_process_data(stitch_state, scene, 0)) {
1368                                         return stitch_cancel(C, op);
1369                                 }
1370                                 break;
1371                         }
1372                         else {
1373                                 return OPERATOR_PASS_THROUGH;
1374                         }
1375                 /* Decrease limit */
1376                 case PADMINUS:
1377                 case WHEELDOWNMOUSE:
1378                         if (event->alt) {
1379                                 stitch_state->limit_dist -= 0.01;
1380                                 stitch_state->limit_dist = MAX2(0.01, stitch_state->limit_dist);
1381                                 if (!stitch_process_data(stitch_state, scene, 0)) {
1382                                         return stitch_cancel(C, op);
1383                                 }
1384                                 break;
1385                         }
1386                         else {
1387                                 return OPERATOR_PASS_THROUGH;
1388                         }
1389
1390                 /* Use Limit (Default off)*/
1391                 case LKEY:
1392                         if (event->val == KM_PRESS) {
1393                                 stitch_state->use_limit = !stitch_state->use_limit;
1394                                 if (!stitch_process_data(stitch_state, scene, 0)) {
1395                                         return stitch_cancel(C, op);
1396                                 }
1397                                 break;
1398                         }
1399                         return OPERATOR_RUNNING_MODAL;
1400
1401                 case IKEY:
1402                         if (event->val == KM_PRESS) {
1403                                 stitch_state->static_island++;
1404                                 stitch_state->static_island %= stitch_state->element_map->totalIslands;
1405
1406                                 if (!stitch_process_data(stitch_state, scene, 0)) {
1407                                         return stitch_cancel(C, op);
1408                                 }
1409                                 break;
1410                         }
1411                         return OPERATOR_RUNNING_MODAL;
1412
1413                 case MKEY:
1414                         if (event->val == KM_PRESS) {
1415                                 stitch_state->midpoints = !stitch_state->midpoints;
1416                                 if (!stitch_process_data(stitch_state, scene, 0)) {
1417                                         return stitch_cancel(C, op);
1418                                 }
1419                         }
1420                         break;
1421
1422                 /* Select geometry*/
1423                 case RIGHTMOUSE:
1424                         if (!event->shift) {
1425                                 return stitch_cancel(C, op);
1426                         }
1427                         if (event->val == KM_RELEASE && !(U.flag & USER_LMOUSESELECT)) {
1428                                 stitch_select(C, scene, event, stitch_state);
1429
1430                                 if (!stitch_process_data(stitch_state, scene, 0)) {
1431                                         return stitch_cancel(C, op);
1432                                 }
1433                                 break;
1434                         }
1435                         return OPERATOR_RUNNING_MODAL;
1436
1437                 /* snap islands on/off */
1438                 case SKEY:
1439                         if (event->val == KM_PRESS) {
1440                                 stitch_state->snap_islands = !stitch_state->snap_islands;
1441                                 if (!stitch_process_data(stitch_state, scene, 0)) {
1442                                         return stitch_cancel(C, op);
1443                                 }
1444                                 break;
1445                         }
1446                         else {
1447                                 return OPERATOR_RUNNING_MODAL;
1448                         }
1449
1450                 default:
1451                         return OPERATOR_RUNNING_MODAL;
1452         }
1453
1454         /* if updated settings, renew feedback message */
1455         stitch_update_header(stitch_state, C);
1456         ED_region_tag_redraw(CTX_wm_region(C));
1457         return OPERATOR_RUNNING_MODAL;
1458 }
1459
1460 void UV_OT_stitch(wmOperatorType *ot)
1461 {
1462         PropertyRNA *prop;
1463
1464         /* identifiers */
1465         ot->name = "Stitch";
1466         ot->description = "Stitch selected UV vertices by proximity";
1467         ot->idname = "UV_OT_stitch";
1468         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1469         
1470         /* api callbacks */
1471         ot->invoke = stitch_invoke;
1472         ot->modal = stitch_modal;
1473         ot->exec = stitch_exec;
1474         ot->cancel = stitch_cancel;
1475         ot->poll = ED_operator_uvedit;
1476
1477         /* properties */
1478         RNA_def_boolean(ot->srna, "use_limit", 0, "Use Limit", "Stitch UVs within a specified limit distance");
1479         RNA_def_boolean(ot->srna, "snap_islands", 1, "Snap Islands",
1480                         "Snap islands together (on edge stitch mode, rotates the islands too)");
1481
1482         RNA_def_float(ot->srna, "limit", 0.01f, 0.0f, FLT_MAX, "Limit",
1483                       "Limit distance in normalized coordinates", 0.0, FLT_MAX);
1484         RNA_def_int(ot->srna, "static_island", 0, 0, INT_MAX, "Static Island",
1485                     "Island that stays in place when stitching islands", 0, INT_MAX);
1486         RNA_def_boolean(ot->srna, "midpoint_snap", 0, "Snap At Midpoint",
1487                         "UVs are stitched at midpoint instead of at static island");
1488         prop = RNA_def_collection_runtime(ot->srna, "selection", &RNA_SelectedUvElement, "Selection", "");
1489         /* Selection should not be editable or viewed in toolbar */
1490         RNA_def_property_flag(prop, PROP_HIDDEN);
1491 }