Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / uvedit / uvedit_ops.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_ops.c
29  *  \ingroup eduv
30  */
31
32
33 #include <stdlib.h>
34 #include <string.h>
35 #include <math.h>
36 #include <string.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "DNA_object_types.h"
41 #include "DNA_material_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_meshdata_types.h"
44 #include "DNA_node_types.h"
45 #include "DNA_image_types.h"
46 #include "DNA_space_types.h"
47 #include "DNA_scene_types.h"
48
49 #include "BLI_utildefines.h"
50 #include "BLI_alloca.h"
51 #include "BLI_math.h"
52 #include "BLI_lasso.h"
53 #include "BLI_blenlib.h"
54 #include "BLI_array.h"
55
56 #include "BLT_translation.h"
57
58 #include "BKE_context.h"
59 #include "BKE_customdata.h"
60 #include "BKE_image.h"
61 #include "BKE_library.h"
62 #include "BKE_main.h"
63 #include "BKE_material.h"
64 #include "BKE_mesh_mapping.h"
65 #include "BKE_node.h"
66 #include "BKE_report.h"
67 #include "BKE_scene.h"
68 #include "BKE_editmesh.h"
69
70 #include "DEG_depsgraph.h"
71
72 #include "ED_image.h"
73 #include "ED_mesh.h"
74 #include "ED_node.h"
75 #include "ED_uvedit.h"
76 #include "ED_object.h"
77 #include "ED_screen.h"
78 #include "ED_transform.h"
79
80 #include "RNA_access.h"
81 #include "RNA_define.h"
82
83 #include "WM_api.h"
84 #include "WM_types.h"
85
86 #include "UI_interface.h"
87 #include "UI_resources.h"
88 #include "UI_view2d.h"
89
90 #include "uvedit_intern.h"
91
92 static void uv_select_all_perform(Scene *scene, Image *ima, BMEditMesh *em, int action);
93 static void uv_select_flush_from_tag_face(SpaceImage *sima, Scene *scene, Object *obedit, const bool select);
94 static void uv_select_flush_from_tag_loop(SpaceImage *sima, Scene *scene, Object *obedit, const bool select);
95
96 /************************* state testing ************************/
97
98 bool ED_uvedit_test(Object *obedit)
99 {
100         BMEditMesh *em;
101         int ret;
102
103         if (!obedit)
104                 return 0;
105         
106         if (obedit->type != OB_MESH)
107                 return 0;
108
109         em = BKE_editmesh_from_object(obedit);
110         ret = EDBM_uv_check(em);
111         
112         return ret;
113 }
114
115 static int ED_operator_uvedit_can_uv_sculpt(struct bContext *C)
116 {
117         SpaceImage *sima = CTX_wm_space_image(C);
118         ToolSettings *toolsettings = CTX_data_tool_settings(C);
119         Object *obedit = CTX_data_edit_object(C);
120
121         return ED_space_image_show_uvedit(sima, obedit) && !(toolsettings->use_uv_sculpt);
122 }
123
124 static int UNUSED_FUNCTION(ED_operator_uvmap_mesh) (bContext *C)
125 {
126         Object *ob = CTX_data_active_object(C);
127
128         if (ob && ob->type == OB_MESH) {
129                 Mesh *me = ob->data;
130
131                 if (CustomData_get_layer(&me->fdata, CD_MTFACE) != NULL)
132                         return 1;
133         }
134
135         return 0;
136 }
137 /**************************** object active image *****************************/
138
139 static bool is_image_texture_node(bNode *node)
140 {
141         return ELEM(node->type, SH_NODE_TEX_IMAGE, SH_NODE_TEX_ENVIRONMENT);
142 }
143
144 bool ED_object_get_active_image(Object *ob, int mat_nr,
145                                 Image **r_ima, ImageUser **r_iuser, bNode **r_node, bNodeTree **r_ntree)
146 {
147         Material *ma = give_current_material(ob, mat_nr);
148         bNodeTree *ntree = (ma && ma->use_nodes) ? ma->nodetree : NULL;
149         bNode *node = (ntree) ? nodeGetActiveTexture(ntree) : NULL;
150
151         if (node && is_image_texture_node(node)) {
152                 if (r_ima) *r_ima = (Image *)node->id;
153                 if (r_iuser) *r_iuser = NULL;
154                 if (r_node) *r_node = node;
155                 if (r_ntree) *r_ntree = ntree;
156                 return true;
157         }
158         
159         if (r_ima) *r_ima = NULL;
160         if (r_iuser) *r_iuser = NULL;
161         if (r_node) *r_node = node;
162         if (r_ntree) *r_ntree = ntree;
163
164         return false;
165 }
166
167 void ED_object_assign_active_image(Main *bmain, Object *ob, int mat_nr, Image *ima)
168 {
169         Material *ma = give_current_material(ob, mat_nr);
170         bNode *node = (ma && ma->use_nodes) ? nodeGetActiveTexture(ma->nodetree) : NULL;
171
172         if (node && is_image_texture_node(node)) {
173                 node->id = &ima->id;
174                 ED_node_tag_update_nodetree(bmain, ma->nodetree, node);
175         }
176 }
177
178 /************************* assign image ************************/
179
180 //#define USE_SWITCH_ASPECT
181
182 void ED_uvedit_assign_image(Main *UNUSED(bmain), Scene *scene, Object *obedit, Image *ima, Image *previma)
183 {
184         BMEditMesh *em;
185         BMIter iter;
186         bool update = false;
187         const bool selected = !(scene->toolsettings->uv_flag & UV_SYNC_SELECTION);
188         
189         /* skip assigning these procedural images... */
190         if (ima && (ima->type == IMA_TYPE_R_RESULT || ima->type == IMA_TYPE_COMPOSITE))
191                 return;
192
193         /* verify we have a mesh we can work with */
194         if (!obedit || (obedit->type != OB_MESH))
195                 return;
196
197         em = BKE_editmesh_from_object(obedit);
198         if (!em || !em->bm->totface) {
199                 return;
200         }
201
202         if (BKE_scene_use_new_shading_nodes(scene)) {
203                 /* new shading system, do not assign anything */
204         }
205         else {
206                 BMFace *efa;
207
208                 int cd_loop_uv_offset;
209                 /* old shading system, assign image to selected faces */
210 #ifdef USE_SWITCH_ASPECT
211                 float prev_aspect[2], fprev_aspect;
212                 float aspect[2], faspect;
213
214                 ED_image_get_uv_aspect(previma, prev_aspect, prev_aspect + 1);
215                 ED_image_get_uv_aspect(ima, aspect, aspect + 1);
216
217                 fprev_aspect = prev_aspect[0] / prev_aspect[1];
218                 faspect = aspect[0] / aspect[1];
219 #endif
220
221                 /* ensure we have a uv map */
222                 if (!CustomData_has_layer(&em->bm->ldata, CD_MLOOPUV)) {
223                         BM_data_layer_add(em->bm, &em->bm->ldata, CD_MLOOPUV);
224                         /* make UVs all nice 0-1 */
225                         ED_mesh_uv_loop_reset_ex(obedit->data, CustomData_get_active_layer_index(&em->bm->ldata, CD_MLOOPUV));
226                         update = true;
227                 }
228
229                 cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
230
231                 /* now assign to all visible faces */
232                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
233                         if (uvedit_face_visible_test(scene, previma, efa) &&
234                             (selected == true || uvedit_face_select_test(scene, efa, cd_loop_uv_offset)))
235                         {
236 #ifdef USE_SWITCH_ASPECT
237                                 if (ima) {
238                                         /* we also need to correct the aspect of uvs */
239                                         if (scene->toolsettings->uvcalc_flag & UVCALC_NO_ASPECT_CORRECT) {
240                                                 /* do nothing */
241                                         }
242                                         else {
243                                                 BMIter liter;
244                                                 BMLoop *l;
245
246                                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
247                                                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
248
249                                                         luv->uv[0] *= fprev_aspect;
250                                                         luv->uv[0] /= faspect;
251                                                 }
252                                         }
253                                 }
254 #endif
255                                 BKE_object_material_edit_image_set(obedit, efa->mat_nr, ima);
256
257                                 update = true;
258                         }
259                 }
260
261                 /* and update depdency graph */
262                 if (update) {
263                         DEG_id_tag_update(obedit->data, 0);
264                 }
265         }
266
267 }
268
269 /*********************** space conversion *********************/
270
271 static void uvedit_pixel_to_float(SpaceImage *sima, float *dist, float pixeldist)
272 {
273         int width, height;
274
275         if (sima) {
276                 ED_space_image_get_size(sima, &width, &height);
277         }
278         else {
279                 width =  IMG_SIZE_FALLBACK;
280                 height = IMG_SIZE_FALLBACK;
281         }
282
283         dist[0] = pixeldist / width;
284         dist[1] = pixeldist / height;
285 }
286
287 /*************** visibility and selection utilities **************/
288
289 bool uvedit_face_visible_nolocal(Scene *scene, BMFace *efa)
290 {
291         ToolSettings *ts = scene->toolsettings;
292
293         if (ts->uv_flag & UV_SYNC_SELECTION)
294                 return (BM_elem_flag_test(efa, BM_ELEM_HIDDEN) == 0);
295         else
296                 return (BM_elem_flag_test(efa, BM_ELEM_HIDDEN) == 0 && BM_elem_flag_test(efa, BM_ELEM_SELECT));
297 }
298
299 bool uvedit_face_visible_test(Scene *scene, Image *ima, BMFace *efa)
300 {
301         ToolSettings *ts = scene->toolsettings;
302
303         if (ts->uv_flag & UV_SHOW_SAME_IMAGE) {
304                 const Image *face_image = BKE_object_material_edit_image_get(scene->obedit, efa->mat_nr);
305                 return (face_image == ima) ? uvedit_face_visible_nolocal(scene, efa) : false;
306         }
307         else {
308                 return uvedit_face_visible_nolocal(scene, efa);
309         }
310 }
311
312 bool uvedit_face_select_test(Scene *scene, BMFace *efa,
313                              const int cd_loop_uv_offset)
314 {
315         ToolSettings *ts = scene->toolsettings;
316         if (ts->uv_flag & UV_SYNC_SELECTION) {
317                 return (BM_elem_flag_test(efa, BM_ELEM_SELECT));
318         }
319         else {
320                 BMLoop *l;
321                 MLoopUV *luv;
322                 BMIter liter;
323
324                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
325                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
326                         if (!(luv->flag & MLOOPUV_VERTSEL))
327                                 return false;
328                 }
329
330                 return true;
331         }
332 }
333
334 bool uvedit_face_select_set(struct Scene *scene, struct BMEditMesh *em, struct BMFace *efa, const bool select,
335                             const bool do_history, const int cd_loop_uv_offset)
336 {
337         if (select) {
338                 return uvedit_face_select_enable(scene, em, efa, do_history, cd_loop_uv_offset);
339         }
340         else {
341                 return uvedit_face_select_disable(scene, em, efa, cd_loop_uv_offset);
342         }
343 }
344
345 bool uvedit_face_select_enable(Scene *scene, BMEditMesh *em, BMFace *efa, const bool do_history,
346                                const int cd_loop_uv_offset)
347 {
348         ToolSettings *ts = scene->toolsettings;
349
350         if (ts->uv_flag & UV_SYNC_SELECTION) {
351                 BM_face_select_set(em->bm, efa, true);
352                 if (do_history) {
353                         BM_select_history_store(em->bm, (BMElem *)efa);
354                 }
355         }
356         else {
357                 BMLoop *l;
358                 MLoopUV *luv;
359                 BMIter liter;
360
361                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
362                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
363                         luv->flag |= MLOOPUV_VERTSEL;
364                 }
365
366                 return true;
367         }
368
369         return false;
370 }
371
372 bool uvedit_face_select_disable(Scene *scene, BMEditMesh *em, BMFace *efa,
373                                 const int cd_loop_uv_offset)
374 {
375         ToolSettings *ts = scene->toolsettings;
376
377         if (ts->uv_flag & UV_SYNC_SELECTION) {
378                 BM_face_select_set(em->bm, efa, false);
379         }
380         else {
381                 BMLoop *l;
382                 MLoopUV *luv;
383                 BMIter liter;
384
385                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
386                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
387                         luv->flag &= ~MLOOPUV_VERTSEL;
388                 }
389
390                 return true;
391         }
392
393         return false;
394 }
395
396 bool uvedit_edge_select_test(Scene *scene, BMLoop *l,
397                              const int cd_loop_uv_offset)
398 {
399         ToolSettings *ts = scene->toolsettings;
400
401         if (ts->uv_flag & UV_SYNC_SELECTION) {
402                 if (ts->selectmode & SCE_SELECT_FACE) {
403                         return BM_elem_flag_test(l->f, BM_ELEM_SELECT);
404                 }
405                 else if (ts->selectmode == SCE_SELECT_EDGE) {
406                         return BM_elem_flag_test(l->e, BM_ELEM_SELECT);
407                 }
408                 else {
409                         return BM_elem_flag_test(l->v, BM_ELEM_SELECT) && 
410                                BM_elem_flag_test(l->next->v, BM_ELEM_SELECT);
411                 }
412         }
413         else {
414                 MLoopUV *luv1, *luv2;
415
416                 luv1 = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
417                 luv2 = BM_ELEM_CD_GET_VOID_P(l->next, cd_loop_uv_offset);
418
419                 return (luv1->flag & MLOOPUV_VERTSEL) && (luv2->flag & MLOOPUV_VERTSEL);
420         }
421 }
422
423 void uvedit_edge_select_set(BMEditMesh *em, Scene *scene, BMLoop *l, const bool select,
424                             const bool do_history, const int cd_loop_uv_offset)
425
426 {
427         if (select) {
428                 uvedit_edge_select_enable(em, scene, l, do_history, cd_loop_uv_offset);
429         }
430         else {
431                 uvedit_edge_select_disable(em, scene, l, cd_loop_uv_offset);
432         }
433 }
434
435 void uvedit_edge_select_enable(BMEditMesh *em, Scene *scene, BMLoop *l, const bool do_history,
436                                const int cd_loop_uv_offset)
437
438 {
439         ToolSettings *ts = scene->toolsettings;
440
441         if (ts->uv_flag & UV_SYNC_SELECTION) {
442                 if (ts->selectmode & SCE_SELECT_FACE)
443                         BM_face_select_set(em->bm, l->f, true);
444                 else if (ts->selectmode & SCE_SELECT_EDGE)
445                         BM_edge_select_set(em->bm, l->e, true);
446                 else {
447                         BM_vert_select_set(em->bm, l->e->v1, true);
448                         BM_vert_select_set(em->bm, l->e->v2, true);
449                 }
450
451                 if (do_history) {
452                         BM_select_history_store(em->bm, (BMElem *)l->e);
453                 }
454         }
455         else {
456                 MLoopUV *luv1, *luv2;
457
458                 luv1 = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
459                 luv2 = BM_ELEM_CD_GET_VOID_P(l->next, cd_loop_uv_offset);
460                 
461                 luv1->flag |= MLOOPUV_VERTSEL;
462                 luv2->flag |= MLOOPUV_VERTSEL;
463         }
464 }
465
466 void uvedit_edge_select_disable(BMEditMesh *em, Scene *scene, BMLoop *l,
467                                 const int cd_loop_uv_offset)
468
469 {
470         ToolSettings *ts = scene->toolsettings;
471
472         if (ts->uv_flag & UV_SYNC_SELECTION) {
473                 if (ts->selectmode & SCE_SELECT_FACE)
474                         BM_face_select_set(em->bm, l->f, false);
475                 else if (ts->selectmode & SCE_SELECT_EDGE)
476                         BM_edge_select_set(em->bm, l->e, false);
477                 else {
478                         BM_vert_select_set(em->bm, l->e->v1, false);
479                         BM_vert_select_set(em->bm, l->e->v2, false);
480                 }
481         }
482         else {
483                 MLoopUV *luv1, *luv2;
484
485                 luv1 = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
486                 luv2 = BM_ELEM_CD_GET_VOID_P(l->next, cd_loop_uv_offset);
487                 
488                 luv1->flag &= ~MLOOPUV_VERTSEL;
489                 luv2->flag &= ~MLOOPUV_VERTSEL;
490         }
491 }
492
493 bool uvedit_uv_select_test(Scene *scene, BMLoop *l,
494                            const int cd_loop_uv_offset)
495 {
496         ToolSettings *ts = scene->toolsettings;
497
498         if (ts->uv_flag & UV_SYNC_SELECTION) {
499                 if (ts->selectmode & SCE_SELECT_FACE)
500                         return BM_elem_flag_test_bool(l->f, BM_ELEM_SELECT);
501                 else
502                         return BM_elem_flag_test_bool(l->v, BM_ELEM_SELECT);
503         }
504         else {
505                 MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
506                 return (luv->flag & MLOOPUV_VERTSEL) != 0;
507         }
508 }
509
510 void uvedit_uv_select_set(BMEditMesh *em, Scene *scene, BMLoop *l, const bool select,
511                           const bool do_history, const int cd_loop_uv_offset)
512 {
513         if (select) {
514                 uvedit_uv_select_enable(em, scene, l, do_history, cd_loop_uv_offset);
515         }
516         else {
517                 uvedit_uv_select_disable(em, scene, l, cd_loop_uv_offset);
518         }
519 }
520
521 void uvedit_uv_select_enable(BMEditMesh *em, Scene *scene, BMLoop *l,
522                              const bool do_history, const int cd_loop_uv_offset)
523 {
524         ToolSettings *ts = scene->toolsettings;
525
526         if (ts->uv_flag & UV_SYNC_SELECTION) {
527                 if (ts->selectmode & SCE_SELECT_FACE)
528                         BM_face_select_set(em->bm, l->f, true);
529                 else
530                         BM_vert_select_set(em->bm, l->v, true);
531
532                 if (do_history) {
533                         BM_select_history_remove(em->bm, (BMElem *)l->v);
534                 }
535         }
536         else {
537                 MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
538                 luv->flag |= MLOOPUV_VERTSEL;
539         }
540 }
541
542 void uvedit_uv_select_disable(BMEditMesh *em, Scene *scene, BMLoop *l,
543                               const int cd_loop_uv_offset)
544 {
545         ToolSettings *ts = scene->toolsettings;
546
547         if (ts->uv_flag & UV_SYNC_SELECTION) {
548                 if (ts->selectmode & SCE_SELECT_FACE)
549                         BM_face_select_set(em->bm, l->f, false);
550                 else
551                         BM_vert_select_set(em->bm, l->v, false);
552         }
553         else {
554                 MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
555                 luv->flag &= ~MLOOPUV_VERTSEL;
556         }
557 }
558
559 /*********************** live unwrap utilities ***********************/
560
561 void uvedit_live_unwrap_update(SpaceImage *sima, Scene *scene, Object *obedit)
562 {
563         if (sima && (sima->flag & SI_LIVE_UNWRAP)) {
564                 ED_uvedit_live_unwrap_begin(scene, obedit);
565                 ED_uvedit_live_unwrap_re_solve();
566                 ED_uvedit_live_unwrap_end(0);
567         }
568 }
569
570 /*********************** geometric utilities ***********************/
571 void uv_poly_center(BMFace *f, float r_cent[2], const int cd_loop_uv_offset)
572 {
573         BMLoop *l;
574         MLoopUV *luv;
575         BMIter liter;
576
577         zero_v2(r_cent);
578
579         BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
580                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
581                 add_v2_v2(r_cent, luv->uv);
582         }
583
584         mul_v2_fl(r_cent, 1.0f / (float)f->len);
585 }
586
587 void uv_poly_copy_aspect(float uv_orig[][2], float uv[][2], float aspx, float aspy, int len)
588 {
589         int i;
590         for (i = 0; i < len; i++) {
591                 uv[i][0] = uv_orig[i][0] * aspx;
592                 uv[i][1] = uv_orig[i][1] * aspy;
593         }
594 }
595
596 bool ED_uvedit_minmax(Scene *scene, Image *ima, Object *obedit, float r_min[2], float r_max[2])
597 {
598         BMEditMesh *em = BKE_editmesh_from_object(obedit);
599         BMFace *efa;
600         BMLoop *l;
601         BMIter iter, liter;
602         MLoopUV *luv;
603         bool changed = false;
604
605         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
606
607         INIT_MINMAX2(r_min, r_max);
608
609         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
610                 if (!uvedit_face_visible_test(scene, ima, efa))
611                         continue;
612                 
613                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
614                         if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
615                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
616                                 minmax_v2v2_v2(r_min, r_max, luv->uv);
617                                 changed = true;
618                         }
619                 }
620         }
621
622         return changed;
623 }
624
625 /* Be careful when using this, it bypasses all synchronization options */
626 void ED_uvedit_select_all(BMesh *bm)
627 {
628         BMFace *efa;
629         BMLoop *l;
630         BMIter iter, liter;
631         MLoopUV *luv;
632
633         const int cd_loop_uv_offset  = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
634
635         BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
636                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
637                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
638                         luv->flag |= MLOOPUV_VERTSEL;
639                 }
640         }
641 }
642
643 static bool ED_uvedit_median(Scene *scene, Image *ima, Object *obedit, float co[2])
644 {
645         BMEditMesh *em = BKE_editmesh_from_object(obedit);
646         BMFace *efa;
647         BMLoop *l;
648         BMIter iter, liter;
649         MLoopUV *luv;
650         unsigned int sel = 0;
651
652         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
653
654         zero_v2(co);
655         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
656                 if (!uvedit_face_visible_test(scene, ima, efa))
657                         continue;
658                 
659                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
660                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
661                         if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
662                                 add_v2_v2(co, luv->uv);
663                                 sel++;
664                         }
665                 }
666         }
667
668         mul_v2_fl(co, 1.0f / (float)sel);
669
670         return (sel != 0);
671 }
672
673 bool ED_uvedit_center(Scene *scene, Image *ima, Object *obedit, float cent[2], char mode)
674 {
675         bool changed = false;
676         
677         if (mode == V3D_AROUND_CENTER_BOUNDS) {  /* bounding box */
678                 float min[2], max[2];
679                 if (ED_uvedit_minmax(scene, ima, obedit, min, max)) {
680                         mid_v2_v2v2(cent, min, max);
681                         changed = true;
682                 }
683         }
684         else {
685                 if (ED_uvedit_median(scene, ima, obedit, cent)) {
686                         changed = true;
687                 }
688         }
689
690         return changed;
691 }
692
693 /************************** find nearest ****************************/
694
695 void uv_find_nearest_edge(Scene *scene, Image *ima, BMEditMesh *em, const float co[2], NearestHit *hit)
696 {
697         BMFace *efa;
698         BMLoop *l;
699         BMIter iter, liter;
700         MLoopUV *luv, *luv_next;
701         float mindist_squared, dist_squared;
702         int i;
703
704         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
705
706         mindist_squared = 1e10f;
707         memset(hit, 0, sizeof(*hit));
708
709         BM_mesh_elem_index_ensure(em->bm, BM_VERT);
710         
711         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
712                 if (!uvedit_face_visible_test(scene, ima, efa))
713                         continue;
714                 
715                 BM_ITER_ELEM_INDEX (l, &liter, efa, BM_LOOPS_OF_FACE, i) {
716                         luv      = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
717                         luv_next = BM_ELEM_CD_GET_VOID_P(l->next, cd_loop_uv_offset);
718
719                         dist_squared = dist_squared_to_line_segment_v2(co, luv->uv, luv_next->uv);
720
721                         if (dist_squared < mindist_squared) {
722                                 hit->efa = efa;
723                                 
724                                 hit->l = l;
725                                 hit->luv = luv;
726                                 hit->luv_next = luv_next;
727                                 hit->lindex = i;
728
729                                 mindist_squared = dist_squared;
730                         }
731                 }
732         }
733 }
734
735 static void uv_find_nearest_face(Scene *scene, Image *ima, BMEditMesh *em, const float co[2], NearestHit *hit)
736 {
737         BMFace *efa;
738         BMIter iter;
739         float mindist, dist, cent[2];
740
741         const int cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
742
743         mindist = 1e10f;
744         memset(hit, 0, sizeof(*hit));
745
746         /*this will fill in hit.vert1 and hit.vert2*/
747         uv_find_nearest_edge(scene, ima, em, co, hit);
748         hit->l = NULL;
749         hit->luv = hit->luv_next = NULL;
750
751         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
752                 if (!uvedit_face_visible_test(scene, ima, efa))
753                         continue;
754
755                 uv_poly_center(efa, cent, cd_loop_uv_offset);
756
757                 dist = len_manhattan_v2v2(co, cent);
758
759                 if (dist < mindist) {
760                         hit->efa = efa;
761                         mindist = dist;
762                 }
763         }
764 }
765
766 static bool uv_nearest_between(const BMLoop *l, const float co[2],
767                                const int cd_loop_uv_offset)
768 {
769         const float *uv_prev = ((MLoopUV *)BM_ELEM_CD_GET_VOID_P(l->prev, cd_loop_uv_offset))->uv;
770         const float *uv_curr = ((MLoopUV *)BM_ELEM_CD_GET_VOID_P(l,       cd_loop_uv_offset))->uv;
771         const float *uv_next = ((MLoopUV *)BM_ELEM_CD_GET_VOID_P(l->next, cd_loop_uv_offset))->uv;
772
773         return ((line_point_side_v2(uv_prev, uv_curr, co) >  0.0f) &&
774                 (line_point_side_v2(uv_next, uv_curr, co) <= 0.0f));
775 }
776
777 void uv_find_nearest_vert(Scene *scene, Image *ima, BMEditMesh *em,
778                           float const co[2], const float penalty[2], NearestHit *hit)
779 {
780         BMFace *efa;
781         BMLoop *l;
782         BMIter iter, liter;
783         MLoopUV *luv;
784         float mindist, dist;
785         int i;
786
787         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
788
789         /*this will fill in hit.vert1 and hit.vert2*/
790         uv_find_nearest_edge(scene, ima, em, co, hit);
791         hit->l = NULL;
792         hit->luv = hit->luv_next = NULL;
793
794         mindist = 1e10f;
795         memset(hit, 0, sizeof(*hit));
796         
797         BM_mesh_elem_index_ensure(em->bm, BM_VERT);
798
799         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
800                 if (!uvedit_face_visible_test(scene, ima, efa))
801                         continue;
802
803                 BM_ITER_ELEM_INDEX (l, &liter, efa, BM_LOOPS_OF_FACE, i) {
804                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
805                         if (penalty && uvedit_uv_select_test(scene, l, cd_loop_uv_offset))
806                                 dist = len_manhattan_v2v2(co, luv->uv) + len_manhattan_v2(penalty);
807                         else
808                                 dist = len_manhattan_v2v2(co, luv->uv);
809
810                         if (dist <= mindist) {
811                                 if (dist == mindist) {
812                                         if (!uv_nearest_between(l, co, cd_loop_uv_offset)) {
813                                                 continue;
814                                         }
815                                 }
816
817                                 mindist = dist;
818
819                                 hit->l = l;
820                                 hit->luv = luv;
821                                 hit->luv_next = BM_ELEM_CD_GET_VOID_P(l->next, cd_loop_uv_offset);
822                                 hit->efa = efa;
823                                 hit->lindex = i;
824                         }
825                 }
826         }
827 }
828
829 bool ED_uvedit_nearest_uv(Scene *scene, Object *obedit, Image *ima, const float co[2], float r_uv[2])
830 {
831         BMEditMesh *em = BKE_editmesh_from_object(obedit);
832         BMFace *efa;
833         BMLoop *l;
834         BMIter iter, liter;
835         MLoopUV *luv;
836         float mindist, dist;
837         bool found = false;
838
839         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
840
841         mindist = 1e10f;
842         copy_v2_v2(r_uv, co);
843         
844         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
845                 if (!uvedit_face_visible_test(scene, ima, efa))
846                         continue;
847                 
848                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
849                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
850                         dist = len_manhattan_v2v2(co, luv->uv);
851
852                         if (dist <= mindist) {
853                                 mindist = dist;
854
855                                 copy_v2_v2(r_uv, luv->uv);
856                                 found = true;
857                         }
858                 }
859         }
860
861         return found;
862 }
863
864 /*********************** loop select ***********************/
865
866 static void uv_select_edgeloop_vertex_loop_flag(UvMapVert *first)
867 {
868         UvMapVert *iterv;
869         int count = 0;
870
871         for (iterv = first; iterv; iterv = iterv->next) {
872                 if (iterv->separate && iterv != first)
873                         break;
874
875                 count++;
876         }
877         
878         if (count < 5)
879                 first->flag = 1;
880 }
881
882 static UvMapVert *uv_select_edgeloop_vertex_map_get(UvVertMap *vmap, BMFace *efa, BMLoop *l)
883 {
884         UvMapVert *iterv, *first;
885         first = BM_uv_vert_map_at_index(vmap,  BM_elem_index_get(l->v));
886
887         for (iterv = first; iterv; iterv = iterv->next) {
888                 if (iterv->separate)
889                         first = iterv;
890                 if (iterv->f == BM_elem_index_get(efa))
891                         return first;
892         }
893         
894         return NULL;
895 }
896
897 static bool uv_select_edgeloop_edge_tag_faces(BMEditMesh *em, UvMapVert *first1, UvMapVert *first2, int *totface)
898 {
899         UvMapVert *iterv1, *iterv2;
900         BMFace *efa;
901         int tot = 0;
902
903         /* count number of faces this edge has */
904         for (iterv1 = first1; iterv1; iterv1 = iterv1->next) {
905                 if (iterv1->separate && iterv1 != first1)
906                         break;
907
908                 for (iterv2 = first2; iterv2; iterv2 = iterv2->next) {
909                         if (iterv2->separate && iterv2 != first2)
910                                 break;
911
912                         if (iterv1->f == iterv2->f) {
913                                 /* if face already tagged, don't do this edge */
914                                 efa = BM_face_at_index(em->bm, iterv1->f);
915                                 if (BM_elem_flag_test(efa, BM_ELEM_TAG))
916                                         return false;
917
918                                 tot++;
919                                 break;
920                         }
921                 }
922         }
923
924         if (*totface == 0) /* start edge */
925                 *totface = tot;
926         else if (tot != *totface) /* check for same number of faces as start edge */
927                 return false;
928
929         /* tag the faces */
930         for (iterv1 = first1; iterv1; iterv1 = iterv1->next) {
931                 if (iterv1->separate && iterv1 != first1)
932                         break;
933
934                 for (iterv2 = first2; iterv2; iterv2 = iterv2->next) {
935                         if (iterv2->separate && iterv2 != first2)
936                                 break;
937
938                         if (iterv1->f == iterv2->f) {
939                                 efa = BM_face_at_index(em->bm, iterv1->f);
940                                 BM_elem_flag_enable(efa, BM_ELEM_TAG);
941                                 break;
942                         }
943                 }
944         }
945
946         return true;
947 }
948
949 static int uv_select_edgeloop(Scene *scene, Image *ima, BMEditMesh *em, NearestHit *hit,
950                               const float limit[2], const bool extend)
951 {
952         BMFace *efa;
953         BMIter iter, liter;
954         BMLoop *l;
955         UvVertMap *vmap;
956         UvMapVert *iterv_curr;
957         UvMapVert *iterv_next;
958         int starttotf;
959         bool looking, select;
960
961         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
962
963         /* setup */
964         BM_mesh_elem_table_ensure(em->bm, BM_FACE);
965         vmap = BM_uv_vert_map_create(em->bm, limit, false, false);
966
967         BM_mesh_elem_index_ensure(em->bm, BM_VERT | BM_FACE);
968
969         if (!extend) {
970                 uv_select_all_perform(scene, ima, em, SEL_DESELECT);
971         }
972
973         BM_mesh_elem_hflag_disable_all(em->bm, BM_FACE, BM_ELEM_TAG, false);
974
975         /* set flags for first face and verts */
976         iterv_curr = uv_select_edgeloop_vertex_map_get(vmap, hit->efa, hit->l);
977         iterv_next = uv_select_edgeloop_vertex_map_get(vmap, hit->efa, hit->l->next);
978         uv_select_edgeloop_vertex_loop_flag(iterv_curr);
979         uv_select_edgeloop_vertex_loop_flag(iterv_next);
980
981         starttotf = 0;
982         uv_select_edgeloop_edge_tag_faces(em, iterv_curr, iterv_next, &starttotf);
983
984         /* sorry, first edge isn't even ok */
985         looking = !(iterv_curr->flag == 0 && iterv_next->flag == 0);
986
987         /* iterate */
988         while (looking) {
989                 looking = false;
990
991                 /* find correct valence edges which are not tagged yet, but connect to tagged one */
992
993                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
994                         if (!BM_elem_flag_test(efa, BM_ELEM_TAG) && uvedit_face_visible_test(scene, ima, efa)) {
995                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
996                                         /* check face not hidden and not tagged */
997                                         if (!(iterv_curr = uv_select_edgeloop_vertex_map_get(vmap, efa, l)))
998                                                 continue;
999                                         if (!(iterv_next = uv_select_edgeloop_vertex_map_get(vmap, efa, l->next)))
1000                                                 continue;
1001
1002                                         /* check if vertex is tagged and has right valence */
1003                                         if (iterv_curr->flag || iterv_next->flag) {
1004                                                 if (uv_select_edgeloop_edge_tag_faces(em, iterv_curr, iterv_next, &starttotf)) {
1005                                                         looking = true;
1006                                                         BM_elem_flag_enable(efa, BM_ELEM_TAG);
1007
1008                                                         uv_select_edgeloop_vertex_loop_flag(iterv_curr);
1009                                                         uv_select_edgeloop_vertex_loop_flag(iterv_next);
1010                                                         break;
1011                                                 }
1012                                         }
1013                                 }
1014                         }
1015                 }
1016         }
1017
1018         /* do the actual select/deselect */
1019         iterv_curr = uv_select_edgeloop_vertex_map_get(vmap, hit->efa, hit->l);
1020         iterv_next = uv_select_edgeloop_vertex_map_get(vmap, hit->efa, hit->l->next);
1021         iterv_curr->flag = 1;
1022         iterv_next->flag = 1;
1023
1024         if (extend) {
1025                 select = !(uvedit_uv_select_test(scene, hit->l, cd_loop_uv_offset));
1026         }
1027         else {
1028                 select = true;
1029         }
1030         
1031         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1032                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1033                         iterv_curr = uv_select_edgeloop_vertex_map_get(vmap, efa, l);
1034
1035                         if (iterv_curr->flag) {
1036                                 uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
1037                         }
1038                 }
1039         }
1040
1041         /* cleanup */
1042         BM_uv_vert_map_free(vmap);
1043
1044         return (select) ? 1 : -1;
1045 }
1046
1047 /*********************** linked select ***********************/
1048
1049 static void uv_select_linked(Scene *scene, Image *ima, BMEditMesh *em, const float limit[2], NearestHit *hit, bool extend, bool select_faces)
1050 {
1051         BMFace *efa;
1052         BMLoop *l;
1053         BMIter iter, liter;
1054         MLoopUV *luv;
1055         UvVertMap *vmap;
1056         UvMapVert *vlist, *iterv, *startv;
1057         int i, stacksize = 0, *stack;
1058         unsigned int a;
1059         char *flag;
1060
1061         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
1062
1063         BM_mesh_elem_table_ensure(em->bm, BM_FACE); /* we can use this too */
1064
1065         /* use winding so we don't consider overlapping islands as connected, see T44320 */
1066         vmap = BM_uv_vert_map_create(em->bm, limit, !select_faces, true);
1067
1068         if (vmap == NULL)
1069                 return;
1070
1071         stack = MEM_mallocN(sizeof(*stack) * (em->bm->totface + 1), "UvLinkStack");
1072         flag = MEM_callocN(sizeof(*flag) * em->bm->totface, "UvLinkFlag");
1073
1074         if (!hit) {
1075                 BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
1076                         if (uvedit_face_visible_test(scene, ima, efa)) {
1077                                 if (select_faces) {
1078                                         if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
1079                                                 stack[stacksize] = a;
1080                                                 stacksize++;
1081                                                 flag[a] = 1;
1082                                         }
1083                                 }
1084                                 else {
1085                                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1086                                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1087
1088                                                 if (luv->flag & MLOOPUV_VERTSEL) {
1089                                                         stack[stacksize] = a;
1090                                                         stacksize++;
1091                                                         flag[a] = 1;
1092
1093                                                         break;
1094                                                 }
1095                                         }
1096                                 }
1097                         }
1098                 }
1099         }
1100         else {
1101                 BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
1102                         if (efa == hit->efa) {
1103                                 stack[stacksize] = a;
1104                                 stacksize++;
1105                                 flag[a] = 1;
1106                                 break;
1107                         }
1108                 }
1109         }
1110
1111         while (stacksize > 0) {
1112
1113                 stacksize--;
1114                 a = stack[stacksize];
1115
1116                 efa = BM_face_at_index(em->bm, a);
1117
1118                 BM_ITER_ELEM_INDEX (l, &liter, efa, BM_LOOPS_OF_FACE, i) {
1119
1120                         /* make_uv_vert_map_EM sets verts tmp.l to the indices */
1121                         vlist = BM_uv_vert_map_at_index(vmap, BM_elem_index_get(l->v));
1122                         
1123                         startv = vlist;
1124
1125                         for (iterv = vlist; iterv; iterv = iterv->next) {
1126                                 if (iterv->separate)
1127                                         startv = iterv;
1128                                 if (iterv->f == a)
1129                                         break;
1130                         }
1131
1132                         for (iterv = startv; iterv; iterv = iterv->next) {
1133                                 if ((startv != iterv) && (iterv->separate))
1134                                         break;
1135                                 else if (!flag[iterv->f]) {
1136                                         flag[iterv->f] = 1;
1137                                         stack[stacksize] = iterv->f;
1138                                         stacksize++;
1139                                 }
1140                         }
1141                 }
1142         }
1143
1144         if (!extend) {
1145                 BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
1146                         if (select_faces) {
1147                                 if (flag[a])
1148                                         BM_face_select_set(em->bm, efa, true);
1149                                 else
1150                                         BM_face_select_set(em->bm, efa, false);
1151                         }
1152                         else {
1153                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1154                                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1155
1156                                         if (flag[a])
1157                                                 luv->flag |= MLOOPUV_VERTSEL;
1158                                         else
1159                                                 luv->flag &= ~MLOOPUV_VERTSEL;
1160                                 }
1161                         }
1162                 }
1163         }
1164         else {
1165                 BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
1166                         if (!flag[a]) {
1167                                 continue;
1168                         }
1169
1170                         if (select_faces) {
1171                                 if (BM_elem_flag_test(efa, BM_ELEM_SELECT) && !BM_elem_flag_test(efa, BM_ELEM_HIDDEN))
1172                                         break;
1173                         }
1174                         else {
1175                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1176                                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1177
1178                                         if (luv->flag & MLOOPUV_VERTSEL) {
1179                                                 break;
1180                                         }
1181                                 }
1182
1183                                 if (l) {
1184                                         break;
1185                                 }
1186                         }
1187                 }
1188
1189                 if (efa) {
1190                         BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
1191                                 if (!flag[a]) {
1192                                         continue;
1193                                 }
1194
1195                                 if (select_faces) {
1196                                         BM_face_select_set(em->bm, efa, false);
1197                                 }
1198                                 else {
1199                                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1200                                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1201
1202                                                 luv->flag &= ~MLOOPUV_VERTSEL;
1203                                         }
1204                                 }
1205                         }
1206                 }
1207                 else {
1208                         BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
1209                                 if (!flag[a]) {
1210                                         continue;
1211                                 }
1212
1213                                 if (select_faces) {
1214                                         BM_face_select_set(em->bm, efa, true);
1215                                 }
1216                                 else {
1217                                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1218                                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1219
1220                                                 luv->flag |= MLOOPUV_VERTSEL;
1221                                         }
1222                                 }
1223                         }
1224                 }
1225         }
1226         
1227         MEM_freeN(stack);
1228         MEM_freeN(flag);
1229         BM_uv_vert_map_free(vmap);
1230 }
1231
1232 /* WATCH IT: this returns first selected UV,
1233  * not ideal in many cases since there could be multiple */
1234 static float *uv_sel_co_from_eve(Scene *scene, Image *ima, BMEditMesh *em, BMVert *eve)
1235 {
1236         BMIter liter;
1237         BMLoop *l;
1238
1239         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
1240
1241         BM_ITER_ELEM (l, &liter, eve, BM_LOOPS_OF_VERT) {
1242                 if (!uvedit_face_visible_test(scene, ima, l->f))
1243                         continue;
1244
1245                 if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
1246                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1247                         return luv->uv;
1248                 }
1249         }
1250
1251         return NULL;
1252 }
1253
1254 static int uv_select_more_less(bContext *C, const bool select)
1255 {
1256         Scene *scene = CTX_data_scene(C);
1257         Object *obedit = CTX_data_edit_object(C);
1258         Image *ima = CTX_data_edit_image(C);
1259         SpaceImage *sima = CTX_wm_space_image(C);
1260         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1261
1262         BMFace *efa;
1263         BMLoop *l;
1264         BMIter iter, liter;
1265         ToolSettings *ts = scene->toolsettings;
1266
1267         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
1268
1269         if (ts->uv_flag & UV_SYNC_SELECTION) {
1270                 if (select) {
1271                         EDBM_select_more(em, true);
1272                 }
1273                 else {
1274                         EDBM_select_less(em, true);
1275                 }
1276
1277                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
1278                 return OPERATOR_FINISHED;
1279         }
1280
1281         if (ts->uv_selectmode == UV_SELECT_FACE) {
1282
1283                 /* clear tags */
1284                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1285                         BM_elem_flag_disable(efa, BM_ELEM_TAG);
1286                 }
1287
1288                 /* mark loops to be selected */
1289                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1290                         if (uvedit_face_visible_test(scene, ima, efa)) {
1291
1292 #define IS_SEL   1
1293 #define IS_UNSEL 2
1294
1295                                 int sel_state = 0;
1296
1297                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1298                                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1299                                         if (luv->flag & MLOOPUV_VERTSEL) {
1300                                                 sel_state |= IS_SEL;
1301                                         }
1302                                         else {
1303                                                 sel_state |= IS_UNSEL;
1304                                         }
1305
1306                                         /* if we have a mixed selection, tag to grow it */
1307                                         if (sel_state == (IS_SEL | IS_UNSEL)) {
1308                                                 BM_elem_flag_enable(efa, BM_ELEM_TAG);
1309                                                 break;
1310                                         }
1311                                 }
1312
1313 #undef IS_SEL
1314 #undef IS_UNSEL
1315
1316                         }
1317                 }
1318
1319                 /* select tagged faces */
1320                 uv_select_flush_from_tag_face(sima, scene, obedit, select);
1321         }
1322         else {
1323
1324                 /* clear tags */
1325                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1326                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1327                                 BM_elem_flag_disable(l, BM_ELEM_TAG);
1328                         }
1329                 }
1330
1331                 /* mark loops to be selected */
1332                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1333                         if (uvedit_face_visible_test(scene, ima, efa)) {
1334                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1335
1336                                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1337
1338                                         if (((luv->flag & MLOOPUV_VERTSEL) != 0) == select) {
1339                                                 BM_elem_flag_enable(l->next, BM_ELEM_TAG);
1340                                                 BM_elem_flag_enable(l->prev, BM_ELEM_TAG);
1341                                         }
1342                                 }
1343                         }
1344                 }
1345
1346                 /* select tagged loops */
1347                 uv_select_flush_from_tag_loop(sima, scene, obedit, select);
1348         }
1349
1350         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
1351
1352         return OPERATOR_FINISHED;
1353 }
1354
1355 static int uv_select_more_exec(bContext *C, wmOperator *UNUSED(op))
1356 {
1357         return uv_select_more_less(C, true);
1358 }
1359
1360 static void UV_OT_select_more(wmOperatorType *ot)
1361 {
1362         /* identifiers */
1363         ot->name = "Select More";
1364         ot->description = "Select more UV vertices connected to initial selection";
1365         ot->idname = "UV_OT_select_more";
1366         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1367
1368         /* api callbacks */
1369         ot->exec = uv_select_more_exec;
1370         ot->poll = ED_operator_uvedit_space_image;
1371 }
1372
1373 static int uv_select_less_exec(bContext *C, wmOperator *UNUSED(op))
1374 {
1375         return uv_select_more_less(C, false);
1376 }
1377
1378 static void UV_OT_select_less(wmOperatorType *ot)
1379 {
1380         /* identifiers */
1381         ot->name = "Select Less";
1382         ot->description = "Deselect UV vertices at the boundary of each selection region";
1383         ot->idname = "UV_OT_select_less";
1384         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1385
1386         /* api callbacks */
1387         ot->exec = uv_select_less_exec;
1388         ot->poll = ED_operator_uvedit_space_image;
1389 }
1390
1391 /* ******************** align operator **************** */
1392
1393 static void uv_weld_align(bContext *C, int tool)
1394 {
1395         Object *obedit = CTX_data_edit_object(C);
1396         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1397         SpaceImage *sima;
1398         Scene *scene;
1399         Image *ima;
1400         float cent[2], min[2], max[2];
1401
1402         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
1403
1404         scene = CTX_data_scene(C);
1405         ima = CTX_data_edit_image(C);
1406         sima = CTX_wm_space_image(C);
1407
1408         INIT_MINMAX2(min, max);
1409
1410         if (tool == 'a') {
1411                 BMIter iter, liter;
1412                 BMFace *efa;
1413                 BMLoop *l;
1414
1415                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1416                         if (!uvedit_face_visible_test(scene, ima, efa))
1417                                 continue;
1418
1419                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1420                                 if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
1421                                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1422                                         minmax_v2v2_v2(min, max, luv->uv);
1423                                 }
1424                         }
1425                 }
1426
1427                 tool = (max[0] - min[0] >= max[1] - min[1]) ? 'y' : 'x';
1428         }
1429
1430         ED_uvedit_center(scene, ima, obedit, cent, 0);
1431
1432         if (tool == 'x' || tool == 'w') {
1433                 BMIter iter, liter;
1434                 BMFace *efa;
1435                 BMLoop *l;
1436
1437                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1438                         if (!uvedit_face_visible_test(scene, ima, efa))
1439                                 continue;
1440
1441                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1442                                 if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
1443                                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1444                                         luv->uv[0] = cent[0];
1445                                 }
1446
1447                         }
1448                 }
1449         }
1450
1451         if (tool == 'y' || tool == 'w') {
1452                 BMIter iter, liter;
1453                 BMFace *efa;
1454                 BMLoop *l;
1455
1456                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1457                         if (!uvedit_face_visible_test(scene, ima, efa))
1458                                 continue;
1459
1460                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1461                                 if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
1462                                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1463                                         luv->uv[1] = cent[1];
1464                                 }
1465
1466                         }
1467                 }
1468         }
1469
1470         if (tool == 's' || tool == 't' || tool == 'u') {
1471                 BMEdge *eed;
1472                 BMLoop *l;
1473                 BMVert *eve;
1474                 BMVert *eve_start;
1475                 BMIter iter, liter, eiter;
1476
1477                 /* clear tag */
1478                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1479                         BM_elem_flag_disable(eve, BM_ELEM_TAG);
1480                 }
1481
1482                 /* tag verts with a selected UV */
1483                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1484                         BM_ITER_ELEM (l, &liter, eve, BM_LOOPS_OF_VERT) {
1485                                 if (!uvedit_face_visible_test(scene, ima, l->f))
1486                                         continue;
1487
1488                                 if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
1489                                         BM_elem_flag_enable(eve, BM_ELEM_TAG);
1490                                         break;
1491                                 }
1492                         }
1493                 }
1494
1495                 /* flush vertex tags to edges */
1496                 BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1497                         BM_elem_flag_set(eed, BM_ELEM_TAG, (BM_elem_flag_test(eed->v1, BM_ELEM_TAG) &&
1498                                                             BM_elem_flag_test(eed->v2, BM_ELEM_TAG)));
1499                 }
1500
1501                 /* find a vertex with only one tagged edge */
1502                 eve_start = NULL;
1503                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1504                         int tot_eed_tag = 0;
1505                         BM_ITER_ELEM (eed, &eiter, eve, BM_EDGES_OF_VERT) {
1506                                 if (BM_elem_flag_test(eed, BM_ELEM_TAG)) {
1507                                         tot_eed_tag++;
1508                                 }
1509                         }
1510
1511                         if (tot_eed_tag == 1) {
1512                                 eve_start = eve;
1513                                 break;
1514                         }
1515                 }
1516
1517                 if (eve_start) {
1518                         BMVert **eve_line = NULL;
1519                         BMVert *eve_next = NULL;
1520                         BLI_array_declare(eve_line);
1521                         int i;
1522
1523                         eve = eve_start;
1524
1525                         /* walk over edges, building an array of verts in a line */
1526                         while (eve) {
1527                                 BLI_array_append(eve_line, eve);
1528                                 /* don't touch again */
1529                                 BM_elem_flag_disable(eve, BM_ELEM_TAG);
1530
1531                                 eve_next = NULL;
1532
1533                                 /* find next eve */
1534                                 BM_ITER_ELEM (eed, &eiter, eve, BM_EDGES_OF_VERT) {
1535                                         if (BM_elem_flag_test(eed, BM_ELEM_TAG)) {
1536                                                 BMVert *eve_other = BM_edge_other_vert(eed, eve);
1537                                                 if (BM_elem_flag_test(eve_other, BM_ELEM_TAG)) {
1538                                                         /* this is a tagged vert we didnt walk over yet, step onto it */
1539                                                         eve_next = eve_other;
1540                                                         break;
1541                                                 }
1542                                         }
1543                                 }
1544
1545                                 eve = eve_next;
1546                         }
1547
1548                         /* now we have all verts, make into a line */
1549                         if (BLI_array_count(eve_line) > 2) {
1550
1551                                 /* we know the returns from these must be valid */
1552                                 const float *uv_start = uv_sel_co_from_eve(scene, ima, em, eve_line[0]);
1553                                 const float *uv_end   = uv_sel_co_from_eve(scene, ima, em, eve_line[BLI_array_count(eve_line) - 1]);
1554                                 /* For t & u modes */
1555                                 float a = 0.0f;
1556
1557                                 if (tool == 't') {
1558                                         if (uv_start[1] == uv_end[1])
1559                                                 tool = 's';
1560                                         else
1561                                                 a = (uv_end[0] - uv_start[0]) / (uv_end[1] - uv_start[1]);
1562                                 }
1563                                 else if (tool == 'u') {
1564                                         if (uv_start[0] == uv_end[0])
1565                                                 tool = 's';
1566                                         else
1567                                                 a = (uv_end[1] - uv_start[1]) / (uv_end[0] - uv_start[0]);
1568                                 }
1569
1570                                 /* go over all verts except for endpoints */
1571                                 for (i = 0; i < BLI_array_count(eve_line); i++) {
1572                                         BM_ITER_ELEM (l, &liter, eve_line[i], BM_LOOPS_OF_VERT) {
1573                                                 if (!uvedit_face_visible_test(scene, ima, l->f))
1574                                                         continue;
1575
1576                                                 if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
1577                                                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1578                                                         /* Projection of point (x, y) over line (x1, y1, x2, y2) along X axis:
1579                                                          * new_y = (y2 - y1) / (x2 - x1) * (x - x1) + y1
1580                                                          * Maybe this should be a BLI func? Or is it already existing?
1581                                                          * Could use interp_v2_v2v2, but not sure it's worth it here...*/
1582                                                         if (tool == 't')
1583                                                                 luv->uv[0] = a * (luv->uv[1] - uv_start[1]) + uv_start[0];
1584                                                         else if (tool == 'u')
1585                                                                 luv->uv[1] = a * (luv->uv[0] - uv_start[0]) + uv_start[1];
1586                                                         else
1587                                                                 closest_to_line_segment_v2(luv->uv, luv->uv, uv_start, uv_end);
1588                                                 }
1589                                         }
1590                                 }
1591                         }
1592                         else {
1593                                 /* error - not a line, needs 3+ points  */
1594                         }
1595
1596                         if (eve_line) {
1597                                 MEM_freeN(eve_line);
1598                         }
1599                 }
1600                 else {
1601                         /* error - cant find an endpoint */
1602                 }
1603         }
1604
1605
1606         uvedit_live_unwrap_update(sima, scene, obedit);
1607         DEG_id_tag_update(obedit->data, 0);
1608         WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
1609 }
1610
1611 static int uv_align_exec(bContext *C, wmOperator *op)
1612 {
1613         uv_weld_align(C, RNA_enum_get(op->ptr, "axis"));
1614
1615         return OPERATOR_FINISHED;
1616 }
1617
1618 static void UV_OT_align(wmOperatorType *ot)
1619 {
1620         static EnumPropertyItem axis_items[] = {
1621                 {'s', "ALIGN_S", 0, "Straighten", "Align UVs along the line defined by the endpoints"},
1622                 {'t', "ALIGN_T", 0, "Straighten X", "Align UVs along the line defined by the endpoints along the X axis"},
1623                 {'u', "ALIGN_U", 0, "Straighten Y", "Align UVs along the line defined by the endpoints along the Y axis"},
1624                 {'a', "ALIGN_AUTO", 0, "Align Auto", "Automatically choose the axis on which there is most alignment already"},
1625                 {'x', "ALIGN_X", 0, "Align X", "Align UVs on X axis"},
1626                 {'y', "ALIGN_Y", 0, "Align Y", "Align UVs on Y axis"},
1627                 {0, NULL, 0, NULL, NULL}};
1628
1629         /* identifiers */
1630         ot->name = "Align";
1631         ot->description = "Align selected UV vertices to an axis";
1632         ot->idname = "UV_OT_align";
1633         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1634         
1635         /* api callbacks */
1636         ot->exec = uv_align_exec;
1637         ot->poll = ED_operator_uvedit;
1638
1639         /* properties */
1640         RNA_def_enum(ot->srna, "axis", axis_items, 'a', "Axis", "Axis to align UV locations on");
1641 }
1642 /* ******************** weld near operator **************** */
1643
1644 typedef struct UVvert {
1645         MLoopUV *uv_loop;
1646         bool weld;
1647 } UVvert;
1648
1649 static int uv_remove_doubles_exec(bContext *C, wmOperator *op)
1650 {
1651         const float threshold = RNA_float_get(op->ptr, "threshold");
1652         const bool use_unselected = RNA_boolean_get(op->ptr, "use_unselected");
1653
1654         SpaceImage *sima;
1655         Scene *scene;
1656         Object *obedit = CTX_data_edit_object(C);
1657         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1658         Image *ima;
1659         int uv_a_index;
1660         int uv_b_index;
1661         float *uv_a;
1662         const float *uv_b;
1663
1664         BMIter iter, liter;
1665         BMFace *efa;
1666         BMLoop *l;
1667
1668         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
1669
1670         sima = CTX_wm_space_image(C);
1671         scene = CTX_data_scene(C);
1672         ima = CTX_data_edit_image(C);
1673
1674         if (use_unselected == false) {
1675                 UVvert *vert_arr = NULL;
1676                 BLI_array_declare(vert_arr);
1677                 MLoopUV **loop_arr = NULL;
1678                 BLI_array_declare(loop_arr);
1679
1680                 /* TODO, use qsort as with MESH_OT_remove_doubles, this isn't optimal */
1681                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1682                         if (!uvedit_face_visible_test(scene, ima, efa))
1683                                 continue;
1684
1685                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1686                                 if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
1687                                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1688                                         UVvert vert;
1689                                         vert.uv_loop = luv;
1690                                         vert.weld = false;
1691                                         BLI_array_append(vert_arr, vert);
1692                                 }
1693
1694                         }
1695                 }
1696
1697                 for (uv_a_index = 0; uv_a_index < BLI_array_count(vert_arr); uv_a_index++) {
1698                         if (vert_arr[uv_a_index].weld == false) {
1699                                 float uv_min[2];
1700                                 float uv_max[2];
1701
1702                                 BLI_array_empty(loop_arr);
1703                                 BLI_array_append(loop_arr, vert_arr[uv_a_index].uv_loop);
1704
1705                                 uv_a = vert_arr[uv_a_index].uv_loop->uv;
1706
1707                                 copy_v2_v2(uv_max, uv_a);
1708                                 copy_v2_v2(uv_min, uv_a);
1709
1710                                 vert_arr[uv_a_index].weld = true;
1711                                 for (uv_b_index = uv_a_index + 1; uv_b_index < BLI_array_count(vert_arr); uv_b_index++) {
1712                                         uv_b = vert_arr[uv_b_index].uv_loop->uv;
1713                                         if ((vert_arr[uv_b_index].weld == false) &&
1714                                             (len_manhattan_v2v2(uv_a, uv_b) < threshold))
1715                                         {
1716                                                 minmax_v2v2_v2(uv_min, uv_max, uv_b);
1717                                                 BLI_array_append(loop_arr, vert_arr[uv_b_index].uv_loop);
1718                                                 vert_arr[uv_b_index].weld = true;
1719                                         }
1720                                 }
1721                                 if (BLI_array_count(loop_arr)) {
1722                                         float uv_mid[2];
1723                                         mid_v2_v2v2(uv_mid, uv_min, uv_max);
1724                                         for (uv_b_index = 0; uv_b_index < BLI_array_count(loop_arr); uv_b_index++) {
1725                                                 copy_v2_v2(loop_arr[uv_b_index]->uv, uv_mid);
1726                                         }
1727                                 }
1728                         }
1729                 }
1730
1731                 BLI_array_free(vert_arr);
1732                 BLI_array_free(loop_arr);
1733         }
1734         else {
1735                 /* selected -> unselected
1736                  *
1737                  * No need to use 'UVvert' here */
1738                 MLoopUV **loop_arr = NULL;
1739                 BLI_array_declare(loop_arr);
1740                 MLoopUV **loop_arr_unselected = NULL;
1741                 BLI_array_declare(loop_arr_unselected);
1742
1743                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1744                         if (!uvedit_face_visible_test(scene, ima, efa))
1745                                 continue;
1746
1747                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1748                                 MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1749                                 if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
1750                                         BLI_array_append(loop_arr, luv);
1751                                 }
1752                                 else {
1753                                         BLI_array_append(loop_arr_unselected, luv);
1754                                 }
1755                         }
1756                 }
1757
1758                 for (uv_a_index = 0; uv_a_index < BLI_array_count(loop_arr); uv_a_index++) {
1759                         float dist_best = FLT_MAX, dist;
1760                         const float *uv_best = NULL;
1761
1762                         uv_a = loop_arr[uv_a_index]->uv;
1763                         for (uv_b_index = 0; uv_b_index < BLI_array_count(loop_arr_unselected); uv_b_index++) {
1764                                 uv_b = loop_arr_unselected[uv_b_index]->uv;
1765                                 dist = len_manhattan_v2v2(uv_a, uv_b);
1766                                 if ((dist < threshold) && (dist < dist_best)) {
1767                                         uv_best = uv_b;
1768                                         dist_best = dist;
1769                                 }
1770                         }
1771                         if (uv_best) {
1772                                 copy_v2_v2(uv_a, uv_best);
1773                         }
1774                 }
1775
1776                 BLI_array_free(loop_arr);
1777                 BLI_array_free(loop_arr_unselected);
1778         }
1779
1780         uvedit_live_unwrap_update(sima, scene, obedit);
1781         DEG_id_tag_update(obedit->data, 0);
1782         WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
1783
1784         return OPERATOR_FINISHED;
1785 }
1786
1787 static void UV_OT_remove_doubles(wmOperatorType *ot)
1788 {
1789         /* identifiers */
1790         ot->name = "Remove Doubles UV";
1791         ot->description = "Selected UV vertices that are within a radius of each other are welded together";
1792         ot->idname = "UV_OT_remove_doubles";
1793         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1794
1795         /* api callbacks */
1796         ot->exec = uv_remove_doubles_exec;
1797         ot->poll = ED_operator_uvedit;
1798
1799         RNA_def_float(ot->srna, "threshold", 0.02f, 0.0f, 10.0f,
1800                       "Merge Distance", "Maximum distance between welded vertices", 0.0f, 1.0f);
1801         RNA_def_boolean(ot->srna, "use_unselected", 0, "Unselected", "Merge selected to other unselected vertices");
1802 }
1803 /* ******************** weld operator **************** */
1804
1805 static int uv_weld_exec(bContext *C, wmOperator *UNUSED(op))
1806 {
1807         uv_weld_align(C, 'w');
1808
1809         return OPERATOR_FINISHED;
1810 }
1811
1812 static void UV_OT_weld(wmOperatorType *ot)
1813 {
1814         /* identifiers */
1815         ot->name = "Weld";
1816         ot->description = "Weld selected UV vertices together";
1817         ot->idname = "UV_OT_weld";
1818         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1819         
1820         /* api callbacks */
1821         ot->exec = uv_weld_exec;
1822         ot->poll = ED_operator_uvedit;
1823 }
1824
1825
1826 /* ******************** (de)select all operator **************** */
1827
1828 static void uv_select_all_perform(Scene *scene, Image *ima, BMEditMesh *em, int action)
1829 {
1830         ToolSettings *ts = scene->toolsettings;
1831         BMFace *efa;
1832         BMLoop *l;
1833         BMIter iter, liter;
1834         MLoopUV *luv;
1835
1836         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
1837
1838         if (ts->uv_flag & UV_SYNC_SELECTION) {
1839
1840                 switch (action) {
1841                         case SEL_TOGGLE:
1842                                 EDBM_select_toggle_all(em);
1843                                 break;
1844                         case SEL_SELECT:
1845                                 EDBM_flag_enable_all(em, BM_ELEM_SELECT);
1846                                 break;
1847                         case SEL_DESELECT:
1848                                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
1849                                 break;
1850                         case SEL_INVERT:
1851                                 EDBM_select_swap(em);
1852                                 EDBM_selectmode_flush(em);
1853                                 break;
1854                 }
1855         }
1856         else {
1857                 if (action == SEL_TOGGLE) {
1858                         action = SEL_SELECT;
1859                         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1860                                 if (!uvedit_face_visible_test(scene, ima, efa))
1861                                         continue;
1862
1863                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1864                                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1865
1866                                         if (luv->flag & MLOOPUV_VERTSEL) {
1867                                                 action = SEL_DESELECT;
1868                                                 break;
1869                                         }
1870                                 }
1871                         }
1872                 }
1873         
1874                 
1875                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1876                         if (!uvedit_face_visible_test(scene, ima, efa))
1877                                 continue;
1878
1879                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1880                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1881
1882                                 switch (action) {
1883                                         case SEL_SELECT:
1884                                                 luv->flag |= MLOOPUV_VERTSEL;
1885                                                 break;
1886                                         case SEL_DESELECT:
1887                                                 luv->flag &= ~MLOOPUV_VERTSEL;
1888                                                 break;
1889                                         case SEL_INVERT:
1890                                                 luv->flag ^= MLOOPUV_VERTSEL;
1891                                                 break;
1892                                 }
1893                         }
1894                 }
1895         }
1896 }
1897
1898 static int uv_select_all_exec(bContext *C, wmOperator *op)
1899 {
1900         Scene *scene = CTX_data_scene(C);
1901         Object *obedit = CTX_data_edit_object(C);
1902         Image *ima = CTX_data_edit_image(C);
1903         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1904
1905         int action = RNA_enum_get(op->ptr, "action");
1906
1907         uv_select_all_perform(scene, ima, em, action);
1908
1909         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
1910
1911         return OPERATOR_FINISHED;
1912 }
1913
1914 static void UV_OT_select_all(wmOperatorType *ot)
1915 {
1916         /* identifiers */
1917         ot->name = "(De)select All";
1918         ot->description = "Change selection of all UV vertices";
1919         ot->idname = "UV_OT_select_all";
1920         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1921         
1922         /* api callbacks */
1923         ot->exec = uv_select_all_exec;
1924         ot->poll = ED_operator_uvedit;
1925
1926         WM_operator_properties_select_all(ot);
1927 }
1928
1929 /* ******************** mouse select operator **************** */
1930
1931 static bool uv_sticky_select(float *limit, int hitv[4], int v, float *hituv[4], float *uv, int sticky, int hitlen)
1932 {
1933         int i;
1934
1935         /* this function test if some vertex needs to selected
1936          * in addition to the existing ones due to sticky select */
1937         if (sticky == SI_STICKY_DISABLE)
1938                 return false;
1939
1940         for (i = 0; i < hitlen; i++) {
1941                 if (hitv[i] == v) {
1942                         if (sticky == SI_STICKY_LOC) {
1943                                 if (fabsf(hituv[i][0] - uv[0]) < limit[0] && fabsf(hituv[i][1] - uv[1]) < limit[1])
1944                                         return true;
1945                         }
1946                         else if (sticky == SI_STICKY_VERTEX)
1947                                 return true;
1948                 }
1949         }
1950
1951         return false;
1952 }
1953
1954 static int uv_mouse_select(bContext *C, const float co[2], bool extend, bool loop)
1955 {
1956         SpaceImage *sima = CTX_wm_space_image(C);
1957         Scene *scene = CTX_data_scene(C);
1958         ToolSettings *ts = scene->toolsettings;
1959         Object *obedit = CTX_data_edit_object(C);
1960         Image *ima = CTX_data_edit_image(C);
1961         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1962         BMFace *efa;
1963         BMLoop *l;
1964         BMIter iter, liter;
1965         MLoopUV *luv;
1966         NearestHit hit;
1967         int i, selectmode, sticky, sync, *hitv = NULL;
1968         bool select = true;
1969         int flush = 0, hitlen = 0; /* 0 == don't flush, 1 == sel, -1 == desel;  only use when selection sync is enabled */
1970         float limit[2], **hituv = NULL;
1971         float penalty[2];
1972
1973         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
1974
1975         /* notice 'limit' is the same no matter the zoom level, since this is like
1976          * remove doubles and could annoying if it joined points when zoomed out.
1977          * 'penalty' is in screen pixel space otherwise zooming in on a uv-vert and
1978          * shift-selecting can consider an adjacent point close enough to add to
1979          * the selection rather than de-selecting the closest. */
1980
1981         uvedit_pixel_to_float(sima, limit, 0.05f);
1982         uvedit_pixel_to_float(sima, penalty, 5.0f / (sima ? sima->zoom : 1.0f));
1983
1984         /* retrieve operation mode */
1985         if (ts->uv_flag & UV_SYNC_SELECTION) {
1986                 sync = 1;
1987
1988                 if (ts->selectmode & SCE_SELECT_FACE)
1989                         selectmode = UV_SELECT_FACE;
1990                 else if (ts->selectmode & SCE_SELECT_EDGE)
1991                         selectmode = UV_SELECT_EDGE;
1992                 else
1993                         selectmode = UV_SELECT_VERTEX;
1994
1995                 sticky = SI_STICKY_DISABLE;
1996         }
1997         else {
1998                 sync = 0;
1999                 selectmode = ts->uv_selectmode;
2000                 sticky = (sima) ? sima->sticky : 1;
2001         }
2002
2003         /* find nearest element */
2004         if (loop) {
2005                 /* find edge */
2006                 uv_find_nearest_edge(scene, ima, em, co, &hit);
2007                 if (hit.efa == NULL) {
2008                         return OPERATOR_CANCELLED;
2009                 }
2010
2011                 hitlen = 0;
2012         }
2013         else if (selectmode == UV_SELECT_VERTEX) {
2014                 /* find vertex */
2015                 uv_find_nearest_vert(scene, ima, em, co, penalty, &hit);
2016                 if (hit.efa == NULL) {
2017                         return OPERATOR_CANCELLED;
2018                 }
2019
2020                 /* mark 1 vertex as being hit */
2021                 hitv  = BLI_array_alloca(hitv,  hit.efa->len);
2022                 hituv = BLI_array_alloca(hituv, hit.efa->len);
2023                 copy_vn_i(hitv, hit.efa->len, 0xFFFFFFFF);
2024
2025                 hitv[hit.lindex] = BM_elem_index_get(hit.l->v);
2026                 hituv[hit.lindex] = hit.luv->uv;
2027
2028                 hitlen = hit.efa->len;
2029         }
2030         else if (selectmode == UV_SELECT_EDGE) {
2031                 /* find edge */
2032                 uv_find_nearest_edge(scene, ima, em, co, &hit);
2033                 if (hit.efa == NULL) {
2034                         return OPERATOR_CANCELLED;
2035                 }
2036
2037                 /* mark 2 edge vertices as being hit */
2038                 hitv  = BLI_array_alloca(hitv,  hit.efa->len);
2039                 hituv = BLI_array_alloca(hituv, hit.efa->len);
2040                 copy_vn_i(hitv, hit.efa->len, 0xFFFFFFFF);
2041
2042                 hitv[hit.lindex] = BM_elem_index_get(hit.l->v);
2043                 hitv[(hit.lindex + 1) % hit.efa->len] = BM_elem_index_get(hit.l->next->v);
2044                 hituv[hit.lindex] = hit.luv->uv;
2045                 hituv[(hit.lindex + 1) % hit.efa->len] = hit.luv_next->uv;
2046
2047                 hitlen = hit.efa->len;
2048         }
2049         else if (selectmode == UV_SELECT_FACE) {
2050                 /* find face */
2051                 uv_find_nearest_face(scene, ima, em, co, &hit);
2052                 if (hit.efa == NULL) {
2053                         return OPERATOR_CANCELLED;
2054                 }
2055                 
2056                 /* make active */
2057                 BM_mesh_active_face_set(em->bm, hit.efa);
2058
2059                 /* mark all face vertices as being hit */
2060
2061                 hitv  = BLI_array_alloca(hitv,  hit.efa->len);
2062                 hituv = BLI_array_alloca(hituv, hit.efa->len);
2063                 BM_ITER_ELEM_INDEX (l, &liter, hit.efa, BM_LOOPS_OF_FACE, i) {
2064                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
2065                         hituv[i] = luv->uv;
2066                         hitv[i] = BM_elem_index_get(l->v);
2067                 }
2068                 
2069                 hitlen = hit.efa->len;
2070         }
2071         else if (selectmode == UV_SELECT_ISLAND) {
2072                 uv_find_nearest_edge(scene, ima, em, co, &hit);
2073
2074                 if (hit.efa == NULL) {
2075                         return OPERATOR_CANCELLED;
2076                 }
2077
2078                 hitlen = 0;
2079         }
2080         else {
2081                 hitlen = 0;
2082                 return OPERATOR_CANCELLED;
2083         }
2084
2085         /* do selection */
2086         if (loop) {
2087                 flush = uv_select_edgeloop(scene, ima, em, &hit, limit, extend);
2088         }
2089         else if (selectmode == UV_SELECT_ISLAND) {
2090                 uv_select_linked(scene, ima, em, limit, &hit, extend, false);
2091         }
2092         else if (extend) {
2093                 if (selectmode == UV_SELECT_VERTEX) {
2094                         /* (de)select uv vertex */
2095                         select = !uvedit_uv_select_test(scene, hit.l, cd_loop_uv_offset);
2096                         uvedit_uv_select_set(em, scene, hit.l, select, true, cd_loop_uv_offset);
2097                         flush = 1;
2098                 }
2099                 else if (selectmode == UV_SELECT_EDGE) {
2100                         /* (de)select edge */
2101                         select = !(uvedit_edge_select_test(scene, hit.l, cd_loop_uv_offset));
2102                         uvedit_edge_select_set(em, scene, hit.l, select, true, cd_loop_uv_offset);
2103                         flush = 1;
2104                 }
2105                 else if (selectmode == UV_SELECT_FACE) {
2106                         /* (de)select face */
2107                         select = !(uvedit_face_select_test(scene, hit.efa, cd_loop_uv_offset));
2108                         uvedit_face_select_set(scene, em, hit.efa, select, true, cd_loop_uv_offset);
2109                         flush = -1;
2110                 }
2111
2112                 /* de-selecting an edge may deselect a face too - validate */
2113                 if (sync) {
2114                         if (select == false) {
2115                                 BM_select_history_validate(em->bm);
2116                         }
2117                 }
2118
2119                 /* (de)select sticky uv nodes */
2120                 if (sticky != SI_STICKY_DISABLE) {
2121
2122                         BM_mesh_elem_index_ensure(em->bm, BM_VERT);
2123
2124                         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2125                                 if (!uvedit_face_visible_test(scene, ima, efa))
2126                                         continue;
2127
2128                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2129                                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
2130                                         if (uv_sticky_select(limit, hitv, BM_elem_index_get(l->v), hituv, luv->uv, sticky, hitlen))
2131                                                 uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
2132                                 }
2133                         }
2134
2135                         flush = select ? 1 : -1;
2136                 }
2137         }
2138         else {
2139                 /* deselect all */
2140                 uv_select_all_perform(scene, ima, em, SEL_DESELECT);
2141
2142                 if (selectmode == UV_SELECT_VERTEX) {
2143                         /* select vertex */
2144                         uvedit_uv_select_enable(em, scene, hit.l, true, cd_loop_uv_offset);
2145                         flush = 1;
2146                 }
2147                 else if (selectmode == UV_SELECT_EDGE) {
2148                         /* select edge */
2149                         uvedit_edge_select_enable(em, scene, hit.l, true, cd_loop_uv_offset);
2150                         flush = 1;
2151                 }
2152                 else if (selectmode == UV_SELECT_FACE) {
2153                         /* select face */
2154                         uvedit_face_select_enable(scene, em, hit.efa, true, cd_loop_uv_offset);
2155                 }
2156
2157                 /* select sticky uvs */
2158                 if (sticky != SI_STICKY_DISABLE) {
2159                         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2160                                 if (!uvedit_face_visible_test(scene, ima, efa))
2161                                         continue;
2162                                 
2163                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2164                                         if (sticky == SI_STICKY_DISABLE) continue;
2165                                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
2166
2167                                         if (uv_sticky_select(limit, hitv, BM_elem_index_get(l->v), hituv, luv->uv, sticky, hitlen))
2168                                                 uvedit_uv_select_enable(em, scene, l, false, cd_loop_uv_offset);
2169
2170                                         flush = 1;
2171                                 }
2172                         }
2173                 }
2174         }
2175
2176         if (sync) {
2177                 /* flush for mesh selection */
2178
2179                 /* before bmesh */
2180 #if 0
2181                 if (ts->selectmode != SCE_SELECT_FACE) {
2182                         if (flush == 1) EDBM_select_flush(em);
2183                         else if (flush == -1) EDBM_deselect_flush(em);
2184                 }
2185 #else
2186                 if (flush != 0) {
2187                         if (loop) {
2188                                 /* push vertex -> edge selection */
2189                                 if (select) {
2190                                         EDBM_select_flush(em);
2191                                 }
2192                                 else {
2193                                         EDBM_deselect_flush(em);
2194                                 }
2195                         }
2196                         else {
2197                                 EDBM_selectmode_flush(em);
2198                         }
2199                 }
2200 #endif
2201         }
2202
2203         DEG_id_tag_update(obedit->data, 0);
2204         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2205
2206         return OPERATOR_PASS_THROUGH | OPERATOR_FINISHED;
2207 }
2208
2209 static int uv_select_exec(bContext *C, wmOperator *op)
2210 {
2211         float co[2];
2212         bool extend, loop;
2213
2214         RNA_float_get_array(op->ptr, "location", co);
2215         extend = RNA_boolean_get(op->ptr, "extend");
2216         loop = false;
2217
2218         return uv_mouse_select(C, co, extend, loop);
2219 }
2220
2221 static int uv_select_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2222 {
2223         ARegion *ar = CTX_wm_region(C);
2224         float co[2];
2225
2226         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &co[0], &co[1]);
2227         RNA_float_set_array(op->ptr, "location", co);
2228
2229         return uv_select_exec(C, op);
2230 }
2231
2232 static void UV_OT_select(wmOperatorType *ot)
2233 {
2234         /* identifiers */
2235         ot->name = "Select";
2236         ot->description = "Select UV vertices";
2237         ot->idname = "UV_OT_select";
2238         ot->flag = OPTYPE_UNDO;
2239         
2240         /* api callbacks */
2241         ot->exec = uv_select_exec;
2242         ot->invoke = uv_select_invoke;
2243         ot->poll = ED_operator_uvedit; /* requires space image */;
2244
2245         /* properties */
2246         RNA_def_boolean(ot->srna, "extend", 0,
2247                         "Extend", "Extend selection rather than clearing the existing selection");
2248         RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX,
2249                              "Location", "Mouse location in normalized coordinates, 0.0 to 1.0 is within the image bounds", -100.0f, 100.0f);
2250 }
2251
2252 /* ******************** loop select operator **************** */
2253
2254 static int uv_select_loop_exec(bContext *C, wmOperator *op)
2255 {
2256         float co[2];
2257         bool extend, loop;
2258
2259         RNA_float_get_array(op->ptr, "location", co);
2260         extend = RNA_boolean_get(op->ptr, "extend");
2261         loop = true;
2262
2263         return uv_mouse_select(C, co, extend, loop);
2264 }
2265
2266 static int uv_select_loop_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2267 {
2268         ARegion *ar = CTX_wm_region(C);
2269         float co[2];
2270
2271         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &co[0], &co[1]);
2272         RNA_float_set_array(op->ptr, "location", co);
2273
2274         return uv_select_loop_exec(C, op);
2275 }
2276
2277 static void UV_OT_select_loop(wmOperatorType *ot)
2278 {
2279         /* identifiers */
2280         ot->name = "Loop Select";
2281         ot->description = "Select a loop of connected UV vertices";
2282         ot->idname = "UV_OT_select_loop";
2283         ot->flag = OPTYPE_UNDO;
2284         
2285         /* api callbacks */
2286         ot->exec = uv_select_loop_exec;
2287         ot->invoke = uv_select_loop_invoke;
2288         ot->poll = ED_operator_uvedit; /* requires space image */;
2289
2290         /* properties */
2291         RNA_def_boolean(ot->srna, "extend", 0,
2292                         "Extend", "Extend selection rather than clearing the existing selection");
2293         RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX,
2294                              "Location", "Mouse location in normalized coordinates, 0.0 to 1.0 is within the image bounds", -100.0f, 100.0f);
2295 }
2296
2297 /* ******************** linked select operator **************** */
2298
2299 static int uv_select_linked_internal(bContext *C, wmOperator *op, const wmEvent *event, int pick)
2300 {
2301         SpaceImage *sima = CTX_wm_space_image(C);
2302         Scene *scene = CTX_data_scene(C);
2303         ToolSettings *ts = scene->toolsettings;
2304         Object *obedit = CTX_data_edit_object(C);
2305         Image *ima = CTX_data_edit_image(C);
2306         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2307         float limit[2];
2308         int extend;
2309         bool select_faces = (ts->uv_flag & UV_SYNC_SELECTION) && (ts->selectmode & SCE_SELECT_FACE);
2310
2311         NearestHit hit, *hit_p = NULL;
2312
2313         if ((ts->uv_flag & UV_SYNC_SELECTION) && !(ts->selectmode & SCE_SELECT_FACE)) {
2314                 BKE_report(op->reports, RPT_ERROR, "Select linked only works in face select mode when sync selection is enabled");
2315                 return OPERATOR_CANCELLED;
2316         }
2317
2318         extend = RNA_boolean_get(op->ptr, "extend");
2319         uvedit_pixel_to_float(sima, limit, 0.05f);
2320
2321         if (pick) {
2322                 float co[2];
2323
2324                 if (event) {
2325                         /* invoke */
2326                         ARegion *ar = CTX_wm_region(C);
2327
2328                         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &co[0], &co[1]);
2329                         RNA_float_set_array(op->ptr, "location", co);
2330                 }
2331                 else {
2332                         /* exec */
2333                         RNA_float_get_array(op->ptr, "location", co);
2334                 }
2335
2336                 uv_find_nearest_edge(scene, ima, em, co, &hit);
2337                 hit_p = &hit;
2338         }
2339
2340         uv_select_linked(scene, ima, em, limit, hit_p, extend, select_faces);
2341
2342         DEG_id_tag_update(obedit->data, 0);
2343         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2344
2345         return OPERATOR_FINISHED;
2346 }
2347
2348 static int uv_select_linked_exec(bContext *C, wmOperator *op)
2349 {
2350         return uv_select_linked_internal(C, op, NULL, 0);
2351 }
2352
2353 static void UV_OT_select_linked(wmOperatorType *ot)
2354 {
2355         /* identifiers */
2356         ot->name = "Select Linked";
2357         ot->description = "Select all UV vertices linked to the active UV map";
2358         ot->idname = "UV_OT_select_linked";
2359         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2360         
2361         /* api callbacks */
2362         ot->exec = uv_select_linked_exec;
2363         ot->poll = ED_operator_uvedit;    /* requires space image */
2364
2365         /* properties */
2366         RNA_def_boolean(ot->srna, "extend", 0,
2367                         "Extend", "Extend selection rather than clearing the existing selection");
2368 }
2369
2370 static int uv_select_linked_pick_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2371 {
2372         return uv_select_linked_internal(C, op, event, 1);
2373 }
2374
2375 static int uv_select_linked_pick_exec(bContext *C, wmOperator *op)
2376 {
2377         return uv_select_linked_internal(C, op, NULL, 1);
2378 }
2379
2380 static void UV_OT_select_linked_pick(wmOperatorType *ot)
2381 {
2382         /* identifiers */
2383         ot->name = "Select Linked Pick";
2384         ot->description = "Select all UV vertices linked under the mouse";
2385         ot->idname = "UV_OT_select_linked_pick";
2386         ot->flag = OPTYPE_UNDO;
2387
2388         /* api callbacks */
2389         ot->invoke = uv_select_linked_pick_invoke;
2390         ot->exec = uv_select_linked_pick_exec;
2391         ot->poll = ED_operator_uvedit; /* requires space image */;
2392
2393         /* properties */
2394         RNA_def_boolean(ot->srna, "extend", 0,
2395                         "Extend", "Extend selection rather than clearing the existing selection");
2396
2397         RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX,
2398                              "Location", "Mouse location in normalized coordinates, 0.0 to 1.0 is within the image bounds", -100.0f, 100.0f);
2399 }
2400
2401 /* note: this is based on similar use case to MESH_OT_split(), which has a similar effect
2402  * but in this case they are not joined to begin with (only having the behavior of being joined)
2403  * so its best to call this uv_select_split() instead of just split(), but assigned to the same key
2404  * as MESH_OT_split - Campbell */
2405 static int uv_select_split_exec(bContext *C, wmOperator *op)
2406 {
2407         Scene *scene = CTX_data_scene(C);
2408         ToolSettings *ts = scene->toolsettings;
2409         Image *ima = CTX_data_edit_image(C);
2410         Object *obedit = CTX_data_edit_object(C);
2411         BMesh *bm = BKE_editmesh_from_object(obedit)->bm;
2412
2413         BMFace *efa;
2414         BMLoop *l;
2415         BMIter iter, liter;
2416         MLoopUV *luv;
2417         bool changed = false;
2418
2419         const int cd_loop_uv_offset  = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
2420
2421         if (ts->uv_flag & UV_SYNC_SELECTION) {
2422                 BKE_report(op->reports, RPT_ERROR, "Cannot split selection when sync selection is enabled");
2423                 return OPERATOR_CANCELLED;
2424         }
2425
2426
2427
2428         BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
2429                 bool is_sel = false;
2430                 bool is_unsel = false;
2431
2432                 if (!uvedit_face_visible_test(scene, ima, efa))
2433                         continue;
2434
2435                 /* are we all selected? */
2436                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2437                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
2438
2439                         if (luv->flag & MLOOPUV_VERTSEL) {
2440                                 is_sel = true;
2441                         }
2442                         else {
2443                                 is_unsel = true;
2444                         }
2445
2446                         /* we have mixed selection, bail out */
2447                         if (is_sel && is_unsel) {
2448                                 break;
2449                         }
2450                 }
2451
2452                 if (is_sel && is_unsel) {
2453                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2454                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
2455                                 luv->flag &= ~MLOOPUV_VERTSEL;
2456                         }
2457
2458                         changed = true;
2459                 }
2460         }
2461
2462         if (changed) {
2463                 WM_event_add_notifier(C, NC_SPACE | ND_SPACE_IMAGE, NULL);
2464                 return OPERATOR_FINISHED;
2465         }
2466         else {
2467                 return OPERATOR_CANCELLED;
2468         }
2469 }
2470
2471
2472 static void UV_OT_select_split(wmOperatorType *ot)
2473 {
2474         /* identifiers */
2475         ot->name = "Select Split";
2476         ot->description = "Select only entirely selected faces";
2477         ot->idname = "UV_OT_select_split";
2478         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2479
2480         /* api callbacks */
2481         ot->exec = uv_select_split_exec;
2482         ot->poll = ED_operator_uvedit; /* requires space image */;
2483 }
2484
2485 static void uv_select_sync_flush(ToolSettings *ts, BMEditMesh *em, const short select)
2486 {
2487         /* bmesh API handles flushing but not on de-select */
2488         if (ts->uv_flag & UV_SYNC_SELECTION) {
2489                 if (ts->selectmode != SCE_SELECT_FACE) {
2490                         if (select == false) {
2491                                 EDBM_deselect_flush(em);
2492                         }
2493                         else {
2494                                 EDBM_select_flush(em);
2495                         }
2496                 }
2497
2498                 if (select == false) {
2499                         BM_select_history_validate(em->bm);
2500                 }
2501         }
2502 }
2503
2504
2505
2506 /* -------------------------------------------------------------------- */
2507 /* Utility functions to flush the uv-selection from tags */
2508
2509 /**
2510  * helper function for #uv_select_flush_from_tag_loop and uv_select_flush_from_tag_face
2511  */
2512 static void uv_select_flush_from_tag_sticky_loc_internal(Scene *scene, BMEditMesh *em, UvVertMap *vmap,
2513                                                          const unsigned int efa_index, BMLoop *l,
2514                                                          const bool select, const int cd_loop_uv_offset)
2515 {
2516         UvMapVert *start_vlist = NULL, *vlist_iter;
2517         BMFace *efa_vlist;
2518
2519         uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
2520
2521         vlist_iter = BM_uv_vert_map_at_index(vmap, BM_elem_index_get(l->v));
2522
2523         while (vlist_iter) {
2524                 if (vlist_iter->separate)
2525                         start_vlist = vlist_iter;
2526
2527                 if (efa_index == vlist_iter->f)
2528                         break;
2529
2530                 vlist_iter = vlist_iter->next;
2531         }
2532
2533         vlist_iter = start_vlist;
2534         while (vlist_iter) {
2535
2536                 if (vlist_iter != start_vlist && vlist_iter->separate)
2537                         break;
2538
2539                 if (efa_index != vlist_iter->f) {
2540                         BMLoop *l_other;
2541                         efa_vlist = BM_face_at_index(em->bm, vlist_iter->f);
2542                         /* tf_vlist = BM_ELEM_CD_GET_VOID_P(efa_vlist, cd_poly_tex_offset); */ /* UNUSED */
2543
2544                         l_other = BM_iter_at_index(em->bm, BM_LOOPS_OF_FACE, efa_vlist, vlist_iter->tfindex);
2545
2546                         uvedit_uv_select_set(em, scene, l_other, select, false, cd_loop_uv_offset);
2547                 }
2548                 vlist_iter = vlist_iter->next;
2549         }
2550 }
2551
2552 /**
2553  * Flush the selection from face tags based on sticky and selection modes.
2554  *
2555  * needed because settings the selection a face is done in a number of places but it also needs to respect
2556  * the sticky modes for the UV verts, so dealing with the sticky modes is best done in a separate function.
2557  *
2558  * \note! This function is very similar to #uv_select_flush_from_tag_loop, be sure to update both upon changing.
2559  */
2560 static void uv_select_flush_from_tag_face(SpaceImage *sima, Scene *scene, Object *obedit, const bool select)
2561 {
2562         /* Selecting UV Faces with some modes requires us to change 
2563          * the selection in other faces (depending on the sticky mode).
2564          * 
2565          * This only needs to be done when the Mesh is not used for
2566          * selection (so for sticky modes, vertex or location based). */
2567         
2568         ToolSettings *ts = scene->toolsettings;
2569         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2570         BMFace *efa;
2571         BMLoop *l;
2572         BMIter iter, liter;
2573         const int cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
2574         
2575         if ((ts->uv_flag & UV_SYNC_SELECTION) == 0 && sima->sticky == SI_STICKY_VERTEX) {
2576                 /* Tag all verts as untouched, then touch the ones that have a face center
2577                  * in the loop and select all MLoopUV's that use a touched vert. */
2578                 BMVert *eve;
2579                 
2580                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2581                         BM_elem_flag_disable(eve, BM_ELEM_TAG);
2582                 }
2583                 
2584                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2585                         if (BM_elem_flag_test(efa, BM_ELEM_TAG)) {
2586                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2587                                         BM_elem_flag_enable(l->v, BM_ELEM_TAG);
2588                                 }
2589                         }
2590                 }
2591
2592                 /* now select tagged verts */
2593                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2594                         /* tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset); */ /* UNUSED */
2595
2596                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2597                                 if (BM_elem_flag_test(l->v, BM_ELEM_TAG)) {
2598                                         uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
2599                                 }
2600                         }
2601                 }
2602         }
2603         else if ((ts->uv_flag & UV_SYNC_SELECTION) == 0 && sima->sticky == SI_STICKY_LOC) {
2604                 struct UvVertMap *vmap;
2605                 float limit[2];
2606                 unsigned int efa_index;
2607                 
2608                 uvedit_pixel_to_float(sima, limit, 0.05);
2609                 
2610                 BM_mesh_elem_table_ensure(em->bm, BM_FACE);
2611                 vmap = BM_uv_vert_map_create(em->bm, limit, false, false);
2612                 if (vmap == NULL) {
2613                         return;
2614                 }
2615                 
2616                 BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, efa_index) {
2617                         if (BM_elem_flag_test(efa, BM_ELEM_TAG)) {
2618                                 /* tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset); */ /* UNUSED */
2619                                 
2620                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2621                                         uv_select_flush_from_tag_sticky_loc_internal(scene, em, vmap, efa_index, l,
2622                                                                                      select, cd_loop_uv_offset);
2623                                 }
2624                         }
2625                 }
2626                 BM_uv_vert_map_free(vmap);
2627                 
2628         }
2629         else { /* SI_STICKY_DISABLE or ts->uv_flag & UV_SYNC_SELECTION */
2630                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2631                         if (BM_elem_flag_test(efa, BM_ELEM_TAG)) {
2632                                 uvedit_face_select_set(scene, em, efa, select, false, cd_loop_uv_offset);
2633                         }
2634                 }
2635         }
2636 }
2637
2638
2639
2640 /**
2641  * Flush the selection from loop tags based on sticky and selection modes.
2642  *
2643  * needed because settings the selection a face is done in a number of places but it also needs to respect
2644  * the sticky modes for the UV verts, so dealing with the sticky modes is best done in a separate function.
2645  *
2646  * \note! This function is very similar to #uv_select_flush_from_tag_loop, be sure to update both upon changing.
2647  */
2648 static void uv_select_flush_from_tag_loop(SpaceImage *sima, Scene *scene, Object *obedit, const bool select)
2649 {
2650         /* Selecting UV Loops with some modes requires us to change
2651          * the selection in other faces (depending on the sticky mode).
2652          *
2653          * This only needs to be done when the Mesh is not used for
2654          * selection (so for sticky modes, vertex or location based). */
2655
2656         ToolSettings *ts = scene->toolsettings;
2657         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2658         BMFace *efa;
2659         BMLoop *l;
2660         BMIter iter, liter;
2661
2662         const int cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
2663
2664
2665         if ((ts->uv_flag & UV_SYNC_SELECTION) == 0 && sima->sticky == SI_STICKY_VERTEX) {
2666                 /* Tag all verts as untouched, then touch the ones that have a face center
2667                  * in the loop and select all MLoopUV's that use a touched vert. */
2668                 BMVert *eve;
2669
2670                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2671                         BM_elem_flag_disable(eve, BM_ELEM_TAG);
2672                 }
2673
2674                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2675                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2676                                 if (BM_elem_flag_test(l, BM_ELEM_TAG)) {
2677                                         BM_elem_flag_enable(l->v, BM_ELEM_TAG);
2678                                 }
2679                         }
2680                 }
2681
2682                 /* now select tagged verts */
2683                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2684                         /* tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset); */ /* UNUSED */
2685
2686                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2687                                 if (BM_elem_flag_test(l->v, BM_ELEM_TAG)) {
2688                                         uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
2689                                 }
2690                         }
2691                 }
2692         }
2693         else if ((ts->uv_flag & UV_SYNC_SELECTION) == 0 && sima->sticky == SI_STICKY_LOC) {
2694                 struct UvVertMap *vmap;
2695                 float limit[2];
2696                 unsigned int efa_index;
2697
2698                 uvedit_pixel_to_float(sima, limit, 0.05);
2699
2700                 BM_mesh_elem_table_ensure(em->bm, BM_FACE);
2701                 vmap = BM_uv_vert_map_create(em->bm, limit, false, false);
2702                 if (vmap == NULL) {
2703                         return;
2704                 }
2705
2706                 BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, efa_index) {
2707                         /* tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset); */ /* UNUSED */
2708
2709                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2710                                 if (BM_elem_flag_test(l, BM_ELEM_TAG)) {
2711                                         uv_select_flush_from_tag_sticky_loc_internal(scene, em, vmap, efa_index, l,
2712                                                                                      select, cd_loop_uv_offset);
2713                                 }
2714                         }
2715                 }
2716                 BM_uv_vert_map_free(vmap);
2717
2718         }
2719         else { /* SI_STICKY_DISABLE or ts->uv_flag & UV_SYNC_SELECTION */
2720                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2721                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2722                                 if (BM_elem_flag_test(l, BM_ELEM_TAG)) {
2723                                         uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
2724                                 }
2725                         }
2726                 }
2727         }
2728 }
2729
2730 /* ******************** border select operator **************** */
2731
2732 static int uv_border_select_exec(bContext *C, wmOperator *op)
2733 {
2734         SpaceImage *sima = CTX_wm_space_image(C);
2735         Scene *scene = CTX_data_scene(C);
2736         ToolSettings *ts = scene->toolsettings;
2737         Object *obedit = CTX_data_edit_object(C);
2738         Image *ima = CTX_data_edit_image(C);
2739         ARegion *ar = CTX_wm_region(C);
2740         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2741         BMFace *efa;
2742         BMLoop *l;
2743         BMIter iter, liter;
2744         MLoopUV *luv;
2745         rctf rectf;
2746         bool changed, pinned, select, extend;
2747         const bool use_face_center = (ts->uv_flag & UV_SYNC_SELECTION) ?
2748                                     (ts->selectmode == SCE_SELECT_FACE) :
2749                                     (ts->uv_selectmode == UV_SELECT_FACE);
2750
2751         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
2752
2753         /* get rectangle from operator */
2754         WM_operator_properties_border_to_rctf(op, &rectf);
2755         UI_view2d_region_to_view_rctf(&ar->v2d, &rectf, &rectf);
2756
2757         /* figure out what to select/deselect */
2758         select = (RNA_int_get(op->ptr, "gesture_mode") == GESTURE_MODAL_SELECT);
2759         pinned = RNA_boolean_get(op->ptr, "pinned");
2760         extend = RNA_boolean_get(op->ptr, "extend");
2761
2762         if (!extend)
2763                 uv_select_all_perform(scene, ima, em, SEL_DESELECT);
2764
2765         /* do actual selection */
2766         if (use_face_center && !pinned) {
2767                 /* handle face selection mode */
2768                 float cent[2];
2769
2770                 changed = false;
2771
2772                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2773                         /* assume not touched */
2774                         BM_elem_flag_disable(efa, BM_ELEM_TAG);
2775
2776                         if (uvedit_face_visible_test(scene, ima, efa)) {
2777                                 uv_poly_center(efa, cent, cd_loop_uv_offset);
2778                                 if (BLI_rctf_isect_pt_v(&rectf, cent)) {
2779                                         BM_elem_flag_enable(efa, BM_ELEM_TAG);
2780                                         changed = true;
2781                                 }
2782                         }
2783                 }
2784
2785                 /* (de)selects all tagged faces and deals with sticky modes */
2786                 if (changed) {
2787                         uv_select_flush_from_tag_face(sima, scene, obedit, select);
2788                 }
2789         }
2790         else {
2791                 /* other selection modes */
2792                 changed = true;
2793                 
2794                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2795                         if (!uvedit_face_visible_test(scene, ima, efa))
2796                                 continue;
2797                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2798                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
2799
2800                                 if (!pinned || (ts->uv_flag & UV_SYNC_SELECTION)) {
2801
2802                                         /* UV_SYNC_SELECTION - can't do pinned selection */
2803                                         if (BLI_rctf_isect_pt_v(&rectf, luv->uv)) {
2804                                                 uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
2805                                         }
2806                                 }
2807                                 else if (pinned) {
2808                                         if ((luv->flag & MLOOPUV_PINNED) && BLI_rctf_isect_pt_v(&rectf, luv->uv)) {
2809                                                 uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
2810                                         }
2811                                 }
2812                         }
2813                 }
2814         }
2815
2816         if (changed) {
2817                 uv_select_sync_flush(ts, em, select);
2818
2819                 if (ts->uv_flag & UV_SYNC_SELECTION) {
2820                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2821                 }
2822                 
2823                 return OPERATOR_FINISHED;
2824         }
2825
2826         return OPERATOR_CANCELLED;
2827
2828
2829 static void UV_OT_select_border(wmOperatorType *ot)
2830 {
2831         /* identifiers */
2832         ot->name = "Border Select";
2833         ot->description = "Select UV vertices using border selection";
2834         ot->idname = "UV_OT_select_border";
2835         
2836         /* api callbacks */
2837         ot->invoke = WM_border_select_invoke;
2838         ot->exec = uv_border_select_exec;
2839         ot->modal = WM_border_select_modal;
2840         ot->poll = ED_operator_uvedit_space_image; /* requires space image */;
2841         ot->cancel = WM_border_select_cancel;
2842         
2843         /* flags */
2844         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2845         
2846         /* properties */
2847         RNA_def_boolean(ot->srna, "pinned", 0, "Pinned", "Border select pinned UVs only");
2848
2849         WM_operator_properties_gesture_border(ot, true);
2850 }
2851
2852 /* ******************** circle select operator **************** */
2853
2854 static int uv_inside_circle(const float uv[2], const float offset[2], const float ellipse[2])
2855 {
2856         /* normalized ellipse: ell[0] = scaleX, ell[1] = scaleY */
2857         float x, y;
2858         x = (uv[0] - offset[0]) * ellipse[0];
2859         y = (uv[1] - offset[1]) * ellipse[1];
2860         return ((x * x + y * y) < 1.0f);
2861 }
2862
2863 static bool uv_select_inside_ellipse(BMEditMesh *em, Scene *scene, const bool select,
2864                                      const float offset[2], const float ellipse[2], BMLoop *l, MLoopUV *luv,
2865                                      const int cd_loop_uv_offset)
2866 {
2867         if (uv_inside_circle(luv->uv, offset, ellipse)) {
2868                 uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
2869                 return true;
2870         }
2871         else {
2872                 return false;
2873         }
2874 }
2875
2876 static int uv_circle_select_exec(bContext *C, wmOperator *op)
2877 {
2878         SpaceImage *sima = CTX_wm_space_image(C);
2879         Scene *scene = CTX_data_scene(C);
2880         ToolSettings *ts = scene->toolsettings;
2881         Object *obedit = CTX_data_edit_object(C);
2882         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2883         ARegion *ar = CTX_wm_region(C);
2884         BMFace *efa;
2885         BMLoop *l;
2886         BMIter iter, liter;
2887         MLoopUV *luv;
2888         int x, y, radius, width, height;
2889         float zoomx, zoomy, offset[2], ellipse[2];
2890         int gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
2891         const bool select = (gesture_mode == GESTURE_MODAL_SELECT);
2892         bool changed = false;
2893         const bool use_face_center = (ts->uv_flag & UV_SYNC_SELECTION) ?
2894                                      (ts->selectmode == SCE_SELECT_FACE) :
2895                                      (ts->uv_selectmode == UV_SELECT_FACE);
2896
2897         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
2898
2899         /* get operator properties */
2900         x = RNA_int_get(op->ptr, "x");
2901         y = RNA_int_get(op->ptr, "y");
2902         radius = RNA_int_get(op->ptr, "radius");
2903
2904         /* compute ellipse size and location, not a circle since we deal
2905          * with non square image. ellipse is normalized, r = 1.0. */
2906         ED_space_image_get_size(sima, &width, &height);
2907         ED_space_image_get_zoom(sima, ar, &zoomx, &zoomy);
2908
2909         ellipse[0] = width * zoomx / radius;
2910         ellipse[1] = height * zoomy / radius;
2911
2912         UI_view2d_region_to_view(&ar->v2d, x, y, &offset[0], &offset[1]);
2913         
2914         /* do selection */
2915         if (use_face_center) {
2916                 changed = false;
2917                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2918                         BM_elem_flag_disable(efa, BM_ELEM_TAG);
2919                         /* assume not touched */
2920                         if (select != uvedit_face_select_test(scene, efa, cd_loop_uv_offset)) {
2921                                 float cent[2];
2922                                 uv_poly_center(efa, cent, cd_loop_uv_offset);
2923                                 if (uv_inside_circle(cent, offset, ellipse)) {
2924                                         BM_elem_flag_enable(efa, BM_ELEM_TAG);
2925                                         changed = true;
2926                                 }
2927                         }
2928                 }
2929
2930                 /* (de)selects all tagged faces and deals with sticky modes */
2931                 if (changed) {
2932                         uv_select_flush_from_tag_face(sima, scene, obedit, select);
2933                 }
2934         }
2935         else {
2936                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2937                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2938                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
2939                                 changed |= uv_select_inside_ellipse(em, scene, select, offset, ellipse, l, luv, cd_loop_uv_offset);
2940                         }
2941                 }
2942         }
2943
2944         if (changed) {
2945                 uv_select_sync_flush(ts, em, select);
2946
2947                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2948         }
2949
2950         return OPERATOR_FINISHED;
2951 }
2952
2953 static void UV_OT_circle_select(wmOperatorType *ot)
2954 {
2955         /* identifiers */
2956         ot->name = "Circle Select";
2957         ot->description = "Select UV vertices using circle selection";
2958         ot->idname = "UV_OT_circle_select";
2959         
2960         /* api callbacks */
2961         ot->invoke = WM_gesture_circle_invoke;
2962         ot->modal = WM_gesture_circle_modal;
2963         ot->exec = uv_circle_select_exec;
2964         ot->poll = ED_operator_uvedit_space_image; /* requires space image */;
2965         ot->cancel = WM_gesture_circle_cancel;
2966         
2967         /* flags */
2968         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2969         
2970         /* properties */
2971         RNA_def_int(ot->srna, "x", 0, INT_MIN, INT_MAX, "X", "", INT_MIN, INT_MAX);
2972         RNA_def_int(ot->srna, "y", 0, INT_MIN, INT_MAX, "Y", "", INT_MIN, INT_MAX);
2973         RNA_def_int(ot->srna, "radius", 1, 1, INT_MAX, "Radius", "", 1, INT_MAX);
2974         RNA_def_int(ot->srna, "gesture_mode", 0, INT_MIN, INT_MAX, "Gesture Mode", "", INT_MIN, INT_MAX);
2975 }
2976
2977
2978 /* ******************** lasso select operator **************** */
2979
2980 static bool do_lasso_select_mesh_uv(bContext *C, const int mcords[][2], short moves,
2981                                     const bool select, const bool extend)
2982 {
2983         SpaceImage *sima = CTX_wm_space_image(C);
2984         Image *ima = CTX_data_edit_image(C);
2985         ARegion *ar = CTX_wm_region(C);
2986         Object *obedit = CTX_data_edit_object(C);
2987         Scene *scene = CTX_data_scene(C);
2988         ToolSettings *ts = scene->toolsettings;
2989         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2990         const bool use_face_center = (
2991                 (ts->uv_flag & UV_SYNC_SELECTION) ?
2992                 (ts->selectmode == SCE_SELECT_FACE) :
2993                 (ts->uv_selectmode == UV_SELECT_FACE));
2994
2995         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
2996
2997         BMIter iter, liter;
2998
2999         BMFace *efa;
3000         BMLoop *l;
3001         int screen_uv[2];
3002         bool changed = false;
3003         rcti rect;
3004
3005         BLI_lasso_boundbox(&rect, mcords, moves);
3006
3007         if (!extend && select) {
3008                 uv_select_all_perform(scene, ima, em, SEL_DESELECT);
3009         }
3010
3011         if (use_face_center) { /* Face Center Sel */
3012                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
3013                         BM_elem_flag_disable(efa, BM_ELEM_TAG);
3014                         /* assume not touched */
3015                         if (select != uvedit_face_select_test(scene, efa, cd_loop_uv_offset)) {
3016                                 float cent[2];
3017                                 uv_poly_center(efa, cent, cd_loop_uv_offset);
3018
3019                                 if (UI_view2d_view_to_region_clip(&ar->v2d, cent[0], cent[1], &screen_uv[0], &screen_uv[1]) &&
3020                                     BLI_rcti_isect_pt_v(&rect, screen_uv) &&
3021                                     BLI_lasso_is_point_inside(mcords, moves, screen_uv[0], screen_uv[1], V2D_IS_CLIPPED))
3022                                 {
3023                                         BM_elem_flag_enable(efa, BM_ELEM_TAG);
3024                                         changed = true;
3025                                 }
3026                         }
3027                 }
3028
3029                 /* (de)selects all tagged faces and deals with sticky modes */
3030                 if (changed) {
3031                         uv_select_flush_from_tag_face(sima, scene, obedit, select);
3032                 }
3033         }
3034         else { /* Vert Sel */
3035                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
3036                         if (uvedit_face_visible_test(scene, ima, efa)) {
3037                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
3038                                         if ((select) != (uvedit_uv_select_test(scene, l, cd_loop_uv_offset))) {
3039                                                 MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
3040                                                 if (UI_view2d_view_to_region_clip(&ar->v2d,
3041                                                                                   luv->uv[0], luv->uv[1],
3042                                                                                   &screen_uv[0], &screen_uv[1]) &&
3043                                                     BLI_rcti_isect_pt_v(&rect, screen_uv) &&
3044                                                     BLI_lasso_is_point_inside(mcords, moves, screen_uv[0], screen_uv[1], V2D_IS_CLIPPED))
3045                                                 {
3046                                                         uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
3047                                                         changed = true;
3048                                                 }
3049                                         }
3050                                 }
3051                         }
3052                 }
3053         }
3054
3055         if (changed) {
3056                 uv_select_sync_flush(scene->toolsettings, em, select);
3057
3058                 if (ts->uv_flag & UV_SYNC_SELECTION) {
3059                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
3060                 }
3061         }
3062
3063         return changed;
3064 }
3065
3066 static int uv_lasso_select_exec(bContext *C, wmOperator *op)
3067 {
3068         int mcords_tot;
3069         const int (*mcords)[2] = WM_gesture_lasso_path_to_array(C, op, &mcords_tot);
3070
3071         if (mcords) {
3072                 bool select, extend;
3073                 bool changed;
3074
3075                 select = !RNA_boolean_get(op->ptr, "deselect");
3076                 extend = RNA_boolean_get(op->ptr, "extend");
3077                 changed = do_lasso_select_mesh_uv(C, mcords, mcords_tot, select, extend);
3078
3079                 MEM_freeN((void *)mcords);
3080
3081                 return changed ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
3082         }
3083
3084         return OPERATOR_PASS_THROUGH;
3085 }
3086
3087 static void UV_OT_select_lasso(wmOperatorType *ot)
3088 {
3089         ot->name = "Lasso Select UV";
3090         ot->description = "Select UVs using lasso selection";
3091         ot->idname = "UV_OT_select_lasso";
3092
3093         ot->invoke = WM_gesture_lasso_invoke;
3094         ot->modal = WM_gesture_lasso_modal;
3095         ot->exec = uv_lasso_select_exec;
3096         ot->poll = ED_operator_uvedit_space_image;
3097         ot->cancel = WM_gesture_lasso_cancel;
3098
3099         /* flags */
3100         ot->flag = OPTYPE_UNDO;
3101
3102         RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
3103         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Deselect rather than select items");
3104         RNA_def_boolean(ot->srna, "extend", 1, "Extend", "Extend selection instead of deselecting everything first");
3105 }
3106
3107
3108
3109 /* ******************** snap cursor operator **************** */
3110
3111 static void uv_snap_to_pixel(float uvco[2], float w, float h)
3112 {
3113         uvco[0] = roundf(uvco[0] * w) / w;
3114         uvco[1] = roundf(uvco[1]&n