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