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