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