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