- remove some unused editmesh functions.
[blender.git] / source / blender / blenlib / intern / scanfill.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) 2001-2002 by NaN Holding BV.
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  * (uit traces) maart 95
27  */
28
29 /** \file blender/blenlib/intern/scanfill.c
30  *  \ingroup bli
31  */
32
33 #include <stdio.h>
34 #include <math.h>
35 #include <stdlib.h>
36 #include <string.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "BLI_callbacks.h"
41 #include "BLI_listbase.h"
42 #include "BLI_math.h"
43 #include "BLI_scanfill.h"
44 #include "BLI_utildefines.h"
45 #include "BLI_threads.h"
46
47 /* callbacks for errors and interrupts and some goo */
48 static void (*BLI_localErrorCallBack)(const char*) = NULL;
49 static int (*BLI_localInterruptCallBack)(void) = NULL;
50
51 void BLI_setErrorCallBack(void (*f)(const char *))
52 {
53         BLI_localErrorCallBack = f;
54 }
55
56 void BLI_setInterruptCallBack(int (*f)(void))
57 {
58         BLI_localInterruptCallBack = f;
59 }
60
61 /* just flush the error to /dev/null if the error handler is missing */
62 void callLocalErrorCallBack(const char* msg)
63 {
64         if (BLI_localErrorCallBack) {
65                 BLI_localErrorCallBack(msg);
66         }
67 }
68
69 #if 0
70 /* ignore if the interrupt wasn't set */
71 static int callLocalInterruptCallBack(void)
72 {
73         if (BLI_localInterruptCallBack) {
74                 return BLI_localInterruptCallBack();
75         } else {
76                 return 0;
77         }
78 }
79 #endif
80
81 /* local types */
82 typedef struct PolyFill {
83         int edges,verts;
84         float min[3],max[3];
85         short f,nr;
86 } PolyFill;
87
88 typedef struct ScanFillVertLink {
89         ScanFillVert *v1;
90         ScanFillEdge *first, *last;
91 } ScanFillVertLink;
92
93
94 /* local funcs */
95
96 #define COMPLIMIT       0.00003
97
98 static ScanFillVertLink *scdata;
99
100 ListBase fillvertbase = {NULL, NULL};
101 ListBase filledgebase = {NULL, NULL};
102 ListBase fillfacebase = {NULL, NULL};
103
104 static int cox, coy;
105
106 /* ****  FUBCTIONS FOR QSORT *************************** */
107
108
109 static int vergscdata(const void *a1, const void *a2)
110 {
111         const ScanFillVertLink *x1=a1,*x2=a2;
112         
113         if( x1->v1->co[coy] < x2->v1->co[coy] ) return 1;
114         else if( x1->v1->co[coy] > x2->v1->co[coy]) return -1;
115         else if( x1->v1->co[cox] > x2->v1->co[cox] ) return 1;
116         else if( x1->v1->co[cox] < x2->v1->co[cox]) return -1;
117
118         return 0;
119 }
120
121 static int vergpoly(const void *a1, const void *a2)
122 {
123         const PolyFill *x1=a1, *x2=a2;
124
125         if( x1->min[cox] > x2->min[cox] ) return 1;
126         else if( x1->min[cox] < x2->min[cox] ) return -1;
127         else if( x1->min[coy] > x2->min[coy] ) return 1;
128         else if( x1->min[coy] < x2->min[coy] ) return -1;
129         
130         return 0;
131 }
132
133 /* ************* MEMORY MANAGEMENT ************* */
134
135 struct mem_elements {
136         struct mem_elements *next, *prev;
137         char *data;
138 };
139
140
141 /* simple optimization for allocating thousands of small memory blocks
142    only to be used within loops, and not by one function at a time
143    free in the end, with argument '-1'
144 */
145 #define MEM_ELEM_BLOCKSIZE 16384
146 static struct mem_elements *  melem__cur= 0;
147 static int                    melem__offs= 0; /* the current free address */
148 static ListBase               melem__lb= {NULL, NULL};
149
150 static void *mem_element_new(int size)
151 {
152         BLI_assert(!(size>10000 || size==0)); /* this is invalid use! */
153
154         size = (size + 3 ) & ~3;        /* allocate in units of 4 */
155         
156         if(melem__cur && (size + melem__offs < MEM_ELEM_BLOCKSIZE)) {
157                 void *adr= (void *) (melem__cur->data+melem__offs);
158                  melem__offs+= size;
159                 return adr;
160         }
161         else {
162                 melem__cur= MEM_callocN( sizeof(struct mem_elements), "newmem");
163                 melem__cur->data= MEM_callocN(MEM_ELEM_BLOCKSIZE, "newmem");
164                 BLI_addtail(&melem__lb, melem__cur);
165
166                 melem__offs= size;
167                 return melem__cur->data;
168         }
169 }
170 static void mem_element_reset(void)
171 {
172         struct mem_elements *first;
173         /*BMESH_TODO: keep the first block, gives memory leak on exit with 'newmem' */
174
175         if((first= melem__lb.first)) { /* can be false if first fill fails */
176                 BLI_remlink(&melem__lb, first);
177
178                 melem__cur= melem__lb.first;
179                 while(melem__cur) {
180                         MEM_freeN(melem__cur->data);
181                         melem__cur= melem__cur->next;
182                 }
183                 BLI_freelistN(&melem__lb);
184
185                 /*reset the block we're keeping*/
186                 BLI_addtail(&melem__lb, first);
187                 memset(first->data, 0, MEM_ELEM_BLOCKSIZE);
188         }
189
190         melem__cur= first;
191         melem__offs= 0;
192 }
193
194 void BLI_end_edgefill(void)
195 {
196         mem_element_reset();
197         
198         fillvertbase.first= fillvertbase.last= 0;
199         filledgebase.first= filledgebase.last= 0;
200         fillfacebase.first= fillfacebase.last= 0;
201         
202         BLI_unlock_thread(LOCK_SCANFILL);       
203 }
204
205 /* ****  FILL ROUTINES *************************** */
206
207 ScanFillVert *BLI_addfillvert(const float vec[3])
208 {
209         ScanFillVert *eve;
210         
211         eve= mem_element_new(sizeof(ScanFillVert));
212         BLI_addtail(&fillvertbase, eve);
213         
214         eve->co[0] = vec[0];
215         eve->co[1] = vec[1];
216         eve->co[2] = vec[2];
217
218         return eve;     
219 }
220
221 ScanFillEdge *BLI_addfilledge(ScanFillVert *v1, ScanFillVert *v2)
222 {
223         ScanFillEdge *newed;
224
225         newed= mem_element_new(sizeof(ScanFillEdge));
226         BLI_addtail(&filledgebase, newed);
227         
228         newed->v1= v1;
229         newed->v2= v2;
230
231         return newed;
232 }
233
234 static void addfillface(ScanFillVert *v1, ScanFillVert *v2, ScanFillVert *v3)
235 {
236         /* does not make edges */
237         ScanFillFace *evl;
238
239         evl= mem_element_new(sizeof(ScanFillFace));
240         BLI_addtail(&fillfacebase, evl);
241         
242         evl->v1= v1;
243         evl->v2= v2;
244         evl->v3= v3;
245 }
246
247 static int boundisect(PolyFill *pf2, PolyFill *pf1)
248 {
249         /* has pf2 been touched (intersected) by pf1 ? with bounding box */
250         /* test first if polys exist */
251
252         if(pf1->edges==0 || pf2->edges==0) return 0;
253
254         if(pf2->max[cox] < pf1->min[cox] ) return 0;
255         if(pf2->max[coy] < pf1->min[coy] ) return 0;
256
257         if(pf2->min[cox] > pf1->max[cox] ) return 0;
258         if(pf2->min[coy] > pf1->max[coy] ) return 0;
259
260         /* join */
261         if(pf2->max[cox]<pf1->max[cox]) pf2->max[cox]= pf1->max[cox];
262         if(pf2->max[coy]<pf1->max[coy]) pf2->max[coy]= pf1->max[coy];
263
264         if(pf2->min[cox]>pf1->min[cox]) pf2->min[cox]= pf1->min[cox];
265         if(pf2->min[coy]>pf1->min[coy]) pf2->min[coy]= pf1->min[coy];
266
267         return 1;
268 }
269
270
271 static void mergepolysSimp(PolyFill *pf1, PolyFill *pf2)        /* add pf2 to pf1 */
272 {
273         ScanFillVert *eve;
274         ScanFillEdge *eed;
275
276         /* replace old poly numbers */
277         eve= fillvertbase.first;
278         while(eve) {
279                 if(eve->poly_nr == pf2->nr) eve->poly_nr = pf1->nr;
280                 eve= eve->next;
281         }
282         eed= filledgebase.first;
283         while(eed) {
284                 if (eed->poly_nr == pf2->nr) eed->poly_nr = pf1->nr;
285                 eed= eed->next;
286         }
287
288         pf1->verts+= pf2->verts;
289         pf1->edges+= pf2->edges;
290         pf2->verts= pf2->edges= 0;
291         pf1->f= (pf1->f | pf2->f);
292 }
293
294 static short testedgeside(float *v1, float *v2, float *v3)
295 /* is v3 to the right of v1-v2 ? With exception: v3==v1 || v3==v2 */
296 {
297         float inp;
298
299         inp= (v2[cox]-v1[cox])*(v1[coy]-v3[coy])
300                 +(v1[coy]-v2[coy])*(v1[cox]-v3[cox]);
301
302         if(inp < 0.0f) return 0;
303         else if(inp==0) {
304                 if(v1[cox]==v3[cox] && v1[coy]==v3[coy]) return 0;
305                 if(v2[cox]==v3[cox] && v2[coy]==v3[coy]) return 0;
306         }
307         return 1;
308 }
309
310 static short addedgetoscanvert(ScanFillVertLink *sc, ScanFillEdge *eed)
311 {
312         /* find first edge to the right of eed, and insert eed before that */
313         ScanFillEdge *ed;
314         float fac,fac1,x,y;
315
316         if(sc->first==0) {
317                 sc->first= sc->last= eed;
318                 eed->prev= eed->next=0;
319                 return 1;
320         }
321
322         x= eed->v1->co[cox];
323         y= eed->v1->co[coy];
324
325         fac1= eed->v2->co[coy]-y;
326         if(fac1==0.0f) {
327                 fac1= 1.0e10f*(eed->v2->co[cox]-x);
328
329         }
330         else fac1= (x-eed->v2->co[cox])/fac1;
331
332         ed= sc->first;
333         while(ed) {
334
335                 if(ed->v2==eed->v2) return 0;
336
337                 fac= ed->v2->co[coy]-y;
338                 if(fac==0.0f) {
339                         fac= 1.0e10f*(ed->v2->co[cox]-x);
340
341                 }
342                 else fac= (x-ed->v2->co[cox])/fac;
343                 if(fac>fac1) break;
344
345                 ed= ed->next;
346         }
347         if(ed) BLI_insertlinkbefore((ListBase *)&(sc->first), ed, eed);
348         else BLI_addtail((ListBase *)&(sc->first),eed);
349
350         return 1;
351 }
352
353
354 static ScanFillVertLink *addedgetoscanlist(ScanFillEdge *eed, int len)
355 {
356         /* inserts edge at correct location in ScanFillVertLink list */
357         /* returns sc when edge already exists */
358         ScanFillVertLink *sc,scsearch;
359         ScanFillVert *eve;
360
361         /* which vert is left-top? */
362         if(eed->v1->co[coy] == eed->v2->co[coy]) {
363                 if(eed->v1->co[cox] > eed->v2->co[cox]) {
364                         eve= eed->v1;
365                         eed->v1= eed->v2;
366                         eed->v2= eve;
367                 }
368         }
369         else if(eed->v1->co[coy] < eed->v2->co[coy]) {
370                 eve= eed->v1;
371                 eed->v1= eed->v2;
372                 eed->v2= eve;
373         }
374         /* find location in list */
375         scsearch.v1= eed->v1;
376         sc= (ScanFillVertLink *)bsearch(&scsearch,scdata,len,
377                 sizeof(ScanFillVertLink), vergscdata);
378
379         if(sc==0) printf("Error in search edge: %p\n", (void *)eed);
380         else if(addedgetoscanvert(sc,eed)==0) return sc;
381
382         return 0;
383 }
384
385 static short boundinsideEV(ScanFillEdge *eed, ScanFillVert *eve)
386 /* is eve inside boundbox eed */
387 {
388         float minx,maxx,miny,maxy;
389
390         if(eed->v1->co[cox]<eed->v2->co[cox]) {
391                 minx= eed->v1->co[cox];
392                 maxx= eed->v2->co[cox];
393         } else {
394                 minx= eed->v2->co[cox];
395                 maxx= eed->v1->co[cox];
396         }
397         if(eve->co[cox]>=minx && eve->co[cox]<=maxx) {
398                 if(eed->v1->co[coy]<eed->v2->co[coy]) {
399                         miny= eed->v1->co[coy];
400                         maxy= eed->v2->co[coy];
401                 } else {
402                         miny= eed->v2->co[coy];
403                         maxy= eed->v1->co[coy];
404                 }
405                 if(eve->co[coy]>=miny && eve->co[coy]<=maxy) return 1;
406         }
407         return 0;
408 }
409
410
411 static void testvertexnearedge(void)
412 {
413         /* only vertices with ->h==1 are being tested for
414                 being close to an edge, if true insert */
415
416         ScanFillVert *eve;
417         ScanFillEdge *eed,*ed1;
418         float dist,vec1[2],vec2[2],vec3[2];
419
420         eve= fillvertbase.first;
421         while(eve) {
422                 if(eve->h==1) {
423                         vec3[0]= eve->co[cox];
424                         vec3[1]= eve->co[coy];
425                         /* find the edge which has vertex eve */
426                         ed1= filledgebase.first;
427                         while(ed1) {
428                                 if(ed1->v1==eve || ed1->v2==eve) break;
429                                 ed1= ed1->next;
430                         }
431                         if(ed1->v1==eve) {
432                                 ed1->v1= ed1->v2;
433                                 ed1->v2= eve;
434                         }
435                         eed= filledgebase.first;
436                         while(eed) {
437                                 if (eve != eed->v1 && eve != eed->v2 && eve->poly_nr == eed->poly_nr) {
438                                         if(compare_v3v3(eve->co,eed->v1->co, COMPLIMIT)) {
439                                                 ed1->v2= eed->v1;
440                                                 eed->v1->h++;
441                                                 eve->h= 0;
442                                                 break;
443                                         }
444                                         else if(compare_v3v3(eve->co,eed->v2->co, COMPLIMIT)) {
445                                                 ed1->v2= eed->v2;
446                                                 eed->v2->h++;
447                                                 eve->h= 0;
448                                                 break;
449                                         }
450                                         else {
451                                                 vec1[0]= eed->v1->co[cox];
452                                                 vec1[1]= eed->v1->co[coy];
453                                                 vec2[0]= eed->v2->co[cox];
454                                                 vec2[1]= eed->v2->co[coy];
455                                                 if(boundinsideEV(eed,eve)) {
456                                                         dist= dist_to_line_v2(vec1,vec2,vec3);
457                                                         if(dist<(float)COMPLIMIT) {
458                                                                 /* new edge */
459                                                                 ed1= BLI_addfilledge(eed->v1, eve);
460                                                                 
461                                                                 /* printf("fill: vertex near edge %x\n",eve); */
462                                                                 ed1->f= 0;
463                                                                 ed1->poly_nr = eed->poly_nr;
464                                                                 eed->v1= eve;
465                                                                 eve->h= 3;
466                                                                 break;
467                                                         }
468                                                 }
469                                         }
470                                 }
471                                 eed= eed->next;
472                         }
473                 }
474                 eve= eve->next;
475         }
476 }
477
478 static void splitlist(ListBase *tempve, ListBase *temped, short nr)
479 {
480         /* everything is in templist, write only poly nr to fillist */
481         ScanFillVert *eve,*nextve;
482         ScanFillEdge *eed,*nexted;
483
484         BLI_movelisttolist(tempve,&fillvertbase);
485         BLI_movelisttolist(temped,&filledgebase);
486
487         eve= tempve->first;
488         while(eve) {
489                 nextve= eve->next;
490                 if (eve->poly_nr == nr) {
491                         BLI_remlink(tempve,eve);
492                         BLI_addtail(&fillvertbase,eve);
493                 }
494                 eve= nextve;
495         }
496         eed= temped->first;
497         while(eed) {
498                 nexted= eed->next;
499                 if(eed->poly_nr==nr) {
500                         BLI_remlink(temped,eed);
501                         BLI_addtail(&filledgebase,eed);
502                 }
503                 eed= nexted;
504         }
505 }
506
507
508 static int scanfill(PolyFill *pf)
509 {
510         ScanFillVertLink *sc = NULL, *sc1;
511         ScanFillVert *eve,*v1,*v2,*v3;
512         ScanFillEdge *eed,*nexted,*ed1,*ed2,*ed3;
513         float miny = 0.0;
514         int a,b,verts, maxface, totface;
515         short nr, test, twoconnected=0;
516
517         nr= pf->nr;
518
519         /* PRINTS
520         verts= pf->verts;
521         eve= fillvertbase.first;
522         while(eve) {
523                 printf("vert: %x co: %f %f\n",eve,eve->co[cox],eve->co[coy]);
524                 eve= eve->next;
525         }       
526         eed= filledgebase.first;
527         while(eed) {
528                 printf("edge: %x  verts: %x %x\n",eed,eed->v1,eed->v2);
529                 eed= eed->next;
530         } */
531
532         /* STEP 0: remove zero sized edges */
533         eed= filledgebase.first;
534         while(eed) {
535                 if(eed->v1->co[cox]==eed->v2->co[cox]) {
536                         if(eed->v1->co[coy]==eed->v2->co[coy]) {
537                                 if(eed->v1->f==255 && eed->v2->f!=255) {
538                                         eed->v2->f= 255;
539                                         eed->v2->tmp.v= eed->v1->tmp.v;
540                                 }
541                                 else if(eed->v2->f==255 && eed->v1->f!=255) {
542                                         eed->v1->f= 255;
543                                         eed->v1->tmp.v= eed->v2->tmp.v;
544                                 }
545                                 else if(eed->v2->f==255 && eed->v1->f==255) {
546                                         eed->v1->tmp.v= eed->v2->tmp.v;
547                                 }
548                                 else {
549                                         eed->v2->f= 255;
550                                         eed->v2->tmp.v = eed->v1;
551                                 }
552                         }
553                 }
554                 eed= eed->next;
555         }
556
557         /* STEP 1: make using FillVert and FillEdge lists a sorted
558                 ScanFillVertLink list
559         */
560         sc= scdata= (ScanFillVertLink *)MEM_callocN(pf->verts*sizeof(ScanFillVertLink),"Scanfill1");
561         eve= fillvertbase.first;
562         verts= 0;
563         while(eve) {
564                 if (eve->poly_nr == nr) {
565                         if (eve->f != 255) {
566                                 verts++;
567                                 eve->f= 0;      /* flag for connectedges later on */
568                                 sc->v1= eve;
569                                 sc++;
570                         }
571                 }
572                 eve= eve->next;
573         }
574
575         qsort(scdata, verts, sizeof(ScanFillVertLink), vergscdata);
576
577         eed= filledgebase.first;
578         while(eed) {
579                 nexted= eed->next;
580                 BLI_remlink(&filledgebase,eed);
581                 /* This code is for handling zero-length edges that get
582                    collapsed in step 0. It was removed for some time to
583                    fix trunk bug #4544, so if that comes back, this code
584                    may need some work, or there will have to be a better
585                    fix to #4544. */
586                 if(eed->v1->f==255) {
587                         v1= eed->v1;
588                         while((eed->v1->f == 255) && (eed->v1->tmp.v != v1)) 
589                                 eed->v1 = eed->v1->tmp.v;
590                 }
591                 if(eed->v2->f==255) {
592                         v2= eed->v2;
593                         while((eed->v2->f == 255) && (eed->v2->tmp.v != v2))
594                                 eed->v2 = eed->v2->tmp.v;
595                 }
596                 if(eed->v1!=eed->v2) addedgetoscanlist(eed,verts);
597
598                 eed= nexted;
599         }
600         /*
601         sc= scdata;
602         for(a=0;a<verts;a++) {
603                 printf("\nscvert: %x\n",sc->v1);
604                 eed= sc->first;
605                 while(eed) {
606                         printf(" ed %x %x %x\n",eed,eed->v1,eed->v2);
607                         eed= eed->next;
608                 }
609                 sc++;
610         }*/
611
612
613         /* STEP 2: FILL LOOP */
614
615         if(pf->f==0) twoconnected= 1;
616
617         /* (temporal) security: never much more faces than vertices */
618         totface= 0;
619         maxface= 2*verts;               /* 2*verts: based at a filled circle within a triangle */
620
621         sc= scdata;
622         for(a=0;a<verts;a++) {
623                 /* printf("VERTEX %d %x\n",a,sc->v1); */
624                 ed1= sc->first;
625                 while(ed1) {    /* set connectflags  */
626                         nexted= ed1->next;
627                         if(ed1->v1->h==1 || ed1->v2->h==1) {
628                                 BLI_remlink((ListBase *)&(sc->first),ed1);
629                                 BLI_addtail(&filledgebase,ed1);
630                                 if(ed1->v1->h>1) ed1->v1->h--;
631                                 if(ed1->v2->h>1) ed1->v2->h--;
632                         }
633                         else ed1->v2->f= 1;
634
635                         ed1= nexted;
636                 }
637                 while(sc->first) {      /* for as long there are edges */
638                         ed1= sc->first;
639                         ed2= ed1->next;
640                         
641                         /* commented out... the ESC here delivers corrupted memory (and doesnt work during grab) */
642                         /* if(callLocalInterruptCallBack()) break; */
643                         if(totface>maxface) {
644                                 /* printf("Fill error: endless loop. Escaped at vert %d,  tot: %d.\n", a, verts); */
645                                 a= verts;
646                                 break;
647                         }
648                         if(ed2==0) {
649                                 sc->first=sc->last= 0;
650                                 /* printf("just 1 edge to vert\n"); */
651                                 BLI_addtail(&filledgebase,ed1);
652                                 ed1->v2->f= 0;
653                                 ed1->v1->h--; 
654                                 ed1->v2->h--;
655                         } else {
656                                 /* test rest of vertices */
657                                 v1= ed1->v2;
658                                 v2= ed1->v1;
659                                 v3= ed2->v2;
660                                 /* this happens with a serial of overlapping edges */
661                                 if(v1==v2 || v2==v3) break;
662                                 /* printf("test verts %x %x %x\n",v1,v2,v3); */
663                                 miny = ( (v1->co[coy])<(v3->co[coy]) ? (v1->co[coy]) : (v3->co[coy]) );
664                                 /*  miny= MIN2(v1->co[coy],v3->co[coy]); */
665                                 sc1= sc+1;
666                                 test= 0;
667
668                                 for(b=a+1;b<verts;b++) {
669                                         if(sc1->v1->f==0) {
670                                                 if(sc1->v1->co[coy] <= miny) break;
671
672                                                 if(testedgeside(v1->co,v2->co,sc1->v1->co))
673                                                         if(testedgeside(v2->co,v3->co,sc1->v1->co))
674                                                                 if(testedgeside(v3->co,v1->co,sc1->v1->co)) {
675                                                                         /* point in triangle */
676                                                                 
677                                                                         test= 1;
678                                                                         break;
679                                                                 }
680                                         }
681                                         sc1++;
682                                 }
683                                 if(test) {
684                                         /* make new edge, and start over */
685                                         /* printf("add new edge %x %x and start again\n",v2,sc1->v1); */
686
687                                         ed3= BLI_addfilledge(v2, sc1->v1);
688                                         BLI_remlink(&filledgebase, ed3);
689                                         BLI_insertlinkbefore((ListBase *)&(sc->first), ed2, ed3);
690                                         ed3->v2->f= 1;
691                                         ed3->f= 2;
692                                         ed3->v1->h++; 
693                                         ed3->v2->h++;
694                                 }
695                                 else {
696                                         /* new triangle */
697                                         /* printf("add face %x %x %x\n",v1,v2,v3); */
698                                         addfillface(v1, v2, v3);
699                                         totface++;
700                                         BLI_remlink((ListBase *)&(sc->first),ed1);
701                                         BLI_addtail(&filledgebase,ed1);
702                                         ed1->v2->f= 0;
703                                         ed1->v1->h--; 
704                                         ed1->v2->h--;
705                                         /* ed2 can be removed when it's a boundary edge */
706                                         if((ed2->f == 0 && twoconnected) || (ed2->f == FILLBOUNDARY)) {
707                                                 BLI_remlink((ListBase *)&(sc->first),ed2);
708                                                 BLI_addtail(&filledgebase,ed2);
709                                                 ed2->v2->f= 0;
710                                                 ed2->v1->h--; 
711                                                 ed2->v2->h--;
712                                         }
713
714                                         /* new edge */
715                                         ed3= BLI_addfilledge(v1, v3);
716                                         BLI_remlink(&filledgebase, ed3);
717                                         ed3->f= 2;
718                                         ed3->v1->h++; 
719                                         ed3->v2->h++;
720                                         
721                                         /* printf("add new edge %x %x\n",v1,v3); */
722                                         sc1= addedgetoscanlist(ed3, verts);
723                                         
724                                         if(sc1) {       /* ed3 already exists: remove if a boundary */
725                                                 /* printf("Edge exists\n"); */
726                                                 ed3->v1->h--; 
727                                                 ed3->v2->h--;
728
729                                                 ed3= sc1->first;
730                                                 while(ed3) {
731                                                         if( (ed3->v1==v1 && ed3->v2==v3) || (ed3->v1==v3 && ed3->v2==v1) ) {
732                                                                 if (twoconnected || ed3->f==FILLBOUNDARY) {
733                                                                         BLI_remlink((ListBase *)&(sc1->first),ed3);
734                                                                         BLI_addtail(&filledgebase,ed3);
735                                                                         ed3->v1->h--; 
736                                                                         ed3->v2->h--;
737                                                                 }
738                                                                 break;
739                                                         }
740                                                         ed3= ed3->next;
741                                                 }
742                                         }
743
744                                 }
745                         }
746                         /* test for loose edges */
747                         ed1= sc->first;
748                         while(ed1) {
749                                 nexted= ed1->next;
750                                 if(ed1->v1->h<2 || ed1->v2->h<2) {
751                                         BLI_remlink((ListBase *)&(sc->first),ed1);
752                                         BLI_addtail(&filledgebase,ed1);
753                                         if(ed1->v1->h>1) ed1->v1->h--;
754                                         if(ed1->v2->h>1) ed1->v2->h--;
755                                 }
756
757                                 ed1= nexted;
758                         }
759                 }
760                 sc++;
761         }
762
763         MEM_freeN(scdata);
764
765         return totface;
766 }
767
768
769 int BLI_begin_edgefill(void)
770 {
771         BLI_lock_thread(LOCK_SCANFILL);
772
773         return 1;
774 }
775
776 int BLI_edgefill(short mat_nr)
777 {
778         /*
779           - fill works with its own lists, so create that first (no faces!)
780           - for vertices, put in ->tmp.v the old pointer
781           - struct elements xs en ys are not used here: don't hide stuff in it
782           - edge flag ->f becomes 2 when it's a new edge
783           - mode: & 1 is check for crossings, then create edges (TO DO )
784           - returns number of triangle faces added.
785         */
786         ListBase tempve, temped;
787         ScanFillVert *eve;
788         ScanFillEdge *eed,*nexted;
789         PolyFill *pflist,*pf;
790         float limit, *minp, *maxp, *v1, *v2, norm[3], len;
791         short a,c,poly=0,ok=0,toggle=0;
792         int totfaces= 0; /* total faces added */
793
794         /* reset variables */
795         eve= fillvertbase.first;
796         a = 0;
797         while(eve) {
798                 eve->f= 0;
799                 eve->poly_nr= 0;
800                 eve->h= 0;
801                 eve= eve->next;
802                 a += 1;
803         }
804
805         if (a == 3 && (mat_nr & 2)) {
806                 eve = fillvertbase.first;
807
808                 addfillface(eve, eve->next, eve->next->next);
809                 return 1;
810         } else if (a == 4 && (mat_nr & 2)) {
811                 float vec1[3], vec2[3];
812
813                 eve = fillvertbase.first;
814                 /* no need to check 'eve->next->next->next' is valid, already counted */
815                 if (1) { //BMESH_TODO) {
816                         /*use shortest diagonal for quad*/
817                         sub_v3_v3v3(vec1, eve->co, eve->next->next->co);
818                         sub_v3_v3v3(vec2, eve->next->co, eve->next->next->next->co);
819                         
820                         if (INPR(vec1, vec1) < INPR(vec2, vec2)) {
821                                 addfillface(eve, eve->next, eve->next->next);
822                                 addfillface(eve->next->next, eve->next->next->next, eve);
823                         } else{
824                                 addfillface(eve->next, eve->next->next, eve->next->next->next);
825                                 addfillface(eve->next->next->next, eve, eve->next);
826                         }
827                 } else {
828                                 addfillface(eve, eve->next, eve->next->next);
829                                 addfillface(eve->next->next, eve->next->next->next, eve);
830                 }
831                 return 2;
832         }
833
834         /* first test vertices if they are in edges */
835         /* including resetting of flags */
836         eed= filledgebase.first;
837         while(eed) {
838                 eed->poly_nr= 0;
839                 eed->v1->f= 1;
840                 eed->v2->f= 1;
841
842                 eed= eed->next;
843         }
844
845         eve= fillvertbase.first;
846         while(eve) {
847                 if(eve->f & 1) {
848                         ok=1; 
849                         break;
850                 }
851                 eve= eve->next;
852         }
853
854         if(ok==0) return 0;
855
856         /* NEW NEW! define projection: with 'best' normal */
857         /* just use the first three different vertices */
858         
859         /* THIS PART STILL IS PRETTY WEAK! (ton) */
860         
861         eve= fillvertbase.last;
862         len= 0.0;
863         v1= eve->co;
864         v2= 0;
865         eve= fillvertbase.first;
866         limit = a < 5 ? FLT_EPSILON*200 : M_PI/24.0;
867         while(eve) {
868                 if(v2) {
869                         if( compare_v3v3(v2, eve->co, COMPLIMIT)==0) {
870                                 float inner = angle_v3v3v3(v1, v2, eve->co);
871                                 
872                                 if (fabsf(inner-M_PI) < limit || fabsf(inner) < limit) {
873                                         eve = eve->next;
874                                         continue;
875                                 }
876
877                                 len= normal_tri_v3( norm,v1, v2, eve->co);
878                                 if(len != 0.0f) break;
879                         }
880                 }
881                 else if(compare_v3v3(v1, eve->co, COMPLIMIT)==0) {
882                         v2= eve->co;
883                 }
884                 eve= eve->next;
885         }
886
887         if(len==0.0f) return 0; /* no fill possible */
888
889         axis_dominant_v3(&cox, &coy, norm);
890
891         /* STEP 1: COUNT POLYS */
892         eve= fillvertbase.first;
893         while(eve) {
894                 /* get first vertex with no poly number */
895                 if (eve->poly_nr==0) {
896                         poly++;
897                         /* now a sortof select connected */
898                         ok= 1;
899                         eve->poly_nr = poly;
900                         
901                         while(ok) {
902                                 
903                                 ok= 0;
904                                 toggle++;
905                                 if(toggle & 1) eed= filledgebase.first;
906                                 else eed= filledgebase.last;
907
908                                 while(eed) {
909                                         if (eed->v1->poly_nr == 0 && eed->v2->poly_nr == poly) {
910                                                 eed->v1->poly_nr = poly;
911                                                 eed->poly_nr= poly;
912                                                 ok= 1;
913                                         }
914                                         else if (eed->v2->poly_nr == 0 && eed->v1->poly_nr == poly) {
915                                                 eed->v2->poly_nr = poly;
916                                                 eed->poly_nr= poly;
917                                                 ok= 1;
918                                         }
919                                         else if (eed->poly_nr == 0) {
920                                                 if (eed->v1->poly_nr == poly && eed->v2->poly_nr == poly) {
921                                                         eed->poly_nr= poly;
922                                                         ok= 1;
923                                                 }
924                                         }
925                                         if(toggle & 1) eed= eed->next;
926                                         else eed= eed->prev;
927                                 }
928                         }
929                 }
930                 eve= eve->next;
931         }
932         /* printf("amount of poly's: %d\n",poly); */
933
934         /* STEP 2: remove loose edges and strings of edges */
935         eed= filledgebase.first;
936         while(eed) {
937                 if(eed->v1->h++ >250) break;
938                 if(eed->v2->h++ >250) break;
939                 eed= eed->next;
940         }
941         if(eed) {
942                 /* otherwise it's impossible to be sure you can clear vertices */
943                 callLocalErrorCallBack("No vertices with 250 edges allowed!");
944                 return 0;
945         }
946         
947         /* does it only for vertices with ->h==1 */
948         testvertexnearedge();
949
950         ok= 1;
951         while(ok) {
952                 ok= 0;
953                 toggle++;
954                 if(toggle & 1) eed= filledgebase.first;
955                 else eed= filledgebase.last;
956                 while(eed) {
957                         if(toggle & 1) nexted= eed->next;
958                         else nexted= eed->prev;
959                         if(eed->v1->h==1) {
960                                 eed->v2->h--;
961                                 BLI_remlink(&fillvertbase,eed->v1); 
962                                 BLI_remlink(&filledgebase,eed); 
963                                 ok= 1;
964                         }
965                         else if(eed->v2->h==1) {
966                                 eed->v1->h--;
967                                 BLI_remlink(&fillvertbase,eed->v2); 
968                                 BLI_remlink(&filledgebase,eed); 
969                                 ok= 1;
970                         }
971                         eed= nexted;
972                 }
973         }
974         if(filledgebase.first==0) {
975                 /* printf("All edges removed\n"); */
976                 return 0;
977         }
978
979
980         /* CURRENT STATUS:
981         - eve->f      :1= availalble in edges
982         - eve->xs     :polynumber
983         - eve->h      :amount of edges connected to vertex
984         - eve->tmp.v  :store! original vertex number
985
986         - eed->f      :1= boundary edge (optionally set by caller)
987         - eed->f1 :poly number
988         */
989
990
991         /* STEP 3: MAKE POLYFILL STRUCT */
992         pflist= (PolyFill *)MEM_callocN(poly*sizeof(PolyFill),"edgefill");
993         pf= pflist;
994         for(a=1;a<=poly;a++) {
995                 pf->nr= a;
996                 pf->min[0]=pf->min[1]=pf->min[2]= 1.0e20;
997                 pf->max[0]=pf->max[1]=pf->max[2]= -1.0e20;
998                 pf++;
999         }
1000         eed= filledgebase.first;
1001         while(eed) {
1002                 pflist[eed->poly_nr-1].edges++;
1003                 eed= eed->next;
1004         }
1005
1006         eve= fillvertbase.first;
1007         while(eve) {
1008                 pflist[eve->poly_nr-1].verts++;
1009                 minp= pflist[eve->poly_nr-1].min;
1010                 maxp= pflist[eve->poly_nr-1].max;
1011
1012                 minp[cox]= (minp[cox])<(eve->co[cox]) ? (minp[cox]) : (eve->co[cox]);
1013                 minp[coy]= (minp[coy])<(eve->co[coy]) ? (minp[coy]) : (eve->co[coy]);
1014                 maxp[cox]= (maxp[cox])>(eve->co[cox]) ? (maxp[cox]) : (eve->co[cox]);
1015                 maxp[coy]= (maxp[coy])>(eve->co[coy]) ? (maxp[coy]) : (eve->co[coy]);
1016                 if(eve->h > 2) pflist[eve->poly_nr-1].f = 1;
1017
1018                 eve= eve->next;
1019         }
1020
1021         /* STEP 4: FIND HOLES OR BOUNDS, JOIN THEM
1022          *  ( bounds just to divide it in pieces for optimization, 
1023          *    the edgefill itself has good auto-hole detection)
1024          * WATCH IT: ONLY WORKS WITH SORTED POLYS!!! */
1025         
1026         if(poly>1) {
1027                 short *polycache, *pc;
1028
1029                 /* so, sort first */
1030                 qsort(pflist, poly, sizeof(PolyFill), vergpoly);
1031                 
1032                 /*pf= pflist;
1033                 for(a=1;a<=poly;a++) {
1034                         printf("poly:%d edges:%d verts:%d flag: %d\n",a,pf->edges,pf->verts,pf->f);
1035                         PRINT2(f, f, pf->min[0], pf->min[1]);
1036                         pf++;
1037                 }*/
1038         
1039                 polycache= pc= MEM_callocN(sizeof(short)*poly, "polycache");
1040                 pf= pflist;
1041                 for(a=0; a<poly; a++, pf++) {
1042                         for(c=a+1;c<poly;c++) {
1043                                 
1044                                 /* if 'a' inside 'c': join (bbox too)
1045                                  * Careful: 'a' can also be inside another poly.
1046                                  */
1047                                 if(boundisect(pf, pflist+c)) {
1048                                         *pc= c;
1049                                         pc++;
1050                                 }
1051                                 /* only for optimize! */
1052                                 /* else if(pf->max[cox] < (pflist+c)->min[cox]) break; */
1053                                 
1054                         }
1055                         while(pc!=polycache) {
1056                                 pc--;
1057                                 mergepolysSimp(pf, pflist+ *pc);
1058                         }
1059                 }
1060                 MEM_freeN(polycache);
1061         }
1062         
1063         /* printf("after merge\n");
1064         pf= pflist;
1065         for(a=1;a<=poly;a++) {
1066                 printf("poly:%d edges:%d verts:%d flag: %d\n",a,pf->edges,pf->verts,pf->f);
1067                 pf++;
1068         } */
1069
1070         /* STEP 5: MAKE TRIANGLES */
1071
1072         tempve.first= fillvertbase.first;
1073         tempve.last= fillvertbase.last;
1074         temped.first= filledgebase.first;
1075         temped.last= filledgebase.last;
1076         fillvertbase.first=fillvertbase.last= 0;
1077         filledgebase.first=filledgebase.last= 0;
1078
1079         pf= pflist;
1080         for(a=0;a<poly;a++) {
1081                 if(pf->edges>1) {
1082                         splitlist(&tempve,&temped,pf->nr);
1083                         totfaces += scanfill(pf);
1084                 }
1085                 pf++;
1086         }
1087         BLI_movelisttolist(&fillvertbase,&tempve);
1088         BLI_movelisttolist(&filledgebase,&temped);
1089
1090         /* FREE */
1091
1092         MEM_freeN(pflist);
1093
1094         return totfaces;
1095 }