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