]> git.imager.perl.org - imager.git/blob - polygon.c
27d2980e71e248d14b6977b3f63908bb7e87e958
[imager.git] / polygon.c
1 #include "image.h"
2 #include "draw.h"
3 #include "log.h"
4
5
6 #define IMTRUNC(x) ((int)((x)*16))
7
8 #define coarse(x) ((x)/16)
9 #define fine(x)   ((x)%16)
10
11 #define POLY_DEB(x)
12
13
14
15 typedef int pcord;
16
17 typedef struct {
18   int n;
19   pcord x,y;
20 } p_point;
21
22 typedef struct {
23   int n;
24   pcord x1,y1;
25   pcord x2,y2;
26   pcord miny,maxy;
27   pcord minx,maxx;
28   int updown; /* -1 means down, 0 vertical, 1 up */
29 } p_line;
30
31 typedef struct {
32   int n;
33   double x;
34 } p_slice;
35
36 typedef struct {
37   int start;
38   int stop;
39 } ss_pair;
40
41 typedef struct {
42   int *line;            /* temporary buffer for scanline */
43   int linelen;          /* length of scanline */
44   ss_pair *ss_list;     /* list of start stop linepairs */
45   int ssnext;           /* index of the next pair to use */
46   int sslen;            /* maximum number of start stop pairs */
47 } ss_scanline;
48
49
50
51
52
53
54
55
56 static
57 int
58 p_compy(const p_point *p1, const p_point *p2) {
59   if (p1->y > p2->y) return 1;
60   if (p1->y < p2->y) return -1;
61   return 0;
62 }
63
64 static
65 int
66 p_compx(const p_slice *p1, const p_slice *p2) {
67   if (p1->x > p2->x) return 1;
68   if (p1->x < p2->x) return -1;
69   return 0;
70 }
71
72 /* Change this to int? and round right goddamn it! */
73
74 static
75 double
76 p_eval_aty(p_line *l, pcord y) {
77   int t;
78   t=l->y2-l->y1;
79   if (t) return ( (y-l->y1)*l->x2 + (l->y2-y)*l->x1 )/t;
80   return (l->x1+l->x2)/2.0;
81 }
82
83 static
84 double
85 p_eval_atx(p_line *l, pcord x) {
86   int t;
87   t = l->x2-l->x1;
88   if (t) return ( (x-l->x1)*l->y2 + (l->x2-x)*l->y1 )/t;
89   return (l->y1+l->y2)/2.0;
90 }
91
92 static
93 p_line *
94 line_set_new(double *x, double *y, int l) {
95   int i;
96   p_line *lset = mymalloc(sizeof(p_line) * l);
97
98   for(i=0; i<l; i++) {
99     lset[i].n=i;
100     lset[i].x1 = IMTRUNC(x[i]);
101     lset[i].y1 = IMTRUNC(y[i]);
102     lset[i].x2 = IMTRUNC(x[(i+1)%l]);
103     lset[i].y2 = IMTRUNC(y[(i+1)%l]);
104     lset[i].miny=min(lset[i].y1,lset[i].y2);
105     lset[i].maxy=max(lset[i].y1,lset[i].y2);
106     lset[i].minx=min(lset[i].x1,lset[i].x2);
107     lset[i].maxx=max(lset[i].x1,lset[i].x2);
108   }
109   return lset;
110 }
111
112 static
113 p_point *
114 point_set_new(double *x, double *y, int l) {
115   int i;
116   p_point *pset = mymalloc(sizeof(p_point) * l);
117   
118   for(i=0; i<l; i++) {
119     pset[i].n=i;
120     pset[i].x=IMTRUNC(x[i]);
121     pset[i].y=IMTRUNC(y[i]);
122   }
123   return pset;
124 }
125
126 static
127 void
128 p_line_dump(p_line *l) {
129   printf("%d (%d,%d)->(%d,%d) [%d-%d,%d-%d]\n", l->n, l->x1, l->y1, l->x2, l->y2, 
130          l->minx, l->maxx, l->miny, l->maxy);
131 }
132
133
134 static
135 void
136 ss_scanline_reset(ss_scanline *ss) {
137   ss->ssnext = 0;
138   memset(ss->line, 0, sizeof(int) * ss->linelen);
139 }
140
141 static
142 void
143 ss_scanline_init(ss_scanline *ss, int linelen, int linepairs) {
144   ss->line    = mymalloc( sizeof(int) * linelen );
145   ss->linelen = linelen;
146   ss->ss_list = mymalloc( sizeof(ss_pair) * linepairs );
147   ss->sslen   = linepairs;
148   ss_scanline_reset(ss);
149 }
150
151
152 /* returns the number of matches */
153
154 static
155 int
156 lines_in_interval(p_line *lset, int l, p_slice *tllist, pcord cc) {
157   int k;
158   int count = 0;
159   for(k=0; k<l; k++) {
160     if (cc >= lset[k].miny && cc <=  lset[k].maxy) {
161       if (lset[k].miny == lset[k].maxy) {
162         POLY_DEB( printf(" HORIZONTAL - skipped\n") );
163       }
164       else {
165         tllist[count].x=p_eval_aty(&lset[k],cc);
166         tllist[count].n=k;
167         count++;
168       }
169     }
170   }
171   return count;
172 }
173
174 /* marks the up variable for all lines in a slice */
175
176 static
177 void
178 mark_updown_slices(p_line *lset, p_slice *tllist, int count) {
179   p_line *l, *r;
180   int k;
181   for(k=0; k<count; k+=2) {
182     l = lset + tllist[k].n;
183     r = lset + tllist[k+1].n;
184
185     if (l->y1 == l->y2) {
186       mm_log((1, "mark_updown_slices: horizontal line being marked: internal error!\n"));
187       exit(3);
188     }
189
190     if (r->y1 == r->y2) {
191       mm_log((1, "mark_updown_slices: horizontal line being marked: internal error!\n"));
192       exit(3);
193     }
194
195     l->updown = (l->x1 == l->x2) ?
196       0 :
197       (l->x1 > l->x2)
198       ? 
199       (l->y1 > l->y2) ? -1 : 1
200       : 
201       (l->y1 > l->y2) ? 1 : -1;
202
203     r->updown = (r->x1 == r->x2) ?
204       0 :
205       (r->x1 > r->x2)
206       ? 
207       (r->y1 > r->y2) ? -1 : 1
208       : 
209       (r->y1 > r->y2) ? 1 : -1;
210     
211     POLY_DEB( printf("marking left line %d as %s(%d)\n", l->n,
212                      l->updown ?  l->updown == 1 ? "up" : "down" : "vert", l->updown, l->updown);
213               printf("marking right line %d as %s(%d)\n", r->n,
214                      r->updown ?  r->updown == 1 ? "up" : "down" : "vert", r->updown, r->updown);
215               );
216   }
217 }
218
219
220
221 static
222 unsigned char
223 saturate(int in) {
224   if (in>255) { return 255; }
225   else if (in>0) return in;
226   return 0;
227 }
228
229
230 /* This function must be modified later to do proper blending */
231
232 void
233 scanline_flush(i_img *im, ss_scanline *ss, int y, i_color *val) {
234   int x, ch, tv;
235   i_color t;
236   for(x=0; x<im->xsize; x++) {
237     tv = saturate(ss->line[x]);
238     i_gpix(im, x, y, &t);
239     for(ch=0; ch<im->channels; ch++) 
240       t.channel[ch] = tv/255.0 * val->channel[ch] + (1.0-tv/255.0) * t.channel[ch];
241     i_ppix(im, x, y, &t);
242   }
243 }
244
245
246
247 static
248 int
249 trap_square(pcord xlen, pcord ylen, double xl, double yl) {
250   POLY_DEB( printf("trap_square: %d %d %.2f %.2f\n", xlen, ylen, xl, yl) );
251   return xlen*ylen-(xl*yl)/2.0;
252 }
253
254
255 /* 
256    pixel_coverage calculates the 'left side' pixel coverage of a pixel that is
257    within the min/max ranges.  The shape always corresponds to a square with some
258    sort of a triangle cut from it (which can also yield a triangle).
259 */
260
261
262 static
263 int 
264 pixel_coverage(p_line *line, pcord minx, pcord maxx, pcord  miny, pcord maxy) {
265   double lycross, rycross;
266   int l, r;
267
268   double xs, ys;
269   
270   if (!line->updown) {
271     l = r = 0;
272   } else {
273     lycross = p_eval_atx(line, minx);
274     rycross = p_eval_atx(line, maxx);
275     l = lycross <= maxy && lycross >= miny; /* true if it enters through left side */
276     r = rycross <= maxy && rycross >= miny; /* true if it enters through left side */
277   }
278   POLY_DEB(
279            printf("%4s(%+d): ", line->updown ?  line->updown == 1 ? "up" : "down" : "vert", line->updown);
280            printf("(%2d,%2d) [%3d-%3d, %3d-%3d] lycross=%.2f rycross=%.2f", coarse(minx), coarse(miny), minx, maxx, miny, maxy, lycross, rycross);
281            printf("    l=%d r=%d\n", l, r)
282            );
283   
284   if (l && r) 
285     return line->updown == 1 ? 
286       (double)(maxx-minx) * (2.0*maxy-lycross-rycross)/2.0  /* up case */
287       :
288       (double)(maxx-minx) * (lycross+rycross-2*miny)/2.0;  /* down case */
289   
290   if (!l && !r) return (maxy-miny)*(maxx*2-p_eval_aty(line, miny)-p_eval_aty(line, maxy))/2.0;
291
292   if (l && !r)
293     return line->updown == 1 ?
294       trap_square(maxx-minx, maxy-miny, p_eval_aty(line, miny)-minx, p_eval_atx(line, minx)-miny) : 
295       trap_square(maxx-minx, maxy-miny, p_eval_aty(line, maxy)-minx, maxy-p_eval_atx(line, minx));
296   
297
298   if (!l && r) {
299     int r = line->updown == 1 ?
300       (maxx-p_eval_aty(line, maxy))*(maxy-p_eval_atx(line, maxx))/2.0 : 
301       (maxx-p_eval_aty(line, miny))*(p_eval_atx(line, maxx)-miny)/2.0;
302     return r;
303   }
304 }
305
306
307
308
309
310 /* 
311    handle the scanline slice in three steps 
312    
313    1.  Where only the left edge is inside a pixel
314    2a. Where both left and right edge are inside a pixel
315    2b. Where neither left or right edge are inside a pixel
316    3.  Where only the right edge is inside a pixel
317 */
318
319 static
320 void
321 render_slice_scanline(ss_scanline *ss, int y, p_line *l, p_line *r) {
322   
323   pcord miny, maxy;     /* y bounds in fine coordinates */
324   pcord lminx, lmaxx;   /* left line min/max within y bounds in fine coords */
325   pcord rminx, rmaxx;   /* right line min/max within y bounds in fine coords */
326   int cpix;             /* x-coordinate of current pixel */
327   int thin;             /* boolean for thin/thick segment */
328   int startpix;         /* temporary variable for "start of this interval" */
329   int stoppix;          /* temporary variable for "end of this interval" */
330   int step2end;         /* temporary variable to mark where step2 ends */
331
332   /* Find the y bounds of scanline_slice */
333
334   maxy = min( l->maxy, r->maxy );
335   miny = max( l->miny, r->miny );
336
337   maxy = min( maxy, (y+1)*16 );
338   miny = max( miny,  y*16 );
339
340   lminx = min( p_eval_aty(l, maxy), p_eval_aty(l, miny) );
341   lmaxx = max( p_eval_aty(l, maxy), p_eval_aty(l, miny) );
342
343   rminx = min( p_eval_aty(r, maxy), p_eval_aty(r, miny) );
344   rmaxx = max( p_eval_aty(r, maxy), p_eval_aty(r, miny) );
345
346   thin = coarse(lmaxx) >= coarse(rminx);
347
348   startpix = max( coarse(lminx), 0 );
349   stoppix  = min( coarse(rmaxx-1), ss->linelen-1 );
350   
351   for(cpix=startpix; cpix<=stoppix; cpix++) {
352     int lt = coarse(lmaxx-1) >= cpix;
353     int rt = coarse(rminx) <= cpix;
354     
355     int A, B, C;
356     
357     POLY_DEB( printf("(%d,%d) lt=%d rt=%d\n", cpix, y, lt, rt) );
358
359     A = lt ? pixel_coverage(l, cpix*16, cpix*16+16, miny, maxy) : 0;
360     B = lt ? 0 : 16*(maxy-miny);
361     C = rt ? pixel_coverage(r, cpix*16, cpix*16+16, miny, maxy) : 0;
362
363     POLY_DEB( printf("A=%d B=%d C=%d\n", A, B, C) );
364
365     ss->line[cpix] += A+B-C;
366
367   }
368   
369 }
370
371
372
373 static
374 void
375 render_slice_scanline_old(ss_scanline *ss, int y, p_line *l, p_line *r) {
376   
377   pcord miny, maxy;     /* y bounds in fine coordinates */
378   pcord lminx, lmaxx;   /* left line min/max within y bounds in fine coords */
379   pcord rminx, rmaxx;   /* right line min/max within y bounds in fine coords */
380   int cpix;             /* x-coordinate of current pixel */
381   int thin;             /* boolean for thin/thick segment */
382   int startpix;         /* temporary variable for "start of this interval" */
383   int stoppix;          /* temporary variable for "end of this interval" */
384   int step2end;         /* temporary variable to mark where step2 ends */
385
386   /* Find the y bounds of scanline_slice */
387
388   maxy = min( l->maxy, r->maxy );
389   miny = max( l->miny, r->miny );
390
391   maxy = min( maxy, (y+1)*16 );
392   miny = max( miny,  y*16 );
393
394   lminx = min( p_eval_aty(l, maxy), p_eval_aty(l, miny) );
395   lmaxx = max( p_eval_aty(l, maxy), p_eval_aty(l, miny) );
396
397   rminx = min( p_eval_aty(r, maxy), p_eval_aty(r, miny) );
398   rmaxx = max( p_eval_aty(r, maxy), p_eval_aty(r, miny) );
399
400   thin = coarse(lmaxx) >= coarse(rminx);
401
402
403   /* First step */
404   startpix = coarse(lminx);                             /* includes tricky starting pixel */
405   stoppix  = min(coarse(lmaxx), coarse(rminx) );        /* last pixel is tricky */
406   
407   /* handle start pixel */
408
409   cpix = startpix;
410   if (cpix < stoppix) {
411     ss->line[cpix] += pixel_coverage(l, cpix*16, cpix*16+16, miny, maxy);
412     printf("%2d: step1 - start pixel\n", cpix);
413   }
414   
415   for(cpix=startpix+1; cpix<stoppix; cpix++) {
416     printf("%2d: step1 pixel\n", cpix);
417     ss->line[cpix] += l->updown == 1 ? 
418       8.0 * (2*maxy-p_eval_atx(l, 16*cpix)-p_eval_atx(l, 16*cpix+16))   /* up case */
419       :
420       8.0 * (p_eval_atx(l, 16*cpix)+p_eval_atx(l, 16*cpix+16)-2*miny);  /* down case */
421   }
422   
423   
424   /* handle stop pixel */
425
426   if (thin) { /* step 2a */
427     startpix = coarse(rminx);
428     stoppix = coarse(lmaxx+15); /* one more than needed */
429     
430     for(cpix=startpix; cpix<stoppix; cpix++) {
431       printf("%2d: step2a pixel\n", cpix);
432       ss->line[cpix] += 
433         pixel_coverage(l, cpix*16, cpix*16+16, miny, maxy)
434         +(cpix*16+16-min(cpix*16+16, l->maxx))*(maxy-miny)
435         -pixel_coverage(r, cpix*16, cpix*16+16, miny, maxy);
436     }
437   } else { /* step 2b */
438     stoppix = coarse(rminx);
439     for(/* cpix already correct */; cpix<stoppix; cpix++) {
440       printf("%2d: step2b pixel\n", cpix);
441       ss->line[cpix] += 16.0*(maxy-miny);
442     }
443   }
444   
445   /* step 3 */
446
447   cpix = max(coarse(rminx), coarse(lmaxx+15));
448   stoppix = coarse(rmaxx-15);
449   
450   printf("step3 from %d to %d\n", cpix, stoppix);
451
452   for(; cpix<stoppix; cpix++) {
453     printf("%2d: step3 pixel\n", cpix);
454     ss->line[cpix] += 0+ 
455       (l->updown == 1 ?
456        8.0 * (2*maxy-p_eval_atx(r, 16*cpix)-p_eval_atx(r, 16*cpix+16))  /* up case */
457        :
458        8.0 * (p_eval_atx(r, 16*cpix)+p_eval_atx(r, 16*cpix+16)-2*miny));  /* down case */
459   }
460   
461   ss->line[cpix] += (16.0)*(maxy-miny) - pixel_coverage(r, cpix*16, cpix*16+16, miny, maxy);
462 }
463
464
465
466
467
468
469 /* Antialiasing polygon algorithm 
470    specs:
471    1. only nice polygons - no crossovers
472    2. 1/16 pixel resolution
473    3. full antialiasing ( complete spectrum of blends )
474    4. uses hardly any memory
475    5. no subsampling phase
476    
477
478    Algorithm outline:
479    1. Split into vertical intervals.
480    2. handle each interval 
481
482    For each interval we must: 
483    1. find which lines are in it
484    2. order the lines from in increasing x order.
485       since we are assuming no crossovers it is sufficent
486       to check a single point on each line.
487 */
488
489 /*
490   Definitions:
491   
492   1. Interval:  A vertical segment in which no lines cross nor end.
493   2. Scanline:  A physical line, contains 16 subpixels in the horizontal direction
494   3. Slice:     A start stop line pair.
495   
496  */
497
498
499 void
500 i_poly_aa(i_img *im, int l, double *x, double *y, i_color *val) {
501   int i ,k;                     /* Index variables */
502   int clc;                      /* Lines inside current interval */
503   pcord miny ,maxy;             /* Min and max values of the current slice in the subcord system */
504   pcord tempy;
505   int cscl;                     /* Current scanline */
506
507   ss_scanline templine;         /* scanline accumulator */
508   p_point *pset;                /* List of points in polygon */
509   p_line  *lset;                /* List of lines in polygon */
510   p_slice *tllist;              /* List of slices */
511
512   fflush(stdout);
513   setbuf(stdout, NULL);
514    
515
516   tllist   = mymalloc(sizeof(p_slice)*l);
517   
518   ss_scanline_init(&templine, im->xsize, l);
519
520   pset     = point_set_new(x, y, l);
521   lset     = line_set_new(x, y, l);
522
523
524   qsort(pset, l, sizeof(p_point), (int(*)(const void *,const void *))p_compy);
525   
526   POLY_DEB(
527            for(i=0;i<l;i++) {
528              printf("%d [ %d ] (%d , %d) -> (%d , %d) yspan ( %d , %d )\n",
529                     i, lset[i].n, lset[i].x1, lset[i].y1, lset[i].x2, lset[i].y2, lset[i].miny, lset[i].maxy);
530            }
531            printf("MAIN LOOP\n\n");
532            );
533   
534
535   /* loop on intervals */
536   for(i=0; i<l-1; i++) {
537     int startscan = max( coarse(pset[i].y), 0);
538     int stopscan = min( coarse(pset[i+1].y+15), im->ysize-1);
539     pcord cc = (pset[i].y + pset[i+1].y)/2;
540
541     POLY_DEB(
542              printf("current slice is %d: %d to %d ( cpoint %d ) scanlines %d to %d\n", 
543                     i, pset[i].y, pset[i+1].y, cc, startscan, stopscan)
544              );
545     
546     if (pset[i].y == pset[i+1].y) {
547       POLY_DEB( printf("current slice thickness = 0 => skipping\n") );
548       continue;
549     }
550     
551     clc = lines_in_interval(lset, l, tllist, cc);
552     qsort(tllist, clc, sizeof(p_slice), (int(*)(const void *,const void *))p_compx);
553
554     mark_updown_slices(lset, tllist, clc);
555
556     POLY_DEB( printf("Interval contains %d lines\n", clc) );
557
558     for(k=0; k<clc; k++) {
559       int lno = tllist[k].n;
560       p_line *ln = lset+lno;
561       POLY_DEB(
562                printf("%d:  line #%2d: (%2d, %2d)->(%2d, %2d) (%2d/%2d, %2d/%2d) -> (%2d/%2d, %2d/%2d) alignment=%s\n",
563                       k, lno, ln->x1, ln->y1, ln->x2, ln->y2, 
564                       coarse(ln->x1), fine(ln->x1), 
565                       coarse(ln->y1), fine(ln->y1), 
566                       coarse(ln->x2), fine(ln->x2), 
567                       coarse(ln->y2), fine(ln->y2),
568                       ln->updown == 0 ? "vert" : ln->updown == 1 ? "up" : "down")
569                );
570     }
571     for(cscl=startscan; cscl<stopscan; cscl++) {
572       tempy = min(cscl*16+16, pset[i+1].y);
573       POLY_DEB( printf("evaluating scan line %d \n", cscl) );
574       for(k=0; k<clc-1; k+=2) {
575         render_slice_scanline(&templine, cscl, lset+tllist[k].n, lset+tllist[k+1].n);
576       }
577       if (16*coarse(tempy) == tempy) {
578         POLY_DEB( printf("flushing scan line %d\n", cscl) );
579         scanline_flush(im, &templine, cscl, val);
580         ss_scanline_reset(&templine);
581       }
582       /*
583         else {
584         scanline_flush(im, &templine, cscl, val);
585         ss_scanline_reset(&templine);
586         return 0;
587         }
588       */
589     }
590   } /* Intervals */
591   if (16*coarse(tempy) != tempy) 
592     scanline_flush(im, &templine, cscl-1, val);
593 } /* Function */
594