merge 17206:17211
[blender-staging.git] / source / blender / src / editface.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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, 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
31 #include <math.h>
32 #include <string.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "BLI_blenlib.h"
37 #include "BLI_arithb.h"
38 #include "BLI_heap.h"
39 #include "BLI_edgehash.h"
40 #include "BLI_editVert.h"
41
42 #include "MTC_matrixops.h"
43
44 #include "IMB_imbuf_types.h"
45 #include "IMB_imbuf.h"
46
47 #include "DNA_image_types.h"
48 #include "DNA_mesh_types.h"
49 #include "DNA_meshdata_types.h"
50 #include "DNA_object_types.h"
51 #include "DNA_space_types.h"
52 #include "DNA_screen_types.h"
53 #include "DNA_scene_types.h"
54 #include "DNA_view3d_types.h"
55
56 #include "BKE_brush.h"
57 #include "BKE_customdata.h"
58 #include "BKE_depsgraph.h"
59 #include "BKE_DerivedMesh.h"
60 #include "BKE_displist.h"
61 #include "BKE_global.h"
62 #include "BKE_mesh.h"
63 #include "BKE_multires.h"
64 #include "BKE_object.h"
65 #include "BKE_texture.h"
66 #include "BKE_utildefines.h"
67 #include "BKE_customdata.h"
68
69 #include "BSE_view.h"
70 #include "BSE_edit.h"
71 #include "BSE_drawview.h"       /* for backdrawview3d */
72
73 #include "BIF_editsima.h"
74 #include "BIF_editmesh.h"
75 #include "BIF_interface.h"
76 #include "BIF_mywindow.h"
77 #include "BIF_toolbox.h"
78 #include "BIF_resources.h"
79 #include "BIF_screen.h"
80 #include "BIF_gl.h"
81 #include "BIF_graphics.h"
82 #include "BIF_space.h"  /* for allqueue */
83 #include "BIF_drawimage.h"      /* for allqueue */
84
85 #include "BDR_editface.h"
86 #include "BDR_vpaint.h"
87
88 #include "BDR_editface.h"
89 #include "BDR_vpaint.h"
90
91 #include "GPU_draw.h"
92
93 #include "mydevice.h"
94 #include "blendef.h"
95 #include "butspace.h"
96
97 #include "BSE_trans_types.h"
98
99 #include "BDR_unwrapper.h"
100 #include "BDR_editobject.h"
101
102 #ifndef DISABLE_PYTHON
103 #include "BPY_extern.h"
104 #include "BPY_menus.h"
105 #endif
106
107 /* Pupmenu codes: */
108 #define UV_CUBE_MAPPING 2
109 #define UV_CYL_MAPPING 3
110 #define UV_SPHERE_MAPPING 4
111 #define UV_BOUNDS_MAPPING 5
112 #define UV_RESET_MAPPING 6
113 #define UV_WINDOW_MAPPING 7
114 #define UV_UNWRAP_MAPPING 8
115 #define UV_CYL_EX 32
116 #define UV_SPHERE_EX 34
117
118 /* Some macro tricks to make pupmenu construction look nicer :-)
119    Sorry, just did it for fun. */
120
121 #define _STR(x) " " #x
122 #define STRING(x) _STR(x)
123
124 #define MENUSTRING(string, code) string " %x" STRING(code)
125 #define MENUTITLE(string) string " %t|" 
126
127
128 /* returns 0 if not found, otherwise 1 */
129 int facesel_face_pick(Mesh *me, short *mval, unsigned int *index, short rect)
130 {
131         if (!me || me->totface==0)
132                 return 0;
133
134         if (G.vd->flag & V3D_NEEDBACKBUFDRAW) {
135                 check_backbuf();
136                 persp(PERSP_VIEW);
137         }
138
139         if (rect) {
140                 /* sample rect to increase changes of selecting, so that when clicking
141                    on an edge in the backbuf, we can still select a face */
142                 int dist;
143                 *index = sample_backbuf_rect(mval, 3, 1, me->totface+1, &dist,0,NULL);
144         }
145         else
146                 /* sample only on the exact position */
147                 *index = sample_backbuf(mval[0], mval[1]);
148
149         if ((*index)<=0 || (*index)>(unsigned int)me->totface)
150                 return 0;
151
152         (*index)--;
153         
154         return 1;
155 }
156
157 /* only operates on the edit object - this is all thats needed at the moment */
158 static void uv_calc_center_vector(float *result, Object *ob, EditMesh *em)
159 {
160         float min[3], max[3], *cursx;
161         
162         EditFace *efa;
163         switch (G.vd->around) 
164         {
165         case V3D_CENTER: /* bounding box center */
166                 min[0]= min[1]= min[2]= 1e20f;
167                 max[0]= max[1]= max[2]= -1e20f; 
168
169                 for (efa= em->faces.first; efa; efa= efa->next) {
170                         if (efa->f & SELECT) {
171                                 DO_MINMAX(efa->v1->co, min, max);
172                                 DO_MINMAX(efa->v2->co, min, max);
173                                 DO_MINMAX(efa->v3->co, min, max);
174                                 if(efa->v4) DO_MINMAX(efa->v4->co, min, max);
175                         }
176                 }
177                 VecMidf(result, min, max);
178                 break;
179         case V3D_CURSOR: /*cursor center*/ 
180                 cursx= give_cursor();
181                 /* shift to objects world */
182                 result[0]= cursx[0]-ob->obmat[3][0];
183                 result[1]= cursx[1]-ob->obmat[3][1];
184                 result[2]= cursx[2]-ob->obmat[3][2];
185                 break;
186         case V3D_LOCAL: /*object center*/
187         case V3D_CENTROID: /* multiple objects centers, only one object here*/
188         default:
189                 result[0]= result[1]= result[2]= 0.0;
190                 break;
191         }
192 }
193
194 static void uv_calc_map_matrix(float result[][4], Object *ob, float upangledeg, float sideangledeg, float radius)
195 {
196         float rotup[4][4], rotside[4][4], viewmatrix[4][4], rotobj[4][4];
197         float sideangle= 0.0, upangle= 0.0;
198         int k;
199
200         /* get rotation of the current view matrix */
201         Mat4CpyMat4(viewmatrix,G.vd->viewmat);
202         /* but shifting */
203         for( k= 0; k< 4; k++) viewmatrix[3][k] =0.0;
204
205         /* get rotation of the current object matrix */
206         Mat4CpyMat4(rotobj,ob->obmat);
207         /* but shifting */
208         for( k= 0; k< 4; k++) rotobj[3][k] =0.0;
209
210         Mat4Clr(*rotup);
211         Mat4Clr(*rotside);
212
213         /* compensate front/side.. against opengl x,y,z world definition */
214         /* this is "kanonen gegen spatzen", a few plus minus 1 will do here */
215         /* i wanted to keep the reason here, so we're rotating*/
216         sideangle= M_PI * (sideangledeg + 180.0) /180.0;
217         rotside[0][0]= (float)cos(sideangle);
218         rotside[0][1]= -(float)sin(sideangle);
219         rotside[1][0]= (float)sin(sideangle);
220         rotside[1][1]= (float)cos(sideangle);
221         rotside[2][2]= 1.0f;
222       
223         upangle= M_PI * upangledeg /180.0;
224         rotup[1][1]= (float)cos(upangle)/radius;
225         rotup[1][2]= -(float)sin(upangle)/radius;
226         rotup[2][1]= (float)sin(upangle)/radius;
227         rotup[2][2]= (float)cos(upangle)/radius;
228         rotup[0][0]= (float)1.0/radius;
229
230         /* calculate transforms*/
231         Mat4MulSerie(result,rotup,rotside,viewmatrix,rotobj,NULL,NULL,NULL,NULL);
232 }
233
234 static void uv_calc_shift_project(float *target, float *shift, float rotmat[][4], int projectionmode, float *source, float *min, float *max)
235 {
236         float pv[3];
237
238         VecSubf(pv, source, shift);
239         Mat4MulVecfl(rotmat, pv);
240
241         switch(projectionmode) {
242         case B_UVAUTO_CYLINDER: 
243                 tubemap(pv[0], pv[1], pv[2], &target[0],&target[1]);
244                 /* split line is always zero */
245                 if (target[0] >= 1.0f) target[0] -= 1.0f;  
246                 break;
247
248         case B_UVAUTO_SPHERE: 
249                 spheremap(pv[0], pv[1], pv[2], &target[0],&target[1]);
250                 /* split line is always zero */
251                 if (target[0] >= 1.0f) target[0] -= 1.0f;
252                 break;
253
254         case 3: /* ortho special case for BOUNDS */
255                 target[0] = -pv[0];
256                 target[1] = pv[2];
257                 break;
258
259         case 4: 
260                 {
261                 /* very special case for FROM WINDOW */
262                 float pv4[4], dx, dy, x= 0.0, y= 0.0;
263
264                 dx= G.vd->area->winx;
265                 dy= G.vd->area->winy;
266
267                 VecCopyf(pv4, source);
268         pv4[3] = 1.0;
269
270                 /* rotmat is the object matrix in this case */
271         Mat4MulVec4fl(rotmat,pv4); 
272
273                 /* almost project_short */
274             Mat4MulVec4fl(G.vd->persmat,pv4);
275                 if (fabs(pv4[3]) > 0.00001) { /* avoid division by zero */
276                         target[0] = dx/2.0 + (dx/2.0)*pv4[0]/pv4[3];
277                         target[1] = dy/2.0 + (dy/2.0)*pv4[1]/pv4[3];
278                 }
279                 else {
280                         /* scaling is lost but give a valid result */
281                         target[0] = dx/2.0 + (dx/2.0)*pv4[0];
282                         target[1] = dy/2.0 + (dy/2.0)*pv4[1];
283                 }
284
285         /* G.vd->persmat seems to do this funky scaling */ 
286                 if(dx > dy) {
287                         y= (dx-dy)/2.0;
288                         dy = dx;
289                 }
290                 else {
291                         x= (dy-dx)/2.0;
292                         dx = dy;
293                 }
294                 target[0]= (x + target[0])/dx;
295                 target[1]= (y + target[1])/dy;
296
297                 }
298                 break;
299
300     default:
301                 target[0] = 0.0;
302                 target[1] = 1.0;
303         }
304
305         /* we know the values here and may need min_max later */
306         /* max requests independand from min; not fastest but safest */ 
307         if(min) {
308                 min[0] = MIN2(target[0], min[0]);
309                 min[1] = MIN2(target[1], min[1]);
310         }
311         if(max) {
312                 max[0] = MAX2(target[0], max[0]);
313                 max[1] = MAX2(target[1], max[1]);
314         }
315 }
316
317 static void correct_uv_aspect( void )
318 {
319         float aspx=1, aspy=1;
320         EditMesh *em = G.editMesh;
321         EditFace *efa = EM_get_actFace(1);
322         MTFace *tface;
323         
324         if (efa) {
325                 tface = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
326                 image_final_aspect(tface->tpage, &aspx, &aspy);
327         }
328         
329         if (aspx != aspy) {
330                 
331                 EditMesh *em = G.editMesh;
332                 float scale;
333                 
334                 if (aspx > aspy) {
335                         scale = aspy/aspx;
336                         for (efa= em->faces.first; efa; efa= efa->next) {
337                                 if (efa->f & SELECT) {
338                                         tface = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
339                                         tface->uv[0][0] = ((tface->uv[0][0]-0.5)*scale)+0.5;
340                                         tface->uv[1][0] = ((tface->uv[1][0]-0.5)*scale)+0.5;
341                                         tface->uv[2][0] = ((tface->uv[2][0]-0.5)*scale)+0.5;
342                                         if(efa->v4) {
343                                                 tface->uv[3][0] = ((tface->uv[3][0]-0.5)*scale)+0.5;
344                                         }
345                                 }
346                         }
347                 } else {
348                         scale = aspx/aspy;
349                         for (efa= em->faces.first; efa; efa= efa->next) {
350                                 if (efa->f & SELECT) {
351                                         tface = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
352                                         tface->uv[0][1] = ((tface->uv[0][1]-0.5)*scale)+0.5;
353                                         tface->uv[1][1] = ((tface->uv[1][1]-0.5)*scale)+0.5;
354                                         tface->uv[2][1] = ((tface->uv[2][1]-0.5)*scale)+0.5;
355                                         if(efa->v4) {
356                                                 tface->uv[3][1] = ((tface->uv[3][1]-0.5)*scale)+0.5;
357                                         }
358                                 }
359                         }
360                 }
361         }
362 }
363
364 void calculate_uv_map(unsigned short mapmode)
365 {
366         MTFace *tface;
367         Object *ob;
368         float dx, dy, rotatematrix[4][4], radius= 1.0, min[3], cent[3], max[3];
369         float fac= 1.0, upangledeg= 0.0, sideangledeg= 90.0;
370         int i, b, mi, n;
371
372         EditMesh *em = G.editMesh;
373         EditFace *efa;
374         
375         if(G.scene->toolsettings->uvcalc_mapdir==1)  {
376                 upangledeg= 90.0;
377                 sideangledeg= 0.0;
378         } else {
379                 upangledeg= 0.0;
380                 if(G.scene->toolsettings->uvcalc_mapalign==1) sideangledeg= 0.0;
381                 else sideangledeg= 90.0;
382         }
383         
384         /* add uvs if there not here */
385         if (!EM_texFaceCheck()) {
386                 if (em && em->faces.first)
387                         EM_add_data_layer(&em->fdata, CD_MTFACE);
388                 
389                 if (G.sima && G.sima->image) /* this is a bit of a kludge, but assume they want the image on their mesh when UVs are added */
390                         image_changed(G.sima, G.sima->image);
391                 
392                 if (!EM_texFaceCheck())
393                         return;
394                 
395                 /* select new UV's */
396                 if ((G.sima && G.sima->flag & SI_SYNC_UVSEL)==0) {
397                         for(efa=em->faces.first; efa; efa=efa->next) {
398                                 MTFace *tf= (MTFace *)CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
399                                 simaFaceSel_Set(efa, tf);
400                         }
401                 }
402         }
403         
404         ob=OBACT;
405         
406         switch(mapmode) {
407         case B_UVAUTO_BOUNDS:
408                 min[0]= min[1]= 10000000.0;
409                 max[0]= max[1]= -10000000.0;
410
411                 cent[0] = cent[1] = cent[2] = 0.0; 
412                 uv_calc_map_matrix(rotatematrix, ob, upangledeg, sideangledeg, 1.0f);
413                 
414                 for (efa= em->faces.first; efa; efa= efa->next) {
415                         if (efa->f & SELECT) {
416                                 tface = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
417                                 uv_calc_shift_project(tface->uv[0],cent,rotatematrix,3, efa->v1->co, min,max);
418                                 uv_calc_shift_project(tface->uv[1],cent,rotatematrix,3, efa->v2->co, min,max);
419                                 uv_calc_shift_project(tface->uv[2],cent,rotatematrix,3, efa->v3->co,min,max);
420                                 if(efa->v4)
421                                         uv_calc_shift_project(tface->uv[3],cent,rotatematrix,3, efa->v4->co,min,max);
422                         }
423                 }
424                 
425                 /* rescale UV to be in 1/1 */
426                 dx= (max[0]-min[0]);
427                 dy= (max[1]-min[1]);
428
429                 for (efa= em->faces.first; efa; efa= efa->next) {
430                         if (efa->f & SELECT) {
431                                 tface = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
432                                 if(efa->v4) b= 3; else b= 2;
433                                 for(; b>=0; b--) {
434                                         tface->uv[b][0]= ((tface->uv[b][0]-min[0])*fac)/dx;
435                                         tface->uv[b][1]= 1.0-fac+((tface->uv[b][1]-min[1])/* *fac */)/dy;
436                                 }
437                         }
438                 }
439                 break;
440
441         case B_UVAUTO_WINDOW:           
442                 cent[0] = cent[1] = cent[2] = 0.0; 
443                 Mat4CpyMat4(rotatematrix,ob->obmat);
444                 for (efa= em->faces.first; efa; efa= efa->next) {
445                         if (efa->f & SELECT) {
446                                 tface = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
447                                 uv_calc_shift_project(tface->uv[0],cent,rotatematrix,4, efa->v1->co, NULL,NULL);
448                                 uv_calc_shift_project(tface->uv[1],cent,rotatematrix,4, efa->v2->co, NULL,NULL);
449                                 uv_calc_shift_project(tface->uv[2],cent,rotatematrix,4, efa->v3->co, NULL,NULL);
450                                 if(efa->v4)
451                                         uv_calc_shift_project(tface->uv[3],cent,rotatematrix,4, efa->v4->co, NULL,NULL);
452                         }
453                 }
454                 break;
455
456         case B_UVAUTO_RESET:
457                 for (efa= em->faces.first; efa; efa= efa->next) {
458                         if (efa->f & SELECT) {
459                                 tface = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
460                                 default_uv(tface->uv, 1.0);
461                         }
462                 }
463                 break;
464
465         case B_UVAUTO_CYLINDER:
466         case B_UVAUTO_SPHERE:
467                 uv_calc_center_vector(cent, ob, em);
468                         
469                 if(mapmode==B_UVAUTO_CYLINDER) radius = G.scene->toolsettings->uvcalc_radius;
470
471                 /* be compatible to the "old" sphere/cylinder mode */
472                 if (G.scene->toolsettings->uvcalc_mapdir== 2)
473                         Mat4One(rotatematrix);
474                 else 
475                         uv_calc_map_matrix(rotatematrix,ob,upangledeg,sideangledeg,radius);
476                 for (efa= em->faces.first; efa; efa= efa->next) {
477                         if (efa->f & SELECT) {
478                                 tface = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
479                                 uv_calc_shift_project(tface->uv[0],cent,rotatematrix,mapmode, efa->v1->co, NULL,NULL);
480                                 uv_calc_shift_project(tface->uv[1],cent,rotatematrix,mapmode, efa->v2->co, NULL,NULL);
481                                 uv_calc_shift_project(tface->uv[2],cent,rotatematrix,mapmode, efa->v3->co, NULL,NULL);
482                                 n = 3;       
483                                 if(efa->v4) {
484                                         uv_calc_shift_project(tface->uv[3],cent,rotatematrix,mapmode, efa->v4->co, NULL,NULL);
485                                         n=4;
486                                 }
487
488                                 mi = 0;
489                                 for (i = 1; i < n; i++)
490                                         if (tface->uv[i][0] > tface->uv[mi][0]) mi = i;
491
492                                 for (i = 0; i < n; i++) {
493                                         if (i != mi) {
494                                                 dx = tface->uv[mi][0] - tface->uv[i][0];
495                                                 if (dx > 0.5) tface->uv[i][0] += 1.0;
496                                         } 
497                                 } 
498                         }
499                 }
500
501                 break;
502
503         case B_UVAUTO_CUBE:
504                 {
505                 /* choose x,y,z axis for projetion depending on the largest normal */
506                 /* component, but clusters all together around the center of map */
507                 float no[3];
508                 short cox, coy;
509                 float *loc= ob->obmat[3];
510                 /*MVert *mv= me->mvert;*/
511                 float cubesize = G.scene->toolsettings->uvcalc_cubesize;
512
513                 for (efa= em->faces.first; efa; efa= efa->next) {
514                         if (efa->f & SELECT) {
515                                 tface = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
516                                 CalcNormFloat(efa->v1->co, efa->v2->co, efa->v3->co, no);
517                                 
518                                 no[0]= fabs(no[0]);
519                                 no[1]= fabs(no[1]);
520                                 no[2]= fabs(no[2]);
521                                 
522                                 cox=0; coy= 1;
523                                 if(no[2]>=no[0] && no[2]>=no[1]);
524                                 else if(no[1]>=no[0] && no[1]>=no[2]) coy= 2;
525                                 else { cox= 1; coy= 2; }
526                                 
527                                 tface->uv[0][0]= 0.5+0.5*cubesize*(loc[cox] + efa->v1->co[cox]);
528                                 tface->uv[0][1]= 0.5+0.5*cubesize*(loc[coy] + efa->v1->co[coy]);
529                                 dx = floor(tface->uv[0][0]);
530                                 dy = floor(tface->uv[0][1]);
531                                 tface->uv[0][0] -= dx;
532                                 tface->uv[0][1] -= dy;
533                                 tface->uv[1][0]= 0.5+0.5*cubesize*(loc[cox] + efa->v2->co[cox]);
534                                 tface->uv[1][1]= 0.5+0.5*cubesize*(loc[coy] + efa->v2->co[coy]);
535                                 tface->uv[1][0] -= dx;
536                                 tface->uv[1][1] -= dy;
537                                 tface->uv[2][0]= 0.5+0.5*cubesize*(loc[cox] + efa->v3->co[cox]);
538                                 tface->uv[2][1]= 0.5+0.5*cubesize*(loc[coy] + efa->v3->co[coy]);
539                                 tface->uv[2][0] -= dx;
540                                 tface->uv[2][1] -= dy;
541                                 if(efa->v4) {
542                                         tface->uv[3][0]= 0.5+0.5*cubesize*(loc[cox] + efa->v4->co[cox]);
543                                         tface->uv[3][1]= 0.5+0.5*cubesize*(loc[coy] + efa->v4->co[coy]);
544                                         tface->uv[3][0] -= dx;
545                                         tface->uv[3][1] -= dy;
546                                 }
547                         }
548                 }
549                 break;
550                 }
551         default:
552                 if ((G.scene->toolsettings->uvcalc_flag & UVCALC_NO_ASPECT_CORRECT)==0)
553                         correct_uv_aspect();
554                 return;
555         } /* end switch mapmode */
556
557         /* clipping and wrapping */
558         if(G.sima && G.sima->flag & SI_CLIP_UV) {
559                 for (efa= em->faces.first; efa; efa= efa->next) {
560                         if (!(efa->f & SELECT)) continue;
561                         tface = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
562                 
563                         dx= dy= 0;
564                         if(efa->v4) b= 3; else b= 2;
565                         for(; b>=0; b--) {
566                                 while(tface->uv[b][0] + dx < 0.0) dx+= 0.5;
567                                 while(tface->uv[b][0] + dx > 1.0) dx-= 0.5;
568                                 while(tface->uv[b][1] + dy < 0.0) dy+= 0.5;
569                                 while(tface->uv[b][1] + dy > 1.0) dy-= 0.5;
570                         }
571         
572                         if(efa->v4) b= 3; else b= 2;
573                         for(; b>=0; b--) {
574                                 tface->uv[b][0]+= dx;
575                                 CLAMP(tface->uv[b][0], 0.0, 1.0);
576                                 
577                                 tface->uv[b][1]+= dy;
578                                 CLAMP(tface->uv[b][1], 0.0, 1.0);
579                         }
580                 }
581         }
582
583         if (    (mapmode!=B_UVAUTO_BOUNDS) &&
584                         (mapmode!=B_UVAUTO_RESET) &&
585                         (G.scene->toolsettings->uvcalc_flag & UVCALC_NO_ASPECT_CORRECT)==0
586                 ) {
587                 correct_uv_aspect();
588         }
589         
590         BIF_undo_push("UV calculation");
591
592         object_uvs_changed(OBACT);
593
594         allqueue(REDRAWVIEW3D, 0);
595         allqueue(REDRAWIMAGE, 0);
596 }
597
598 /* last_sel, use em->act_face otherwise get the last selected face in the editselections
599  * at the moment, last_sel is mainly useful for gaking sure the space image dosnt flicker */
600 MTFace *get_active_mtface(EditFace **act_efa, MCol **mcol, int sloppy)
601 {
602         EditMesh *em = G.editMesh;
603         EditFace *efa = NULL;
604         
605         if(!EM_texFaceCheck())
606                 return NULL;
607         
608         efa = EM_get_actFace(sloppy);
609         
610         if (efa) {
611                 if (mcol) {
612                         if (CustomData_has_layer(&em->fdata, CD_MCOL))
613                                 *mcol = CustomData_em_get(&em->fdata, efa->data, CD_MCOL);
614                         else
615                                 *mcol = NULL;
616                 }
617                 if (act_efa) *act_efa = efa; 
618                 return CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
619         }
620         if (act_efa) *act_efa= NULL;
621         if(mcol) *mcol = NULL;
622         return NULL;
623 }
624
625 void default_uv(float uv[][2], float size)
626 {
627         int dy;
628         
629         if(size>1.0) size= 1.0;
630
631         dy= 1.0-size;
632         
633         uv[0][0]= 0;
634         uv[0][1]= size+dy;
635         
636         uv[1][0]= 0;
637         uv[1][1]= dy;
638         
639         uv[2][0]= size;
640         uv[2][1]= dy;
641         
642         uv[3][0]= size;
643         uv[3][1]= size+dy;
644 }
645
646 void make_tfaces(Mesh *me) 
647 {
648         if(!me->mtface) {
649                 if(me->mr) {
650                         multires_add_layer(me, &me->mr->fdata, CD_MTFACE,
651                                            CustomData_number_of_layers(&me->fdata, CD_MTFACE));
652                 }
653                 else {
654                         me->mtface= CustomData_add_layer(&me->fdata, CD_MTFACE, CD_DEFAULT,
655                                 NULL, me->totface);
656                 }
657         }
658 }
659
660 void reveal_tface()
661 {
662         Mesh *me;
663         MFace *mface;
664         int a;
665         
666         me= get_mesh(OBACT);
667         if(me==0 || me->totface==0) return;
668         
669         mface= me->mface;
670         a= me->totface;
671         while(a--) {
672                 if(mface->flag & ME_HIDE) {
673                         mface->flag |= ME_FACE_SEL;
674                         mface->flag -= ME_HIDE;
675                 }
676                 mface++;
677         }
678
679         BIF_undo_push("Reveal face");
680
681         object_tface_flags_changed(OBACT, 0);
682 }
683
684 void hide_tface()
685 {
686         Mesh *me;
687         MFace *mface;
688         int a;
689         
690         me= get_mesh(OBACT);
691         if(me==0 || me->totface==0) return;
692         
693         if(G.qual & LR_ALTKEY) {
694                 reveal_tface();
695                 return;
696         }
697         
698         mface= me->mface;
699         a= me->totface;
700         while(a--) {
701                 if(mface->flag & ME_HIDE);
702                 else {
703                         if(G.qual & LR_SHIFTKEY) {
704                                 if( (mface->flag & ME_FACE_SEL)==0) mface->flag |= ME_HIDE;
705                         }
706                         else {
707                                 if( (mface->flag & ME_FACE_SEL)) mface->flag |= ME_HIDE;
708                         }
709                 }
710                 if(mface->flag & ME_HIDE) mface->flag &= ~ME_FACE_SEL;
711                 
712                 mface++;
713         }
714
715         BIF_undo_push("Hide face");
716
717         object_tface_flags_changed(OBACT, 0);
718 }
719
720 void select_linked_tfaces(int mode)
721 {
722         Object *ob;
723         Mesh *me;
724         short mval[2];
725         unsigned int index=0;
726
727         ob = OBACT;
728         me = get_mesh(ob);
729         if(me==0 || me->totface==0) return;
730
731         if (mode==0 || mode==1) {
732                 if (!(ob->lay & G.vd->lay))
733                         error("The active object is not in this layer");
734                         
735                 getmouseco_areawin(mval);
736                 if (!facesel_face_pick(me, mval, &index, 1)) return;
737         }
738
739         select_linked_tfaces_with_seams(mode, me, index);
740 }
741
742 void deselectall_tface()
743 {
744         Mesh *me;
745         MFace *mface;
746         int a, sel;
747                 
748         me= get_mesh(OBACT);
749         if(me==0) return;
750         
751         mface= me->mface;
752         a= me->totface;
753         sel= 0;
754         while(a--) {
755                 if(mface->flag & ME_HIDE);
756                 else if(mface->flag & ME_FACE_SEL) sel= 1;
757                 mface++;
758         }
759         
760         mface= me->mface;
761         a= me->totface;
762         while(a--) {
763                 if(mface->flag & ME_HIDE);
764                 else {
765                         if(sel) mface->flag &= ~ME_FACE_SEL;
766                         else mface->flag |= ME_FACE_SEL;
767                 }
768                 mface++;
769         }
770
771         BIF_undo_push("(De)select all faces");
772
773         object_tface_flags_changed(OBACT, 0);
774 }
775
776 void selectswap_tface(void)
777 {
778         Mesh *me;
779         MFace *mface;
780         int a;
781                 
782         me= get_mesh(OBACT);
783         if(me==0) return;
784         
785         mface= me->mface;
786         a= me->totface;
787         while(a--) {
788                 if(mface->flag & ME_HIDE);
789                 else {
790                         if(mface->flag & ME_FACE_SEL) mface->flag &= ~ME_FACE_SEL;
791                         else mface->flag |= ME_FACE_SEL;
792                 }
793                 mface++;
794         }
795
796         BIF_undo_push("Select inverse face");
797
798         object_tface_flags_changed(OBACT, 0);
799 }
800
801 int minmax_tface(float *min, float *max)
802 {
803         Object *ob;
804         Mesh *me;
805         MFace *mf;
806         MTFace *tf;
807         MVert *mv;
808         int a, ok=0;
809         float vec[3], bmat[3][3];
810         
811         ob = OBACT;
812         if (ob==0) return ok;
813         me= get_mesh(ob);
814         if(me==0 || me->mtface==0) return ok;
815         
816         Mat3CpyMat4(bmat, ob->obmat);
817
818         mv= me->mvert;
819         mf= me->mface;
820         tf= me->mtface;
821         for (a=me->totface; a>0; a--, mf++, tf++) {
822                 if (mf->flag & ME_HIDE || !(mf->flag & ME_FACE_SEL))
823                         continue;
824
825                 VECCOPY(vec, (mv+mf->v1)->co);
826                 Mat3MulVecfl(bmat, vec);
827                 VecAddf(vec, vec, ob->obmat[3]);
828                 DO_MINMAX(vec, min, max);               
829
830                 VECCOPY(vec, (mv+mf->v2)->co);
831                 Mat3MulVecfl(bmat, vec);
832                 VecAddf(vec, vec, ob->obmat[3]);
833                 DO_MINMAX(vec, min, max);               
834
835                 VECCOPY(vec, (mv+mf->v3)->co);
836                 Mat3MulVecfl(bmat, vec);
837                 VecAddf(vec, vec, ob->obmat[3]);
838                 DO_MINMAX(vec, min, max);               
839
840                 if (mf->v4) {
841                         VECCOPY(vec, (mv+mf->v4)->co);
842                         Mat3MulVecfl(bmat, vec);
843                         VecAddf(vec, vec, ob->obmat[3]);
844                         DO_MINMAX(vec, min, max);
845                 }
846                 ok= 1;
847         }
848         return ok;
849 }
850
851 #define ME_SEAM_DONE 2          /* reuse this flag */
852
853 static float edgetag_cut_cost(EditMesh *em, int e1, int e2, int vert)
854 {
855         EditVert *v = EM_get_vert_for_index(vert);
856         EditEdge *eed1 = EM_get_edge_for_index(e1), *eed2 = EM_get_edge_for_index(e2);
857         EditVert *v1 = EM_get_vert_for_index( (eed1->v1->tmp.l == vert)? eed1->v2->tmp.l: eed1->v1->tmp.l );
858         EditVert *v2 = EM_get_vert_for_index( (eed2->v1->tmp.l == vert)? eed2->v2->tmp.l: eed2->v1->tmp.l );
859         float cost, d1[3], d2[3];
860
861         cost = VecLenf(v1->co, v->co);
862         cost += VecLenf(v->co, v2->co);
863
864         VecSubf(d1, v->co, v1->co);
865         VecSubf(d2, v2->co, v->co);
866
867         cost = cost + 0.5f*cost*(2.0f - fabs(d1[0]*d2[0] + d1[1]*d2[1] + d1[2]*d2[2]));
868
869         return cost;
870 }
871
872 static void edgetag_add_adjacent(EditMesh *em, Heap *heap, int mednum, int vertnum, int *nedges, int *edges, int *prevedge, float *cost)
873 {
874         int startadj, endadj = nedges[vertnum+1];
875
876         for (startadj = nedges[vertnum]; startadj < endadj; startadj++) {
877                 int adjnum = edges[startadj];
878                 EditEdge *eedadj = EM_get_edge_for_index(adjnum);
879                 float newcost;
880
881                 if (eedadj->f2 & ME_SEAM_DONE)
882                         continue;
883
884                 newcost = cost[mednum] + edgetag_cut_cost(em, mednum, adjnum, vertnum);
885
886                 if (cost[adjnum] > newcost) {
887                         cost[adjnum] = newcost;
888                         prevedge[adjnum] = mednum;
889                         BLI_heap_insert(heap, newcost, SET_INT_IN_POINTER(adjnum));
890                 }
891         }
892 }
893
894 void edgetag_context_set(EditEdge *eed, int val)
895 {
896         switch (G.scene->toolsettings->edge_mode) {
897         case EDGE_MODE_TAG_SEAM:
898                 if (val)                {eed->seam = 255;}
899                 else                    {eed->seam = 0;}
900                 break;
901         case EDGE_MODE_TAG_SHARP:
902                 if (val)                {eed->sharp = 1;}
903                 else                    {eed->sharp = 0;}
904                 break;                          
905         case EDGE_MODE_TAG_CREASE:      
906                 if (val)                {eed->crease = 1.0f;}
907                 else                    {eed->crease = 0.0f;}
908                 break;
909         case EDGE_MODE_TAG_BEVEL:
910                 if (val)                {eed->bweight = 1.0f;}
911                 else                    {eed->bweight = 0.0f;}
912                 break;
913         }
914 }
915
916 int edgetag_context_check(EditEdge *eed)
917 {
918         switch (G.scene->toolsettings->edge_mode) {
919         case EDGE_MODE_TAG_SEAM:
920                 return eed->seam ? 1 : 0;
921         case EDGE_MODE_TAG_SHARP:
922                 return eed->sharp ? 1 : 0;
923         case EDGE_MODE_TAG_CREASE:      
924                 return eed->crease ? 1 : 0;
925         case EDGE_MODE_TAG_BEVEL:
926                 return eed->bweight ? 1 : 0;
927         }
928         return 0;
929 }
930
931
932 int edgetag_shortest_path(EditEdge *source, EditEdge *target)
933 {
934         EditMesh *em = G.editMesh;
935         EditEdge *eed;
936         EditVert *ev;
937         
938         Heap *heap;
939         float *cost;
940         int a, totvert=0, totedge=0, *nedges, *edges, *prevedge, mednum = -1, nedgeswap = 0;
941
942
943         /* we need the vert */
944         for (ev= em->verts.first, totvert=0; ev; ev= ev->next) {
945                 ev->tmp.l = totvert;
946                 totvert++;
947         }
948
949         for (eed= em->edges.first; eed; eed = eed->next) {
950                 eed->f2 = 0;
951                 if (eed->h) {
952                         eed->f2 |= ME_SEAM_DONE;
953                 }
954                 eed->tmp.l = totedge;
955                 totedge++;
956         }
957
958         /* alloc */
959         nedges = MEM_callocN(sizeof(*nedges)*totvert+1, "SeamPathNEdges");
960         edges = MEM_mallocN(sizeof(*edges)*totedge*2, "SeamPathEdges");
961         prevedge = MEM_mallocN(sizeof(*prevedge)*totedge, "SeamPathPrevious");
962         cost = MEM_mallocN(sizeof(*cost)*totedge, "SeamPathCost");
963
964         /* count edges, compute adjacent edges offsets and fill adjacent edges */
965         for (eed= em->edges.first; eed; eed = eed->next) {
966                 nedges[eed->v1->tmp.l+1]++;
967                 nedges[eed->v2->tmp.l+1]++;
968         }
969
970         for (a=1; a<totvert; a++) {
971                 int newswap = nedges[a+1];
972                 nedges[a+1] = nedgeswap + nedges[a];
973                 nedgeswap = newswap;
974         }
975         nedges[0] = nedges[1] = 0;
976
977         for (a=0, eed= em->edges.first; eed; a++, eed = eed->next) {
978                 edges[nedges[eed->v1->tmp.l+1]++] = a;
979                 edges[nedges[eed->v2->tmp.l+1]++] = a;
980
981                 cost[a] = 1e20f;
982                 prevedge[a] = -1;
983         }
984
985         /* regular dijkstra shortest path, but over edges instead of vertices */
986         heap = BLI_heap_new();
987         BLI_heap_insert(heap, 0.0f, SET_INT_IN_POINTER(source->tmp.l));
988         cost[source->tmp.l] = 0.0f;
989
990         EM_init_index_arrays(1, 1, 0);
991
992
993         while (!BLI_heap_empty(heap)) {
994                 mednum = GET_INT_FROM_POINTER(BLI_heap_popmin(heap));
995                 eed = EM_get_edge_for_index( mednum );
996
997                 if (mednum == target->tmp.l)
998                         break;
999
1000                 if (eed->f2 & ME_SEAM_DONE)
1001                         continue;
1002
1003                 eed->f2 |= ME_SEAM_DONE;
1004
1005                 edgetag_add_adjacent(em, heap, mednum, eed->v1->tmp.l, nedges, edges, prevedge, cost);
1006                 edgetag_add_adjacent(em, heap, mednum, eed->v2->tmp.l, nedges, edges, prevedge, cost);
1007         }
1008         
1009         
1010         MEM_freeN(nedges);
1011         MEM_freeN(edges);
1012         MEM_freeN(cost);
1013         BLI_heap_free(heap, NULL);
1014
1015         for (eed= em->edges.first; eed; eed = eed->next) {
1016                 eed->f2 &= ~ME_SEAM_DONE;
1017         }
1018
1019         if (mednum != target->tmp.l) {
1020                 MEM_freeN(prevedge);
1021                 EM_free_index_arrays();
1022                 return 0;
1023         }
1024
1025         /* follow path back to source and mark as seam */
1026         if (mednum == target->tmp.l) {
1027                 short allseams = 1;
1028
1029                 mednum = target->tmp.l;
1030                 do {
1031                         eed = EM_get_edge_for_index( mednum );
1032                         if (!edgetag_context_check(eed)) {
1033                                 allseams = 0;
1034                                 break;
1035                         }
1036                         mednum = prevedge[mednum];
1037                 } while (mednum != source->tmp.l);
1038
1039                 mednum = target->tmp.l;
1040                 do {
1041                         eed = EM_get_edge_for_index( mednum );
1042                         if (allseams)
1043                                 edgetag_context_set(eed, 0);
1044                         else
1045                                 edgetag_context_set(eed, 1);
1046                         mednum = prevedge[mednum];
1047                 } while (mednum != -1);
1048         }
1049
1050         MEM_freeN(prevedge);
1051         EM_free_index_arrays();
1052         return 1;
1053 }
1054
1055 static void seam_edgehash_insert_face(EdgeHash *ehash, MFace *mf)
1056 {
1057         BLI_edgehash_insert(ehash, mf->v1, mf->v2, NULL);
1058         BLI_edgehash_insert(ehash, mf->v2, mf->v3, NULL);
1059         if (mf->v4) {
1060                 BLI_edgehash_insert(ehash, mf->v3, mf->v4, NULL);
1061                 BLI_edgehash_insert(ehash, mf->v4, mf->v1, NULL);
1062         }
1063         else
1064                 BLI_edgehash_insert(ehash, mf->v3, mf->v1, NULL);
1065 }
1066
1067 void seam_mark_clear_tface(short mode)
1068 {
1069         Mesh *me;
1070         MFace *mf;
1071         MEdge *med;
1072         int a;
1073         
1074         me= get_mesh(OBACT);
1075         if(me==0 ||  me->totface==0) return;
1076
1077         if (mode == 0)
1078                 mode = pupmenu("Seams%t|Mark Border Seam %x1|Clear Seam %x2");
1079
1080         if (mode != 1 && mode != 2)
1081                 return;
1082
1083         if (mode == 2) {
1084                 EdgeHash *ehash = BLI_edgehash_new();
1085
1086                 for (a=0, mf=me->mface; a<me->totface; a++, mf++)
1087                         if (!(mf->flag & ME_HIDE) && (mf->flag & ME_FACE_SEL))
1088                                 seam_edgehash_insert_face(ehash, mf);
1089
1090                 for (a=0, med=me->medge; a<me->totedge; a++, med++)
1091                         if (BLI_edgehash_haskey(ehash, med->v1, med->v2))
1092                                 med->flag &= ~ME_SEAM;
1093
1094                 BLI_edgehash_free(ehash, NULL);
1095         }
1096         else {
1097                 /* mark edges that are on both selected and deselected faces */
1098                 EdgeHash *ehash1 = BLI_edgehash_new();
1099                 EdgeHash *ehash2 = BLI_edgehash_new();
1100
1101                 for (a=0, mf=me->mface; a<me->totface; a++, mf++) {
1102                         if ((mf->flag & ME_HIDE) || !(mf->flag & ME_FACE_SEL))
1103                                 seam_edgehash_insert_face(ehash1, mf);
1104                         else
1105                                 seam_edgehash_insert_face(ehash2, mf);
1106                 }
1107
1108                 for (a=0, med=me->medge; a<me->totedge; a++, med++)
1109                         if (BLI_edgehash_haskey(ehash1, med->v1, med->v2) &&
1110                             BLI_edgehash_haskey(ehash2, med->v1, med->v2))
1111                                 med->flag |= ME_SEAM;
1112
1113                 BLI_edgehash_free(ehash1, NULL);
1114                 BLI_edgehash_free(ehash2, NULL);
1115         }
1116
1117         if (G.rt == 8)
1118                 unwrap_lscm(1);
1119
1120         G.f |= G_DRAWSEAMS;
1121         BIF_undo_push("Mark Seam");
1122
1123         object_tface_flags_changed(OBACT, 1);
1124 }
1125
1126 void face_select()
1127 {
1128         Object *ob;
1129         Mesh *me;
1130         MFace *mface, *msel;
1131         short mval[2];
1132         unsigned int a, index;
1133
1134         /* Get the face under the cursor */
1135         ob = OBACT;
1136         if (!(ob->lay & G.vd->lay)) {
1137                 error("The active object is not in this layer");
1138         }
1139         me = get_mesh(ob);
1140         getmouseco_areawin(mval);
1141
1142         if (!facesel_face_pick(me, mval, &index, 1)) return;
1143         
1144         msel= (((MFace*)me->mface)+index);
1145         if (msel->flag & ME_HIDE) return;
1146         
1147         /* clear flags */
1148         mface = me->mface;
1149         a = me->totface;
1150         if ((G.qual & LR_SHIFTKEY)==0) {
1151                 while (a--) {
1152                         mface->flag &= ~ME_FACE_SEL;
1153                         mface++;
1154                 }
1155         }
1156         
1157         me->act_face = (int)index;
1158
1159         if (G.qual & LR_SHIFTKEY) {
1160                 if (msel->flag & ME_FACE_SEL)
1161                         msel->flag &= ~ME_FACE_SEL;
1162                 else
1163                         msel->flag |= ME_FACE_SEL;
1164         }
1165         else msel->flag |= ME_FACE_SEL;
1166         
1167         /* image window redraw */
1168         
1169         BIF_undo_push("Select UV face");
1170
1171         object_tface_flags_changed(OBACT, 1);
1172 }
1173
1174 void face_borderselect()
1175 {
1176         Mesh *me;
1177         MFace *mface;
1178         rcti rect;
1179         struct ImBuf *ibuf;
1180         unsigned int *rt;
1181         int a, sx, sy, index, val;
1182         char *selar;
1183         
1184         me= get_mesh(OBACT);
1185         if(me==0) return;
1186         if(me->totface==0) return;
1187         
1188         val= get_border(&rect, 3);
1189         
1190         /* why readbuffer here? shouldn't be necessary (maybe a flush or so) */
1191         glReadBuffer(GL_BACK);
1192 #ifdef __APPLE__
1193         glReadBuffer(GL_AUX0); /* apple only */
1194 #endif
1195         
1196         if(val) {
1197                 selar= MEM_callocN(me->totface+1, "selar");
1198                 
1199                 sx= (rect.xmax-rect.xmin+1);
1200                 sy= (rect.ymax-rect.ymin+1);
1201                 if(sx*sy<=0) return;
1202
1203                 ibuf = IMB_allocImBuf(sx,sy,32,IB_rect,0);
1204                 rt = ibuf->rect;
1205                 glReadPixels(rect.xmin+curarea->winrct.xmin,  rect.ymin+curarea->winrct.ymin, sx, sy, GL_RGBA, GL_UNSIGNED_BYTE,  ibuf->rect);
1206                 if(G.order==B_ENDIAN) IMB_convert_rgba_to_abgr(ibuf);
1207
1208                 a= sx*sy;
1209                 while(a--) {
1210                         if(*rt) {
1211                                 index= framebuffer_to_index(*rt);
1212                                 if(index<=me->totface) selar[index]= 1;
1213                         }
1214                         rt++;
1215                 }
1216                 
1217                 mface= me->mface;
1218                 for(a=1; a<=me->totface; a++, mface++) {
1219                         if(selar[a]) {
1220                                 if(mface->flag & ME_HIDE);
1221                                 else {
1222                                         if(val==LEFTMOUSE) mface->flag |= ME_FACE_SEL;
1223                                         else mface->flag &= ~ME_FACE_SEL;
1224                                 }
1225                         }
1226                 }
1227                 
1228                 IMB_freeImBuf(ibuf);
1229                 MEM_freeN(selar);
1230
1231                 BIF_undo_push("Border Select UV face");
1232
1233                 object_tface_flags_changed(OBACT, 0);
1234         }
1235 #ifdef __APPLE__        
1236         glReadBuffer(GL_BACK);
1237 #endif
1238 }
1239
1240 void uv_autocalc_tface()
1241 {
1242         short mode, i=0, has_pymenu=0; /* pymenu must be bigger then UV_*_MAPPING */
1243 #ifndef DISABLE_PYTHON
1244         BPyMenu *pym;
1245 #endif
1246         char menu_number[3];
1247         
1248         /* uvmenu, will add python items */
1249         char uvmenu[4096]=MENUTITLE("UV Calculation")
1250                                         MENUSTRING("Unwrap",                            UV_UNWRAP_MAPPING) "|%l|"
1251                                         
1252                                         MENUSTRING("Cube Projection",                   UV_CUBE_MAPPING) "|"
1253                                         MENUSTRING("Cylinder from View",                UV_CYL_MAPPING) "|"
1254                                         MENUSTRING("Sphere from View",                  UV_SPHERE_MAPPING) "|%l|"
1255
1256                                         MENUSTRING("Project From View",                 UV_WINDOW_MAPPING) "|"
1257                                         MENUSTRING("Project from View (Bounds)",UV_BOUNDS_MAPPING) "|%l|"
1258                                         
1259                                         MENUSTRING("Reset",                                             UV_RESET_MAPPING);
1260 #ifndef DISABLE_PYTHON
1261         /* note that we account for the 10 previous entries with i+10: */
1262         for (pym = BPyMenuTable[PYMENU_UVCALCULATION]; pym; pym = pym->next, i++) {
1263                 
1264                 if (!has_pymenu) {
1265                         strcat(uvmenu, "|%l");
1266                         has_pymenu = 1;
1267                 }
1268                 
1269                 strcat(uvmenu, "|");
1270                 strcat(uvmenu, pym->name);
1271                 strcat(uvmenu, " %x");
1272                 sprintf(menu_number, "%d", i+10);
1273                 strcat(uvmenu, menu_number);
1274         }
1275 #endif
1276         
1277         mode= pupmenu(uvmenu);
1278 #ifndef DISABLE_PYTHON
1279         if (mode >= 10) {
1280                 BPY_menu_do_python(PYMENU_UVCALCULATION, mode - 10);
1281                 return;
1282         }
1283 #endif  
1284         switch(mode) {
1285         case UV_CUBE_MAPPING:
1286                 calculate_uv_map(B_UVAUTO_CUBE); break;
1287         case UV_CYL_MAPPING:
1288                 calculate_uv_map(B_UVAUTO_CYLINDER); break;
1289         case UV_SPHERE_MAPPING:
1290                 calculate_uv_map(B_UVAUTO_SPHERE); break;
1291         case UV_BOUNDS_MAPPING:
1292                 calculate_uv_map(B_UVAUTO_BOUNDS); break;
1293         case UV_RESET_MAPPING:
1294                 calculate_uv_map(B_UVAUTO_RESET); break;
1295         case UV_WINDOW_MAPPING:
1296                 calculate_uv_map(B_UVAUTO_WINDOW); break;
1297         case UV_UNWRAP_MAPPING:
1298                 unwrap_lscm(0); break;
1299         }
1300 }
1301
1302 /* Texture Paint */
1303
1304 void set_texturepaint() /* toggle */
1305 {
1306         Object *ob = OBACT;
1307         Mesh *me = 0;
1308         
1309         scrarea_queue_headredraw(curarea);
1310         if(ob==NULL) return;
1311         
1312         if (object_data_is_libdata(ob)) {
1313                 error_libdata();
1314                 return;
1315         }
1316
1317         me= get_mesh(ob);
1318         
1319         if(me)
1320                 DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
1321
1322         if(G.f & G_TEXTUREPAINT) {
1323                 G.f &= ~G_TEXTUREPAINT;
1324                 GPU_paint_set_mipmap(1);
1325         }
1326         else if (me) {
1327                 G.f |= G_TEXTUREPAINT;
1328
1329                 if(me->mtface==NULL)
1330                         make_tfaces(me);
1331
1332                 brush_check_exists(&G.scene->toolsettings->imapaint.brush);
1333                 GPU_paint_set_mipmap(0);
1334         }
1335
1336         allqueue(REDRAWVIEW3D, 0);
1337         allqueue(REDRAWBUTSEDIT, 0);
1338 }
1339
1340 static void texpaint_project(Object *ob, float *model, float *proj, float *co, float *pco)
1341 {
1342         VECCOPY(pco, co);
1343         pco[3]= 1.0f;
1344
1345         Mat4MulVecfl(ob->obmat, pco);
1346         Mat4MulVecfl((float(*)[4])model, pco);
1347         Mat4MulVec4fl((float(*)[4])proj, pco);
1348 }
1349
1350 static void texpaint_tri_weights(Object *ob, float *v1, float *v2, float *v3, float *co, float *w)
1351 {
1352         float pv1[4], pv2[4], pv3[4], h[3], divw;
1353         float model[16], proj[16], wmat[3][3], invwmat[3][3];
1354         GLint view[4];
1355
1356         /* compute barycentric coordinates */
1357
1358         /* get the needed opengl matrices */
1359         glGetIntegerv(GL_VIEWPORT, view);
1360         glGetFloatv(GL_MODELVIEW_MATRIX, model);
1361         glGetFloatv(GL_PROJECTION_MATRIX, proj);
1362         view[0] = view[1] = 0;
1363
1364         /* project the verts */
1365         texpaint_project(ob, model, proj, v1, pv1);
1366         texpaint_project(ob, model, proj, v2, pv2);
1367         texpaint_project(ob, model, proj, v3, pv3);
1368
1369         /* do inverse view mapping, see gluProject man page */
1370         h[0]= (co[0] - view[0])*2.0f/view[2] - 1;
1371         h[1]= (co[1] - view[1])*2.0f/view[3] - 1;
1372         h[2]= 1.0f;
1373
1374         /* solve for (w1,w2,w3)/perspdiv in:
1375            h*perspdiv = Project*Model*(w1*v1 + w2*v2 + w3*v3) */
1376
1377         wmat[0][0]= pv1[0];  wmat[1][0]= pv2[0];  wmat[2][0]= pv3[0];
1378         wmat[0][1]= pv1[1];  wmat[1][1]= pv2[1];  wmat[2][1]= pv3[1];
1379         wmat[0][2]= pv1[3];  wmat[1][2]= pv2[3];  wmat[2][2]= pv3[3];
1380
1381         Mat3Inv(invwmat, wmat);
1382         Mat3MulVecfl(invwmat, h);
1383
1384         VECCOPY(w, h);
1385
1386         /* w is still divided by perspdiv, make it sum to one */
1387         divw= w[0] + w[1] + w[2];
1388         if(divw != 0.0f)
1389                 VecMulf(w, 1.0f/divw);
1390 }
1391
1392 /* compute uv coordinates of mouse in face */
1393 void texpaint_pick_uv(Object *ob, Mesh *mesh, unsigned int faceindex, short *xy, float *uv)
1394 {
1395         DerivedMesh *dm = mesh_get_derived_final(ob, CD_MASK_BAREMESH);
1396         int *index = dm->getFaceDataArray(dm, CD_ORIGINDEX);
1397         MTFace *tface = dm->getFaceDataArray(dm, CD_MTFACE), *tf;
1398         int numfaces = dm->getNumFaces(dm), a;
1399         float p[2], w[3], absw, minabsw;
1400         MFace mf;
1401         MVert mv[4];
1402
1403         minabsw = 1e10;
1404         uv[0] = uv[1] = 0.0;
1405
1406         persp(PERSP_VIEW);
1407
1408         /* test all faces in the derivedmesh with the original index of the picked face */
1409         for (a = 0; a < numfaces; a++) {
1410                 if (index[a] == faceindex) {
1411                         dm->getFace(dm, a, &mf);
1412
1413                         dm->getVert(dm, mf.v1, &mv[0]);
1414                         dm->getVert(dm, mf.v2, &mv[1]);
1415                         dm->getVert(dm, mf.v3, &mv[2]);
1416                         if (mf.v4)
1417                                 dm->getVert(dm, mf.v4, &mv[3]);
1418
1419                         tf= &tface[a];
1420
1421                         p[0]= xy[0];
1422                         p[1]= xy[1];
1423
1424                         if (mf.v4) {
1425                                 /* the triangle with the largest absolute values is the one
1426                                    with the most negative weights */
1427                                 texpaint_tri_weights(ob, mv[0].co, mv[1].co, mv[3].co, p, w);
1428                                 absw= fabs(w[0]) + fabs(w[1]) + fabs(w[2]);
1429                                 if(absw < minabsw) {
1430                                         uv[0]= tf->uv[0][0]*w[0] + tf->uv[1][0]*w[1] + tf->uv[3][0]*w[2];
1431                                         uv[1]= tf->uv[0][1]*w[0] + tf->uv[1][1]*w[1] + tf->uv[3][1]*w[2];
1432                                         minabsw = absw;
1433                                 }
1434
1435                                 texpaint_tri_weights(ob, mv[1].co, mv[2].co, mv[3].co, p, w);
1436                                 absw= fabs(w[0]) + fabs(w[1]) + fabs(w[2]);
1437                                 if (absw < minabsw) {
1438                                         uv[0]= tf->uv[1][0]*w[0] + tf->uv[2][0]*w[1] + tf->uv[3][0]*w[2];
1439                                         uv[1]= tf->uv[1][1]*w[0] + tf->uv[2][1]*w[1] + tf->uv[3][1]*w[2];
1440                                         minabsw = absw;
1441                                 }
1442                         }
1443                         else {
1444                                 texpaint_tri_weights(ob, mv[0].co, mv[1].co, mv[2].co, p, w);
1445                                 absw= fabs(w[0]) + fabs(w[1]) + fabs(w[2]);
1446                                 if (absw < minabsw) {
1447                                         uv[0]= tf->uv[0][0]*w[0] + tf->uv[1][0]*w[1] + tf->uv[2][0]*w[2];
1448                                         uv[1]= tf->uv[0][1]*w[0] + tf->uv[1][1]*w[1] + tf->uv[2][1]*w[2];
1449                                         minabsw = absw;
1450                                 }
1451                         }
1452                 }
1453         }
1454
1455         dm->release(dm);
1456 }