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