=bmesh= merge from trunk at r36529
[blender.git] / source / blender / editors / uvedit / uvedit_unwrap_ops.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /** \file blender/editors/uvedit/uvedit_unwrap_ops.c
31  *  \ingroup eduv
32  */
33
34
35 #include <string.h>
36 #include <stdlib.h>
37 #include <math.h>
38
39 #include "MEM_guardedalloc.h"
40
41 #include "DNA_camera_types.h"
42 #include "DNA_meshdata_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_scene_types.h"
45
46 #include "BLI_math.h"
47 #include "BLI_edgehash.h"
48 #include "BLI_editVert.h"
49 #include "BLI_uvproject.h"
50 #include "BLI_utildefines.h"
51 #include "BLI_rand.h"
52
53 #include "BKE_context.h"
54 #include "BKE_customdata.h"
55 #include "BKE_depsgraph.h"
56 #include "BKE_image.h"
57 #include "BKE_mesh.h"
58 #include "BKE_tessmesh.h"
59
60 #include "BLI_math.h"
61 #include "BLI_edgehash.h"
62 #include "BLI_editVert.h"
63 #include "BLI_scanfill.h"
64 #include "BLI_array.h"
65 #include "BLI_uvproject.h"
66
67 #include "PIL_time.h"
68
69 #include "ED_image.h"
70 #include "ED_mesh.h"
71 #include "ED_screen.h"
72 #include "ED_uvedit.h"
73 #include "ED_view3d.h"
74
75 #include "RNA_access.h"
76 #include "RNA_define.h"
77
78
79 #include "WM_api.h"
80 #include "WM_types.h"
81
82 #include "uvedit_intern.h"
83 #include "uvedit_parametrizer.h"
84
85 static int ED_uvedit_ensure_uvs(bContext *C, Scene *scene, Object *obedit)
86 {
87         BMEditMesh *em= ((Mesh*)obedit->data)->edit_btmesh;
88         BMFace *efa;
89         BMIter iter;
90         Image *ima;
91         bScreen *sc;
92         ScrArea *sa;
93         SpaceLink *slink;
94         SpaceImage *sima;
95
96         if(ED_uvedit_test(obedit)) {
97                 return 1;
98         }
99
100         if(em && em->bm->totface && !CustomData_has_layer(&em->bm->pdata, CD_MTEXPOLY)) {
101                 BM_add_data_layer(em->bm, &em->bm->pdata, CD_MTEXPOLY);
102                 BM_add_data_layer(em->bm, &em->bm->ldata, CD_MLOOPUV);
103         }
104
105         if(!ED_uvedit_test(obedit)) {
106                 return 0;
107         }
108
109         ima= CTX_data_edit_image(C);
110
111         if(!ima) {
112                 /* no image in context in the 3d view, we find first image window .. */
113                 sc= CTX_wm_screen(C);
114
115                 for(sa=sc->areabase.first; sa; sa=sa->next) {
116                         slink= sa->spacedata.first;
117                         if(slink->spacetype == SPACE_IMAGE) {
118                                 sima= (SpaceImage*)slink;
119
120                                 ima= sima->image;
121                                 if(ima) {
122                                         if(ima->type==IMA_TYPE_R_RESULT || ima->type==IMA_TYPE_COMPOSITE)
123                                                 ima= NULL;
124                                         else
125                                                 break;
126                                 }
127                         }
128                 }
129         }
130         
131         if(ima)
132                 ED_uvedit_assign_image(scene, obedit, ima, NULL);
133         
134         /* select new UV's */
135         BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
136                 uvedit_face_select(scene, em, efa);
137         }
138
139         return 1;
140 }
141
142 /****************** Parametrizer Conversion ***************/
143
144 static ParamHandle *construct_param_handle(Scene *scene, BMEditMesh *em, 
145                                     short implicit, short fill, short sel, 
146                                     short correct_aspect)
147 {
148         ParamHandle *handle;
149         BMFace *efa;
150         BMLoop *l;
151         BMEdge *eed;
152         BMVert *ev;
153         BMIter iter, liter;
154         MTexPoly *tf;
155         int a;
156         
157         handle = param_construct_begin();
158
159         if(correct_aspect) {
160                 efa = EDBM_get_actFace(em, 1);
161
162                 if(efa) {
163                         MTexPoly *tf= CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
164                         float aspx, aspy;
165
166                         ED_image_uv_aspect(tf->tpage, &aspx, &aspy);
167                 
168                         if(aspx!=aspy)
169                                 param_aspect_ratio(handle, aspx, aspy);
170                 }
171         }
172         
173         /* we need the vert indices */
174         a = 0;
175         BM_ITER(ev, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
176                 BMINDEX_SET(ev, a);
177                 a++;
178         }
179         
180         BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
181                 EditVert *v, *lastv, *firstv;
182                 EditFace *sefa;
183                 ParamKey key, vkeys[4];
184                 ParamBool pin[4], select[4];
185                 BMLoop *ls[3];
186                 MLoopUV *luvs[3];
187                 float *co[4];
188                 float *uv[4];
189                 int lsel;
190                 
191                 if(scene->toolsettings->uv_flag & UV_SYNC_SELECTION) {
192                         if(BM_TestHFlag(efa, BM_HIDDEN)) {
193                                 continue;
194                         }
195                 }
196                 else {
197                         if((BM_TestHFlag(efa, BM_HIDDEN)) || (sel && BM_TestHFlag(efa, BM_SELECT)==0)) 
198                                 continue;
199                 }
200
201                 tf= (MTexPoly *)CustomData_em_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
202                 lsel = 0;
203
204                 BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
205                         if (uvedit_uv_selected(em, scene, l)) {
206                                 lsel = 1;
207                                 break;
208                         }
209                 }
210
211                 if (implicit && !lsel)
212                         continue;
213
214                 key = (ParamKey)efa;
215
216                 /*scanfill time!*/
217                 BLI_begin_edgefill();
218                 
219                 firstv = lastv = NULL;
220                 BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
221                         int i;
222                         
223                         v = BLI_addfillvert(l->v->co);
224                         
225                         /*add small random offset*/
226                         for (i=0; i<3; i++) {
227                                 v->co[i] += (BLI_drand()-0.5f)*FLT_EPSILON*50;
228                         }
229                         
230                         v->tmp.p = l;
231
232                         if (lastv) {
233                                 BLI_addfilledge(lastv, v);
234                         }
235
236                         lastv = v;
237                         if (!firstv) 
238                                 firstv = v;
239                 }
240
241                 BLI_addfilledge(firstv, v);
242                 
243                 /*mode 2 enables faster handling of tri/quads*/
244                 BLI_edgefill(2);
245                 for (sefa = fillfacebase.first; sefa; sefa=sefa->next) {
246                         ls[0] = sefa->v1->tmp.p;
247                         ls[1] = sefa->v2->tmp.p;
248                         ls[2] = sefa->v3->tmp.p;
249                         
250                         luvs[0] = CustomData_bmesh_get(&em->bm->ldata, ls[0]->head.data, CD_MLOOPUV);
251                         luvs[1] = CustomData_bmesh_get(&em->bm->ldata, ls[1]->head.data, CD_MLOOPUV);
252                         luvs[2] = CustomData_bmesh_get(&em->bm->ldata, ls[2]->head.data, CD_MLOOPUV);
253
254                         vkeys[0] = (ParamKey)BMINDEX_GET(ls[0]->v);
255                         vkeys[1] = (ParamKey)BMINDEX_GET(ls[1]->v);
256                         vkeys[2] = (ParamKey)BMINDEX_GET(ls[2]->v);
257
258                         co[0] = ls[0]->v->co;
259                         co[1] = ls[1]->v->co;
260                         co[2] = ls[2]->v->co;
261
262                         uv[0] = luvs[0]->uv;
263                         uv[1] = luvs[1]->uv;
264                         uv[2] = luvs[2]->uv;
265
266                         pin[0] = (luvs[0]->flag & MLOOPUV_PINNED) != 0;
267                         pin[1] = (luvs[1]->flag & MLOOPUV_PINNED) != 0;
268                         pin[2] = (luvs[2]->flag & MLOOPUV_PINNED) != 0;
269
270                         select[0] = uvedit_uv_selected(em, scene, ls[0]) != 0;
271                         select[1] = uvedit_uv_selected(em, scene, ls[1]) != 0;
272                         select[2] = uvedit_uv_selected(em, scene, ls[2]) != 0;
273
274                         if (!p_face_exists(handle,vkeys,0,1,2))
275                                         param_face_add(handle, key, 3, vkeys, co, uv, pin, select);
276                 }
277
278                 BLI_end_edgefill();
279         }
280
281         if(!implicit) {
282                 BM_ITER(eed, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
283                         if(BM_TestHFlag(eed, BM_SEAM)) {
284                                 ParamKey vkeys[2];
285                                 vkeys[0] = (ParamKey)BMINDEX_GET(eed->v1);
286                                 vkeys[1] = (ParamKey)BMINDEX_GET(eed->v2);
287                                 param_edge_set_seam(handle, vkeys);
288                         }
289                 }
290         }
291
292         param_construct_end(handle, fill, implicit);
293
294         return handle;
295 }
296
297 /* ******************** Minimize Stretch operator **************** */
298
299 typedef struct MinStretch {
300         Scene *scene;
301         Object *obedit;
302         BMEditMesh *em;
303         ParamHandle *handle;
304         float blend;
305         double lasttime;
306         int i, iterations;
307         wmTimer *timer;
308 } MinStretch;
309
310 static void minimize_stretch_init(bContext *C, wmOperator *op)
311 {
312         Scene *scene= CTX_data_scene(C);
313         Object *obedit= CTX_data_edit_object(C);
314         BMEditMesh *em= ((Mesh*)obedit->data)->edit_btmesh;
315         MinStretch *ms;
316         int fill_holes= RNA_boolean_get(op->ptr, "fill_holes");
317
318         ms= MEM_callocN(sizeof(MinStretch), "MinStretch");
319         ms->scene= scene;
320         ms->obedit= obedit;
321         ms->em= em;
322         ms->blend= RNA_float_get(op->ptr, "blend");
323         ms->iterations= RNA_int_get(op->ptr, "iterations");
324         ms->handle= construct_param_handle(scene, em, 1, fill_holes, 1, 1);
325         ms->lasttime= PIL_check_seconds_timer();
326
327         param_stretch_begin(ms->handle);
328         if(ms->blend != 0.0f)
329                 param_stretch_blend(ms->handle, ms->blend);
330
331         op->customdata= ms;
332 }
333
334 static void minimize_stretch_iteration(bContext *C, wmOperator *op, int interactive)
335 {
336         MinStretch *ms= op->customdata;
337         ScrArea *sa= CTX_wm_area(C);
338
339         param_stretch_blend(ms->handle, ms->blend);
340         param_stretch_iter(ms->handle);
341
342         if(interactive && (PIL_check_seconds_timer() - ms->lasttime > 0.5)) {
343                 char str[100];
344
345                 param_flush(ms->handle);
346
347                 if(sa) {
348                         sprintf(str, "Minimize Stretch. Blend %.2f.", ms->blend);
349                         ED_area_headerprint(sa, str);
350                 }
351
352                 ms->lasttime = PIL_check_seconds_timer();
353
354                 DAG_id_tag_update(ms->obedit->data, 0);
355                 WM_event_add_notifier(C, NC_GEOM|ND_DATA, ms->obedit->data);
356         }
357 }
358
359 static void minimize_stretch_exit(bContext *C, wmOperator *op, int cancel)
360 {
361         MinStretch *ms= op->customdata;
362         ScrArea *sa= CTX_wm_area(C);
363
364         if(sa)
365                 ED_area_headerprint(sa, NULL);
366         if(ms->timer)
367                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), ms->timer);
368
369         if(cancel)
370                 param_flush_restore(ms->handle);
371         else
372                 param_flush(ms->handle);
373
374         param_stretch_end(ms->handle);
375         param_delete(ms->handle);
376
377         DAG_id_tag_update(ms->obedit->data, 0);
378         WM_event_add_notifier(C, NC_GEOM|ND_DATA, ms->obedit->data);
379
380         MEM_freeN(ms);
381         op->customdata= NULL;
382 }
383
384 static int minimize_stretch_exec(bContext *C, wmOperator *op)
385 {
386         int i, iterations;
387
388         minimize_stretch_init(C, op);
389
390         iterations= RNA_int_get(op->ptr, "iterations");
391         for(i=0; i<iterations; i++)
392                 minimize_stretch_iteration(C, op, 0);
393         minimize_stretch_exit(C, op, 0);
394
395         return OPERATOR_FINISHED;
396 }
397
398 static int minimize_stretch_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
399 {
400         MinStretch *ms;
401
402         minimize_stretch_init(C, op);
403         minimize_stretch_iteration(C, op, 1);
404
405         ms= op->customdata;
406         WM_event_add_modal_handler(C, op);
407         ms->timer= WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.01f);
408
409         return OPERATOR_RUNNING_MODAL;
410 }
411
412 static int minimize_stretch_modal(bContext *C, wmOperator *op, wmEvent *event)
413 {
414         MinStretch *ms= op->customdata;
415
416         switch(event->type) {
417                 case ESCKEY:
418                 case RIGHTMOUSE:
419                         minimize_stretch_exit(C, op, 1);
420                         return OPERATOR_CANCELLED;
421                 case RETKEY:
422                 case PADENTER:
423                 case LEFTMOUSE:
424                         minimize_stretch_exit(C, op, 0);
425                         return OPERATOR_FINISHED;
426                 case PADPLUSKEY:
427                 case WHEELUPMOUSE:
428                         if(ms->blend < 0.95f) {
429                                 ms->blend += 0.1f;
430                                 ms->lasttime= 0.0f;
431                                 RNA_float_set(op->ptr, "blend", ms->blend);
432                                 minimize_stretch_iteration(C, op, 1);
433                         }
434                         break;
435                 case PADMINUS:
436                 case WHEELDOWNMOUSE:
437                         if(ms->blend > 0.05f) {
438                                 ms->blend -= 0.1f;
439                                 ms->lasttime= 0.0f;
440                                 RNA_float_set(op->ptr, "blend", ms->blend);
441                                 minimize_stretch_iteration(C, op, 1);
442                         }
443                         break;
444                 case TIMER:
445                         if(ms->timer == event->customdata) {
446                                 double start= PIL_check_seconds_timer();
447
448                                 do {
449                                         minimize_stretch_iteration(C, op, 1);
450                                 } while(PIL_check_seconds_timer() - start < 0.01);
451                         }
452                         break;
453         }
454
455         if(ms->iterations && ms->i >= ms->iterations) {
456                 minimize_stretch_exit(C, op, 0);
457                 return OPERATOR_FINISHED;
458         }
459
460         return OPERATOR_RUNNING_MODAL;
461 }
462
463 static int minimize_stretch_cancel(bContext *C, wmOperator *op)
464 {
465         minimize_stretch_exit(C, op, 1);
466
467         return OPERATOR_CANCELLED;
468 }
469
470 void UV_OT_minimize_stretch(wmOperatorType *ot)
471 {
472         /* identifiers */
473         ot->name= "Minimize Stretch";
474         ot->idname= "UV_OT_minimize_stretch";
475         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
476         ot->description="Reduce UV stretching by relaxing angles";
477         
478         /* api callbacks */
479         ot->exec= minimize_stretch_exec;
480         ot->invoke= minimize_stretch_invoke;
481         ot->modal= minimize_stretch_modal;
482         ot->cancel= minimize_stretch_cancel;
483         ot->poll= ED_operator_uvedit;
484
485         /* properties */
486         RNA_def_boolean(ot->srna, "fill_holes", 1, "Fill Holes", "Virtual fill holes in mesh before unwrapping, to better avoid overlaps and preserve symmetry.");
487         RNA_def_float_factor(ot->srna, "blend", 0.0f, 0.0f, 1.0f, "Blend", "Blend factor between stretch minimized and original.", 0.0f, 1.0f);
488         RNA_def_int(ot->srna, "iterations", 0, 0, INT_MAX, "Iterations", "Number of iterations to run, 0 is unlimited when run interactively.", 0, 100);
489 }
490
491 /* ******************** Pack Islands operator **************** */
492
493 static int pack_islands_exec(bContext *C, wmOperator *op)
494 {
495         Scene *scene= CTX_data_scene(C);
496         Object *obedit= CTX_data_edit_object(C);
497         BMEditMesh *em= ((Mesh*)obedit->data)->edit_btmesh;
498         ParamHandle *handle;
499
500         if(RNA_property_is_set(op->ptr, "margin")) {
501                 scene->toolsettings->uvcalc_margin= RNA_float_get(op->ptr, "margin");
502         }
503         else {
504                 RNA_float_set(op->ptr, "margin", scene->toolsettings->uvcalc_margin);
505         }
506
507         handle = construct_param_handle(scene, em, 1, 0, 1, 1);
508         param_pack(handle, scene->toolsettings->uvcalc_margin);
509         param_flush(handle);
510         param_delete(handle);
511         
512         DAG_id_tag_update(obedit->data, 0);
513         WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data);
514
515         return OPERATOR_FINISHED;
516 }
517
518 void UV_OT_pack_islands(wmOperatorType *ot)
519 {
520         /* identifiers */
521         ot->name= "Pack Islands";
522         ot->idname= "UV_OT_pack_islands";
523         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
524         
525         /* api callbacks */
526         ot->exec= pack_islands_exec;
527         ot->poll= ED_operator_uvedit;
528
529         /* properties */
530         RNA_def_float_factor(ot->srna, "margin", 0.0f, 0.0f, 1.0f, "Margin", "Space between islands", 0.0f, 1.0f);
531 }
532
533 /* ******************** Average Islands Scale operator **************** */
534
535 static int average_islands_scale_exec(bContext *C, wmOperator *UNUSED(op))
536 {
537         Scene *scene= CTX_data_scene(C);
538         Object *obedit= CTX_data_edit_object(C);
539         BMEditMesh *em= ((Mesh*)obedit->data)->edit_btmesh;
540         ParamHandle *handle;
541
542         handle= construct_param_handle(scene, em, 1, 0, 1, 1);
543         param_average(handle);
544         param_flush(handle);
545         param_delete(handle);
546         
547         DAG_id_tag_update(obedit->data, 0);
548         WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data);
549
550         return OPERATOR_FINISHED;
551 }
552
553 void UV_OT_average_islands_scale(wmOperatorType *ot)
554 {
555         /* identifiers */
556         ot->name= "Average Islands Scale";
557         ot->idname= "UV_OT_average_islands_scale";
558         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
559         
560         /* api callbacks */
561         ot->exec= average_islands_scale_exec;
562         ot->poll= ED_operator_uvedit;
563 }
564
565 /**************** Live Unwrap *****************/
566
567 static ParamHandle *liveHandle = NULL;
568
569 void ED_uvedit_live_unwrap_begin(Scene *scene, Object *obedit)
570 {
571         BMEditMesh *em= ((Mesh*)obedit->data)->edit_btmesh;
572         short abf = scene->toolsettings->unwrapper == 0;
573         short fillholes = scene->toolsettings->uvcalc_flag & UVCALC_FILLHOLES;
574
575         if(!ED_uvedit_test(obedit)) {
576                 return;
577         }
578
579         liveHandle = construct_param_handle(scene, em, 0, fillholes, 0, 1);
580
581         param_lscm_begin(liveHandle, PARAM_TRUE, abf);
582 }
583
584 void ED_uvedit_live_unwrap_re_solve(void)
585 {
586         if(liveHandle) {
587                 param_lscm_solve(liveHandle);
588                 param_flush(liveHandle);
589         }
590 }
591         
592 void ED_uvedit_live_unwrap_end(short cancel)
593 {
594         if(liveHandle) {
595                 param_lscm_end(liveHandle);
596                 if(cancel)
597                         param_flush_restore(liveHandle);
598                 param_delete(liveHandle);
599                 liveHandle = NULL;
600         }
601 }
602
603 /*************** UV Map Common Transforms *****************/
604
605 #define VIEW_ON_EQUATOR 0
606 #define VIEW_ON_POLES   1
607 #define ALIGN_TO_OBJECT 2
608
609 #define POLAR_ZX        0
610 #define POLAR_ZY        1
611
612 static void uv_map_transform_center(Scene *scene, View3D *v3d, float *result, 
613                                     Object *ob, BMEditMesh *em)
614 {
615         BMFace *efa;
616         BMLoop *l;
617         BMIter iter, liter;
618         float min[3], max[3], *cursx;
619         int around= (v3d)? v3d->around: V3D_CENTER;
620
621         /* only operates on the edit object - this is all that's needed now */
622
623         switch(around)  {
624                 case V3D_CENTER: /* bounding box center */
625                         min[0]= min[1]= min[2]= 1e20f;
626                         max[0]= max[1]= max[2]= -1e20f; 
627                         
628                         BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL)  {
629                                 if(BM_TestHFlag(efa, BM_SELECT)) {
630                                         BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
631                                                 DO_MINMAX(l->v->co, min, max);
632                                         }
633                                 }
634                         }
635                         mid_v3_v3v3(result, min, max);
636                         break;
637
638                 case V3D_CURSOR: /*cursor center*/ 
639                         cursx= give_cursor(scene, v3d);
640                         /* shift to objects world */
641                         result[0]= cursx[0]-ob->obmat[3][0];
642                         result[1]= cursx[1]-ob->obmat[3][1];
643                         result[2]= cursx[2]-ob->obmat[3][2];
644                         break;
645
646                 case V3D_LOCAL: /*object center*/
647                 case V3D_CENTROID: /* multiple objects centers, only one object here*/
648                 default:
649                         result[0]= result[1]= result[2]= 0.0;
650                         break;
651         }
652 }
653
654 static void uv_map_rotation_matrix(float result[][4], RegionView3D *rv3d, Object *ob, float upangledeg, float sideangledeg, float radius)
655 {
656         float rotup[4][4], rotside[4][4], viewmatrix[4][4], rotobj[4][4];
657         float sideangle= 0.0f, upangle= 0.0f;
658         int k;
659
660         /* get rotation of the current view matrix */
661         if(rv3d)
662                 copy_m4_m4(viewmatrix, rv3d->viewmat);
663         else
664                 unit_m4(viewmatrix);
665
666         /* but shifting */
667         for(k=0; k<4; k++)
668                 viewmatrix[3][k] =0.0f;
669
670         /* get rotation of the current object matrix */
671         copy_m4_m4(rotobj,ob->obmat);
672
673         /* but shifting */
674         for(k=0; k<4; k++)
675                 rotobj[3][k] =0.0f;
676
677         zero_m4(rotup);
678         zero_m4(rotside);
679
680         /* compensate front/side.. against opengl x,y,z world definition */
681         /* this is "kanonen gegen spatzen", a few plus minus 1 will do here */
682         /* i wanted to keep the reason here, so we're rotating*/
683         sideangle= (float)M_PI*(sideangledeg + 180.0f)/180.0f;
684         rotside[0][0]= (float)cos(sideangle);
685         rotside[0][1]= -(float)sin(sideangle);
686         rotside[1][0]= (float)sin(sideangle);
687         rotside[1][1]= (float)cos(sideangle);
688         rotside[2][2]= 1.0f;
689
690         upangle= (float)M_PI*upangledeg/180.0f;
691         rotup[1][1]= (float)cos(upangle)/radius;
692         rotup[1][2]= -(float)sin(upangle)/radius;
693         rotup[2][1]= (float)sin(upangle)/radius;
694         rotup[2][2]= (float)cos(upangle)/radius;
695         rotup[0][0]= (float)1.0f/radius;
696
697         /* calculate transforms*/
698         mul_serie_m4(result, rotup, rotside, viewmatrix, rotobj, NULL, NULL, NULL, NULL);
699 }
700
701 static void uv_map_transform(bContext *C, wmOperator *op, float center[3], float rotmat[4][4])
702 {
703         /* context checks are messy here, making it work in both 3d view and uv editor */
704         Scene *scene= CTX_data_scene(C);
705         Object *obedit= CTX_data_edit_object(C);
706         BMEditMesh *em= ((Mesh*)obedit->data)->edit_btmesh;
707         View3D *v3d= CTX_wm_view3d(C);
708         RegionView3D *rv3d= CTX_wm_region_view3d(C);
709         /* common operator properties */
710         int align= RNA_enum_get(op->ptr, "align");
711         int direction= RNA_enum_get(op->ptr, "direction");
712         float radius= RNA_struct_find_property(op->ptr, "radius")? RNA_float_get(op->ptr, "radius"): 1.0f;
713         float upangledeg, sideangledeg;
714
715         uv_map_transform_center(scene, v3d, center, obedit, em);
716
717         if(direction == VIEW_ON_EQUATOR) {
718                 upangledeg= 90.0f;
719                 sideangledeg= 0.0f;
720         }
721         else {
722                 upangledeg= 0.0f;
723                 if(align == POLAR_ZY) sideangledeg= 0.0f;
724                 else sideangledeg= 90.0f;
725         }
726
727         /* be compatible to the "old" sphere/cylinder mode */
728         if(direction == ALIGN_TO_OBJECT)
729                 unit_m4(rotmat);
730         else 
731                 uv_map_rotation_matrix(rotmat, rv3d, obedit, upangledeg, sideangledeg, radius);
732
733 }
734
735 static void uv_transform_properties(wmOperatorType *ot, int radius)
736 {
737         static EnumPropertyItem direction_items[]= {
738                 {VIEW_ON_EQUATOR, "VIEW_ON_EQUATOR", 0, "View on Equator", "3D view is on the equator"},
739                 {VIEW_ON_POLES, "VIEW_ON_POLES", 0, "View on Poles", "3D view is on the poles"},
740                 {ALIGN_TO_OBJECT, "ALIGN_TO_OBJECT", 0, "Align to Object", "Align according to object transform"},
741                 {0, NULL, 0, NULL, NULL}
742         };
743         static EnumPropertyItem align_items[]= {
744                 {POLAR_ZX, "POLAR_ZX", 0, "Polar ZX", "Polar 0 is X"},
745                 {POLAR_ZY, "POLAR_ZY", 0, "Polar ZY", "Polar 0 is Y"},
746                 {0, NULL, 0, NULL, NULL}
747         };
748
749         RNA_def_enum(ot->srna, "direction", direction_items, VIEW_ON_EQUATOR, "Direction", "Direction of the sphere or cylinder.");
750         RNA_def_enum(ot->srna, "align", align_items, VIEW_ON_EQUATOR, "Align", "How to determine rotation around the pole.");
751         if(radius)
752                 RNA_def_float(ot->srna, "radius", 1.0f, 0.0f, FLT_MAX, "Radius", "Radius of the sphere or cylinder.", 0.0001f, 100.0f);
753 }
754
755 static void correct_uv_aspect(BMEditMesh *em)
756 {
757         BMFace *efa= EDBM_get_actFace(em, 1);
758         BMLoop *l;
759         BMIter iter, liter;
760         MTexPoly *tf;
761         MLoopUV *luv;
762         float scale, aspx= 1.0f, aspy=1.0f;
763         
764         if(efa) {
765                 tf= CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
766                 ED_image_uv_aspect(tf->tpage, &aspx, &aspy);
767         }
768         
769         if(aspx == aspy)
770                 return;
771                 
772         if(aspx > aspy) {
773                 scale= aspy/aspx;
774
775                 BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
776                         tf = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
777                         if (!BM_TestHFlag(efa, BM_SELECT) || BM_TestHFlag(efa, BM_HIDDEN))
778                                 continue;
779                         
780                         BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
781                                 luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
782                                 luv->uv[0] = ((luv->uv[0]-0.5)*scale)+0.5;
783                         }
784                 }
785         }
786         else {
787                 scale= aspx/aspy;
788
789                 BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
790                         tf = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
791                         if (!BM_TestHFlag(efa, BM_SELECT)||BM_TestHFlag(efa, BM_HIDDEN))
792                                 continue;
793                         
794                         BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
795                                 luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
796                                 luv->uv[1] = ((luv->uv[1]-0.5)*scale)+0.5;
797                         }
798                 }
799         }
800 }
801
802 /******************** Map Clip & Correct ******************/
803
804 static void uv_map_clip_correct_properties(wmOperatorType *ot)
805 {
806         RNA_def_boolean(ot->srna, "correct_aspect", 1, "Correct Aspect", "Map UV's taking image aspect ratio into account.");
807         RNA_def_boolean(ot->srna, "clip_to_bounds", 0, "Clip to Bounds", "Clip UV coordinates to bounds after unwrapping.");
808         RNA_def_boolean(ot->srna, "scale_to_bounds", 0, "Scale to Bounds", "Scale UV coordinates to bounds after unwrapping.");
809 }
810
811 static void uv_map_clip_correct(BMEditMesh *em, wmOperator *op)
812 {
813         BMFace *efa;
814         BMLoop *l;
815         BMIter iter, liter;
816         MLoopUV *luv;
817         float dx, dy, min[2], max[2];
818         int b, nverts;
819         int correct_aspect= RNA_boolean_get(op->ptr, "correct_aspect");
820         int clip_to_bounds= RNA_boolean_get(op->ptr, "clip_to_bounds");
821         int scale_to_bounds= RNA_boolean_get(op->ptr, "scale_to_bounds");
822
823         /* correct for image aspect ratio */
824         if(correct_aspect)
825                 correct_uv_aspect(em);
826
827         if(scale_to_bounds) {
828                 INIT_MINMAX2(min, max);
829                 
830                 BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
831                         if (!BM_TestHFlag(efa, BM_SELECT))
832                                 continue;
833
834                         BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
835                                 luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
836                                 DO_MINMAX2(luv->uv, min, max);
837                         }
838                 }
839                 
840                 /* rescale UV to be in 1/1 */
841                 dx= (max[0]-min[0]);
842                 dy= (max[1]-min[1]);
843
844                 if(dx > 0.0f)
845                         dx= 1.0f/dx;
846                 if(dy > 0.0f)
847                         dy= 1.0f/dy;
848
849                 BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
850                         if (!BM_TestHFlag(efa, BM_SELECT))
851                                 continue;
852
853                         BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
854                                 luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
855                                 
856                                 luv->uv[0] = (luv->uv[0]-min[0])*dx;
857                                 luv->uv[1] = (luv->uv[1]-min[1])*dy;
858                         }
859                 }
860         }
861         else if(clip_to_bounds) {
862                 /* clipping and wrapping */
863                 BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
864                         if (!BM_TestHFlag(efa, BM_SELECT))
865                                 continue;
866
867                         BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
868                                 luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
869                                 CLAMP(luv->uv[0], 0.0f, 1.0f);
870                                 CLAMP(luv->uv[1], 0.0f, 1.0f);
871                         }
872                 }
873         }
874 }
875
876 /* ******************** Unwrap operator **************** */
877
878 /* assumes UV layer is checked, doesn't run update funcs */
879 void ED_unwrap_lscm(Scene *scene, Object *obedit, const short sel)
880 {
881         BMEditMesh *em= ((Mesh*)obedit->data)->edit_btmesh;
882
883         const short fill_holes= scene->toolsettings->uvcalc_flag & UVCALC_FILLHOLES;
884         const short correct_aspect= !(scene->toolsettings->uvcalc_flag & UVCALC_NO_ASPECT_CORRECT);
885
886         ParamHandle *handle= construct_param_handle(scene, em, 0, fill_holes, sel, correct_aspect);
887
888         param_lscm_begin(handle, PARAM_FALSE, scene->toolsettings->unwrapper == 0);
889         param_lscm_solve(handle);
890         param_lscm_end(handle);
891
892         param_pack(handle, scene->toolsettings->uvcalc_margin);
893
894         param_flush(handle);
895
896         param_delete(handle);
897 }
898
899 static int unwrap_exec(bContext *C, wmOperator *op)
900 {
901         Scene *scene= CTX_data_scene(C);
902         Object *obedit= CTX_data_edit_object(C);
903         BMEditMesh *em= ((Mesh*)obedit->data)->edit_btmesh;
904         ParamHandle *handle;
905         int method = RNA_enum_get(op->ptr, "method");
906         int fill_holes = RNA_boolean_get(op->ptr, "fill_holes");
907         int correct_aspect = RNA_boolean_get(op->ptr, "correct_aspect");
908         
909         /* add uvs if they don't exist yet */
910         if(!ED_uvedit_ensure_uvs(C, scene, obedit)) {
911                 return OPERATOR_CANCELLED;
912         }
913
914         /* remember last method for live unwrap */
915         scene->toolsettings->unwrapper = method;
916
917         if(fill_holes)          scene->toolsettings->uvcalc_flag |=  UVCALC_FILLHOLES;
918         else                            scene->toolsettings->uvcalc_flag &= ~UVCALC_FILLHOLES;
919
920         if(correct_aspect)      scene->toolsettings->uvcalc_flag &= ~UVCALC_NO_ASPECT_CORRECT;
921         else                            scene->toolsettings->uvcalc_flag |=  UVCALC_NO_ASPECT_CORRECT;
922
923         /* execute unwrap */
924         ED_unwrap_lscm(scene, obedit, TRUE);
925
926         DAG_id_tag_update(obedit->data, 0);
927         WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data);
928
929         return OPERATOR_FINISHED;
930 }
931
932 void UV_OT_unwrap(wmOperatorType *ot)
933 {
934         static EnumPropertyItem method_items[] = {
935                 {0, "ANGLE_BASED", 0, "Angle Based", ""},
936                 {1, "CONFORMAL", 0, "Conformal", ""},
937                 {0, NULL, 0, NULL, NULL}};
938
939         /* identifiers */
940         ot->name= "Unwrap";
941         ot->idname= "UV_OT_unwrap";
942         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
943         
944         /* api callbacks */
945         ot->exec= unwrap_exec;
946         ot->poll= ED_operator_uvmap;
947
948         /* properties */
949         RNA_def_enum(ot->srna, "method", method_items, 0, "Method", "Unwrapping method. Angle Based usually gives better results than Conformal, while being somewhat slower.");
950         RNA_def_boolean(ot->srna, "fill_holes", 1, "Fill Holes", "Virtual fill holes in mesh before unwrapping, to better avoid overlaps and preserve symmetry.");
951         RNA_def_boolean(ot->srna, "correct_aspect", 1, "Correct Aspect", "Map UV's taking image aspect ratio into account.");
952 }
953
954 /**************** Project From View operator **************/
955 static int uv_from_view_exec(bContext *C, wmOperator *op)
956 {
957         Scene *scene= CTX_data_scene(C);
958         Object *obedit= CTX_data_edit_object(C);
959         Camera *camera= NULL;
960         BMEditMesh *em= ((Mesh*)obedit->data)->edit_btmesh;
961         ARegion *ar = CTX_wm_region(C);
962         View3D *v3d= CTX_wm_view3d(C);
963         RegionView3D *rv3d= CTX_wm_region_view3d(C);
964         BMFace *efa;
965         BMLoop *l;
966         BMIter iter, liter;
967         MLoopUV *luv;
968         float rotmat[4][4];
969
970         /* add uvs if they don't exist yet */
971         if(!ED_uvedit_ensure_uvs(C, scene, obedit)) {
972                 return OPERATOR_CANCELLED;
973         }
974
975         /* establish the camera object, so we can default to view mapping if anything is wrong with it */
976         if ((rv3d->persp==RV3D_CAMOB) && (v3d->camera) && (v3d->camera->type==OB_CAMERA)) {
977                 camera= v3d->camera->data;
978         }
979
980         if(RNA_boolean_get(op->ptr, "orthographic")) {
981                 uv_map_rotation_matrix(rotmat, rv3d, obedit, 90.0f, 0.0f, 1.0f);
982                 
983                 BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
984                         if (!BM_TestHFlag(efa, BM_SELECT))
985                                 continue;
986
987                         BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
988                                 luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
989                                 project_from_view_ortho(luv->uv, l->v->co, rotmat);
990                         }
991                 }
992         }
993         else if (camera) {
994                 struct UvCameraInfo *uci= project_camera_info(v3d->camera, obedit->obmat, scene->r.xsch, scene->r.ysch);
995                 
996                 if(uci) {
997                         BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
998                                 if (!BM_TestHFlag(efa, BM_SELECT))
999                                         continue;
1000
1001                                 BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
1002                                         luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
1003                                         project_from_camera(luv->uv, l->v->co, uci);
1004                                 }
1005                         }
1006                         
1007                         MEM_freeN(uci);
1008                 }
1009         }
1010         else {
1011                 copy_m4_m4(rotmat, obedit->obmat);
1012
1013                 BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1014                         if (!BM_TestHFlag(efa, BM_SELECT))
1015                                 continue;
1016
1017                         BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
1018                                 luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
1019                                 project_from_view(luv->uv, l->v->co, rv3d->persmat, rotmat, ar->winx, ar->winy);
1020                         }
1021                 }
1022         }
1023
1024         uv_map_clip_correct(em, op);
1025
1026         DAG_id_tag_update(obedit->data, 0);
1027         WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data);
1028
1029         return OPERATOR_FINISHED;
1030 }
1031
1032 static int uv_from_view_poll(bContext *C)
1033 {
1034         RegionView3D *rv3d= CTX_wm_region_view3d(C);
1035
1036         if(!ED_operator_uvmap(C))
1037                 return 0;
1038
1039         return (rv3d != NULL);
1040 }
1041
1042 void UV_OT_from_view(wmOperatorType *ot)
1043 {
1044         /* identifiers */
1045         ot->name= "Project From View";
1046         ot->idname= "UV_OT_project_from_view";
1047         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1048         
1049         /* api callbacks */
1050         ot->exec= uv_from_view_exec;
1051         ot->poll= uv_from_view_poll;
1052
1053         /* properties */
1054         RNA_def_boolean(ot->srna, "orthographic", 0, "Orthographic", "Use orthographic projection.");
1055         uv_map_clip_correct_properties(ot);
1056 }
1057
1058 /********************** Reset operator ********************/
1059
1060 static int reset_exec(bContext *C, wmOperator *UNUSED(op))
1061 {
1062         Scene *scene= CTX_data_scene(C);
1063         Object *obedit= CTX_data_edit_object(C);
1064         BMEditMesh *em= ((Mesh*)obedit->data)->edit_btmesh;
1065         BMFace *efa;
1066         BMLoop *l;
1067         BMIter iter, liter;
1068         MTexPoly *tf;
1069         MLoopUV *luv;
1070         BLI_array_declare(uvs);
1071         float **uvs = NULL;
1072         int i;
1073
1074         /* add uvs if they don't exist yet */
1075         if(!ED_uvedit_ensure_uvs(C, scene, obedit)) {
1076                 return OPERATOR_CANCELLED;
1077         }
1078
1079         BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1080                 if (!BM_TestHFlag(efa, BM_SELECT))
1081                         continue;
1082                 
1083                 BLI_array_empty(uvs);
1084                 i = 0;
1085                 BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
1086                         luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
1087                         BLI_array_growone(uvs);
1088
1089                         uvs[i++] = luv->uv;
1090                 }
1091
1092                 if (i == 3) {
1093                         uvs[0][0] = 0.0;
1094                         uvs[0][1] = 0.0;
1095                         
1096                         uvs[1][0] = 1.0;
1097                         uvs[1][1] = 0.0;
1098
1099                         uvs[2][0] = 1.0;
1100                         uvs[2][1] = 1.0;
1101                 } else if (i == 4) {
1102                         uvs[0][0] = 0.0;
1103                         uvs[0][1] = 0.0;
1104                         
1105                         uvs[1][0] = 1.0;
1106                         uvs[1][1] = 0.0;
1107
1108                         uvs[2][0] = 1.0;
1109                         uvs[2][1] = 1.0;
1110
1111                         uvs[3][0] = 0.0;
1112                         uvs[3][1] = 1.0;
1113                   /*make sure we ignore 2-sided faces*/
1114                 } else if (i > 2) {
1115                         float fac = 0.0f, dfac = 1.0f / (float)efa->len;
1116
1117                         dfac *= M_PI*2;
1118
1119                         for (i=0; i<efa->len; i++) {
1120                                 uvs[i][0] = sin(fac);
1121                                 uvs[i][1] = cos(fac);
1122
1123                                 fac += dfac;
1124                         }
1125                 }
1126         }
1127
1128         DAG_id_tag_update(obedit->data, 0);
1129         WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data);
1130         
1131         BLI_array_free(uvs);
1132
1133         return OPERATOR_FINISHED;
1134 }
1135
1136 void UV_OT_reset(wmOperatorType *ot)
1137 {
1138         /* identifiers */
1139         ot->name= "Reset";
1140         ot->idname= "UV_OT_reset";
1141         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1142         
1143         /* api callbacks */
1144         ot->exec= reset_exec;
1145         ot->poll= ED_operator_uvmap;
1146 }
1147
1148 /****************** Sphere Project operator ***************/
1149
1150 static void uv_sphere_project(float target[2], float source[3], float center[3], float rotmat[4][4])
1151 {
1152         float pv[3];
1153
1154         sub_v3_v3v3(pv, source, center);
1155         mul_m4_v3(rotmat, pv);
1156
1157         map_to_sphere( &target[0], &target[1],pv[0], pv[1], pv[2]);
1158
1159         /* split line is always zero */
1160         if(target[0] >= 1.0f)
1161                 target[0] -= 1.0f;  
1162 }
1163
1164 static void uv_map_mirror(BMEditMesh *em, BMFace *efa, MTexPoly *tf)
1165 {
1166         BMLoop *l;
1167         BMIter liter;
1168         MLoopUV *luv;
1169         BLI_array_declare(uvs);
1170         float **uvs = NULL;
1171         float dx;
1172         int i, mi;
1173
1174         i = 0;
1175         BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
1176                 luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
1177                 BLI_array_growone(uvs);
1178
1179                 uvs[i] = luv->uv;
1180                 i++;
1181         }
1182
1183         mi = 0;
1184         for(i=1; i<efa->len; i++)
1185                 if(uvs[i][0] > uvs[mi][0])
1186                         mi = i;
1187
1188         for(i=0; i<efa->len; i++) {
1189                 if(i != mi) {
1190                         dx = uvs[mi][0] - uvs[i][0];
1191                         if(dx > 0.5f) uvs[i][0] += 1.0f;
1192                 } 
1193         } 
1194
1195         BLI_array_free(uvs);
1196 }
1197
1198 static int sphere_project_exec(bContext *C, wmOperator *op)
1199 {
1200         Scene *scene= CTX_data_scene(C);
1201         Object *obedit= CTX_data_edit_object(C);
1202         BMEditMesh *em= ((Mesh*)obedit->data)->edit_btmesh;
1203         BMFace *efa;
1204         BMLoop *l;
1205         BMIter iter, liter;
1206         MTexPoly *tf;
1207         MLoopUV *luv;
1208         float center[3], rotmat[4][4];
1209
1210         /* add uvs if they don't exist yet */
1211         if(!ED_uvedit_ensure_uvs(C, scene, obedit)) {
1212                 return OPERATOR_CANCELLED;
1213         }
1214
1215         uv_map_transform(C, op, center, rotmat);
1216
1217         BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1218                 if (!BM_TestHFlag(efa, BM_SELECT))
1219                         continue;
1220
1221                 BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
1222                         luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
1223
1224                         uv_sphere_project(luv->uv, l->v->co, center, rotmat);
1225                 }
1226
1227                 tf = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
1228                 uv_map_mirror(em, efa, tf);
1229         }
1230
1231         uv_map_clip_correct(em, op);
1232
1233         DAG_id_tag_update(obedit->data, 0);
1234         WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data);
1235
1236         return OPERATOR_FINISHED;
1237 }
1238
1239 void UV_OT_sphere_project(wmOperatorType *ot)
1240 {
1241         /* identifiers */
1242         ot->name= "Sphere Projection";
1243         ot->idname= "UV_OT_sphere_project";
1244         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1245         
1246         /* api callbacks */
1247         ot->exec= sphere_project_exec;
1248         ot->poll= ED_operator_uvmap;
1249
1250         /* properties */
1251         uv_transform_properties(ot, 0);
1252         uv_map_clip_correct_properties(ot);
1253 }
1254
1255 /***************** Cylinder Project operator **************/
1256
1257 static void uv_cylinder_project(float target[2], float source[3], float center[3], float rotmat[4][4])
1258 {
1259         float pv[3];
1260
1261         sub_v3_v3v3(pv, source, center);
1262         mul_m4_v3(rotmat, pv);
1263
1264         map_to_tube( &target[0], &target[1],pv[0], pv[1], pv[2]);
1265
1266         /* split line is always zero */
1267         if(target[0] >= 1.0f)
1268                 target[0] -= 1.0f;  
1269 }
1270
1271 static int cylinder_project_exec(bContext *C, wmOperator *op)
1272 {
1273         Scene *scene= CTX_data_scene(C);
1274         Object *obedit= CTX_data_edit_object(C);
1275         BMEditMesh *em= ((Mesh*)obedit->data)->edit_btmesh;
1276         BMFace *efa;
1277         BMLoop *l;
1278         BMIter iter, liter;
1279         MTexPoly *tf;
1280         MLoopUV *luv;
1281         float center[3], rotmat[4][4];
1282
1283         /* add uvs if they don't exist yet */
1284         if(!ED_uvedit_ensure_uvs(C, scene, obedit)) {
1285                 return OPERATOR_CANCELLED;
1286         }
1287
1288         uv_map_transform(C, op, center, rotmat);
1289
1290         BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1291                 tf = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
1292                 if (!BM_TestHFlag(efa, BM_SELECT))
1293                         continue;
1294                 
1295                 BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
1296                         luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
1297
1298                         uv_cylinder_project(luv->uv, l->v->co, center, rotmat);
1299                 }
1300
1301                 uv_map_mirror(em, efa, tf);
1302         }
1303
1304         uv_map_clip_correct(em, op);
1305
1306         DAG_id_tag_update(obedit->data, 0);
1307         WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data);
1308
1309         return OPERATOR_FINISHED;
1310 }
1311
1312 void UV_OT_cylinder_project(wmOperatorType *ot)
1313 {
1314         /* identifiers */
1315         ot->name= "Cylinder Projection";
1316         ot->idname= "UV_OT_cylinder_project";
1317         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1318         
1319         /* api callbacks */
1320         ot->exec= cylinder_project_exec;
1321         ot->poll= ED_operator_uvmap;
1322
1323         /* properties */
1324         uv_transform_properties(ot, 1);
1325         uv_map_clip_correct_properties(ot);
1326 }
1327
1328 /******************* Cube Project operator ****************/
1329
1330 static int cube_project_exec(bContext *C, wmOperator *op)
1331 {
1332         Scene *scene= CTX_data_scene(C);
1333         Object *obedit= CTX_data_edit_object(C);
1334         BMEditMesh *em= ((Mesh*)obedit->data)->edit_btmesh;
1335         BMFace *efa;
1336         BMLoop *l;
1337         BMIter iter, liter;
1338         MTexPoly *tf;
1339         MLoopUV *luv;
1340         float no[3], cube_size, *loc, dx, dy;
1341         int cox, coy;
1342
1343         /* add uvs if they don't exist yet */
1344         if(!ED_uvedit_ensure_uvs(C, scene, obedit)) {
1345                 return OPERATOR_CANCELLED;
1346         }
1347
1348         loc= obedit->obmat[3];
1349         cube_size= RNA_float_get(op->ptr, "cube_size");
1350
1351         /* choose x,y,z axis for projection depending on the largest normal
1352          * component, but clusters all together around the center of map. */
1353
1354         BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1355                 int first=1;
1356
1357                 tf = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
1358                 if (!BM_TestHFlag(efa, BM_SELECT))
1359                         continue;
1360                 
1361                 VECCOPY(no, efa->no);
1362
1363                 no[0]= fabs(no[0]);
1364                 no[1]= fabs(no[1]);
1365                 no[2]= fabs(no[2]);
1366                 
1367                 cox=0; coy= 1;
1368                 if(no[2]>=no[0] && no[2]>=no[1]);
1369                 else if(no[1]>=no[0] && no[1]>=no[2]) coy= 2;
1370                 else { cox= 1; coy= 2; }
1371                 
1372                 dx = dy = 0;
1373                 BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
1374                         luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
1375
1376                         luv->uv[0] = 0.5f+0.5f*cube_size*(loc[cox] + l->v->co[cox]);
1377                         luv->uv[1] = 0.5f+0.5f*cube_size*(loc[coy] + l->v->co[coy]);
1378                         
1379                         if (first) {
1380                                 dx = floor(luv->uv[0]);
1381                                 dy = floor(luv->uv[1]);
1382                                 first = 0;
1383                         }
1384                         
1385
1386                         luv->uv[0] -= dx;
1387                         luv->uv[1] -= dy;
1388                 }
1389         }
1390
1391         uv_map_clip_correct(em, op);
1392
1393         DAG_id_tag_update(obedit->data, 0);
1394         WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data);
1395
1396         return OPERATOR_FINISHED;
1397 }
1398
1399 void UV_OT_cube_project(wmOperatorType *ot)
1400 {
1401         /* identifiers */
1402         ot->name= "Cube Projection";
1403         ot->idname= "UV_OT_cube_project";
1404         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1405         
1406         /* api callbacks */
1407         ot->exec= cube_project_exec;
1408         ot->poll= ED_operator_uvmap;
1409
1410         /* properties */
1411         RNA_def_float(ot->srna, "cube_size", 1.0f, 0.0f, FLT_MAX, "Cube Size", "Size of the cube to project on.", 0.001f, 100.0f);
1412         uv_map_clip_correct_properties(ot);
1413 }