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