a63f4995acc8c28848aee4f3bc263aa142986d79
[blender-staging.git] / source / blender / editors / mesh / editmesh.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) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * Contributor(s): Blender Foundation, full recode 2002-2008
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28
29 #include <stdlib.h>
30 #include <string.h>
31 #include <math.h>
32
33 #include "MEM_guardedalloc.h"
34
35
36 #include "DNA_key_types.h"
37
38 #include "BLI_blenlib.h"
39 #include "BLI_math.h"
40 #include "BLI_editVert.h"
41 #include "BLI_dynstr.h"
42 #include "BLI_rand.h"
43
44 #include "BKE_cloth.h"
45 #include "BKE_context.h"
46 #include "BKE_customdata.h"
47 #include "BKE_depsgraph.h"
48 #include "BKE_DerivedMesh.h"
49 #include "BKE_global.h"
50 #include "BKE_key.h"
51 #include "BKE_library.h"
52 #include "BKE_main.h"
53 #include "BKE_material.h"
54 #include "BKE_mesh.h"
55 #include "BKE_modifier.h"
56 #include "BKE_object.h"
57 #include "BKE_paint.h"
58 #include "BKE_pointcache.h"
59 #include "BKE_softbody.h"
60 #include "BKE_texture.h"
61 #include "BKE_utildefines.h"
62
63 #include "ED_mesh.h"
64 #include "ED_object.h"
65 #include "ED_retopo.h"
66 #include "ED_screen.h"
67 #include "ED_util.h"
68 #include "ED_view3d.h"
69
70 #include "RNA_access.h"
71 #include "RNA_define.h"
72
73 #include "WM_api.h"
74 #include "WM_types.h"
75
76 /* own include */
77 #include "mesh_intern.h"
78
79 /* 
80 editmesh.c:
81         - add/alloc/free data
82         - hashtables
83         - enter/exit editmode
84 */
85
86 /* XXX */
87 static void BIF_undo_push(const char *dummy) {}
88 static void error(const char *dummy) {}
89
90
91 /* ***************** HASH ********************* */
92
93
94 #define EDHASHSIZE              (512*512)
95 #define EDHASH(a, b)    (a % EDHASHSIZE)
96
97
98 /* ************ ADD / REMOVE / FIND ****************** */
99
100 static void *calloc_em(EditMesh *em, size_t size, size_t nr)
101 {
102         return calloc(size, nr);
103 }
104
105 /* used to bypass normal calloc with fast one */
106 static void *(*callocvert)(EditMesh *, size_t, size_t) = calloc_em;
107 static void *(*callocedge)(EditMesh *, size_t, size_t) = calloc_em;
108 static void *(*callocface)(EditMesh *, size_t, size_t) = calloc_em;
109
110 EditVert *addvertlist(EditMesh *em, float *vec, EditVert *example)
111 {
112         EditVert *eve;
113         static int hashnr= 0;
114
115         eve= callocvert(em, sizeof(EditVert), 1);
116         BLI_addtail(&em->verts, eve);
117         em->totvert++;
118         
119         if(vec) VECCOPY(eve->co, vec);
120
121         eve->hash= hashnr++;
122         if( hashnr>=EDHASHSIZE) hashnr= 0;
123
124         /* new verts get keyindex of -1 since they did not
125          * have a pre-editmode vertex order
126          */
127         eve->keyindex = -1;
128
129         if(example) {
130                 CustomData_em_copy_data(&em->vdata, &em->vdata, example->data, &eve->data);
131                 eve->bweight = example->bweight;
132         }
133         else {
134                 CustomData_em_set_default(&em->vdata, &eve->data);
135         }
136
137         return eve;
138 }
139
140 void free_editvert (EditMesh *em, EditVert *eve)
141 {
142
143         EM_remove_selection(em, eve, EDITVERT);
144         CustomData_em_free_block(&em->vdata, &eve->data);
145         if(eve->fast==0)
146                 free(eve);
147         
148         em->totvert--;
149 }
150
151
152 EditEdge *findedgelist(EditMesh *em, EditVert *v1, EditVert *v2)
153 {
154         EditVert *v3;
155         struct HashEdge *he;
156
157         /* swap ? */
158         if( v1 > v2) {
159                 v3= v2; 
160                 v2= v1; 
161                 v1= v3;
162         }
163         
164         if(em->hashedgetab==NULL)
165                 em->hashedgetab= MEM_callocN(EDHASHSIZE*sizeof(struct HashEdge), "hashedgetab");
166
167         he= em->hashedgetab + EDHASH(v1->hash, v2->hash);
168         
169         while(he) {
170                 
171                 if(he->eed && he->eed->v1==v1 && he->eed->v2==v2) return he->eed;
172                 
173                 he= he->next;
174         }
175         return 0;
176 }
177
178 static void insert_hashedge(EditMesh *em, EditEdge *eed)
179 {
180         /* assuming that eed is not in the list yet, and that a find has been done before */
181         
182         struct HashEdge *first, *he;
183
184         first= em->hashedgetab + EDHASH(eed->v1->hash, eed->v2->hash);
185
186         if( first->eed==0 ) {
187                 first->eed= eed;
188         }
189         else {
190                 he= &eed->hash; 
191                 he->eed= eed;
192                 he->next= first->next;
193                 first->next= he;
194         }
195 }
196
197 static void remove_hashedge(EditMesh *em, EditEdge *eed)
198 {
199         /* assuming eed is in the list */
200         
201         struct HashEdge *first, *he, *prev=NULL;
202
203         he=first= em->hashedgetab + EDHASH(eed->v1->hash, eed->v2->hash);
204
205         while(he) {
206                 if(he->eed == eed) {
207                         /* remove from list */
208                         if(he==first) {
209                                 if(first->next) {
210                                         he= first->next;
211                                         first->eed= he->eed;
212                                         first->next= he->next;
213                                 }
214                                 else he->eed= 0;
215                         }
216                         else {
217                                 prev->next= he->next;
218                         }
219                         return;
220                 }
221                 prev= he;
222                 he= he->next;
223         }
224 }
225
226 EditEdge *addedgelist(EditMesh *em, EditVert *v1, EditVert *v2, EditEdge *example)
227 {
228         EditVert *v3;
229         EditEdge *eed;
230         int swap= 0;
231         
232         if(v1==v2) return NULL;
233         if(v1==NULL || v2==NULL) return NULL;
234
235         /* swap ? */
236         if(v1>v2) {
237                 v3= v2; 
238                 v2= v1; 
239                 v1= v3;
240                 swap= 1;
241         }
242         
243         /* find in hashlist */
244         eed= findedgelist(em, v1, v2);
245
246         if(eed==NULL) {
247         
248                 eed= (EditEdge *)callocedge(em, sizeof(EditEdge), 1);
249                 eed->v1= v1;
250                 eed->v2= v2;
251                 BLI_addtail(&em->edges, eed);
252                 eed->dir= swap;
253                 insert_hashedge(em, eed);
254                 em->totedge++;
255                 
256                 /* copy edge data:
257                    rule is to do this with addedgelist call, before addfacelist */
258                 if(example) {
259                         eed->crease= example->crease;
260                         eed->bweight= example->bweight;
261                         eed->sharp = example->sharp;
262                         eed->seam = example->seam;
263                         eed->h |= (example->h & EM_FGON);
264                 }
265         }
266
267         return eed;
268 }
269
270 void remedge(EditMesh *em, EditEdge *eed)
271 {
272         BLI_remlink(&em->edges, eed);
273         remove_hashedge(em, eed);
274         
275         em->totedge--;
276 }
277
278 void free_editedge(EditMesh *em, EditEdge *eed)
279 {
280         EM_remove_selection(em, eed, EDITEDGE);
281         if(eed->fast==0){ 
282                 free(eed);
283         }
284 }
285
286 void free_editface(EditMesh *em, EditFace *efa)
287 {
288         EM_remove_selection(em, efa, EDITFACE);
289         
290         if (em->act_face==efa) {
291                 EM_set_actFace(em, em->faces.first == efa ? NULL : em->faces.first);
292         }
293                 
294         CustomData_em_free_block(&em->fdata, &efa->data);
295         if(efa->fast==0)
296                 free(efa);
297         
298         em->totface--;
299 }
300
301 void free_vertlist(EditMesh *em, ListBase *edve) 
302 {
303         EditVert *eve, *next;
304
305         if (!edve) return;
306
307         eve= edve->first;
308         while(eve) {
309                 next= eve->next;
310                 free_editvert(em, eve);
311                 eve= next;
312         }
313         edve->first= edve->last= NULL;
314         em->totvert= em->totvertsel= 0;
315 }
316
317 void free_edgelist(EditMesh *em, ListBase *lb)
318 {
319         EditEdge *eed, *next;
320         
321         eed= lb->first;
322         while(eed) {
323                 next= eed->next;
324                 free_editedge(em, eed);
325                 eed= next;
326         }
327         lb->first= lb->last= NULL;
328         em->totedge= em->totedgesel= 0;
329 }
330
331 void free_facelist(EditMesh *em, ListBase *lb)
332 {
333         EditFace *efa, *next;
334         
335         efa= lb->first;
336         while(efa) {
337                 next= efa->next;
338                 free_editface(em, efa);
339                 efa= next;
340         }
341         lb->first= lb->last= NULL;
342         em->totface= em->totfacesel= 0;
343 }
344
345 EditFace *addfacelist(EditMesh *em, EditVert *v1, EditVert *v2, EditVert *v3, EditVert *v4, EditFace *example, EditFace *exampleEdges)
346 {
347         EditFace *efa;
348         EditEdge *e1, *e2=0, *e3=0, *e4=0;
349
350         /* added sanity check... seems to happen for some tools, or for enter editmode for corrupted meshes */
351         if(v1==v4 || v2==v4 || v3==v4) v4= NULL;
352         
353         /* add face to list and do the edges */
354         if(exampleEdges) {
355                 e1= addedgelist(em, v1, v2, exampleEdges->e1);
356                 e2= addedgelist(em, v2, v3, exampleEdges->e2);
357                 if(v4) e3= addedgelist(em, v3, v4, exampleEdges->e3); 
358                 else e3= addedgelist(em, v3, v1, exampleEdges->e3);
359                 if(v4) e4= addedgelist(em, v4, v1, exampleEdges->e4);
360         }
361         else {
362                 e1= addedgelist(em, v1, v2, NULL);
363                 e2= addedgelist(em, v2, v3, NULL);
364                 if(v4) e3= addedgelist(em, v3, v4, NULL); 
365                 else e3= addedgelist(em, v3, v1, NULL);
366                 if(v4) e4= addedgelist(em, v4, v1, NULL);
367         }
368         
369         if(v1==v2 || v2==v3 || v1==v3) return NULL;
370         if(e2==0) return NULL;
371
372         efa= (EditFace *)callocface(em, sizeof(EditFace), 1);
373         efa->v1= v1;
374         efa->v2= v2;
375         efa->v3= v3;
376         efa->v4= v4;
377
378         efa->e1= e1;
379         efa->e2= e2;
380         efa->e3= e3;
381         efa->e4= e4;
382
383         if(example) {
384                 efa->mat_nr= example->mat_nr;
385                 efa->flag= example->flag;
386                 CustomData_em_copy_data(&em->fdata, &em->fdata, example->data, &efa->data);
387         }
388         else {
389                 efa->mat_nr= em->mat_nr;
390
391                 CustomData_em_set_default(&em->fdata, &efa->data);
392         }
393
394         BLI_addtail(&em->faces, efa);
395         em->totface++;
396         
397         if(efa->v4) {
398                 normal_quad_v3( efa->n,efa->v1->co, efa->v2->co, efa->v3->co, efa->v4->co);
399                 cent_quad_v3(efa->cent, efa->v1->co, efa->v2->co, efa->v3->co, efa->v4->co);
400         }
401         else {
402                 normal_tri_v3( efa->n,efa->v1->co, efa->v2->co, efa->v3->co);
403                 cent_tri_v3(efa->cent, efa->v1->co, efa->v2->co, efa->v3->co);
404         }
405
406         return efa;
407 }
408
409 /* ************************ end add/new/find ************  */
410
411 /* ************************ Edit{Vert,Edge,Face} utilss ***************************** */
412
413 /* some nice utility functions */
414
415 EditVert *editedge_getOtherVert(EditEdge *eed, EditVert *eve)
416 {
417         if (eve==eed->v1) {
418                 return eed->v2;
419         } else if (eve==eed->v2) {
420                 return eed->v1;
421         } else {
422                 return NULL;
423         }
424 }
425
426 EditVert *editedge_getSharedVert(EditEdge *eed, EditEdge *eed2) 
427 {
428         if (eed->v1==eed2->v1 || eed->v1==eed2->v2) {
429                 return eed->v1;
430         } else if (eed->v2==eed2->v1 || eed->v2==eed2->v2) {
431                 return eed->v2;
432         } else {
433                 return NULL;
434         }
435 }
436
437 int editedge_containsVert(EditEdge *eed, EditVert *eve) 
438 {
439         return (eed->v1==eve || eed->v2==eve);
440 }
441
442 int editface_containsVert(EditFace *efa, EditVert *eve) 
443 {
444         return (efa->v1==eve || efa->v2==eve || efa->v3==eve || (efa->v4 && efa->v4==eve));
445 }
446
447 int editface_containsEdge(EditFace *efa, EditEdge *eed) 
448 {
449         return (efa->e1==eed || efa->e2==eed || efa->e3==eed || (efa->e4 && efa->e4==eed));
450 }
451
452
453 /* ************************ stuct EditMesh manipulation ***************************** */
454
455 /* fake callocs for fastmalloc below */
456 static void *calloc_fastvert(EditMesh *em, size_t size, size_t nr)
457 {
458         EditVert *eve= em->curvert++;
459         eve->fast= 1;
460         return eve;
461 }
462 static void *calloc_fastedge(EditMesh *em, size_t size, size_t nr)
463 {
464         EditEdge *eed= em->curedge++;
465         eed->fast= 1;
466         return eed;
467 }
468 static void *calloc_fastface(EditMesh *em, size_t size, size_t nr)
469 {
470         EditFace *efa= em->curface++;
471         efa->fast= 1;
472         return efa;
473 }
474
475 /* allocate 1 chunk for all vertices, edges, faces. These get tagged to
476    prevent it from being freed
477 */
478 static void init_editmesh_fastmalloc(EditMesh *em, int totvert, int totedge, int totface)
479 {
480         if(totvert) em->allverts= MEM_callocN(totvert*sizeof(EditVert), "allverts");
481         else em->allverts= NULL;
482         em->curvert= em->allverts;
483         
484         if(totedge==0) totedge= 4*totface;      // max possible
485
486         if(totedge) em->alledges= MEM_callocN(totedge*sizeof(EditEdge), "alledges");
487         else em->alledges= NULL;
488         em->curedge= em->alledges;
489         
490         if(totface) em->allfaces= MEM_callocN(totface*sizeof(EditFace), "allfaces");
491         else em->allfaces= NULL;
492         em->curface= em->allfaces;
493
494         callocvert= calloc_fastvert;
495         callocedge= calloc_fastedge;
496         callocface= calloc_fastface;
497 }
498
499 static void end_editmesh_fastmalloc(void)
500 {
501         callocvert= calloc_em;
502         callocedge= calloc_em;
503         callocface= calloc_em;
504 }
505
506 /* do not free editmesh itself here */
507 void free_editMesh(EditMesh *em)
508 {
509         if(em==NULL) return;
510
511         if(em->verts.first) free_vertlist(em, &em->verts);
512         if(em->edges.first) free_edgelist(em, &em->edges);
513         if(em->faces.first) free_facelist(em, &em->faces);
514         if(em->selected.first) BLI_freelistN(&(em->selected));
515
516         CustomData_free(&em->vdata, 0);
517         CustomData_free(&em->fdata, 0);
518
519         if(em->derivedFinal) {
520                 if (em->derivedFinal!=em->derivedCage) {
521                         em->derivedFinal->needsFree= 1;
522                         em->derivedFinal->release(em->derivedFinal);
523                 }
524                 em->derivedFinal= NULL;
525         }
526         if(em->derivedCage) {
527                 em->derivedCage->needsFree= 1;
528                 em->derivedCage->release(em->derivedCage);
529                 em->derivedCage= NULL;
530         }
531
532         /* DEBUG: hashtabs are slowest part of enter/exit editmode. here a testprint */
533 #if 0
534         if(em->hashedgetab) {
535                 HashEdge *he, *hen;
536                 int a, used=0, max=0, nr;
537                 he= em->hashedgetab;
538                 for(a=0; a<EDHASHSIZE; a++, he++) {
539                         if(he->eed) used++;
540                         hen= he->next;
541                         nr= 0;
542                         while(hen) {
543                                 nr++;
544                                 hen= hen->next;
545                         }
546                         if(max<nr) max= nr;
547                 }
548                 printf("hastab used %d max %d\n", used, max);
549         }
550 #endif
551         if(em->hashedgetab) MEM_freeN(em->hashedgetab);
552         em->hashedgetab= NULL;
553         
554         if(em->allverts) MEM_freeN(em->allverts);
555         if(em->alledges) MEM_freeN(em->alledges);
556         if(em->allfaces) MEM_freeN(em->allfaces);
557         
558         em->allverts= em->curvert= NULL;
559         em->alledges= em->curedge= NULL;
560         em->allfaces= em->curface= NULL;
561         
562         mesh_octree_table(NULL, NULL, NULL, 'e');
563         mesh_mirrtopo_table(NULL, 'e');
564
565         em->totvert= em->totedge= em->totface= 0;
566
567 // XXX  if(em->retopo_paint_data) retopo_free_paint_data(em->retopo_paint_data);
568         em->retopo_paint_data= NULL;
569         em->act_face = NULL;
570 }
571
572 static void editMesh_set_hash(EditMesh *em)
573 {
574         EditEdge *eed;
575
576         if(em->hashedgetab) MEM_freeN(em->hashedgetab);
577         em->hashedgetab= NULL;
578         
579         for(eed=em->edges.first; eed; eed= eed->next)  {
580                 if( findedgelist(em, eed->v1, eed->v2)==NULL )
581                         insert_hashedge(em, eed);
582         }
583
584 }
585
586
587 /* ************************ IN & OUT EDITMODE ***************************** */
588
589
590 static void edge_normal_compare(EditEdge *eed, EditFace *efa1)
591 {
592         EditFace *efa2;
593         float cent1[3], cent2[3];
594         float inp;
595         
596         efa2 = eed->tmp.f;
597         if(efa1==efa2) return;
598         
599         inp= efa1->n[0]*efa2->n[0] + efa1->n[1]*efa2->n[1] + efa1->n[2]*efa2->n[2];
600         if(inp<0.999 && inp >-0.999) eed->f2= 1;
601                 
602         if(efa1->v4) cent_quad_v3(cent1, efa1->v1->co, efa1->v2->co, efa1->v3->co, efa1->v4->co);
603         else cent_tri_v3(cent1, efa1->v1->co, efa1->v2->co, efa1->v3->co);
604         if(efa2->v4) cent_quad_v3(cent2, efa2->v1->co, efa2->v2->co, efa2->v3->co, efa2->v4->co);
605         else cent_tri_v3(cent2, efa2->v1->co, efa2->v2->co, efa2->v3->co);
606         
607         sub_v3_v3v3(cent1, cent2, cent1);
608         normalize_v3(cent1);
609         inp= cent1[0]*efa1->n[0] + cent1[1]*efa1->n[1] + cent1[2]*efa1->n[2]; 
610
611         if(inp < -0.001 ) eed->f1= 1;
612 }
613
614 #if 0
615 typedef struct {
616         EditEdge *eed;
617         float noLen,no[3];
618         int adjCount;
619 } EdgeDrawFlagInfo;
620
621 static int edgeDrawFlagInfo_cmp(const void *av, const void *bv)
622 {
623         const EdgeDrawFlagInfo *a = av;
624         const EdgeDrawFlagInfo *b = bv;
625
626         if (a->noLen<b->noLen) return -1;
627         else if (a->noLen>b->noLen) return 1;
628         else return 0;
629 }
630 #endif
631
632 static void edge_drawflags(Mesh *me, EditMesh *em)
633 {
634         EditVert *eve;
635         EditEdge *eed, *e1, *e2, *e3, *e4;
636         EditFace *efa;
637         
638         /* - count number of times edges are used in faces: 0 en 1 time means draw edge
639          * - edges more than 1 time used: in *tmp.f is pointer to first face
640          * - check all faces, when normal differs to much: draw (flag becomes 1)
641          */
642
643         /* later on: added flags for 'cylinder' and 'sphere' intersection tests in old
644            game engine (2.04)
645          */
646         
647         recalc_editnormals(em);
648         
649         /* init */
650         eve= em->verts.first;
651         while(eve) {
652                 eve->f1= 1;             /* during test it's set at zero */
653                 eve= eve->next;
654         }
655         eed= em->edges.first;
656         while(eed) {
657                 eed->f2= eed->f1= 0;
658                 eed->tmp.f = 0;
659                 eed= eed->next;
660         }
661
662         efa= em->faces.first;
663         while(efa) {
664                 e1= efa->e1;
665                 e2= efa->e2;
666                 e3= efa->e3;
667                 e4= efa->e4;
668                 if(e1->f2<4) e1->f2+= 1;
669                 if(e2->f2<4) e2->f2+= 1;
670                 if(e3->f2<4) e3->f2+= 1;
671                 if(e4 && e4->f2<4) e4->f2+= 1;
672                 
673                 if(e1->tmp.f == 0) e1->tmp.f = (void *) efa;
674                 if(e2->tmp.f == 0) e2->tmp.f = (void *) efa;
675                 if(e3->tmp.f ==0) e3->tmp.f = (void *) efa;
676                 if(e4 && (e4->tmp.f == 0)) e4->tmp.f = (void *) efa;
677                 
678                 efa= efa->next;
679         }
680
681         if(me->drawflag & ME_ALLEDGES) {
682                 efa= em->faces.first;
683                 while(efa) {
684                         if(efa->e1->f2>=2) efa->e1->f2= 1;
685                         if(efa->e2->f2>=2) efa->e2->f2= 1;
686                         if(efa->e3->f2>=2) efa->e3->f2= 1;
687                         if(efa->e4 && efa->e4->f2>=2) efa->e4->f2= 1;
688                         
689                         efa= efa->next;
690                 }               
691         }       
692         else {
693                 
694                 /* handle single-edges for 'test cylinder flag' (old engine) */
695                 
696                 eed= em->edges.first;
697                 while(eed) {
698                         if(eed->f2==1) eed->f1= 1;
699                         eed= eed->next;
700                 }
701
702                 /* all faces, all edges with flag==2: compare normal */
703                 efa= em->faces.first;
704                 while(efa) {
705                         if(efa->e1->f2==2) edge_normal_compare(efa->e1, efa);
706                         else efa->e1->f2= 1;
707                         if(efa->e2->f2==2) edge_normal_compare(efa->e2, efa);
708                         else efa->e2->f2= 1;
709                         if(efa->e3->f2==2) edge_normal_compare(efa->e3, efa);
710                         else efa->e3->f2= 1;
711                         if(efa->e4) {
712                                 if(efa->e4->f2==2) edge_normal_compare(efa->e4, efa);
713                                 else efa->e4->f2= 1;
714                         }
715                         efa= efa->next;
716                 }
717                 
718                 /* sphere collision flag */
719                 
720                 eed= em->edges.first;
721                 while(eed) {
722                         if(eed->f1!=1) {
723                                 eed->v1->f1= eed->v2->f1= 0;
724                         }
725                         eed= eed->next;
726                 }
727                 
728         }
729 }
730
731 /* turns Mesh into editmesh */
732 void make_editMesh(Scene *scene, Object *ob)
733 {
734         Mesh *me= ob->data;
735         MFace *mface;
736         MVert *mvert;
737         MSelect *mselect;
738         KeyBlock *actkey;
739         EditMesh *em;
740         EditVert *eve, **evlist, *eve1, *eve2, *eve3, *eve4;
741         EditFace *efa, *efa_last_sel= NULL;
742         EditEdge *eed;
743         EditSelection *ese;
744         float *co, (*keyco)[3]= NULL;
745         int tot, a, eekadoodle= 0;
746
747         if(me->edit_mesh==NULL)
748                 me->edit_mesh= MEM_callocN(sizeof(EditMesh), "editmesh");
749         else 
750                 /* because of reload */
751                 free_editMesh(me->edit_mesh);
752         
753         em= me->edit_mesh;
754         
755         em->selectmode= scene->toolsettings->selectmode; // warning needs to be synced
756         em->act_face = NULL;
757         em->totvert= tot= me->totvert;
758         em->totedge= me->totedge;
759         em->totface= me->totface;
760         
761         if(tot==0) {
762                 return;
763         }
764         
765         if(ob->actcol > 0)
766                 em->mat_nr= ob->actcol-1;
767
768         /* initialize fastmalloc for editmesh */
769         init_editmesh_fastmalloc(em, me->totvert, me->totedge, me->totface);
770
771         actkey = ob_get_keyblock(ob);
772         if(actkey) {
773                 /* undo-ing in past for previous editmode sessions gives corrupt 'keyindex' values */
774                 undo_editmode_clear();
775                 keyco= actkey->data;
776                 em->shapenr= ob->shapenr;
777         }
778
779         /* make editverts */
780         CustomData_copy(&me->vdata, &em->vdata, CD_MASK_EDITMESH, CD_CALLOC, 0);
781         mvert= me->mvert;
782
783         evlist= (EditVert **)MEM_mallocN(tot*sizeof(void *),"evlist");
784         for(a=0; a<tot; a++, mvert++) {
785                 
786                 co= mvert->co;
787
788                 /* edit the shape key coordinate if available */
789                 if(keyco && a < actkey->totelem)
790                         co= keyco[a];
791
792                 eve= addvertlist(em, co, NULL);
793                 evlist[a]= eve;
794                 
795                 /* face select sets selection in next loop */
796                 if(!paint_facesel_test(ob))
797                         eve->f |= (mvert->flag & 1);
798                 
799                 if (mvert->flag & ME_HIDE) eve->h= 1;           
800                 eve->no[0]= mvert->no[0]/32767.0;
801                 eve->no[1]= mvert->no[1]/32767.0;
802                 eve->no[2]= mvert->no[2]/32767.0;
803
804                 eve->bweight= ((float)mvert->bweight)/255.0f;
805
806                 /* lets overwrite the keyindex of the editvert
807                  * with the order it used to be in before
808                  * editmode
809                  */
810                 eve->keyindex = a;
811
812                 CustomData_to_em_block(&me->vdata, &em->vdata, a, &eve->data);
813         }
814
815         if(actkey && actkey->totelem!=me->totvert);
816         else {
817                 MEdge *medge= me->medge;
818                 
819                 CustomData_copy(&me->edata, &em->edata, CD_MASK_EDITMESH, CD_CALLOC, 0);
820                 /* make edges */
821                 for(a=0; a<me->totedge; a++, medge++) {
822                         eed= addedgelist(em, evlist[medge->v1], evlist[medge->v2], NULL);
823                         /* eed can be zero when v1 and v2 are identical, dxf import does this... */
824                         if(eed) {
825                                 eed->crease= ((float)medge->crease)/255.0f;
826                                 eed->bweight= ((float)medge->bweight)/255.0f;
827                                 
828                                 if(medge->flag & ME_SEAM) eed->seam= 1;
829                                 if(medge->flag & ME_SHARP) eed->sharp = 1;
830                                 if(medge->flag & SELECT) eed->f |= SELECT;
831                                 if(medge->flag & ME_FGON) eed->h= EM_FGON;      // 2 different defines!
832                                 if(medge->flag & ME_HIDE) eed->h |= 1;
833                                 if(em->selectmode==SCE_SELECT_EDGE) 
834                                         EM_select_edge(eed, eed->f & SELECT);           // force edge selection to vertices, seems to be needed ...
835                                 CustomData_to_em_block(&me->edata,&em->edata, a, &eed->data);
836                         }
837                 }
838                 
839                 CustomData_copy(&me->fdata, &em->fdata, CD_MASK_EDITMESH, CD_CALLOC, 0);
840
841                 /* make faces */
842                 mface= me->mface;
843
844                 for(a=0; a<me->totface; a++, mface++) {
845                         eve1= evlist[mface->v1];
846                         eve2= evlist[mface->v2];
847                         if(!mface->v3) eekadoodle= 1;
848                         eve3= evlist[mface->v3];
849                         if(mface->v4) eve4= evlist[mface->v4]; else eve4= NULL;
850                         
851                         efa= addfacelist(em, eve1, eve2, eve3, eve4, NULL, NULL);
852
853                         if(efa) {
854                                 CustomData_to_em_block(&me->fdata, &em->fdata, a, &efa->data);
855
856                                 efa->mat_nr= mface->mat_nr;
857                                 efa->flag= mface->flag & ~ME_HIDE;
858                                 
859                                 /* select and hide face flag */
860                                 if(mface->flag & ME_HIDE) {
861                                         efa->h= 1;
862                                 } else {
863                                         if (a==me->act_face) {
864                                                 EM_set_actFace(em, efa);
865                                         }
866                                         
867                                         /* dont allow hidden and selected */
868                                         if(mface->flag & ME_FACE_SEL) {
869                                                 efa->f |= SELECT;
870                                                 
871                                                 if(paint_facesel_test(ob)) {
872                                                         EM_select_face(efa, 1); /* flush down */
873                                                 }
874
875                                                 efa_last_sel= efa;
876                                         }
877                                 }
878                         }
879                 }
880         }
881         
882         if(EM_get_actFace(em, 0)==NULL && efa_last_sel) {
883                 EM_set_actFace(em, efa_last_sel);
884         }
885
886         if(eekadoodle)
887                 error("This Mesh has old style edgecodes, please put it in the bugtracker!");
888         
889         MEM_freeN(evlist);
890
891         end_editmesh_fastmalloc();      // resets global function pointers
892         
893         if(me->mselect){
894                 //restore editselections
895                 EM_init_index_arrays(em, 1,1,1);
896                 mselect = me->mselect;
897                 
898                 for(a=0; a<me->totselect; a++, mselect++){
899                         /*check if recorded selection is still valid, if so copy into editmesh*/
900                         if( (mselect->type == EDITVERT && me->mvert[mselect->index].flag & SELECT) || (mselect->type == EDITEDGE && me->medge[mselect->index].flag & SELECT) || (mselect->type == EDITFACE && me->mface[mselect->index].flag & ME_FACE_SEL) ){
901                                 ese = MEM_callocN(sizeof(EditSelection), "Edit Selection");
902                                 ese->type = mselect->type;      
903                                 if(ese->type == EDITVERT) ese->data = EM_get_vert_for_index(mselect->index); else
904                                 if(ese->type == EDITEDGE) ese->data = EM_get_edge_for_index(mselect->index); else
905                                 if(ese->type == EDITFACE) ese->data = EM_get_face_for_index(mselect->index);
906                                 BLI_addtail(&(em->selected),ese);
907                         }
908                 }
909                 EM_free_index_arrays();
910         }
911         /* this creates coherent selections. also needed for older files */
912         EM_selectmode_set(em);
913         /* paranoia check to enforce hide rules */
914         EM_hide_reset(em);
915         /* sets helper flags which arent saved */
916         EM_fgon_flags(em);
917         
918         if (EM_get_actFace(em, 0)==NULL) {
919                 EM_set_actFace(em, em->faces.first ); /* will use the first face, this is so we alwats have an active face */
920         }
921 }
922
923 /* makes Mesh out of editmesh */
924 void load_editMesh(Scene *scene, Object *ob)
925 {
926         Mesh *me= ob->data;
927         MVert *mvert, *oldverts;
928         MEdge *medge;
929         MFace *mface;
930         MSelect *mselect;
931         EditMesh *em= me->edit_mesh;
932         EditVert *eve;
933         EditFace *efa, *efa_act;
934         EditEdge *eed;
935         EditSelection *ese;
936         float *fp, *newkey, *oldkey, nor[3];
937         int i, a, ototvert;
938         
939         /* this one also tests of edges are not in faces: */
940         /* eed->f2==0: not in face, f2==1: draw it */
941         /* eed->f1 : flag for dynaface (cylindertest, old engine) */
942         /* eve->f1 : flag for dynaface (sphere test, old engine) */
943         /* eve->f2 : being used in vertexnormals */
944         edge_drawflags(me, em);
945         
946         EM_stats_update(em);
947         
948         /* new Vertex block */
949         if(em->totvert==0) mvert= NULL;
950         else mvert= MEM_callocN(em->totvert*sizeof(MVert), "loadeditMesh vert");
951
952         /* new Edge block */
953         if(em->totedge==0) medge= NULL;
954         else medge= MEM_callocN(em->totedge*sizeof(MEdge), "loadeditMesh edge");
955         
956         /* new Face block */
957         if(em->totface==0) mface= NULL;
958         else mface= MEM_callocN(em->totface*sizeof(MFace), "loadeditMesh face");
959
960         /* lets save the old verts just in case we are actually working on
961          * a key ... we now do processing of the keys at the end */
962         oldverts= me->mvert;
963         ototvert= me->totvert;
964
965         /* don't free this yet */
966         CustomData_set_layer(&me->vdata, CD_MVERT, NULL);
967
968         /* free custom data */
969         CustomData_free(&me->vdata, me->totvert);
970         CustomData_free(&me->edata, me->totedge);
971         CustomData_free(&me->fdata, me->totface);
972
973         /* add new custom data */
974         me->totvert= em->totvert;
975         me->totedge= em->totedge;
976         me->totface= em->totface;
977
978         CustomData_copy(&em->vdata, &me->vdata, CD_MASK_MESH, CD_CALLOC, me->totvert);
979         CustomData_copy(&em->edata, &me->edata, CD_MASK_MESH, CD_CALLOC, me->totedge);
980         CustomData_copy(&em->fdata, &me->fdata, CD_MASK_MESH, CD_CALLOC, me->totface);
981
982         CustomData_add_layer(&me->vdata, CD_MVERT, CD_ASSIGN, mvert, me->totvert);
983         CustomData_add_layer(&me->edata, CD_MEDGE, CD_ASSIGN, medge, me->totedge);
984         CustomData_add_layer(&me->fdata, CD_MFACE, CD_ASSIGN, mface, me->totface);
985         mesh_update_customdata_pointers(me);
986
987         /* the vertices, use ->tmp.l as counter */
988         eve= em->verts.first;
989         a= 0;
990
991         while(eve) {
992                 VECCOPY(mvert->co, eve->co);
993
994                 mvert->mat_nr= 32767;  /* what was this for, halos? */
995                 
996                 /* vertex normal */
997                 VECCOPY(nor, eve->no);
998                 mul_v3_fl(nor, 32767.0);
999                 VECCOPY(mvert->no, nor);
1000
1001                 /* note: it used to remove me->dvert when it was not in use, cancelled
1002                    that... annoying when you have a fresh vgroup */
1003                 CustomData_from_em_block(&em->vdata, &me->vdata, eve->data, a);
1004
1005                 eve->tmp.l = a++;  /* counter */
1006                         
1007                 mvert->flag= 0;
1008                 mvert->flag |= (eve->f & SELECT);
1009                 if (eve->h) mvert->flag |= ME_HIDE;
1010                 
1011                 mvert->bweight= (char)(255.0*eve->bweight);
1012
1013                 eve= eve->next;
1014                 mvert++;
1015         }
1016
1017         /* the edges */
1018         a= 0;
1019         eed= em->edges.first;
1020         while(eed) {
1021                 medge->v1= (unsigned int) eed->v1->tmp.l;
1022                 medge->v2= (unsigned int) eed->v2->tmp.l;
1023                 
1024                 medge->flag= (eed->f & SELECT) | ME_EDGERENDER;
1025                 if(eed->f2<2) medge->flag |= ME_EDGEDRAW;
1026                 if(eed->f2==0) medge->flag |= ME_LOOSEEDGE;
1027                 if(eed->sharp) medge->flag |= ME_SHARP;
1028                 if(eed->seam) medge->flag |= ME_SEAM;
1029                 if(eed->h & EM_FGON) medge->flag |= ME_FGON;    // different defines yes
1030                 if(eed->h & 1) medge->flag |= ME_HIDE;
1031                 
1032                 medge->crease= (char)(255.0*eed->crease);
1033                 medge->bweight= (char)(255.0*eed->bweight);
1034                 CustomData_from_em_block(&em->edata, &me->edata, eed->data, a);         
1035
1036                 eed->tmp.l = a++;
1037                 
1038                 medge++;
1039                 eed= eed->next;
1040         }
1041
1042         /* the faces */
1043         a = 0;
1044         efa= em->faces.first;
1045         efa_act= EM_get_actFace(em, 0);
1046         i = 0;
1047         me->act_face = -1;
1048         while(efa) {
1049                 mface= &((MFace *) me->mface)[i];
1050                 
1051                 mface->v1= (unsigned int) efa->v1->tmp.l;
1052                 mface->v2= (unsigned int) efa->v2->tmp.l;
1053                 mface->v3= (unsigned int) efa->v3->tmp.l;
1054                 if (efa->v4) mface->v4 = (unsigned int) efa->v4->tmp.l;
1055
1056                 mface->mat_nr= efa->mat_nr;
1057                 
1058                 mface->flag= efa->flag;
1059                 /* bit 0 of flag is already taken for smooth... */
1060                 
1061                 if(efa->h) {
1062                         mface->flag |= ME_HIDE;
1063                         mface->flag &= ~ME_FACE_SEL;
1064                 } else {
1065                         if(efa->f & 1) mface->flag |= ME_FACE_SEL;
1066                         else mface->flag &= ~ME_FACE_SEL;
1067                 }
1068                 
1069                 /* mat_nr in vertex */
1070                 if(me->totcol>1) {
1071                         mvert= me->mvert+mface->v1;
1072                         if(mvert->mat_nr == (char)32767) mvert->mat_nr= mface->mat_nr;
1073                         mvert= me->mvert+mface->v2;
1074                         if(mvert->mat_nr == (char)32767) mvert->mat_nr= mface->mat_nr;
1075                         mvert= me->mvert+mface->v3;
1076                         if(mvert->mat_nr == (char)32767) mvert->mat_nr= mface->mat_nr;
1077                         if(mface->v4) {
1078                                 mvert= me->mvert+mface->v4;
1079                                 if(mvert->mat_nr == (char)32767) mvert->mat_nr= mface->mat_nr;
1080                         }
1081                 }
1082                         
1083                 /* watch: efa->e1->f2==0 means loose edge */ 
1084                         
1085                 if(efa->e1->f2==1) {
1086                         efa->e1->f2= 2;
1087                 }                       
1088                 if(efa->e2->f2==1) {
1089                         efa->e2->f2= 2;
1090                 }
1091                 if(efa->e3->f2==1) {
1092                         efa->e3->f2= 2;
1093                 }
1094                 if(efa->e4 && efa->e4->f2==1) {
1095                         efa->e4->f2= 2;
1096                 }
1097
1098                 CustomData_from_em_block(&em->fdata, &me->fdata, efa->data, i);
1099
1100                 /* no index '0' at location 3 or 4 */
1101                 test_index_face(mface, &me->fdata, i, efa->v4?4:3);
1102                 
1103                 if (efa_act == efa)
1104                         me->act_face = a;
1105
1106                 efa->tmp.l = a++;
1107                 i++;
1108                 efa= efa->next;
1109         }
1110
1111         /* patch hook indices and vertex parents */
1112         {
1113                 Object *ob;
1114                 ModifierData *md;
1115                 EditVert **vertMap = NULL;
1116                 int i,j;
1117
1118                 for (ob=G.main->object.first; ob; ob=ob->id.next) {
1119                         if (ob->parent==ob && ELEM(ob->partype, PARVERT1,PARVERT3)) {
1120                                 
1121                                 /* duplicate code from below, make it function later...? */
1122                                 if (!vertMap) {
1123                                         vertMap = MEM_callocN(sizeof(*vertMap)*ototvert, "vertMap");
1124                                         
1125                                         for (eve=em->verts.first; eve; eve=eve->next) {
1126                                                 if (eve->keyindex!=-1)
1127                                                         vertMap[eve->keyindex] = eve;
1128                                         }
1129                                 }
1130                                 if(ob->par1 < ototvert) {
1131                                         eve = vertMap[ob->par1];
1132                                         if(eve) ob->par1= eve->tmp.l;
1133                                 }
1134                                 if(ob->par2 < ototvert) {
1135                                         eve = vertMap[ob->par2];
1136                                         if(eve) ob->par2= eve->tmp.l;
1137                                 }
1138                                 if(ob->par3 < ototvert) {
1139                                         eve = vertMap[ob->par3];
1140                                         if(eve) ob->par3= eve->tmp.l;
1141                                 }
1142                                 
1143                         }
1144                         if (ob->data==me) {
1145                                 for (md=ob->modifiers.first; md; md=md->next) {
1146                                         if (md->type==eModifierType_Hook) {
1147                                                 HookModifierData *hmd = (HookModifierData*) md;
1148
1149                                                 if (!vertMap) {
1150                                                         vertMap = MEM_callocN(sizeof(*vertMap)*ototvert, "vertMap");
1151
1152                                                         for (eve=em->verts.first; eve; eve=eve->next) {
1153                                                                 if (eve->keyindex!=-1)
1154                                                                         vertMap[eve->keyindex] = eve;
1155                                                         }
1156                                                 }
1157                                                 
1158                                                 for (i=j=0; i<hmd->totindex; i++) {
1159                                                         if(hmd->indexar[i] < ototvert) {
1160                                                                 eve = vertMap[hmd->indexar[i]];
1161                                                                 
1162                                                                 if (eve) {
1163                                                                         hmd->indexar[j++] = eve->tmp.l;
1164                                                                 }
1165                                                         }
1166                                                         else j++;
1167                                                 }
1168
1169                                                 hmd->totindex = j;
1170                                         }
1171                                 }
1172                         }
1173                 }
1174
1175                 if (vertMap) MEM_freeN(vertMap);
1176         }
1177
1178         /* are there keys? */
1179         if(me->key) {
1180                 KeyBlock *currkey;
1181                 KeyBlock *actkey= BLI_findlink(&me->key->block, em->shapenr-1);
1182
1183                 float (*ofs)[3] = NULL;
1184
1185                 /* editing the base key should update others */
1186                 if(me->key->type==KEY_RELATIVE && oldverts) {
1187                         int act_is_basis = 0;
1188                         /* find if this key is a basis for any others */
1189                         for(currkey = me->key->block.first; currkey; currkey= currkey->next) {
1190                                 if(em->shapenr-1 == currkey->relative) {
1191                                         act_is_basis = 1;
1192                                         break;
1193                                 }
1194                         }
1195
1196                         if(act_is_basis) { /* active key is a base */
1197                                 i=0;
1198                                 ofs= MEM_callocN(sizeof(float) * 3 * em->totvert,  "currkey->data");
1199                                 eve= em->verts.first;
1200                                 mvert = me->mvert;
1201                                 while(eve) {
1202                                         VECSUB(ofs[i], mvert->co, oldverts[eve->keyindex].co);
1203                                         eve= eve->next;
1204                                         i++;
1205                                         mvert++;
1206                                 }
1207                         }
1208                 }
1209
1210
1211                 /* Lets reorder the key data so that things line up roughly
1212                  * with the way things were before editmode */
1213                 currkey = me->key->block.first;
1214                 while(currkey) {
1215                         int apply_offset = (ofs && (currkey != actkey) && (em->shapenr-1 == currkey->relative));
1216
1217                         fp= newkey= MEM_callocN(me->key->elemsize*em->totvert,  "currkey->data");
1218                         oldkey = currkey->data;
1219
1220                         eve= em->verts.first;
1221
1222                         i = 0;
1223                         mvert = me->mvert;
1224                         while(eve) {
1225                                 if (eve->keyindex >= 0 && eve->keyindex < currkey->totelem) { // valid old vertex
1226                                         if(currkey == actkey) {
1227                                                 if(actkey == me->key->refkey) {
1228                                                         VECCOPY(fp, mvert->co);
1229                                                 }
1230                                                 else {
1231                                                         VECCOPY(fp, mvert->co);
1232                                                         if(oldverts) {
1233                                                                 VECCOPY(mvert->co, oldverts[eve->keyindex].co);
1234                                                         }
1235                                                 }
1236                                         }
1237                                         else {
1238                                                 if(oldkey) {
1239                                                         VECCOPY(fp, oldkey + 3 * eve->keyindex);
1240                                                 }
1241                                         }
1242                                 }
1243                                 else {
1244                                         VECCOPY(fp, mvert->co);
1245                                 }
1246
1247                                 /* propagate edited basis offsets to other shapes */
1248                                 if(apply_offset) {
1249                                         VECADD(fp, fp, ofs[i]);
1250                                 }
1251
1252                                 fp+= 3;
1253                                 ++i;
1254                                 ++mvert;
1255                                 eve= eve->next;
1256                         }
1257                         currkey->totelem= em->totvert;
1258                         if(currkey->data) MEM_freeN(currkey->data);
1259                         currkey->data = newkey;
1260                         
1261                         currkey= currkey->next;
1262                 }
1263
1264                 if(ofs) MEM_freeN(ofs);
1265         }
1266
1267         if(oldverts) MEM_freeN(oldverts);
1268         
1269         i = 0;
1270         for(ese=em->selected.first; ese; ese=ese->next) i++;
1271         me->totselect = i;
1272         if(i==0) mselect= NULL;
1273         else mselect= MEM_callocN(i*sizeof(MSelect), "loadeditMesh selections");
1274         
1275         if(me->mselect) MEM_freeN(me->mselect);
1276         me->mselect= mselect;
1277         
1278         for(ese=em->selected.first; ese; ese=ese->next){
1279                 mselect->type = ese->type;
1280                 if(ese->type == EDITVERT) mselect->index = ((EditVert*)ese->data)->tmp.l;
1281                 else if(ese->type == EDITEDGE) mselect->index = ((EditEdge*)ese->data)->tmp.l;
1282                 else if(ese->type == EDITFACE) mselect->index = ((EditFace*)ese->data)->tmp.l;
1283                 mselect++;
1284         }
1285         
1286         /* to be sure: clear ->tmp.l pointers */
1287         eve= em->verts.first;
1288         while(eve) {
1289                 eve->tmp.l = 0;
1290                 eve= eve->next;
1291         }
1292         
1293         eed= em->edges.first;
1294         while(eed) { 
1295                 eed->tmp.l = 0;
1296                 eed= eed->next;
1297         }
1298         
1299         efa= em->faces.first;
1300         while(efa) {
1301                 efa->tmp.l = 0;
1302                 efa= efa->next;
1303         }
1304         
1305         /* remake softbody of all users */
1306         if(me->id.us>1) {
1307                 Base *base;
1308                 for(base= scene->base.first; base; base= base->next)
1309                         if(base->object->data==me)
1310                                 base->object->recalc |= OB_RECALC_DATA;
1311         }
1312
1313         mesh_calc_normals(me->mvert, me->totvert, me->mface, me->totface, NULL);
1314 }
1315
1316 void remake_editMesh(Scene *scene, Object *ob)
1317 {
1318         make_editMesh(scene, ob);
1319         DAG_id_flush_update(&ob->id, OB_RECALC_DATA);
1320         BIF_undo_push("Undo all changes");
1321 }
1322
1323 /* *************** Operator: separate parts *************/
1324
1325 static EnumPropertyItem prop_separate_types[] = {
1326         {0, "SELECTED", 0, "Selection", ""},
1327         {1, "MATERIAL", 0, "By Material", ""},
1328         {2, "LOOSE", 0, "By loose parts", ""},
1329         {0, NULL, 0, NULL, NULL}
1330 };
1331
1332 /* return 1: success */
1333 static int mesh_separate_selected(Main *bmain, Scene *scene, Base *editbase)
1334 {
1335         EditMesh *em, *emnew;
1336         EditVert *eve, *v1;
1337         EditEdge *eed, *e1;
1338         EditFace *efa, *f1;
1339         Object *obedit;
1340         Mesh *me, *menew;
1341         Base *basenew;
1342         
1343         if(editbase==NULL) return 0;
1344         
1345         obedit= editbase->object;
1346         me= obedit->data;
1347         em= BKE_mesh_get_editmesh(me);
1348         if(me->key) {
1349                 error("Can't separate with vertex keys");
1350                 BKE_mesh_end_editmesh(me, em);
1351                 return 0;
1352         }
1353         
1354         if(em->selected.first) 
1355                 BLI_freelistN(&(em->selected)); /* clear the selection order */
1356                 
1357         EM_selectmode_set(em);  // enforce full consistent selection flags 
1358         
1359         EM_stats_update(em);
1360         
1361         if(em->totvertsel==0) {
1362                 BKE_mesh_end_editmesh(me, em);
1363                 return 0;
1364         }
1365         
1366         /* we are going to work as follows:
1367          * 1. add a linked duplicate object: this will be the new one, we remember old pointer
1368          * 2. give new object empty mesh and put in editmode
1369          * 3: do a split if needed on current editmesh.
1370          * 4. copy over: all NOT selected verts, edges, faces
1371          * 5. call load_editMesh() on the new object
1372          */
1373         
1374         /* 1 */
1375         basenew= ED_object_add_duplicate(bmain, scene, editbase, 0);    /* 0 = fully linked */
1376         ED_base_object_select(basenew, BA_DESELECT);
1377         
1378         /* 2 */
1379         basenew->object->data= menew= add_mesh(me->id.name+2);  /* empty */
1380         assign_matarar(basenew->object, give_matarar(obedit), *give_totcolp(obedit)); /* new in 2.5 */
1381         me->id.us--;
1382         make_editMesh(scene, basenew->object);
1383         emnew= menew->edit_mesh;
1384         CustomData_copy(&em->vdata, &emnew->vdata, CD_MASK_EDITMESH, CD_DEFAULT, 0);
1385         CustomData_copy(&em->edata, &emnew->edata, CD_MASK_EDITMESH, CD_DEFAULT, 0);
1386         CustomData_copy(&em->fdata, &emnew->fdata, CD_MASK_EDITMESH, CD_DEFAULT, 0);
1387         
1388         /* 3 */
1389         /* SPLIT: first make duplicate */
1390         adduplicateflag(em, SELECT);
1391         /* SPLIT: old faces have 3x flag 128 set, delete these ones */
1392         delfaceflag(em, 128);
1393         /* since we do tricky things with verts/edges/faces, this makes sure all is selected coherent */
1394         EM_selectmode_set(em);
1395         
1396         /* 4 */
1397         /* move over: everything that is selected */
1398         for(eve= em->verts.first; eve; eve= v1) {
1399                 v1= eve->next;
1400                 if(eve->f & SELECT) {
1401                         BLI_remlink(&em->verts, eve);
1402                         BLI_addtail(&emnew->verts, eve);
1403                 }
1404         }
1405         
1406         for(eed= em->edges.first; eed; eed= e1) {
1407                 e1= eed->next;
1408                 if(eed->f & SELECT) {
1409                         BLI_remlink(&em->edges, eed);
1410                         BLI_addtail(&emnew->edges, eed);
1411                 }
1412         }
1413         
1414         for(efa= em->faces.first; efa; efa= f1) {
1415                 f1= efa->next;
1416                 if (efa == em->act_face && (efa->f & SELECT)) {
1417                         EM_set_actFace(em, NULL);
1418                 }
1419
1420                 if(efa->f & SELECT) {
1421                         BLI_remlink(&em->faces, efa);
1422                         BLI_addtail(&emnew->faces, efa);
1423                 }
1424         }
1425
1426         /* 5 */
1427         load_editMesh(scene, basenew->object);
1428         free_editMesh(emnew);
1429         MEM_freeN(menew->edit_mesh);
1430         menew->edit_mesh= NULL;
1431         
1432         /* hashedges are invalid now, make new! */
1433         editMesh_set_hash(em);
1434
1435         DAG_id_flush_update(&obedit->id, OB_RECALC_DATA);       
1436         DAG_id_flush_update(&basenew->object->id, OB_RECALC_DATA);      
1437
1438         BKE_mesh_end_editmesh(me, em);
1439
1440         return 1;
1441 }
1442
1443 /* return 1: success */
1444 static int mesh_separate_material(Main *bmain, Scene *scene, Base *editbase)
1445 {
1446         Mesh *me= editbase->object->data;
1447         EditMesh *em= BKE_mesh_get_editmesh(me);
1448         unsigned char curr_mat;
1449         
1450         for (curr_mat = 1; curr_mat < editbase->object->totcol; ++curr_mat) {
1451                 /* clear selection, we're going to use that to select material group */
1452                 EM_clear_flag_all(em, SELECT);
1453                 /* select the material */
1454                 EM_select_by_material(em, curr_mat);
1455                 /* and now separate */
1456                 if(0==mesh_separate_selected(bmain, scene, editbase)) {
1457                         BKE_mesh_end_editmesh(me, em);
1458                         return 0;
1459                 }
1460         }
1461
1462         BKE_mesh_end_editmesh(me, em);
1463         return 1;
1464 }
1465
1466 /* return 1: success */
1467 static int mesh_separate_loose(Main *bmain, Scene *scene, Base *editbase)
1468 {
1469         Mesh *me;
1470         EditMesh *em;
1471         int doit= 1;
1472         
1473         me= editbase->object->data;
1474         em= BKE_mesh_get_editmesh(me);
1475         
1476         if(me->key) {
1477                 error("Can't separate with vertex keys");
1478                 BKE_mesh_end_editmesh(me, em);
1479                 return 0;
1480         }
1481         
1482         EM_clear_flag_all(em, SELECT);
1483
1484         while(doit) {
1485                 /* Select a random vert to start with */
1486                 EditVert *eve;
1487                 int tot;
1488
1489                 /* check if all verts that are visible have been done */
1490                 for(eve=em->verts.first; eve; eve= eve->next)
1491                         if(!eve->h) break;
1492                 if(eve==NULL) break; /* only hidden verts left, quit early */
1493
1494                 /* first non hidden vert */
1495                 eve->f |= SELECT;
1496                 
1497                 selectconnected_mesh_all(em);
1498                 
1499                 /* don't separate the very last part */
1500                 for(eve=em->verts.first; eve; eve= eve->next)
1501                         if((eve->f & SELECT)==0) break;
1502                 if(eve==NULL) break;
1503
1504                 tot= BLI_countlist(&em->verts);
1505
1506                 /* and now separate */
1507                 doit= mesh_separate_selected(bmain, scene, editbase);
1508
1509                 /* with hidden verts this can happen */
1510                 if(tot == BLI_countlist(&em->verts))
1511                         break;
1512         }
1513
1514         BKE_mesh_end_editmesh(me, em);
1515         return 1;
1516 }
1517
1518
1519 static int mesh_separate_exec(bContext *C, wmOperator *op)
1520 {
1521         Main *bmain= CTX_data_main(C);
1522         Scene *scene= CTX_data_scene(C);
1523         Base *base= CTX_data_active_base(C);
1524         int retval= 0, type= RNA_enum_get(op->ptr, "type");
1525         
1526         if(type == 0)
1527                 retval= mesh_separate_selected(bmain, scene, base);
1528         else if(type == 1)
1529                 retval= mesh_separate_material(bmain, scene, base);
1530         else if(type == 2)
1531                 retval= mesh_separate_loose(bmain, scene, base);
1532            
1533         if(retval) {
1534                 WM_event_add_notifier(C, NC_GEOM|ND_DATA, base->object->data);
1535                 return OPERATOR_FINISHED;
1536         }
1537         return OPERATOR_CANCELLED;
1538 }
1539
1540 void MESH_OT_separate(wmOperatorType *ot)
1541 {
1542         /* identifiers */
1543         ot->name= "Separate";
1544         ot->description= "Separate selected geometry into a new mesh";
1545         ot->idname= "MESH_OT_separate";
1546         
1547         /* api callbacks */
1548         ot->invoke= WM_menu_invoke;
1549         ot->exec= mesh_separate_exec;
1550         ot->poll= ED_operator_editmesh;
1551         
1552         /* flags */
1553         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1554         
1555         ot->prop= RNA_def_enum(ot->srna, "type", prop_separate_types, 0, "Type", "");
1556 }
1557
1558
1559 /* ******************************************** */
1560
1561 /* *************** UNDO ***************************** */
1562 /* new mesh undo, based on pushing editmesh data itself */
1563 /* reuses same code as for global and curve undo... unify that (ton) */
1564
1565 /* only one 'hack', to save memory it doesn't store the first push, but does a remake editmesh */
1566
1567 /* a compressed version of editmesh data */
1568
1569 typedef struct EditVertC
1570 {
1571         float no[3];
1572         float co[3];
1573         unsigned char f, h;
1574         short bweight;
1575         int keyindex;
1576 } EditVertC;
1577
1578 typedef struct EditEdgeC
1579 {
1580         int v1, v2;
1581         unsigned char f, h, seam, sharp, pad;
1582         short crease, bweight, fgoni;
1583 } EditEdgeC;
1584
1585 typedef struct EditFaceC
1586 {
1587         int v1, v2, v3, v4;
1588         unsigned char flag, f, h, fgonf, pad1;
1589         short mat_nr;
1590 } EditFaceC;
1591
1592 typedef struct EditSelectionC{
1593         short type;
1594         int index;
1595 }EditSelectionC;
1596
1597 typedef struct UndoMesh {
1598         EditVertC *verts;
1599         EditEdgeC *edges;
1600         EditFaceC *faces;
1601         EditSelectionC *selected;
1602         int totvert, totedge, totface, totsel;
1603         int selectmode, shapenr;
1604         RetopoPaintData *retopo_paint_data;
1605         char retopo_mode;
1606         CustomData vdata, edata, fdata;
1607 } UndoMesh;
1608
1609 /* for callbacks */
1610
1611 static void free_undoMesh(void *umv)
1612 {
1613         UndoMesh *um= umv;
1614         
1615         if(um->verts) MEM_freeN(um->verts);
1616         if(um->edges) MEM_freeN(um->edges);
1617         if(um->faces) MEM_freeN(um->faces);
1618         if(um->selected) MEM_freeN(um->selected);
1619 // XXX  if(um->retopo_paint_data) retopo_free_paint_data(um->retopo_paint_data);
1620         CustomData_free(&um->vdata, um->totvert);
1621         CustomData_free(&um->edata, um->totedge);
1622         CustomData_free(&um->fdata, um->totface);
1623         MEM_freeN(um);
1624 }
1625
1626 static void *editMesh_to_undoMesh(void *emv)
1627 {
1628         EditMesh *em= (EditMesh *)emv;
1629         UndoMesh *um;
1630         EditVert *eve;
1631         EditEdge *eed;
1632         EditFace *efa;
1633         EditSelection *ese;
1634         EditVertC *evec=NULL;
1635         EditEdgeC *eedc=NULL;
1636         EditFaceC *efac=NULL;
1637         EditSelectionC *esec=NULL;
1638         int a;
1639
1640         um= MEM_callocN(sizeof(UndoMesh), "undomesh");
1641         
1642         um->selectmode = em->selectmode;
1643         um->shapenr = em->shapenr;
1644         
1645         for(eve=em->verts.first; eve; eve= eve->next) um->totvert++;
1646         for(eed=em->edges.first; eed; eed= eed->next) um->totedge++;
1647         for(efa=em->faces.first; efa; efa= efa->next) um->totface++;
1648         for(ese=em->selected.first; ese; ese=ese->next) um->totsel++; 
1649         /* malloc blocks */
1650         
1651         if(um->totvert) evec= um->verts= MEM_callocN(um->totvert*sizeof(EditVertC), "allvertsC");
1652         if(um->totedge) eedc= um->edges= MEM_callocN(um->totedge*sizeof(EditEdgeC), "alledgesC");
1653         if(um->totface) efac= um->faces= MEM_callocN(um->totface*sizeof(EditFaceC), "allfacesC");
1654         if(um->totsel) esec= um->selected= MEM_callocN(um->totsel*sizeof(EditSelectionC), "allselections");
1655
1656         if(um->totvert) CustomData_copy(&em->vdata, &um->vdata, CD_MASK_EDITMESH, CD_CALLOC, um->totvert);
1657         if(um->totedge) CustomData_copy(&em->edata, &um->edata, CD_MASK_EDITMESH, CD_CALLOC, um->totedge);
1658         if(um->totface) CustomData_copy(&em->fdata, &um->fdata, CD_MASK_EDITMESH, CD_CALLOC, um->totface);
1659         
1660         /* now copy vertices */
1661         a = 0;
1662         for(eve=em->verts.first; eve; eve= eve->next, evec++, a++) {
1663                 VECCOPY(evec->co, eve->co);
1664                 VECCOPY(evec->no, eve->no);
1665
1666                 evec->f= eve->f;
1667                 evec->h= eve->h;
1668                 evec->keyindex= eve->keyindex;
1669                 eve->tmp.l = a; /*store index*/
1670                 evec->bweight= (short)(eve->bweight*255.0);
1671
1672                 CustomData_from_em_block(&em->vdata, &um->vdata, eve->data, a);
1673         }
1674         
1675         /* copy edges */
1676         a = 0;
1677         for(eed=em->edges.first; eed; eed= eed->next, eedc++, a++)  {
1678                 eedc->v1= (int)eed->v1->tmp.l;
1679                 eedc->v2= (int)eed->v2->tmp.l;
1680                 eedc->f= eed->f;
1681                 eedc->h= eed->h;
1682                 eedc->seam= eed->seam;
1683                 eedc->sharp= eed->sharp;
1684                 eedc->crease= (short)(eed->crease*255.0);
1685                 eedc->bweight= (short)(eed->bweight*255.0);
1686                 eedc->fgoni= eed->fgoni;
1687                 eed->tmp.l = a; /*store index*/
1688                 CustomData_from_em_block(&em->edata, &um->edata, eed->data, a);
1689         
1690         }
1691         
1692         /* copy faces */
1693         a = 0;
1694         for(efa=em->faces.first; efa; efa= efa->next, efac++, a++) {
1695                 efac->v1= (int)efa->v1->tmp.l;
1696                 efac->v2= (int)efa->v2->tmp.l;
1697                 efac->v3= (int)efa->v3->tmp.l;
1698                 if(efa->v4) efac->v4= (int)efa->v4->tmp.l;
1699                 else efac->v4= -1;
1700                 
1701                 efac->mat_nr= efa->mat_nr;
1702                 efac->flag= efa->flag;
1703                 efac->f= efa->f;
1704                 efac->h= efa->h;
1705                 efac->fgonf= efa->fgonf;
1706
1707                 efa->tmp.l = a; /*store index*/
1708
1709                 CustomData_from_em_block(&em->fdata, &um->fdata, efa->data, a);
1710         }
1711         
1712         a = 0;
1713         for(ese=em->selected.first; ese; ese=ese->next, esec++){
1714                 esec->type = ese->type;
1715                 if(ese->type == EDITVERT) a = esec->index = ((EditVert*)ese->data)->tmp.l; 
1716                 else if(ese->type == EDITEDGE) a = esec->index = ((EditEdge*)ese->data)->tmp.l; 
1717                 else if(ese->type == EDITFACE) a = esec->index = ((EditFace*)ese->data)->tmp.l;
1718         }
1719
1720 // XXX  um->retopo_paint_data= retopo_paint_data_copy(em->retopo_paint_data);
1721 //      um->retopo_mode= scene->toolsettings->retopo_mode;
1722         
1723         return um;
1724 }
1725
1726 static void undoMesh_to_editMesh(void *umv, void *emv)
1727 {
1728         EditMesh *em= (EditMesh *)emv;
1729         UndoMesh *um= (UndoMesh *)umv;
1730         EditVert *eve, **evar=NULL;
1731         EditEdge *eed;
1732         EditFace *efa;
1733         EditSelection *ese;
1734         EditVertC *evec;
1735         EditEdgeC *eedc;
1736         EditFaceC *efac;
1737         EditSelectionC *esec;
1738         int a=0;
1739
1740         free_editMesh(em);
1741         
1742         /* malloc blocks */
1743         memset(em, 0, sizeof(EditMesh));
1744                 
1745         em->selectmode = um->selectmode;
1746         em->shapenr = um->shapenr;
1747         
1748         init_editmesh_fastmalloc(em, um->totvert, um->totedge, um->totface);
1749
1750         CustomData_free(&em->vdata, 0);
1751         CustomData_free(&em->edata, 0);
1752         CustomData_free(&em->fdata, 0);
1753
1754         CustomData_copy(&um->vdata, &em->vdata, CD_MASK_EDITMESH, CD_CALLOC, 0);
1755         CustomData_copy(&um->edata, &em->edata, CD_MASK_EDITMESH, CD_CALLOC, 0);
1756         CustomData_copy(&um->fdata, &em->fdata, CD_MASK_EDITMESH, CD_CALLOC, 0);
1757
1758         /* now copy vertices */
1759
1760         if(um->totvert) evar= MEM_mallocN(um->totvert*sizeof(EditVert *), "vertex ar");
1761         for(a=0, evec= um->verts; a<um->totvert; a++, evec++) {
1762                 eve= addvertlist(em, evec->co, NULL);
1763                 evar[a]= eve;
1764
1765                 VECCOPY(eve->no, evec->no);
1766                 eve->f= evec->f;
1767                 eve->h= evec->h;
1768                 eve->keyindex= evec->keyindex;
1769                 eve->bweight= ((float)evec->bweight)/255.0f;
1770
1771                 CustomData_to_em_block(&um->vdata, &em->vdata, a, &eve->data);
1772         }
1773
1774         /* copy edges */
1775         for(a=0, eedc= um->edges; a<um->totedge; a++, eedc++) {
1776                 eed= addedgelist(em, evar[eedc->v1], evar[eedc->v2], NULL);
1777
1778                 eed->f= eedc->f;
1779                 eed->h= eedc->h;
1780                 eed->seam= eedc->seam;
1781                 eed->sharp= eedc->sharp;
1782                 eed->fgoni= eedc->fgoni;
1783                 eed->crease= ((float)eedc->crease)/255.0f;
1784                 eed->bweight= ((float)eedc->bweight)/255.0f;
1785                 CustomData_to_em_block(&um->edata, &em->edata, a, &eed->data);
1786         }
1787         
1788         /* copy faces */
1789         for(a=0, efac= um->faces; a<um->totface; a++, efac++) {
1790                 if(efac->v4 != -1)
1791                         efa= addfacelist(em, evar[efac->v1], evar[efac->v2], evar[efac->v3], evar[efac->v4], NULL, NULL);
1792                 else 
1793                         efa= addfacelist(em, evar[efac->v1], evar[efac->v2], evar[efac->v3], NULL, NULL ,NULL);
1794
1795                 efa->mat_nr= efac->mat_nr;
1796                 efa->flag= efac->flag;
1797                 efa->f= efac->f;
1798                 efa->h= efac->h;
1799                 efa->fgonf= efac->fgonf;
1800                 
1801                 CustomData_to_em_block(&um->fdata, &em->fdata, a, &efa->data);
1802         }
1803         
1804         end_editmesh_fastmalloc();
1805         if(evar) MEM_freeN(evar);
1806         
1807         em->totvert = um->totvert;
1808         em->totedge = um->totedge;
1809         em->totface = um->totface;
1810         /*restore stored editselections*/
1811         if(um->totsel){
1812                 EM_init_index_arrays(em, 1,1,1);
1813                 for(a=0, esec= um->selected; a<um->totsel; a++, esec++){
1814                         ese = MEM_callocN(sizeof(EditSelection), "Edit Selection");
1815                         ese->type = esec->type;
1816                         if(ese->type == EDITVERT) ese->data = EM_get_vert_for_index(esec->index); else
1817                         if(ese->type == EDITEDGE) ese->data = EM_get_edge_for_index(esec->index); else
1818                         if(ese->type == EDITFACE) ese->data = EM_get_face_for_index(esec->index);
1819                         BLI_addtail(&(em->selected),ese);
1820                 }
1821                 EM_free_index_arrays();
1822         }
1823
1824         /* restore total selections */
1825         EM_nvertices_selected(em);
1826         EM_nedges_selected(em);
1827         EM_nfaces_selected(em);
1828
1829 // XXX  retopo_free_paint();
1830 //      em->retopo_paint_data= retopo_paint_data_copy(um->retopo_paint_data);
1831 //      scene->toolsettings->retopo_mode= um->retopo_mode;
1832 //      if(scene->toolsettings->retopo_mode) {
1833 // XXX          if(G.vd->depths) G.vd->depths->damaged= 1;
1834 //              retopo_queue_updates(G.vd);
1835 //              retopo_paint_view_update(G.vd);
1836 //      }
1837         
1838 }
1839
1840 static void *getEditMesh(bContext *C)
1841 {
1842         Object *obedit= CTX_data_edit_object(C);
1843         if(obedit && obedit->type==OB_MESH) {
1844                 Mesh *me= obedit->data;
1845                 return me->edit_mesh;
1846         }
1847         return NULL;
1848 }
1849
1850 /* and this is all the undo system needs to know */
1851 void undo_push_mesh(bContext *C, char *name)
1852 {
1853         undo_editmode_push(C, name, getEditMesh, free_undoMesh, undoMesh_to_editMesh, editMesh_to_undoMesh, NULL);
1854 }
1855
1856
1857
1858 /* *************** END UNDO *************/
1859
1860 static EditVert **g_em_vert_array = NULL;
1861 static EditEdge **g_em_edge_array = NULL;
1862 static EditFace **g_em_face_array = NULL;
1863
1864 void EM_init_index_arrays(EditMesh *em, int forVert, int forEdge, int forFace)
1865 {
1866         EditVert *eve;
1867         EditEdge *eed;
1868         EditFace *efa;
1869         int i;
1870
1871         if (forVert) {
1872                 em->totvert= BLI_countlist(&em->verts);
1873
1874                 if(em->totvert) {
1875                         g_em_vert_array = MEM_mallocN(sizeof(*g_em_vert_array)*em->totvert, "em_v_arr");
1876
1877                         for (i=0,eve=em->verts.first; eve; i++,eve=eve->next)
1878                                 g_em_vert_array[i] = eve;
1879                 }
1880         }
1881
1882         if (forEdge) {
1883                 em->totedge= BLI_countlist(&em->edges);
1884
1885                 if(em->totedge) {
1886                         g_em_edge_array = MEM_mallocN(sizeof(*g_em_edge_array)*em->totedge, "em_e_arr");
1887
1888                         for (i=0,eed=em->edges.first; eed; i++,eed=eed->next)
1889                                 g_em_edge_array[i] = eed;
1890                 }
1891         }
1892
1893         if (forFace) {
1894                 em->totface= BLI_countlist(&em->faces);
1895
1896                 if(em->totface) {
1897                         g_em_face_array = MEM_mallocN(sizeof(*g_em_face_array)*em->totface, "em_f_arr");
1898
1899                         for (i=0,efa=em->faces.first; efa; i++,efa=efa->next)
1900                                 g_em_face_array[i] = efa;
1901                 }
1902         }
1903 }
1904
1905 void EM_free_index_arrays(void)
1906 {
1907         if (g_em_vert_array) MEM_freeN(g_em_vert_array);
1908         if (g_em_edge_array) MEM_freeN(g_em_edge_array);
1909         if (g_em_face_array) MEM_freeN(g_em_face_array);
1910         g_em_vert_array = NULL;
1911         g_em_edge_array = NULL;
1912         g_em_face_array = NULL;
1913 }
1914
1915 EditVert *EM_get_vert_for_index(int index)
1916 {
1917         return g_em_vert_array?g_em_vert_array[index]:NULL;
1918 }
1919
1920 EditEdge *EM_get_edge_for_index(int index)
1921 {
1922         return g_em_edge_array?g_em_edge_array[index]:NULL;
1923 }
1924
1925 EditFace *EM_get_face_for_index(int index)
1926 {
1927         return g_em_face_array?g_em_face_array[index]:NULL;
1928 }
1929
1930 /* can we edit UV's for this mesh?*/
1931 int EM_texFaceCheck(EditMesh *em)
1932 {
1933         /* some of these checks could be a touch overkill */
1934         if (    (em) &&
1935                         (em->faces.first) &&
1936                         (CustomData_has_layer(&em->fdata, CD_MTFACE)))
1937                 return 1;
1938         return 0;
1939 }
1940
1941 /* can we edit colors for this mesh?*/
1942 int EM_vertColorCheck(EditMesh *em)
1943 {
1944         /* some of these checks could be a touch overkill */
1945         if (    (em) &&
1946                         (em->faces.first) &&
1947                         (CustomData_has_layer(&em->fdata, CD_MCOL)))
1948                 return 1;
1949         return 0;
1950 }
1951
1952
1953 void em_setup_viewcontext(bContext *C, ViewContext *vc)
1954 {
1955         view3d_set_viewcontext(C, vc);
1956         
1957         if(vc->obedit) {
1958                 Mesh *me= vc->obedit->data;
1959                 vc->em= me->edit_mesh;
1960         }
1961 }