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