more lint includes
[blender.git] / source / blender / editors / mesh / meshtools.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2004 by Blender Foundation
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         meshtools.c: no editmode (violated already :), tools operating on meshes
32 */
33
34 #include <stddef.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <math.h>
38 #include <float.h>
39
40 #include "MEM_guardedalloc.h"
41
42 #include "DNA_key_types.h"
43 #include "DNA_material_types.h"
44 #include "DNA_meshdata_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_scene_types.h"
47 #include "DNA_view3d_types.h"
48
49 #include "BLI_math.h"
50 #include "BLI_blenlib.h"
51 #include "BLI_editVert.h"
52 #include "BLI_ghash.h"
53 #include "BLI_rand.h" /* for randome face sorting */
54 #include "BLI_threads.h"
55
56
57 #include "BKE_blender.h"
58 #include "BKE_context.h"
59 #include "BKE_depsgraph.h"
60 #include "BKE_DerivedMesh.h"
61 #include "BKE_customdata.h"
62 #include "BKE_global.h"
63 #include "BKE_image.h"
64 #include "BKE_key.h"
65 #include "BKE_library.h"
66 #include "BKE_main.h"
67 #include "BKE_mesh.h"
68 #include "BKE_material.h"
69 #include "BKE_object.h"
70 #include "BKE_utildefines.h"
71 #include "BKE_report.h"
72
73 #include "BLO_sys_types.h" // for intptr_t support
74
75 #include "ED_mesh.h"
76 #include "ED_object.h"
77 #include "ED_view3d.h"
78
79 #include "WM_api.h"
80 #include "WM_types.h"
81
82 /* own include */
83 #include "mesh_intern.h"
84
85 /* XXX */
86 static int pupmenu() {return 0;}
87 /* XXX */
88
89
90 /* * ********************** no editmode!!! *********** */
91
92 /*********************** JOIN ***************************/
93
94 /* join selected meshes into the active mesh, context sensitive
95 return 0 if no join is made (error) and 1 of the join is done */
96
97 int join_mesh_exec(bContext *C, wmOperator *op)
98 {
99         Scene *scene= CTX_data_scene(C);
100         Object *ob= CTX_data_active_object(C);
101         Material **matar, *ma;
102         Mesh *me;
103         MVert *mvert, *mv, *mvertmain;
104         MEdge *medge = NULL, *medgemain;
105         MFace *mface = NULL, *mfacemain;
106         Key *key, *nkey=NULL;
107         KeyBlock *kb, *okb, *kbn;
108         float imat[4][4], cmat[4][4], *fp1, *fp2, curpos;
109         int a, b, totcol, totmat=0, totedge=0, totvert=0, totface=0, ok=0;
110         int vertofs, *matmap=NULL;
111         int     i, j, index, haskey=0, edgeofs, faceofs;
112         bDeformGroup *dg, *odg;
113         MDeformVert *dvert;
114         CustomData vdata, edata, fdata;
115
116         if(scene->obedit)
117                 return OPERATOR_CANCELLED;
118         
119         /* ob is the object we are adding geometry to */
120         if(!ob || ob->type!=OB_MESH)
121                 return OPERATOR_CANCELLED;
122         
123         /* count & check */
124         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
125                 if(base->object->type==OB_MESH) {
126                         me= base->object->data;
127                         
128                         totvert+= me->totvert;
129                         totedge+= me->totedge;
130                         totface+= me->totface;
131                         totmat+= base->object->totcol;
132                         
133                         if(base->object == ob)
134                                 ok= 1;
135                         
136                         /* check for shapekeys */
137                         if(me->key)
138                                 haskey++;
139                 }
140         }
141         CTX_DATA_END;
142         
143         /* that way the active object is always selected */ 
144         if(ok==0)
145                 return OPERATOR_CANCELLED;
146         
147         /* only join meshes if there are verts to join, there aren't too many, and we only had one mesh selected */
148         me= (Mesh *)ob->data;
149         key= me->key;
150         if(totvert==0 || totvert>MESH_MAX_VERTS || totvert==me->totvert) 
151                 return OPERATOR_CANCELLED;
152         
153         /* new material indices and material array */
154         matar= MEM_callocN(sizeof(void*)*totmat, "join_mesh matar");
155         if (totmat) matmap= MEM_callocN(sizeof(int)*totmat, "join_mesh matmap");
156         totcol= ob->totcol;
157         
158         /* obact materials in new main array, is nicer start! */
159         for(a=0; a<ob->totcol; a++) {
160                 matar[a]= give_current_material(ob, a+1);
161                 id_us_plus((ID *)matar[a]);
162                 /* increase id->us : will be lowered later */
163         }
164         
165         /* - if destination mesh had shapekeys, move them somewhere safe, and set up placeholders
166          *      with arrays that are large enough to hold shapekey data for all meshes
167          * -    if destination mesh didn't have shapekeys, but we encountered some in the meshes we're 
168          *      joining, set up a new keyblock and assign to the mesh
169          */
170         if(key) {
171                 /* make a duplicate copy that will only be used here... (must remember to free it!) */
172                 nkey= copy_key(key);
173                 
174                 /* for all keys in old block, clear data-arrays */
175                 for(kb= key->block.first; kb; kb= kb->next) {
176                         if(kb->data) MEM_freeN(kb->data);
177                         kb->data= MEM_callocN(sizeof(float)*3*totvert, "join_shapekey");
178                         kb->totelem= totvert;
179                         kb->weights= NULL;
180                 }
181         }
182         else if(haskey) {
183                 /* add a new key-block and add to the mesh */
184                 key= me->key= add_key((ID *)me);
185                 key->type = KEY_RELATIVE;
186         }
187         
188         /* first pass over objects - copying materials and vertexgroups across */
189         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
190                 /* only act if a mesh, and not the one we're joining to */
191                 if((ob!=base->object) && (base->object->type==OB_MESH)) {
192                         me= base->object->data;
193                         
194                         /* Join this object's vertex groups to the base one's */
195                         for(dg=base->object->defbase.first; dg; dg=dg->next) {
196                                 /* See if this group exists in the object (if it doesn't, add it to the end) */
197                                 for(odg=ob->defbase.first; odg; odg=odg->next) {
198                                         if(!strcmp(odg->name, dg->name)) {
199                                                 break;
200                                         }
201                                 }
202                                 if(!odg) {
203                                         odg = MEM_callocN(sizeof(bDeformGroup), "join deformGroup");
204                                         memcpy(odg, dg, sizeof(bDeformGroup));
205                                         BLI_addtail(&ob->defbase, odg);
206                                 }
207                         }
208                         if(ob->defbase.first && ob->actdef==0)
209                                 ob->actdef=1;
210                         
211                         
212                         if(me->totvert) {
213                                 /* Add this object's materials to the base one's if they don't exist already (but only if limits not exceeded yet) */
214                                 if(totcol < MAXMAT-1) {
215                                         for(a=1; a<=base->object->totcol; a++) {
216                                                 ma= give_current_material(base->object, a);
217
218                                                 for(b=0; b<totcol; b++) {
219                                                         if(ma == matar[b]) break;
220                                                 }
221                                                 if(b==totcol) {
222                                                         matar[b]= ma;
223                                                         if(ma)
224                                                                 ma->id.us++;
225                                                         totcol++;
226                                                 }
227                                                 if(totcol>=MAXMAT-1) 
228                                                         break;
229                                         }
230                                 }
231                                 
232                                 /* if this mesh has shapekeys, check if destination mesh already has matching entries too */
233                                 if(me->key && key) {
234                                         for(kb= me->key->block.first; kb; kb= kb->next) {
235                                                 /* if key doesn't exist in destination mesh, add it */
236                                                 if(key_get_named_keyblock(key, kb->name) == NULL) {
237                                                         /* copy this existing one over to the new shapekey block */
238                                                         kbn= MEM_dupallocN(kb);
239                                                         kbn->prev= kbn->next= NULL;
240                                                         
241                                                         /* adjust adrcode and other settings to fit (allocate a new data-array) */
242                                                         kbn->data= MEM_callocN(sizeof(float)*3*totvert, "joined_shapekey");
243                                                         kbn->totelem= totvert;
244                                                         kbn->weights= NULL;
245                                                         
246                                                         okb= key->block.last;
247                                                         curpos= (okb) ? okb->pos : -0.1f;
248                                                         if(key->type == KEY_RELATIVE)
249                                                                 kbn->pos= curpos + 0.1f;
250                                                         else
251                                                                 kbn->pos= curpos;
252                                                         
253                                                         BLI_addtail(&key->block, kbn);
254                                                         kbn->adrcode= key->totkey;
255                                                         key->totkey++;
256                                                         if(key->totkey==1) key->refkey= kbn;
257                                                         
258                                                         // XXX 2.5 Animato
259 #if 0
260                                                         /* also, copy corresponding ipo-curve to ipo-block if applicable */
261                                                         if(me->key->ipo && key->ipo) {
262                                                                 // FIXME... this is a luxury item!
263                                                                 puts("FIXME: ignoring IPO's when joining shapekeys on Meshes for now...");
264                                                         }
265 #endif
266                                                 }
267                                         }
268                                 }
269                         }
270                 }
271         }
272         CTX_DATA_END;
273         
274         /* setup new data for destination mesh */
275         memset(&vdata, 0, sizeof(vdata));
276         memset(&edata, 0, sizeof(edata));
277         memset(&fdata, 0, sizeof(fdata));
278         
279         mvert= CustomData_add_layer(&vdata, CD_MVERT, CD_CALLOC, NULL, totvert);
280         medge= CustomData_add_layer(&edata, CD_MEDGE, CD_CALLOC, NULL, totedge);
281         mface= CustomData_add_layer(&fdata, CD_MFACE, CD_CALLOC, NULL, totface);
282         
283         mvertmain= mvert;
284         medgemain= medge;
285         mfacemain= mface;
286         
287         vertofs= 0;
288         edgeofs= 0;
289         faceofs= 0;
290         
291         /* inverse transform for all selected meshes in this object */
292         invert_m4_m4(imat, ob->obmat);
293         
294         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
295                 /* only join if this is a mesh */
296                 if(base->object->type==OB_MESH) {
297                         me= base->object->data;
298                         
299                         if(me->totvert) {
300                                 /* standard data */
301                                 CustomData_merge(&me->vdata, &vdata, CD_MASK_MESH, CD_DEFAULT, totvert);
302                                 CustomData_copy_data(&me->vdata, &vdata, 0, vertofs, me->totvert);
303                                 
304                                 /* vertex groups */
305                                 dvert= CustomData_get(&vdata, vertofs, CD_MDEFORMVERT);
306                                 
307                                 /* NB: vertex groups here are new version */
308                                 if(dvert) {
309                                         for(i=0; i<me->totvert; i++) {
310                                                 for(j=0; j<dvert[i].totweight; j++) {
311                                                         /*      Find the old vertex group */
312                                                         odg = BLI_findlink(&base->object->defbase, dvert[i].dw[j].def_nr);
313                                                         if(odg) {
314                                                                 /*      Search for a match in the new object, and set new index */
315                                                                 for(dg=ob->defbase.first, index=0; dg; dg=dg->next, index++) {
316                                                                         if(!strcmp(dg->name, odg->name)) {
317                                                                                 dvert[i].dw[j].def_nr = index;
318                                                                                 break;
319                                                                         }
320                                                                 }
321                                                         }
322                                                 }
323                                         }
324                                 }
325                                 
326                                 /* if this is the object we're merging into, no need to do anything */
327                                 if(base->object != ob) {
328                                         /* watch this: switch matmul order really goes wrong */
329                                         mul_m4_m4m4(cmat, base->object->obmat, imat);
330                                         
331                                         /* transform vertex coordinates into new space */
332                                         for(a=0, mv=mvert; a < me->totvert; a++, mv++) {
333                                                 mul_m4_v3(cmat, mv->co);
334                                         }
335                                         
336                                         /* for each shapekey in destination mesh:
337                                          *      - if there's a matching one, copy it across (will need to transform vertices into new space...)
338                                          *      - otherwise, just copy own coordinates of mesh (no need to transform vertex coordinates into new space)
339                                          */
340                                         if(key) {
341                                                 /* if this mesh has any shapekeys, check first, otherwise just copy coordinates */
342                                                 for(kb= key->block.first; kb; kb= kb->next) {
343                                                         /* get pointer to where to write data for this mesh in shapekey's data array */
344                                                         fp1= ((float *)kb->data) + (vertofs*3); 
345                                                         
346                                                         /* check if this mesh has such a shapekey */
347                                                         okb= key_get_named_keyblock(me->key, kb->name);
348                                                         if(okb) {
349                                                                 /* copy this mesh's shapekey to the destination shapekey (need to transform first) */
350                                                                 fp2= ((float *)(okb->data));
351                                                                 for(a=0; a < me->totvert; a++, fp1+=3, fp2+=3) {
352                                                                         VECCOPY(fp1, fp2);
353                                                                         mul_m4_v3(cmat, fp1);
354                                                                 }
355                                                         }
356                                                         else {
357                                                                 /* copy this mesh's vertex coordinates to the destination shapekey */
358                                                                 mv= mvert;
359                                                                 for(a=0; a < me->totvert; a++, fp1+=3, mv++) {
360                                                                         VECCOPY(fp1, mv->co);
361                                                                 }
362                                                         }
363                                                 }
364                                         }
365                                 }
366                                 else {
367                                         /* for each shapekey in destination mesh:
368                                          *      - if it was an 'original', copy the appropriate data from nkey
369                                          *      - otherwise, copy across plain coordinates (no need to transform coordinates)
370                                          */
371                                         if(key) {
372                                                 for(kb= key->block.first; kb; kb= kb->next) {
373                                                         /* get pointer to where to write data for this mesh in shapekey's data array */
374                                                         fp1= ((float *)kb->data) + (vertofs*3); 
375                                                         
376                                                         /* check if this was one of the original shapekeys */
377                                                         okb= key_get_named_keyblock(nkey, kb->name);
378                                                         if(okb) {
379                                                                 /* copy this mesh's shapekey to the destination shapekey */
380                                                                 fp2= ((float *)(okb->data));
381                                                                 for(a=0; a < me->totvert; a++, fp1+=3, fp2+=3) {
382                                                                         VECCOPY(fp1, fp2);
383                                                                 }
384                                                         }
385                                                         else {
386                                                                 /* copy base-coordinates to the destination shapekey */
387                                                                 mv= mvert;
388                                                                 for(a=0; a < me->totvert; a++, fp1+=3, mv++) {
389                                                                         VECCOPY(fp1, mv->co);
390                                                                 }
391                                                         }
392                                                 }
393                                         }
394                                 }
395                                 
396                                 /* advance mvert pointer to end of base mesh's data */
397                                 mvert+= me->totvert;
398                         }
399                         
400                         if(me->totface) {
401                                 /* make mapping for materials */
402                                 for(a=1; a<=base->object->totcol; a++) {
403                                         ma= give_current_material(base->object, a);
404
405                                         for(b=0; b<totcol; b++) {
406                                                 if(ma == matar[b]) {
407                                                         matmap[a-1]= b;
408                                                         break;
409                                                 }
410                                         }
411                                 }
412                                 
413                                 CustomData_merge(&me->fdata, &fdata, CD_MASK_MESH, CD_DEFAULT, totface);
414                                 CustomData_copy_data(&me->fdata, &fdata, 0, faceofs, me->totface);
415                                 
416                                 for(a=0; a<me->totface; a++, mface++) {
417                                         mface->v1+= vertofs;
418                                         mface->v2+= vertofs;
419                                         mface->v3+= vertofs;
420                                         if(mface->v4) mface->v4+= vertofs;
421                                         
422                                         if (matmap)
423                                                 mface->mat_nr= matmap[(int)mface->mat_nr];
424                                         else 
425                                                 mface->mat_nr= 0;
426                                 }
427                                 
428                                 faceofs += me->totface;
429                         }
430                         
431                         if(me->totedge) {
432                                 CustomData_merge(&me->edata, &edata, CD_MASK_MESH, CD_DEFAULT, totedge);
433                                 CustomData_copy_data(&me->edata, &edata, 0, edgeofs, me->totedge);
434                                 
435                                 for(a=0; a<me->totedge; a++, medge++) {
436                                         medge->v1+= vertofs;
437                                         medge->v2+= vertofs;
438                                 }
439                                 
440                                 edgeofs += me->totedge;
441                         }
442                         
443                         /* vertofs is used to help newly added verts be reattached to their edge/face 
444                          * (cannot be set earlier, or else reattaching goes wrong)
445                          */
446                         vertofs += me->totvert;
447                         
448                         /* free base, now that data is merged */
449                         if(base->object != ob)
450                                 ED_base_object_free_and_unlink(scene, base);
451                 }
452         }
453         CTX_DATA_END;
454         
455         /* return to mesh we're merging to */
456         me= ob->data;
457         
458         CustomData_free(&me->vdata, me->totvert);
459         CustomData_free(&me->edata, me->totedge);
460         CustomData_free(&me->fdata, me->totface);
461
462         me->totvert= totvert;
463         me->totedge= totedge;
464         me->totface= totface;
465         
466         me->vdata= vdata;
467         me->edata= edata;
468         me->fdata= fdata;
469
470         mesh_update_customdata_pointers(me);
471         
472         /* old material array */
473         for(a=1; a<=ob->totcol; a++) {
474                 ma= ob->mat[a-1];
475                 if(ma) ma->id.us--;
476         }
477         for(a=1; a<=me->totcol; a++) {
478                 ma= me->mat[a-1];
479                 if(ma) ma->id.us--;
480         }
481         if(ob->mat) MEM_freeN(ob->mat);
482         if(ob->matbits) MEM_freeN(ob->matbits);
483         if(me->mat) MEM_freeN(me->mat);
484         ob->mat= me->mat= NULL;
485         ob->matbits= NULL;
486         
487         if(totcol) {
488                 me->mat= matar;
489                 ob->mat= MEM_callocN(sizeof(void *)*totcol, "join obmatar");
490                 ob->matbits= MEM_callocN(sizeof(char)*totcol, "join obmatbits");
491         }
492         else
493                 MEM_freeN(matar);
494         
495         ob->totcol= me->totcol= totcol;
496         ob->colbits= 0;
497
498         if (matmap) MEM_freeN(matmap);
499         
500         /* other mesh users */
501         test_object_materials((ID *)me);
502         
503         /* free temp copy of destination shapekeys (if applicable) */
504         if(nkey) {
505                 // XXX 2.5 Animato
506 #if 0
507                 /* free it's ipo too - both are not actually freed from memory yet as ID-blocks */
508                 if(nkey->ipo) {
509                         free_ipo(nkey->ipo);
510                         BLI_remlink(&G.main->ipo, nkey->ipo);
511                         MEM_freeN(nkey->ipo);
512                 }
513 #endif
514                 
515                 free_key(nkey);
516                 BLI_remlink(&G.main->key, nkey);
517                 MEM_freeN(nkey);
518         }
519         
520         DAG_scene_sort(scene);  // removed objects, need to rebuild dag before editmode call
521         
522         ED_object_enter_editmode(C, EM_WAITCURSOR);
523         ED_object_exit_editmode(C, EM_FREEDATA|EM_WAITCURSOR|EM_DO_UNDO);
524
525         WM_event_add_notifier(C, NC_SCENE|ND_OB_ACTIVE, scene);
526
527         return OPERATOR_FINISHED;
528 }
529
530 /*********************** JOIN AS SHAPES ***************************/
531
532 /* Append selected meshes vertex locations as shapes of the active mesh, 
533   return 0 if no join is made (error) and 1 of the join is done */
534
535 int join_mesh_shapes_exec(bContext *C, wmOperator *op)
536 {
537         Scene *scene= CTX_data_scene(C);
538         Object *ob= CTX_data_active_object(C);
539         Mesh *me= (Mesh *)ob->data;
540         Mesh *selme=NULL;
541         DerivedMesh *dm=NULL;
542         Key *key=me->key;
543         KeyBlock *kb;
544         int ok=0, nonequal_verts=0;
545         
546         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
547                 if (base->object == ob) continue;
548                 
549                 if (base->object->type==OB_MESH) {
550                         selme = (Mesh *)base->object->data;
551                         
552                         if (selme->totvert==me->totvert)
553                                 ok++;
554                         else
555                                 nonequal_verts=1;
556                 }
557         }
558         CTX_DATA_END;
559         
560         if (!ok) {
561                 if (nonequal_verts)
562                         BKE_report(op->reports, RPT_ERROR, "Selected meshes must have equal numbers of vertices.");
563                 else
564                         BKE_report(op->reports, RPT_ERROR, "No additional selected meshes with equal vertex count to join.");
565                 return OPERATOR_CANCELLED;
566         }
567         
568         if(key == NULL) {
569                 key= me->key= add_key((ID *)me);
570                 key->type= KEY_RELATIVE;
571
572                 /* first key added, so it was the basis. initialise it with the existing mesh */
573                 kb= add_keyblock(key, NULL);
574                 mesh_to_key(me, kb);
575         }
576         
577         /* now ready to add new keys from selected meshes */
578         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
579                 if (base->object == ob) continue;
580                 
581                 if(base->object->type==OB_MESH) {
582                         selme = (Mesh *)base->object->data;
583                         
584                         if (selme->totvert==me->totvert) {
585                                 dm = mesh_get_derived_deform(scene, base->object, CD_MASK_BAREMESH);
586                                 
587                                 if (!dm) continue;
588                                         
589                                 kb= add_keyblock(key, base->object->id.name+2);
590                                 
591                                 DM_to_meshkey(dm, me, kb);
592                                 
593                                 dm->release(dm);
594                         }
595                 }
596         }
597         CTX_DATA_END;
598         
599         WM_event_add_notifier(C, NC_SCENE|ND_OB_ACTIVE, scene);
600         
601         return OPERATOR_FINISHED;
602 }
603
604 /* ********************** SORT FACES ******************* */
605
606 static void permutate(void *list, int num, int size, int *index)
607 {
608         void *buf;
609         int len;
610         int i;
611
612         len = num * size;
613
614         buf = MEM_mallocN(len, "permutate");
615         memcpy(buf, list, len);
616         
617         for (i = 0; i < num; i++) {
618                 memcpy((char *)list + (i * size), (char *)buf + (index[i] * size), size);
619         }
620         MEM_freeN(buf);
621 }
622
623 /* sort faces on view axis */
624 static float *face_sort_floats;
625 static int float_sort(const void *v1, const void *v2)
626 {
627         float x1, x2;
628         
629         x1 = face_sort_floats[((int *) v1)[0]];
630         x2 = face_sort_floats[((int *) v2)[0]];
631         
632         if( x1 > x2 ) return 1;
633         else if( x1 < x2 ) return -1;
634         return 0;
635 }
636
637
638 void sort_faces(Scene *scene, View3D *v3d)
639 {
640         RegionView3D *rv3d= NULL; // get from context 
641         Object *ob= OBACT;
642         Mesh *me;
643         CustomDataLayer *layer;
644         int i, *index;
645         short event;
646         float reverse = 1;
647         int ctrl= 0;    // XXX
648         
649         if(!ob) return;
650         if(scene->obedit) return;
651         if(ob->type!=OB_MESH) return;
652         if (!v3d) return;
653         
654         me= ob->data;
655         if(me->totface==0) return;
656         
657         event = pupmenu(
658         "Sort Faces (Ctrl to reverse)%t|"
659         "View Axis%x1|"
660         "Cursor Distance%x2|"
661         "Material%x3|"
662         "Selection%x4|"
663         "Randomize%x5");
664         
665         if (event==-1) return;
666         
667         if(ctrl)
668                 reverse = -1;
669         
670 /*      create index list */
671         index = (int *) MEM_mallocN(sizeof(int) * me->totface, "sort faces");
672         for (i = 0; i < me->totface; i++) {
673                 index[i] = i;
674         }
675         
676         face_sort_floats = (float *) MEM_mallocN(sizeof(float) * me->totface, "sort faces float");
677         
678 /* sort index list instead of faces itself 
679    and apply this permutation to all face layers */
680    
681           if (event == 5) {
682                 /* Random */
683                 for(i=0; i<me->totface; i++) {
684                         face_sort_floats[i] = BLI_frand();
685                 }
686                 qsort(index, me->totface, sizeof(int), float_sort);             
687         } else {
688                 MFace *mf;
689                 float vec[3];
690                 float mat[4][4];
691                 float cur[3];
692                 
693                 if (event == 1)
694                         mul_m4_m4m4(mat, OBACT->obmat, rv3d->viewmat); /* apply the view matrix to the object matrix */
695                 else if (event == 2) { /* sort from cursor */
696                         if( v3d && v3d->localvd ) {
697                                 VECCOPY(cur, v3d->cursor);
698                         } else {
699                                 VECCOPY(cur, scene->cursor);
700                         }
701                         invert_m4_m4(mat, OBACT->obmat);
702                         mul_m4_v3(mat, cur);
703                 }
704                 
705                 mf= me->mface;
706                 for(i=0; i<me->totface; i++, mf++) {
707                         
708                         if (event==3) {
709                                 face_sort_floats[i] = ((float)mf->mat_nr)*reverse;
710                         } else if (event==4) {
711                                 /*selected first*/
712                                 if (mf->flag & ME_FACE_SEL)     face_sort_floats[i] = 0.0;
713                                 else                                            face_sort_floats[i] = reverse;
714                         } else {
715                                 /* find the faces center */
716                                 add_v3_v3v3(vec, (me->mvert+mf->v1)->co, (me->mvert+mf->v2)->co);
717                                 if (mf->v4) {
718                                         add_v3_v3v3(vec, vec, (me->mvert+mf->v3)->co);
719                                         add_v3_v3v3(vec, vec, (me->mvert+mf->v4)->co);
720                                         mul_v3_fl(vec, 0.25f);
721                                 } else {
722                                         add_v3_v3v3(vec, vec, (me->mvert+mf->v3)->co);
723                                         mul_v3_fl(vec, 1.0f/3.0f);
724                                 } /* done */
725                                 
726                                 if (event == 1) { /* sort on view axis */
727                                         mul_m4_v3(mat, vec);
728                                         face_sort_floats[i] = vec[2] * reverse;
729                                 } else if(event == 2) { /* distance from cursor*/
730                                         face_sort_floats[i] = len_v3v3(cur, vec) * reverse; /* back to front */
731                                 }
732                         }
733                 }
734                 qsort(index, me->totface, sizeof(int), float_sort);
735         }
736         
737         MEM_freeN(face_sort_floats);
738         
739         for(i = 0; i < me->fdata.totlayer; i++) {
740                 layer = &me->fdata.layers[i];
741                 permutate(layer->data, me->totface, CustomData_sizeof(layer->type), index);
742         }
743
744         MEM_freeN(index);
745
746         DAG_id_flush_update(ob->data, OB_RECALC_DATA);
747 }
748
749
750
751 /* ********************* MESH VERTEX OCTREE LOOKUP ************* */
752
753 /* important note; this is unfinished, needs better API for editmode, and custom threshold */
754
755 #define MOC_RES                 8
756 #define MOC_NODE_RES    8
757 #define MOC_THRESH              0.00002f
758
759 typedef struct MocNode {
760         struct MocNode *next;
761         intptr_t index[MOC_NODE_RES];
762 } MocNode;
763
764 static int mesh_octree_get_base_offs(float *co, float *offs, float *div)
765 {
766         int vx, vy, vz;
767         
768         vx= floor( (co[0]-offs[0])/div[0] );
769         vy= floor( (co[1]-offs[1])/div[1] );
770         vz= floor( (co[2]-offs[2])/div[2] );
771         
772         CLAMP(vx, 0, MOC_RES-1);
773         CLAMP(vy, 0, MOC_RES-1);
774         CLAMP(vz, 0, MOC_RES-1);
775
776         return (vx*MOC_RES*MOC_RES) + vy*MOC_RES + vz;
777 }
778
779 static void mesh_octree_add_node(MocNode **bt, intptr_t index)
780 {
781         if(*bt==NULL) {
782                 *bt= MEM_callocN(sizeof(MocNode), "MocNode");
783                 (*bt)->index[0]= index;
784         }
785         else {
786                 int a;
787                 for(a=0; a<MOC_NODE_RES; a++) {
788                         if((*bt)->index[a]==index)
789                                 return;
790                         else if((*bt)->index[a]==0) {
791                                 (*bt)->index[a]= index;
792                                 return;
793                         }
794                 }
795                 mesh_octree_add_node(&(*bt)->next, index);
796         }
797 }
798
799 static void mesh_octree_free_node(MocNode **bt)
800 {
801         if( (*bt)->next ) {
802                 mesh_octree_free_node(&(*bt)->next);
803         }
804         MEM_freeN(*bt);
805 }
806
807
808 /* temporal define, just to make nicer code below */
809 #define MOC_ADDNODE(vx, vy, vz) mesh_octree_add_node(basetable + ((vx)*MOC_RES*MOC_RES) + (vy)*MOC_RES + (vz), index)
810
811 static void mesh_octree_add_nodes(MocNode **basetable, float *co, float *offs, float *div, intptr_t index)
812 {
813         float fx, fy, fz;
814         int vx, vy, vz;
815         
816         if (!finite(co[0]) ||
817                 !finite(co[1]) ||
818                 !finite(co[2])
819         ) {
820                 return;
821         }
822         
823         fx= (co[0]-offs[0])/div[0];
824         fy= (co[1]-offs[1])/div[1];
825         fz= (co[2]-offs[2])/div[2];
826         CLAMP(fx, 0.0f, MOC_RES-MOC_THRESH);
827         CLAMP(fy, 0.0f, MOC_RES-MOC_THRESH);
828         CLAMP(fz, 0.0f, MOC_RES-MOC_THRESH);
829         
830         vx= floor(fx);
831         vy= floor(fy);
832         vz= floor(fz);
833         
834         MOC_ADDNODE(vx, vy, vz);
835         
836         if( vx>0 )
837                 if( fx-((float)vx)-MOC_THRESH < 0.0f)
838                         MOC_ADDNODE(vx-1, vy, vz);
839         if( vx<MOC_RES-2 )
840                 if( fx-((float)vx)+MOC_THRESH > 1.0f)
841                         MOC_ADDNODE(vx+1, vy, vz);
842
843         if( vy>0 )
844                 if( fy-((float)vy)-MOC_THRESH < 0.0f) 
845                         MOC_ADDNODE(vx, vy-1, vz);
846         if( vy<MOC_RES-2 )
847                 if( fy-((float)vy)+MOC_THRESH > 1.0f) 
848                         MOC_ADDNODE(vx, vy+1, vz);
849
850         if( vz>0 )
851                 if( fz-((float)vz)-MOC_THRESH < 0.0f) 
852                         MOC_ADDNODE(vx, vy, vz-1);
853         if( vz<MOC_RES-2 )
854                 if( fz-((float)vz)+MOC_THRESH > 1.0f) 
855                         MOC_ADDNODE(vx, vy, vz+1);
856         
857 }
858
859 static intptr_t mesh_octree_find_index(MocNode **bt, MVert *mvert, float *co)
860 {
861         float *vec;
862         int a;
863         
864         if(*bt==NULL)
865                 return -1;
866         
867         for(a=0; a<MOC_NODE_RES; a++) {
868                 if((*bt)->index[a]) {
869                         /* does mesh verts and editmode, code looks potential dangerous, octree should really be filled OK! */
870                         if(mvert) {
871                                 vec= (mvert+(*bt)->index[a]-1)->co;
872                                 if(compare_v3v3(vec, co, MOC_THRESH))
873                                         return (*bt)->index[a]-1;
874                         }
875                         else {
876                                 EditVert *eve= (EditVert *)((*bt)->index[a]);
877                                 if(compare_v3v3(eve->co, co, MOC_THRESH))
878                                         return (*bt)->index[a];
879                         }
880                 }
881                 else return -1;
882         }
883         if( (*bt)->next)
884                 return mesh_octree_find_index(&(*bt)->next, mvert, co);
885         
886         return -1;
887 }
888
889 static struct {
890         MocNode **table;
891         float offs[3], div[3];
892 } MeshOctree = {NULL, {0, 0, 0}, {0, 0, 0}};
893
894 /* mode is 's' start, or 'e' end, or 'u' use */
895 /* if end, ob can be NULL */
896 intptr_t mesh_octree_table(Object *ob, EditMesh *em, float *co, char mode)
897 {
898         MocNode **bt;
899         
900         if(mode=='u') {         /* use table */
901                 if(MeshOctree.table==NULL)
902                         mesh_octree_table(ob, em, NULL, 's');
903            
904                 if(MeshOctree.table) {
905                         Mesh *me= ob->data;
906                         bt= MeshOctree.table + mesh_octree_get_base_offs(co, MeshOctree.offs, MeshOctree.div);
907                         if(em)
908                                 return mesh_octree_find_index(bt, NULL, co);
909                         else
910                                 return mesh_octree_find_index(bt, me->mvert, co);
911                 }
912                 return -1;
913         }
914         else if(mode=='s') {    /* start table */
915                 Mesh *me= ob->data;
916                 float min[3], max[3];
917
918                 /* we compute own bounding box and don't reuse ob->bb because
919                  * we are using the undeformed coordinates*/
920                 INIT_MINMAX(min, max);
921
922                 if(em && me->edit_mesh==em) {
923                         EditVert *eve;
924                         
925                         for(eve= em->verts.first; eve; eve= eve->next)
926                                 DO_MINMAX(eve->co, min, max)
927                 }
928                 else {          
929                         MVert *mvert;
930                         int a;
931                         
932                         for(a=0, mvert= me->mvert; a<me->totvert; a++, mvert++)
933                                 DO_MINMAX(mvert->co, min, max);
934                 }
935                 
936                 /* for quick unit coordinate calculus */
937                 VECCOPY(MeshOctree.offs, min);
938                 MeshOctree.offs[0]-= MOC_THRESH;                /* we offset it 1 threshold unit extra */
939                 MeshOctree.offs[1]-= MOC_THRESH;
940                 MeshOctree.offs[2]-= MOC_THRESH;
941                 
942                 sub_v3_v3v3(MeshOctree.div, max, min);
943                 MeshOctree.div[0]+= 2*MOC_THRESH;       /* and divide with 2 threshold unit more extra (try 8x8 unit grid on paint) */
944                 MeshOctree.div[1]+= 2*MOC_THRESH;
945                 MeshOctree.div[2]+= 2*MOC_THRESH;
946                 
947                 mul_v3_fl(MeshOctree.div, 1.0f/MOC_RES);
948                 if(MeshOctree.div[0]==0.0f) MeshOctree.div[0]= 1.0f;
949                 if(MeshOctree.div[1]==0.0f) MeshOctree.div[1]= 1.0f;
950                 if(MeshOctree.div[2]==0.0f) MeshOctree.div[2]= 1.0f;
951                         
952                 if(MeshOctree.table) /* happens when entering this call without ending it */
953                         mesh_octree_table(ob, em, co, 'e');
954                 
955                 MeshOctree.table= MEM_callocN(MOC_RES*MOC_RES*MOC_RES*sizeof(void *), "sym table");
956                 
957                 if(em && me->edit_mesh==em) {
958                         EditVert *eve;
959
960                         for(eve= em->verts.first; eve; eve= eve->next) {
961                                 mesh_octree_add_nodes(MeshOctree.table, eve->co, MeshOctree.offs, MeshOctree.div, (intptr_t)(eve));
962                         }
963                 }
964                 else {          
965                         MVert *mvert;
966                         int a;
967                         
968                         for(a=0, mvert= me->mvert; a<me->totvert; a++, mvert++)
969                                 mesh_octree_add_nodes(MeshOctree.table, mvert->co, MeshOctree.offs, MeshOctree.div, a+1);
970                 }
971         }
972         else if(mode=='e') { /* end table */
973                 if(MeshOctree.table) {
974                         int a;
975                         
976                         for(a=0, bt=MeshOctree.table; a<MOC_RES*MOC_RES*MOC_RES; a++, bt++) {
977                                 if(*bt) mesh_octree_free_node(bt);
978                         }
979                         MEM_freeN(MeshOctree.table);
980                         MeshOctree.table= NULL;
981                 }
982         }
983         return 0;
984 }
985
986
987 /* ********************* MESH VERTEX MIRR TOPO LOOKUP *************** */
988
989 #define MIRRHASH_TYPE int
990
991 typedef struct MirrTopoPair {
992         long hash;
993         int vIndex;
994 } MirrTopoPair;
995
996 static int MirrTopo_long_sort(const void *l1, const void *l2)
997 {
998         if(                     (MIRRHASH_TYPE)(intptr_t)l1 > (MIRRHASH_TYPE)(intptr_t)l2 ) return  1;
999         else if(        (MIRRHASH_TYPE)(intptr_t)l1 < (MIRRHASH_TYPE)(intptr_t)l2 ) return -1;
1000         return 0;
1001 }
1002
1003 static int MirrTopo_item_sort(const void *v1, const void *v2)
1004 {
1005         if(                     ((MirrTopoPair *)v1)->hash > ((MirrTopoPair *)v2)->hash ) return  1;
1006         else if(        ((MirrTopoPair *)v1)->hash < ((MirrTopoPair *)v2)->hash ) return -1;
1007         return 0;
1008 }
1009
1010 static long *mesh_topo_lookup = NULL;
1011 static int  mesh_topo_lookup_tot = -1;
1012 static int  mesh_topo_lookup_mode = -1;
1013
1014 /* mode is 's' start, or 'e' end, or 'u' use */
1015 /* if end, ob can be NULL */
1016 long mesh_mirrtopo_table(Object *ob, char mode)
1017 {
1018         if(mode=='u') {         /* use table */
1019                 Mesh *me= ob->data;
1020                 if(     (mesh_topo_lookup==NULL) ||
1021                         (mesh_topo_lookup_mode != ob->mode) ||
1022                         (me->edit_mesh && me->edit_mesh->totvert != mesh_topo_lookup_tot) ||
1023                         (me->edit_mesh==NULL && me->totvert != mesh_topo_lookup_tot)
1024                 ) {
1025                         mesh_mirrtopo_table(ob, 's');
1026                 }
1027         } else if(mode=='s') { /* start table */
1028                 Mesh *me= ob->data;
1029                 MEdge *medge;
1030                 EditMesh *em= me->edit_mesh;
1031
1032
1033                 /* editmode*/
1034                 EditEdge *eed;
1035
1036                 int a, last, totvert;
1037                 int totUnique= -1, totUniqueOld= -1;
1038
1039                 MIRRHASH_TYPE *MirrTopoHash = NULL;
1040                 MIRRHASH_TYPE *MirrTopoHash_Prev = NULL;
1041                 MirrTopoPair *MirrTopoPairs;
1042                 mesh_topo_lookup_mode= ob->mode;
1043
1044                 /* reallocate if needed */
1045                 if (mesh_topo_lookup) {
1046                         MEM_freeN(mesh_topo_lookup);
1047                         mesh_topo_lookup = NULL;
1048                 }
1049
1050                 if(em) {
1051                         EditVert *eve;
1052                         totvert= 0;
1053                         for(eve= em->verts.first; eve; eve= eve->next) {
1054                                 eve->hash = totvert++;
1055                         }
1056                 } else {
1057                         totvert = me->totvert;
1058                 }
1059
1060                 MirrTopoHash = MEM_callocN( totvert * sizeof(MIRRHASH_TYPE), "TopoMirr" );
1061
1062                 /* Initialize the vert-edge-user counts used to detect unique topology */
1063                 if(em) {
1064                         for(eed=em->edges.first; eed; eed= eed->next) {
1065                                 MirrTopoHash[eed->v1->hash]++;
1066                                 MirrTopoHash[eed->v2->hash]++;
1067                         }
1068                 } else {
1069                         for(a=0, medge=me->medge; a<me->totedge; a++, medge++) {
1070                                 MirrTopoHash[medge->v1]++;
1071                                 MirrTopoHash[medge->v2]++;
1072                         }
1073                 }
1074
1075                 MirrTopoHash_Prev = MEM_dupallocN( MirrTopoHash );
1076
1077                 totUniqueOld = -1;
1078                 while(1) {
1079                         /* use the number of edges per vert to give verts unique topology IDs */
1080
1081                         if(em) {
1082                                 for(eed=em->edges.first; eed; eed= eed->next) {
1083                                         MirrTopoHash[eed->v1->hash] += MirrTopoHash_Prev[eed->v2->hash];
1084                                         MirrTopoHash[eed->v2->hash] += MirrTopoHash_Prev[eed->v1->hash];
1085                                 }
1086                         } else {
1087                                 for(a=0, medge=me->medge; a<me->totedge; a++, medge++) {
1088                                         /* This can make realy big numbers, wrapping around here is fine */
1089                                         MirrTopoHash[medge->v1] += MirrTopoHash_Prev[medge->v2];
1090                                         MirrTopoHash[medge->v2] += MirrTopoHash_Prev[medge->v1];
1091                                 }
1092                         }
1093                         memcpy(MirrTopoHash_Prev, MirrTopoHash, sizeof(MIRRHASH_TYPE) * totvert);
1094
1095                         /* sort so we can count unique values */
1096                         qsort(MirrTopoHash_Prev, totvert, sizeof(MIRRHASH_TYPE), MirrTopo_long_sort);
1097
1098                         totUnique = 1; /* account for skiping the first value */
1099                         for(a=1; a<totvert; a++) {
1100                                 if (MirrTopoHash_Prev[a-1] != MirrTopoHash_Prev[a]) {
1101                                         totUnique++;
1102                                 }
1103                         }
1104
1105                         if (totUnique <= totUniqueOld) {
1106                                 /* Finish searching for unique valus when 1 loop dosnt give a
1107                                  * higher number of unique values compared to the previous loop */
1108                                 break;
1109                         } else {
1110                                 totUniqueOld = totUnique;
1111                         }
1112                         /* Copy the hash calculated this iter, so we can use them next time */
1113                         memcpy(MirrTopoHash_Prev, MirrTopoHash, sizeof(MIRRHASH_TYPE) * totvert);
1114                 }
1115
1116                 /* Hash/Index pairs are needed for sorting to find index pairs */
1117                 MirrTopoPairs= MEM_callocN( sizeof(MirrTopoPair) * totvert, "MirrTopoPairs");
1118
1119                 /* since we are looping through verts, initialize these values here too */
1120                 mesh_topo_lookup = MEM_mallocN( totvert * sizeof(long), "mesh_topo_lookup" );
1121
1122                 if(em) {
1123                         EM_init_index_arrays(em,1,0,0);
1124                 }
1125
1126
1127                 for(a=0; a<totvert; a++) {
1128                         MirrTopoPairs[a].hash= MirrTopoHash[a];
1129                         MirrTopoPairs[a].vIndex = a;
1130
1131                         /* initialize lookup */
1132                         mesh_topo_lookup[a] = -1;
1133                 }
1134
1135                 qsort(MirrTopoPairs, totvert, sizeof(MirrTopoPair), MirrTopo_item_sort);
1136
1137                 /* Since the loop starts at 2, we must define the last index where the hash's differ */
1138                 last = ((totvert >= 2) && (MirrTopoPairs[0].hash == MirrTopoPairs[1].hash)) ? 0 : 1;
1139
1140                 /* Get the pairs out of the sorted hashes, note, totvert+1 means we can use the previous 2,
1141                  * but you cant ever access the last 'a' index of MirrTopoPairs */
1142                 for(a=2; a < totvert+1; a++) {
1143                         /* printf("I %d %ld %d\n", (a-last), MirrTopoPairs[a  ].hash, MirrTopoPairs[a  ].vIndex ); */
1144                         if ((a==totvert) || (MirrTopoPairs[a-1].hash != MirrTopoPairs[a].hash)) {
1145                                 if (a-last==2) {
1146                                         if(em) {
1147                                                 mesh_topo_lookup[MirrTopoPairs[a-1].vIndex] =   (long)EM_get_vert_for_index(MirrTopoPairs[a-2].vIndex);
1148                                                 mesh_topo_lookup[MirrTopoPairs[a-2].vIndex] =   (long)EM_get_vert_for_index(MirrTopoPairs[a-1].vIndex);
1149                                         } else {
1150                                                 mesh_topo_lookup[MirrTopoPairs[a-1].vIndex] =   MirrTopoPairs[a-2].vIndex;
1151                                                 mesh_topo_lookup[MirrTopoPairs[a-2].vIndex] =   MirrTopoPairs[a-1].vIndex;
1152                                         }
1153                                 }
1154                                 last= a;
1155                         }
1156                 }
1157                 if(em) {
1158                         EM_free_index_arrays();
1159                 }
1160
1161                 MEM_freeN( MirrTopoPairs );
1162                 MirrTopoPairs = NULL;
1163
1164                 MEM_freeN( MirrTopoHash );
1165                 MEM_freeN( MirrTopoHash_Prev );
1166
1167                 mesh_topo_lookup_tot = totvert;
1168
1169         } else if(mode=='e') { /* end table */
1170                 if (mesh_topo_lookup) {
1171                         MEM_freeN(mesh_topo_lookup);
1172                 }
1173                 mesh_topo_lookup = NULL;
1174                 mesh_topo_lookup_tot= -1;
1175         }
1176         return 0;
1177 }
1178
1179 int mesh_get_x_mirror_vert_spacial(Object *ob, int index)
1180 {
1181         Mesh *me= ob->data;
1182         MVert *mvert;
1183         float vec[3];
1184         
1185         mvert= me->mvert+index;
1186         vec[0]= -mvert->co[0];
1187         vec[1]= mvert->co[1];
1188         vec[2]= mvert->co[2];
1189         
1190         return mesh_octree_table(ob, NULL, vec, 'u');
1191 }
1192
1193 static int mesh_get_x_mirror_vert_topo(Object *ob, int index)
1194 {
1195         if (mesh_mirrtopo_table(ob, 'u')==-1)
1196                 return -1;
1197
1198         return mesh_topo_lookup[index];
1199 }
1200
1201 int mesh_get_x_mirror_vert(Object *ob, int index)
1202 {
1203         if (((Mesh *)ob->data)->editflag & ME_EDIT_MIRROR_TOPO) {
1204                 return mesh_get_x_mirror_vert_topo(ob, index);
1205         } else {
1206                 return mesh_get_x_mirror_vert_spacial(ob, index);
1207         }
1208 }
1209
1210 static EditVert *editmesh_get_x_mirror_vert_spacial(Object *ob, EditMesh *em, float *co)
1211 {
1212         float vec[3];
1213         intptr_t poinval;
1214         
1215         /* ignore nan verts */
1216         if (!finite(co[0]) ||
1217                 !finite(co[1]) ||
1218                 !finite(co[2])
1219            )
1220                 return NULL;
1221         
1222         vec[0]= -co[0];
1223         vec[1]= co[1];
1224         vec[2]= co[2];
1225         
1226         poinval= mesh_octree_table(ob, em, vec, 'u');
1227         if(poinval != -1)
1228                 return (EditVert *)(poinval);
1229         return NULL;
1230 }
1231
1232 static EditVert *editmesh_get_x_mirror_vert_topo(Object *ob, struct EditMesh *em, EditVert *eve, int index)
1233 {
1234         long poinval;
1235         if (mesh_mirrtopo_table(ob, 'u')==-1)
1236                 return NULL;
1237
1238         if (index!=-1) {
1239                 index = BLI_findindex(&em->verts, eve);
1240         }
1241
1242         if (index==-1)
1243                 return NULL;
1244
1245         poinval= mesh_topo_lookup[ index ];
1246
1247         if(poinval != -1)
1248                 return (EditVert *)(poinval);
1249         return NULL;
1250 }
1251
1252 EditVert *editmesh_get_x_mirror_vert(Object *ob, struct EditMesh *em, EditVert *eve, float *co, int index)
1253 {
1254         if (((Mesh *)ob->data)->editflag & ME_EDIT_MIRROR_TOPO) {
1255                 return editmesh_get_x_mirror_vert_topo(ob, em, eve, index);
1256         } else {
1257                 return editmesh_get_x_mirror_vert_spacial(ob, em, eve->co);
1258         }
1259 }
1260
1261
1262 #if 0
1263 float *editmesh_get_mirror_uv(int axis, float *uv, float *mirrCent, float *face_cent)
1264 {
1265         float vec[2];
1266         float cent_vec[2];
1267         float cent[2];
1268
1269         /* ignore nan verts */
1270         if (isnan(uv[0]) || !finite(uv[0]) ||
1271                 isnan(uv[1]) || !finite(uv[1])
1272            )
1273                 return NULL;
1274
1275         if (axis) {
1276                 vec[0]= uv[0];
1277                 vec[1]= -((uv[1])-mirrCent[1]) + mirrCent[1];
1278
1279                 cent_vec[0] = face_cent[0];
1280                 cent_vec[1]= -((face_cent[1])-mirrCent[1]) + mirrCent[1];
1281         } else {
1282                 vec[0]= -((uv[0])-mirrCent[0]) + mirrCent[0];
1283                 vec[1]= uv[1];
1284
1285                 cent_vec[0]= -((face_cent[0])-mirrCent[0]) + mirrCent[0];
1286                 cent_vec[1] = face_cent[1];
1287         }
1288
1289         /*
1290         G.v2d->cursor[0] = mirrCent[0];
1291         G.v2d->cursor[1] = mirrCent[1];
1292         */
1293
1294         /* TODO - Optimize */
1295         {
1296                 EditFace *efa;
1297                 int i, len;
1298                 for(efa=em->faces.first; efa; efa=efa->next) {
1299                         MTFace *tf= (MTFace *)CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1300                         uv_center(tf->uv, cent, (void *)efa->v4);
1301
1302                         if ( (fabs(cent[0] - cent_vec[0]) < 0.001) && (fabs(cent[1] - cent_vec[1]) < 0.001) ) {
1303                                 len = efa->v4 ? 4 : 3;
1304                                 for (i=0; i<len; i++) {
1305                                         if ( (fabs(tf->uv[i][0] - vec[0]) < 0.001) && (fabs(tf->uv[i][1] - vec[1]) < 0.001) ) {
1306                                                 return tf->uv[i];
1307                                         }
1308                                 }
1309                         }
1310                 }
1311         }
1312
1313         return NULL;
1314 }
1315 #endif
1316
1317 static unsigned int mirror_facehash(void *ptr)
1318 {
1319         MFace *mf= ptr;
1320         int v0, v1;
1321
1322         if(mf->v4) {
1323                 v0= MIN4(mf->v1, mf->v2, mf->v3, mf->v4);
1324                 v1= MAX4(mf->v1, mf->v2, mf->v3, mf->v4);
1325         }
1326         else {
1327                 v0= MIN3(mf->v1, mf->v2, mf->v3);
1328                 v1= MAX3(mf->v1, mf->v2, mf->v3);
1329         }
1330
1331         return ((v0*39)^(v1*31));
1332 }
1333
1334 static int mirror_facerotation(MFace *a, MFace *b)
1335 {
1336         if(b->v4) {
1337                 if(a->v1==b->v1 && a->v2==b->v2 && a->v3==b->v3 && a->v4==b->v4)
1338                         return 0;
1339                 else if(a->v4==b->v1 && a->v1==b->v2 && a->v2==b->v3 && a->v3==b->v4)
1340                         return 1;
1341                 else if(a->v3==b->v1 && a->v4==b->v2 && a->v1==b->v3 && a->v2==b->v4)
1342                         return 2;
1343                 else if(a->v2==b->v1 && a->v3==b->v2 && a->v4==b->v3 && a->v1==b->v4)
1344                         return 3;
1345         }
1346         else {
1347                 if(a->v1==b->v1 && a->v2==b->v2 && a->v3==b->v3)
1348                         return 0;
1349                 else if(a->v3==b->v1 && a->v1==b->v2 && a->v2==b->v3)
1350                         return 1;
1351                 else if(a->v2==b->v1 && a->v3==b->v2 && a->v1==b->v3)
1352                         return 2;
1353         }
1354         
1355         return -1;
1356 }
1357
1358 static int mirror_facecmp(void *a, void *b)
1359 {
1360         return (mirror_facerotation((MFace*)a, (MFace*)b) == -1);
1361 }
1362
1363 int *mesh_get_x_mirror_faces(Object *ob, EditMesh *em)
1364 {
1365         Mesh *me= ob->data;
1366         MVert *mv, *mvert= me->mvert;
1367         MFace mirrormf, *mf, *hashmf, *mface= me->mface;
1368         GHash *fhash;
1369         int *mirrorverts, *mirrorfaces;
1370         int a;
1371
1372         mirrorverts= MEM_callocN(sizeof(int)*me->totvert, "MirrorVerts");
1373         mirrorfaces= MEM_callocN(sizeof(int)*2*me->totface, "MirrorFaces");
1374
1375         mesh_octree_table(ob, em, NULL, 's');
1376
1377         for(a=0, mv=mvert; a<me->totvert; a++, mv++)
1378                 mirrorverts[a]= mesh_get_x_mirror_vert(ob, a);
1379
1380         mesh_octree_table(ob, em, NULL, 'e');
1381
1382         fhash= BLI_ghash_new(mirror_facehash, mirror_facecmp);
1383         for(a=0, mf=mface; a<me->totface; a++, mf++)
1384                 BLI_ghash_insert(fhash, mf, mf);
1385
1386         for(a=0, mf=mface; a<me->totface; a++, mf++) {
1387                 mirrormf.v1= mirrorverts[mf->v3];
1388                 mirrormf.v2= mirrorverts[mf->v2];
1389                 mirrormf.v3= mirrorverts[mf->v1];
1390                 mirrormf.v4= (mf->v4)? mirrorverts[mf->v4]: 0;
1391
1392                 /* make sure v4 is not 0 if a quad */
1393                 if(mf->v4 && mirrormf.v4==0) {
1394                         SWAP(int, mirrormf.v1, mirrormf.v3);
1395                         SWAP(int, mirrormf.v2, mirrormf.v4);
1396                 }
1397
1398                 hashmf= BLI_ghash_lookup(fhash, &mirrormf);
1399                 if(hashmf) {
1400                         mirrorfaces[a*2]= hashmf - mface;
1401                         mirrorfaces[a*2+1]= mirror_facerotation(&mirrormf, hashmf);
1402                 }
1403                 else
1404                         mirrorfaces[a*2]= -1;
1405         }
1406
1407         BLI_ghash_free(fhash, NULL, NULL);
1408         MEM_freeN(mirrorverts);
1409         
1410         return mirrorfaces;
1411 }