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