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