svn merge ^/trunk/blender -r41998:42009
[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);
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         ob->colbits= 0;
552
553         if (matmap) MEM_freeN(matmap);
554         
555         /* other mesh users */
556         test_object_materials((ID *)me);
557         
558         /* free temp copy of destination shapekeys (if applicable) */
559         if(nkey) {
560                 // XXX 2.5 Animato
561 #if 0
562                 /* free it's ipo too - both are not actually freed from memory yet as ID-blocks */
563                 if(nkey->ipo) {
564                         free_ipo(nkey->ipo);
565                         BLI_remlink(&bmain->ipo, nkey->ipo);
566                         MEM_freeN(nkey->ipo);
567                 }
568 #endif
569                 
570                 free_key(nkey);
571                 BLI_remlink(&bmain->key, nkey);
572                 MEM_freeN(nkey);
573         }
574         
575         DAG_scene_sort(bmain, scene);   // removed objects, need to rebuild dag before editmode call
576
577 #if 0
578         ED_object_enter_editmode(C, EM_WAITCURSOR);
579         ED_object_exit_editmode(C, EM_FREEDATA|EM_WAITCURSOR|EM_DO_UNDO);
580 #else
581         /* toggle editmode using lower level functions so this can be called from python */
582         EDBM_MakeEditBMesh(scene->toolsettings, scene, ob);
583         EDBM_LoadEditBMesh(scene, ob);
584         EDBM_FreeEditBMesh(me->edit_btmesh);
585         MEM_freeN(me->edit_btmesh);
586         me->edit_btmesh= NULL;
587         DAG_id_tag_update(&ob->id, OB_RECALC_OB|OB_RECALC_DATA);
588 #endif
589         WM_event_add_notifier(C, NC_SCENE|ND_OB_ACTIVE, scene);
590
591         return OPERATOR_FINISHED;
592 }
593
594 /*********************** JOIN AS SHAPES ***************************/
595
596 /* Append selected meshes vertex locations as shapes of the active mesh, 
597   return 0 if no join is made (error) and 1 of the join is done */
598
599 int join_mesh_shapes_exec(bContext *C, wmOperator *op)
600 {
601         Scene *scene= CTX_data_scene(C);
602         Object *ob= CTX_data_active_object(C);
603         Mesh *me= (Mesh *)ob->data;
604         Mesh *selme=NULL;
605         DerivedMesh *dm=NULL;
606         Key *key=me->key;
607         KeyBlock *kb;
608         int ok=0, nonequal_verts=0;
609         
610         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
611                 if (base->object == ob) continue;
612                 
613                 if (base->object->type==OB_MESH) {
614                         selme = (Mesh *)base->object->data;
615                         
616                         if (selme->totvert==me->totvert)
617                                 ok++;
618                         else
619                                 nonequal_verts=1;
620                 }
621         }
622         CTX_DATA_END;
623         
624         if (!ok) {
625                 if (nonequal_verts)
626                         BKE_report(op->reports, RPT_WARNING, "Selected meshes must have equal numbers of vertices");
627                 else
628                         BKE_report(op->reports, RPT_WARNING, "No additional selected meshes with equal vertex count to join");
629                 return OPERATOR_CANCELLED;
630         }
631         
632         if(key == NULL) {
633                 key= me->key= add_key((ID *)me);
634                 key->type= KEY_RELATIVE;
635
636                 /* first key added, so it was the basis. initialise it with the existing mesh */
637                 kb= add_keyblock(key, NULL);
638                 mesh_to_key(me, kb);
639         }
640         
641         /* now ready to add new keys from selected meshes */
642         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
643                 if (base->object == ob) continue;
644                 
645                 if(base->object->type==OB_MESH) {
646                         selme = (Mesh *)base->object->data;
647                         
648                         if (selme->totvert==me->totvert) {
649                                 dm = mesh_get_derived_deform(scene, base->object, CD_MASK_BAREMESH);
650                                 
651                                 if (!dm) continue;
652                                         
653                                 kb= add_keyblock(key, base->object->id.name+2);
654                                 
655                                 DM_to_meshkey(dm, me, kb);
656                                 
657                                 dm->release(dm);
658                         }
659                 }
660         }
661         CTX_DATA_END;
662         
663         WM_event_add_notifier(C, NC_SCENE|ND_OB_ACTIVE, scene);
664         
665         return OPERATOR_FINISHED;
666 }
667
668 /* ********************* MESH VERTEX OCTREE LOOKUP ************* */
669
670 /* important note; this is unfinished, needs better API for editmode, and custom threshold */
671
672 #define MOC_RES                 8
673 #define MOC_NODE_RES    8
674 #define MOC_THRESH              0.00002f
675
676 typedef struct MocNode {
677         struct MocNode *next;
678         intptr_t index[MOC_NODE_RES];
679 } MocNode;
680
681 static int mesh_octree_get_base_offs(float *co, float *offs, float *div)
682 {
683         int vx, vy, vz;
684         
685         vx= floor( (co[0]-offs[0])/div[0] );
686         vy= floor( (co[1]-offs[1])/div[1] );
687         vz= floor( (co[2]-offs[2])/div[2] );
688         
689         CLAMP(vx, 0, MOC_RES-1);
690         CLAMP(vy, 0, MOC_RES-1);
691         CLAMP(vz, 0, MOC_RES-1);
692
693         return (vx*MOC_RES*MOC_RES) + vy*MOC_RES + vz;
694 }
695
696 static void mesh_octree_add_node(MocNode **bt, intptr_t index)
697 {
698         if(*bt==NULL) {
699                 *bt= MEM_callocN(sizeof(MocNode), "MocNode");
700                 (*bt)->index[0]= index;
701         }
702         else {
703                 int a;
704                 for(a=0; a<MOC_NODE_RES; a++) {
705                         if((*bt)->index[a]==index)
706                                 return;
707                         else if((*bt)->index[a]==0) {
708                                 (*bt)->index[a]= index;
709                                 return;
710                         }
711                 }
712                 mesh_octree_add_node(&(*bt)->next, index);
713         }
714 }
715
716 static void mesh_octree_free_node(MocNode **bt)
717 {
718         if( (*bt)->next ) {
719                 mesh_octree_free_node(&(*bt)->next);
720         }
721         MEM_freeN(*bt);
722 }
723
724
725 /* temporal define, just to make nicer code below */
726 #define MOC_ADDNODE(vx, vy, vz) mesh_octree_add_node(basetable + ((vx)*MOC_RES*MOC_RES) + (vy)*MOC_RES + (vz), index)
727
728 static void mesh_octree_add_nodes(MocNode **basetable, float *co, float *offs, float *div, intptr_t index)
729 {
730         float fx, fy, fz;
731         int vx, vy, vz;
732         
733         if (!finite(co[0]) ||
734                 !finite(co[1]) ||
735                 !finite(co[2])
736         ) {
737                 return;
738         }
739         
740         fx= (co[0]-offs[0])/div[0];
741         fy= (co[1]-offs[1])/div[1];
742         fz= (co[2]-offs[2])/div[2];
743         CLAMP(fx, 0.0f, MOC_RES-MOC_THRESH);
744         CLAMP(fy, 0.0f, MOC_RES-MOC_THRESH);
745         CLAMP(fz, 0.0f, MOC_RES-MOC_THRESH);
746         
747         vx= floor(fx);
748         vy= floor(fy);
749         vz= floor(fz);
750         
751         MOC_ADDNODE(vx, vy, vz);
752         
753         if( vx>0 )
754                 if( fx-((float)vx)-MOC_THRESH < 0.0f)
755                         MOC_ADDNODE(vx-1, vy, vz);
756         if( vx<MOC_RES-2 )
757                 if( fx-((float)vx)+MOC_THRESH > 1.0f)
758                         MOC_ADDNODE(vx+1, vy, vz);
759
760         if( vy>0 )
761                 if( fy-((float)vy)-MOC_THRESH < 0.0f) 
762                         MOC_ADDNODE(vx, vy-1, vz);
763         if( vy<MOC_RES-2 )
764                 if( fy-((float)vy)+MOC_THRESH > 1.0f) 
765                         MOC_ADDNODE(vx, vy+1, vz);
766
767         if( vz>0 )
768                 if( fz-((float)vz)-MOC_THRESH < 0.0f) 
769                         MOC_ADDNODE(vx, vy, vz-1);
770         if( vz<MOC_RES-2 )
771                 if( fz-((float)vz)+MOC_THRESH > 1.0f) 
772                         MOC_ADDNODE(vx, vy, vz+1);
773         
774 }
775
776 static intptr_t mesh_octree_find_index(MocNode **bt, MVert *mvert, float *co)
777 {
778         float *vec;
779         int a;
780         
781         if(*bt==NULL)
782                 return -1;
783         
784         for(a=0; a<MOC_NODE_RES; a++) {
785                 if((*bt)->index[a]) {
786                         /* does mesh verts and editmode, code looks potential dangerous, octree should really be filled OK! */
787                         if(mvert) {
788                                 vec= (mvert+(*bt)->index[a]-1)->co;
789                                 if(compare_v3v3(vec, co, MOC_THRESH))
790                                         return (*bt)->index[a]-1;
791                         }
792                         else {
793                                 BMVert *eve= (BMVert *)((*bt)->index[a]);
794                                 if(compare_v3v3(eve->co, co, MOC_THRESH))
795                                         return (*bt)->index[a];
796                         }
797                 }
798                 else return -1;
799         }
800         if( (*bt)->next)
801                 return mesh_octree_find_index(&(*bt)->next, mvert, co);
802         
803         return -1;
804 }
805
806 static struct {
807         MocNode **table;
808         float offs[3], div[3];
809 } MeshOctree = {NULL, {0, 0, 0}, {0, 0, 0}};
810
811 /* mode is 's' start, or 'e' end, or 'u' use */
812 /* if end, ob can be NULL */
813 intptr_t mesh_octree_table(Object *ob, BMEditMesh *em, float *co, char mode)
814 {
815         MocNode **bt;
816         
817         if(mode=='u') {         /* use table */
818                 if(MeshOctree.table==NULL)
819                         mesh_octree_table(ob, em, NULL, 's');
820            
821                 if(MeshOctree.table) {
822                         Mesh *me= ob->data;
823                         bt= MeshOctree.table + mesh_octree_get_base_offs(co, MeshOctree.offs, MeshOctree.div);
824                         if(em)
825                                 return mesh_octree_find_index(bt, NULL, co);
826                         else
827                                 return mesh_octree_find_index(bt, me->mvert, co);
828                 }
829                 return -1;
830         }
831         else if(mode=='s') {    /* start table */
832                 Mesh *me= ob->data;
833                 float min[3], max[3];
834
835                 /* we compute own bounding box and don't reuse ob->bb because
836                  * we are using the undeformed coordinates*/
837                 INIT_MINMAX(min, max);
838
839                 if(em && me->edit_btmesh==em) {
840                         BMIter iter;
841                         BMVert *eve;
842                         
843                         BM_ITER(eve, &iter, em->bm, BM_VERTS_OF_MESH, NULL)
844                                 DO_MINMAX(eve->co, min, max)
845                 }
846                 else {          
847                         MVert *mvert;
848                         int a;
849                         
850                         for(a=0, mvert= me->mvert; a<me->totvert; a++, mvert++)
851                                 DO_MINMAX(mvert->co, min, max);
852                 }
853                 
854                 /* for quick unit coordinate calculus */
855                 VECCOPY(MeshOctree.offs, min);
856                 MeshOctree.offs[0]-= MOC_THRESH;                /* we offset it 1 threshold unit extra */
857                 MeshOctree.offs[1]-= MOC_THRESH;
858                 MeshOctree.offs[2]-= MOC_THRESH;
859                 
860                 sub_v3_v3v3(MeshOctree.div, max, min);
861                 MeshOctree.div[0]+= 2*MOC_THRESH;       /* and divide with 2 threshold unit more extra (try 8x8 unit grid on paint) */
862                 MeshOctree.div[1]+= 2*MOC_THRESH;
863                 MeshOctree.div[2]+= 2*MOC_THRESH;
864                 
865                 mul_v3_fl(MeshOctree.div, 1.0f/MOC_RES);
866                 if(MeshOctree.div[0]==0.0f) MeshOctree.div[0]= 1.0f;
867                 if(MeshOctree.div[1]==0.0f) MeshOctree.div[1]= 1.0f;
868                 if(MeshOctree.div[2]==0.0f) MeshOctree.div[2]= 1.0f;
869                         
870                 if(MeshOctree.table) /* happens when entering this call without ending it */
871                         mesh_octree_table(ob, em, co, 'e');
872                 
873                 MeshOctree.table= MEM_callocN(MOC_RES*MOC_RES*MOC_RES*sizeof(void *), "sym table");
874                 
875                 if(em && me->edit_btmesh==em) {
876                         BMVert *eve;
877                         BMIter iter;
878
879                         BM_ITER(eve, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
880                                 mesh_octree_add_nodes(MeshOctree.table, eve->co, MeshOctree.offs, MeshOctree.div, (intptr_t)(eve));
881                         }
882                 }
883                 else {          
884                         MVert *mvert;
885                         int a;
886                         
887                         for(a=0, mvert= me->mvert; a<me->totvert; a++, mvert++)
888                                 mesh_octree_add_nodes(MeshOctree.table, mvert->co, MeshOctree.offs, MeshOctree.div, a+1);
889                 }
890         }
891         else if(mode=='e') { /* end table */
892                 if(MeshOctree.table) {
893                         int a;
894                         
895                         for(a=0, bt=MeshOctree.table; a<MOC_RES*MOC_RES*MOC_RES; a++, bt++) {
896                                 if(*bt) mesh_octree_free_node(bt);
897                         }
898                         MEM_freeN(MeshOctree.table);
899                         MeshOctree.table= NULL;
900                 }
901         }
902         return 0;
903 }
904
905
906 /* ********************* MESH VERTEX MIRR TOPO LOOKUP *************** */
907
908 #define MIRRHASH_TYPE int
909
910 typedef struct MirrTopoPair {
911         long hash;
912         int vIndex;
913 } MirrTopoPair;
914
915 static int MirrTopo_long_sort(const void *l1, const void *l2)
916 {
917         if(                     (MIRRHASH_TYPE)(intptr_t)l1 > (MIRRHASH_TYPE)(intptr_t)l2 ) return  1;
918         else if(        (MIRRHASH_TYPE)(intptr_t)l1 < (MIRRHASH_TYPE)(intptr_t)l2 ) return -1;
919         return 0;
920 }
921
922 static int MirrTopo_item_sort(const void *v1, const void *v2)
923 {
924         if(                     ((MirrTopoPair *)v1)->hash > ((MirrTopoPair *)v2)->hash ) return  1;
925         else if(        ((MirrTopoPair *)v1)->hash < ((MirrTopoPair *)v2)->hash ) return -1;
926         return 0;
927 }
928
929 static long *mesh_topo_lookup = NULL;
930 static int  mesh_topo_lookup_tot = -1;
931 static int  mesh_topo_lookup_mode = -1;
932
933 /* mode is 's' start, or 'e' end, or 'u' use */
934 /* if end, ob can be NULL */
935 long mesh_mirrtopo_table(Object *ob, char mode)
936 {
937         if(mode=='u') {         /* use table */
938                 Mesh *me= ob->data;
939                 if(     (mesh_topo_lookup==NULL) ||
940                         (mesh_topo_lookup_mode != ob->mode) ||
941                         (me->edit_btmesh && me->edit_btmesh->bm->totvert != mesh_topo_lookup_tot) ||
942                         (me->edit_btmesh==NULL && me->totvert != mesh_topo_lookup_tot)
943                 ) {
944                         mesh_mirrtopo_table(ob, 's');
945                 }
946         } else if(mode=='s') { /* start table */
947                 Mesh *me= ob->data;
948                 MEdge *medge;
949                 BMEditMesh *em= me->edit_btmesh;
950                 BMEdge *eed;
951                 BMIter iter;
952                 MIRRHASH_TYPE *MirrTopoHash = NULL;
953                 MIRRHASH_TYPE *MirrTopoHash_Prev = NULL;
954                 MirrTopoPair *MirrTopoPairs;
955                 int a, last, totvert;
956                 int totUnique= -1, totUniqueOld= -1;
957
958                 mesh_topo_lookup_mode= ob->mode;
959
960                 /* reallocate if needed */
961                 if (mesh_topo_lookup) {
962                         MEM_freeN(mesh_topo_lookup);
963                         mesh_topo_lookup = NULL;
964                 }
965
966                 if(em) {
967                         BM_ElemIndex_Ensure(em->bm, BM_VERT);
968
969                         totvert= em->bm->totvert;
970                 }
971                 else {
972                         totvert = me->totvert;
973                 }
974
975                 MirrTopoHash = MEM_callocN( totvert * sizeof(MIRRHASH_TYPE), "TopoMirr" );
976
977                 /* Initialize the vert-edge-user counts used to detect unique topology */
978                 if(em) {
979                         BM_ITER(eed, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
980                                 MirrTopoHash[BM_GetIndex(eed->v1)]++;
981                                 MirrTopoHash[BM_GetIndex(eed->v2)]++;
982                         }
983                 } else {
984                         for(a=0, medge=me->medge; a<me->totedge; a++, medge++) {
985                                 MirrTopoHash[medge->v1]++;
986                                 MirrTopoHash[medge->v2]++;
987                         }
988                 }
989
990                 MirrTopoHash_Prev = MEM_dupallocN( MirrTopoHash );
991
992                 totUniqueOld = -1;
993                 while(1) {
994                         /* use the number of edges per vert to give verts unique topology IDs */
995
996                         if(em) {
997                                 BM_ITER(eed, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
998                                         MirrTopoHash[BM_GetIndex(eed->v1)] += MirrTopoHash_Prev[BM_GetIndex(eed->v2)];
999                                         MirrTopoHash[BM_GetIndex(eed->v2)] += MirrTopoHash_Prev[BM_GetIndex(eed->v1)];
1000                                 }
1001                         } else {
1002                                 for(a=0, medge=me->medge; a<me->totedge; a++, medge++) {
1003                                         /* This can make really big numbers, wrapping around here is fine */
1004                                         MirrTopoHash[medge->v1] += MirrTopoHash_Prev[medge->v2];
1005                                         MirrTopoHash[medge->v2] += MirrTopoHash_Prev[medge->v1];
1006                                 }
1007                         }
1008                         memcpy(MirrTopoHash_Prev, MirrTopoHash, sizeof(MIRRHASH_TYPE) * totvert);
1009
1010                         /* sort so we can count unique values */
1011                         qsort(MirrTopoHash_Prev, totvert, sizeof(MIRRHASH_TYPE), MirrTopo_long_sort);
1012
1013                         totUnique = 1; /* account for skiping the first value */
1014                         for(a=1; a<totvert; a++) {
1015                                 if (MirrTopoHash_Prev[a-1] != MirrTopoHash_Prev[a]) {
1016                                         totUnique++;
1017                                 }
1018                         }
1019
1020                         if (totUnique <= totUniqueOld) {
1021                                 /* Finish searching for unique valus when 1 loop dosnt give a
1022                                  * higher number of unique values compared to the previous loop */
1023                                 break;
1024                         } else {
1025                                 totUniqueOld = totUnique;
1026                         }
1027                         /* Copy the hash calculated this iter, so we can use them next time */
1028                         memcpy(MirrTopoHash_Prev, MirrTopoHash, sizeof(MIRRHASH_TYPE) * totvert);
1029                 }
1030
1031                 /* Hash/Index pairs are needed for sorting to find index pairs */
1032                 MirrTopoPairs= MEM_callocN( sizeof(MirrTopoPair) * totvert, "MirrTopoPairs");
1033
1034                 /* since we are looping through verts, initialize these values here too */
1035                 mesh_topo_lookup = MEM_mallocN( totvert * sizeof(long), "mesh_topo_lookup" );
1036
1037                 if(em) {
1038                         EDBM_init_index_arrays(em,1,0,0);
1039                 }
1040
1041
1042                 for(a=0; a<totvert; a++) {
1043                         MirrTopoPairs[a].hash= MirrTopoHash[a];
1044                         MirrTopoPairs[a].vIndex = a;
1045
1046                         /* initialize lookup */
1047                         mesh_topo_lookup[a] = -1;
1048                 }
1049
1050                 qsort(MirrTopoPairs, totvert, sizeof(MirrTopoPair), MirrTopo_item_sort);
1051
1052                 /* Since the loop starts at 2, we must define the last index where the hash's differ */
1053                 last = ((totvert >= 2) && (MirrTopoPairs[0].hash == MirrTopoPairs[1].hash)) ? 0 : 1;
1054
1055                 /* Get the pairs out of the sorted hashes, note, totvert+1 means we can use the previous 2,
1056                  * but you cant ever access the last 'a' index of MirrTopoPairs */
1057                 for(a=2; a < totvert+1; a++) {
1058                         /* printf("I %d %ld %d\n", (a-last), MirrTopoPairs[a  ].hash, MirrTopoPairs[a  ].vIndex ); */
1059                         if ((a==totvert) || (MirrTopoPairs[a-1].hash != MirrTopoPairs[a].hash)) {
1060                                 if (a-last==2) {
1061                                         if(em) {
1062                                                 mesh_topo_lookup[MirrTopoPairs[a-1].vIndex] =   (long)EDBM_get_vert_for_index(em, MirrTopoPairs[a-2].vIndex);
1063                                                 mesh_topo_lookup[MirrTopoPairs[a-2].vIndex] =   (long)EDBM_get_vert_for_index(em, MirrTopoPairs[a-1].vIndex);
1064                                         } else {
1065                                                 mesh_topo_lookup[MirrTopoPairs[a-1].vIndex] =   MirrTopoPairs[a-2].vIndex;
1066                                                 mesh_topo_lookup[MirrTopoPairs[a-2].vIndex] =   MirrTopoPairs[a-1].vIndex;
1067                                         }
1068                                 }
1069                                 last= a;
1070                         }
1071                 }
1072                 if(em) {
1073                         EDBM_free_index_arrays(em);
1074                 }
1075
1076                 MEM_freeN( MirrTopoPairs );
1077                 MirrTopoPairs = NULL;
1078
1079                 MEM_freeN( MirrTopoHash );
1080                 MEM_freeN( MirrTopoHash_Prev );
1081
1082                 mesh_topo_lookup_tot = totvert;
1083
1084         } else if(mode=='e') { /* end table */
1085                 if (mesh_topo_lookup) {
1086                         MEM_freeN(mesh_topo_lookup);
1087                 }
1088                 mesh_topo_lookup = NULL;
1089                 mesh_topo_lookup_tot= -1;
1090         }
1091         return 0;
1092 }
1093
1094 static int mesh_get_x_mirror_vert_spacial(Object *ob, int index)
1095 {
1096         Mesh *me= ob->data;
1097         MVert *mvert;
1098         float vec[3];
1099         
1100         mvert= me->mvert+index;
1101         vec[0]= -mvert->co[0];
1102         vec[1]= mvert->co[1];
1103         vec[2]= mvert->co[2];
1104         
1105         return mesh_octree_table(ob, NULL, vec, 'u');
1106 }
1107
1108 static int mesh_get_x_mirror_vert_topo(Object *ob, int index)
1109 {
1110         if (mesh_mirrtopo_table(ob, 'u')==-1)
1111                 return -1;
1112
1113         return mesh_topo_lookup[index];
1114 }
1115
1116 int mesh_get_x_mirror_vert(Object *ob, int index)
1117 {
1118         if (((Mesh *)ob->data)->editflag & ME_EDIT_MIRROR_TOPO) {
1119                 return mesh_get_x_mirror_vert_topo(ob, index);
1120         } else {
1121                 return mesh_get_x_mirror_vert_spacial(ob, index);
1122         }
1123         return 0;
1124 }
1125
1126 static BMVert *editbmesh_get_x_mirror_vert_spacial(Object *ob, BMEditMesh *em, float *co)
1127 {
1128         float vec[3];
1129         intptr_t poinval;
1130         
1131         /* ignore nan verts */
1132         if (!finite(co[0]) ||
1133                 !finite(co[1]) ||
1134                 !finite(co[2])
1135            )
1136                 return NULL;
1137         
1138         vec[0]= -co[0];
1139         vec[1]= co[1];
1140         vec[2]= co[2];
1141         
1142         poinval= mesh_octree_table(ob, em, vec, 'u');
1143         if(poinval != -1)
1144                 return (BMVert *)(poinval);
1145         return NULL;
1146 }
1147
1148 static BMVert *editbmesh_get_x_mirror_vert_topo(Object *ob, struct BMEditMesh *em, BMVert *eve, int index)
1149 {
1150         long poinval;
1151         if (mesh_mirrtopo_table(ob, 'u')==-1)
1152                 return NULL;
1153
1154         if (index == -1) {
1155                 BMIter iter;
1156                 BMVert *v;
1157                 
1158                 index = 0;
1159                 BM_ITER(v, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
1160                         if (v == eve)
1161                                 break;
1162                         index++;
1163                 }
1164                 
1165                 if (index == em->bm->totvert) {
1166                         return NULL;
1167                 }
1168         }
1169
1170         poinval= mesh_topo_lookup[ index ];
1171
1172         if(poinval != -1)
1173                 return (BMVert *)(poinval);
1174         return NULL;
1175 }       
1176
1177 BMVert *editbmesh_get_x_mirror_vert(Object *ob, struct BMEditMesh *em, BMVert *eve, float *co, int index)
1178 {
1179         //BMESH_TODO use this flag, ME_EDIT_MIRROR_TOPO, at appropriate places
1180         if (((Mesh *)ob->data)->editflag & ME_EDIT_MIRROR_TOPO) {
1181                 return editbmesh_get_x_mirror_vert_topo(ob, em, eve, index);
1182         } else {
1183                 return editbmesh_get_x_mirror_vert_spacial(ob, em, co);
1184         }
1185 }
1186
1187
1188
1189 static float *editmesh_get_mirror_uv(BMEditMesh *em, int axis, float *uv, float *mirrCent, float *face_cent)
1190 {
1191         float vec[2];
1192         float cent_vec[2];
1193         float cent[2];
1194
1195         /* ignore nan verts */
1196         if (isnan(uv[0]) || !finite(uv[0]) ||
1197                 isnan(uv[1]) || !finite(uv[1])
1198            )
1199                 return NULL;
1200
1201         if (axis) {
1202                 vec[0]= uv[0];
1203                 vec[1]= -((uv[1])-mirrCent[1]) + mirrCent[1];
1204
1205                 cent_vec[0] = face_cent[0];
1206                 cent_vec[1]= -((face_cent[1])-mirrCent[1]) + mirrCent[1];
1207         } else {
1208                 vec[0]= -((uv[0])-mirrCent[0]) + mirrCent[0];
1209                 vec[1]= uv[1];
1210
1211                 cent_vec[0]= -((face_cent[0])-mirrCent[0]) + mirrCent[0];
1212                 cent_vec[1] = face_cent[1];
1213         }
1214
1215         /* TODO - Optimize */
1216         {
1217                 BMIter iter;
1218                 BMFace *efa;
1219                 
1220                 BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1221                         poly_uv_center(em, efa, cent);
1222                         
1223                         if ( (fabs(cent[0] - cent_vec[0]) < 0.001) && (fabs(cent[1] - cent_vec[1]) < 0.001) ) {
1224                                 BMIter liter;
1225                                 BMLoop *l;
1226                                 
1227                                 BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
1228                                         MLoopUV *luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
1229                                         if ( (fabs(luv->uv[0] - vec[0]) < 0.001) && (fabs(luv->uv[1] - vec[1]) < 0.001) ) {
1230                                                 return luv->uv;
1231                                                                 
1232                                 }
1233                         }
1234                 }
1235         }
1236         }
1237
1238         return NULL;
1239 }
1240
1241 static unsigned int mirror_facehash(const void *ptr)
1242 {
1243         const MFace *mf= ptr;
1244         int v0, v1;
1245
1246         if(mf->v4) {
1247                 v0= MIN4(mf->v1, mf->v2, mf->v3, mf->v4);
1248                 v1= MAX4(mf->v1, mf->v2, mf->v3, mf->v4);
1249         }
1250         else {
1251                 v0= MIN3(mf->v1, mf->v2, mf->v3);
1252                 v1= MAX3(mf->v1, mf->v2, mf->v3);
1253         }
1254
1255         return ((v0*39)^(v1*31));
1256 }
1257
1258 static int mirror_facerotation(MFace *a, MFace *b)
1259 {
1260         if(b->v4) {
1261                 if(a->v1==b->v1 && a->v2==b->v2 && a->v3==b->v3 && a->v4==b->v4)
1262                         return 0;
1263                 else if(a->v4==b->v1 && a->v1==b->v2 && a->v2==b->v3 && a->v3==b->v4)
1264                         return 1;
1265                 else if(a->v3==b->v1 && a->v4==b->v2 && a->v1==b->v3 && a->v2==b->v4)
1266                         return 2;
1267                 else if(a->v2==b->v1 && a->v3==b->v2 && a->v4==b->v3 && a->v1==b->v4)
1268                         return 3;
1269         }
1270         else {
1271                 if(a->v1==b->v1 && a->v2==b->v2 && a->v3==b->v3)
1272                         return 0;
1273                 else if(a->v3==b->v1 && a->v1==b->v2 && a->v2==b->v3)
1274                         return 1;
1275                 else if(a->v2==b->v1 && a->v3==b->v2 && a->v1==b->v3)
1276                         return 2;
1277         }
1278         
1279         return -1;
1280 }
1281
1282 static int mirror_facecmp(const void *a, const void *b)
1283 {
1284         return (mirror_facerotation((MFace*)a, (MFace*)b) == -1);
1285 }
1286
1287 int *mesh_get_x_mirror_faces(Object *ob, BMEditMesh *em)
1288 {
1289         Mesh *me= ob->data;
1290         MVert *mv, *mvert= me->mvert;
1291         MFace mirrormf, *mf, *hashmf, *mface= me->mface;
1292         GHash *fhash;
1293         int *mirrorverts, *mirrorfaces;
1294         int a;
1295
1296         mirrorverts= MEM_callocN(sizeof(int)*me->totvert, "MirrorVerts");
1297         mirrorfaces= MEM_callocN(sizeof(int)*2*me->totface, "MirrorFaces");
1298
1299         mesh_octree_table(ob, em, NULL, 's');
1300
1301         for(a=0, mv=mvert; a<me->totvert; a++, mv++)
1302                 mirrorverts[a]= mesh_get_x_mirror_vert(ob, a);
1303
1304         mesh_octree_table(ob, em, NULL, 'e');
1305
1306         fhash= BLI_ghash_new(mirror_facehash, mirror_facecmp, "mirror_facehash gh");
1307         for(a=0, mf=mface; a<me->totface; a++, mf++)
1308                 BLI_ghash_insert(fhash, mf, mf);
1309
1310         for(a=0, mf=mface; a<me->totface; a++, mf++) {
1311                 mirrormf.v1= mirrorverts[mf->v3];
1312                 mirrormf.v2= mirrorverts[mf->v2];
1313                 mirrormf.v3= mirrorverts[mf->v1];
1314                 mirrormf.v4= (mf->v4)? mirrorverts[mf->v4]: 0;
1315
1316                 /* make sure v4 is not 0 if a quad */
1317                 if(mf->v4 && mirrormf.v4==0) {
1318                         SWAP(int, mirrormf.v1, mirrormf.v3);
1319                         SWAP(int, mirrormf.v2, mirrormf.v4);
1320                 }
1321
1322                 hashmf= BLI_ghash_lookup(fhash, &mirrormf);
1323                 if(hashmf) {
1324                         mirrorfaces[a*2]= hashmf - mface;
1325                         mirrorfaces[a*2+1]= mirror_facerotation(&mirrormf, hashmf);
1326                 }
1327                 else
1328                         mirrorfaces[a*2]= -1;
1329         }
1330
1331         BLI_ghash_free(fhash, NULL, NULL);
1332         MEM_freeN(mirrorverts);
1333         
1334         return mirrorfaces;
1335 }