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