]> git.imager.perl.org - imager.git/blob - polygon.c
9a2a64d26aba41739c905f4c9e54f65948f41113
[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 static
152 void
153 ss_scanline_exorcise(ss_scanline *ss) {
154   myfree(ss->line);
155   myfree(ss->ss_list);
156 }
157   
158                      
159
160
161 /* returns the number of matches */
162
163 static
164 int
165 lines_in_interval(p_line *lset, int l, p_slice *tllist, pcord cc) {
166   int k;
167   int count = 0;
168   for(k=0; k<l; k++) {
169     if (cc >= lset[k].miny && cc <=  lset[k].maxy) {
170       if (lset[k].miny == lset[k].maxy) {
171         POLY_DEB( printf(" HORIZONTAL - skipped\n") );
172       }
173       else {
174         tllist[count].x=p_eval_aty(&lset[k],cc);
175         tllist[count].n=k;
176         count++;
177       }
178     }
179   }
180   return count;
181 }
182
183 /* marks the up variable for all lines in a slice */
184
185 static
186 void
187 mark_updown_slices(p_line *lset, p_slice *tllist, int count) {
188   p_line *l, *r;
189   int k;
190   for(k=0; k<count; k+=2) {
191     l = lset + tllist[k].n;
192
193     if (l->y1 == l->y2) {
194       mm_log((1, "mark_updown_slices: horizontal line being marked: internal error!\n"));
195       exit(3);
196     }
197
198     l->updown = (l->x1 == l->x2) ?
199       0 :
200       (l->x1 > l->x2)
201       ? 
202       (l->y1 > l->y2) ? -1 : 1
203       : 
204       (l->y1 > l->y2) ? 1 : -1;
205
206     POLY_DEB( printf("marking left line %d as %s(%d)\n", l->n,
207                      l->updown ?  l->updown == 1 ? "up" : "down" : "vert", l->updown, l->updown)
208               );
209
210     if (k+1 >= count) {
211       mm_log((1, "Invalid polygon spec, odd number of line crossings.\n"));
212       return;
213     }
214
215     r = lset + tllist[k+1].n;
216     if (r->y1 == r->y2) {
217       mm_log((1, "mark_updown_slices: horizontal line being marked: internal error!\n"));
218       exit(3);
219     }
220
221     r->updown = (r->x1 == r->x2) ?
222       0 :
223       (r->x1 > r->x2)
224       ? 
225       (r->y1 > r->y2) ? -1 : 1
226       : 
227       (r->y1 > r->y2) ? 1 : -1;
228     
229     POLY_DEB( printf("marking right line %d as %s(%d)\n", r->n,
230                      r->updown ?  r->updown == 1 ? "up" : "down" : "vert", r->updown, r->updown)
231               );
232   }
233 }
234
235
236
237 static
238 unsigned char
239 saturate(int in) {
240   if (in>255) { return 255; }
241   else if (in>0) return in;
242   return 0;
243 }
244
245
246 /* This function must be modified later to do proper blending */
247
248 void
249 scanline_flush(i_img *im, ss_scanline *ss, int y, i_color *val) {
250   int x, ch, tv;
251   i_color t;
252   for(x=0; x<im->xsize; x++) {
253     tv = saturate(ss->line[x]);
254     i_gpix(im, x, y, &t);
255     for(ch=0; ch<im->channels; ch++) 
256       t.channel[ch] = tv/255.0 * val->channel[ch] + (1.0-tv/255.0) * t.channel[ch];
257     i_ppix(im, x, y, &t);
258   }
259 }
260
261
262
263 static
264 int
265 trap_square(pcord xlen, pcord ylen, double xl, double yl) {
266   POLY_DEB( printf("trap_square: %d %d %.2f %.2f\n", xlen, ylen, xl, yl) );
267   return xlen*ylen-(xl*yl)/2.0;
268 }
269
270
271 /* 
272    pixel_coverage calculates the 'left side' pixel coverage of a pixel that is
273    within the min/max ranges.  The shape always corresponds to a square with some
274    sort of a triangle cut from it (which can also yield a triangle).
275 */
276
277
278 static
279 int 
280 pixel_coverage(p_line *line, pcord minx, pcord maxx, pcord  miny, pcord maxy) {
281   double lycross, rycross;
282   int l, r;
283
284   double xs, ys;
285   
286   if (!line->updown) {
287     l = r = 0;
288   } else {
289     lycross = p_eval_atx(line, minx);
290     rycross = p_eval_atx(line, maxx);
291     l = lycross <= maxy && lycross >= miny; /* true if it enters through left side */
292     r = rycross <= maxy && rycross >= miny; /* true if it enters through left side */
293   }
294   POLY_DEB(
295            printf("%4s(%+d): ", line->updown ?  line->updown == 1 ? "up" : "down" : "vert", line->updown);
296            printf("(%2d,%2d) [%3d-%3d, %3d-%3d] lycross=%.2f rycross=%.2f", coarse(minx), coarse(miny), minx, maxx, miny, maxy, lycross, rycross);
297            printf("    l=%d r=%d\n", l, r)
298            );
299   
300   if (l && r) 
301     return line->updown == 1 ? 
302       (double)(maxx-minx) * (2.0*maxy-lycross-rycross)/2.0  /* up case */
303       :
304       (double)(maxx-minx) * (lycross+rycross-2*miny)/2.0;  /* down case */
305   
306   if (!l && !r) return (maxy-miny)*(maxx*2-p_eval_aty(line, miny)-p_eval_aty(line, maxy))/2.0;
307
308   if (l && !r)
309     return line->updown == 1 ?
310       trap_square(maxx-minx, maxy-miny, p_eval_aty(line, miny)-minx, p_eval_atx(line, minx)-miny) : 
311       trap_square(maxx-minx, maxy-miny, p_eval_aty(line, maxy)-minx, maxy-p_eval_atx(line, minx));
312   
313
314   if (!l && r) {
315     int r = line->updown == 1 ?
316       (maxx-p_eval_aty(line, maxy))*(maxy-p_eval_atx(line, maxx))/2.0 : 
317       (maxx-p_eval_aty(line, miny))*(p_eval_atx(line, maxx)-miny)/2.0;
318     return r;
319   }
320 }
321
322
323
324
325
326 /* 
327    handle the scanline slice in three steps 
328    
329    1.  Where only the left edge is inside a pixel
330    2a. Where both left and right edge are inside a pixel
331    2b. Where neither left or right edge are inside a pixel
332    3.  Where only the right edge is inside a pixel
333 */
334
335 static
336 void
337 render_slice_scanline(ss_scanline *ss, int y, p_line *l, p_line *r) {
338   
339   pcord miny, maxy;     /* y bounds in fine coordinates */
340   pcord lminx, lmaxx;   /* left line min/max within y bounds in fine coords */
341   pcord rminx, rmaxx;   /* right line min/max within y bounds in fine coords */
342   int cpix;             /* x-coordinate of current pixel */
343   int thin;             /* boolean for thin/thick segment */
344   int startpix;         /* temporary variable for "start of this interval" */
345   int stoppix;          /* temporary variable for "end of this interval" */
346   int step2end;         /* temporary variable to mark where step2 ends */
347
348   /* Find the y bounds of scanline_slice */
349
350   maxy = min( l->maxy, r->maxy );
351   miny = max( l->miny, r->miny );
352
353   maxy = min( maxy, (y+1)*16 );
354   miny = max( miny,  y*16 );
355
356   lminx = min( p_eval_aty(l, maxy), p_eval_aty(l, miny) );
357   lmaxx = max( p_eval_aty(l, maxy), p_eval_aty(l, miny) );
358
359   rminx = min( p_eval_aty(r, maxy), p_eval_aty(r, miny) );
360   rmaxx = max( p_eval_aty(r, maxy), p_eval_aty(r, miny) );
361
362   thin = coarse(lmaxx) >= coarse(rminx);
363
364   startpix = max( coarse(lminx), 0 );
365   stoppix  = min( coarse(rmaxx-1), ss->linelen-1 );
366   
367   for(cpix=startpix; cpix<=stoppix; cpix++) {
368     int lt = coarse(lmaxx-1) >= cpix;
369     int rt = coarse(rminx) <= cpix;
370     
371     int A, B, C;
372     
373     POLY_DEB( printf("(%d,%d) lt=%d rt=%d\n", cpix, y, lt, rt) );
374
375     A = lt ? pixel_coverage(l, cpix*16, cpix*16+16, miny, maxy) : 0;
376     B = lt ? 0 : 16*(maxy-miny);
377     C = rt ? pixel_coverage(r, cpix*16, cpix*16+16, miny, maxy) : 0;
378
379     POLY_DEB( printf("A=%d B=%d C=%d\n", A, B, C) );
380
381     ss->line[cpix] += A+B-C;
382
383   }
384   
385 }
386
387
388
389 static
390 void
391 render_slice_scanline_old(ss_scanline *ss, int y, p_line *l, p_line *r) {
392   
393   pcord miny, maxy;     /* y bounds in fine coordinates */
394   pcord lminx, lmaxx;   /* left line min/max within y bounds in fine coords */
395   pcord rminx, rmaxx;   /* right line min/max within y bounds in fine coords */
396   int cpix;             /* x-coordinate of current pixel */
397   int thin;             /* boolean for thin/thick segment */
398   int startpix;         /* temporary variable for "start of this interval" */
399   int stoppix;          /* temporary variable for "end of this interval" */
400   int step2end;         /* temporary variable to mark where step2 ends */
401
402   /* Find the y bounds of scanline_slice */
403
404   maxy = min( l->maxy, r->maxy );
405   miny = max( l->miny, r->miny );
406
407   maxy = min( maxy, (y+1)*16 );
408   miny = max( miny,  y*16 );
409
410   lminx = min( p_eval_aty(l, maxy), p_eval_aty(l, miny) );
411   lmaxx = max( p_eval_aty(l, maxy), p_eval_aty(l, miny) );
412
413   rminx = min( p_eval_aty(r, maxy), p_eval_aty(r, miny) );
414   rmaxx = max( p_eval_aty(r, maxy), p_eval_aty(r, miny) );
415
416   thin = coarse(lmaxx) >= coarse(rminx);
417
418
419   /* First step */
420   startpix = coarse(lminx);                             /* includes tricky starting pixel */
421   stoppix  = min(coarse(lmaxx), coarse(rminx) );        /* last pixel is tricky */
422   
423   /* handle start pixel */
424
425   cpix = startpix;
426   if (cpix < stoppix) {
427     ss->line[cpix] += pixel_coverage(l, cpix*16, cpix*16+16, miny, maxy);
428     printf("%2d: step1 - start pixel\n", cpix);
429   }
430   
431   for(cpix=startpix+1; cpix<stoppix; cpix++) {
432     printf("%2d: step1 pixel\n", cpix);
433     ss->line[cpix] += l->updown == 1 ? 
434       8.0 * (2*maxy-p_eval_atx(l, 16*cpix)-p_eval_atx(l, 16*cpix+16))   /* up case */
435       :
436       8.0 * (p_eval_atx(l, 16*cpix)+p_eval_atx(l, 16*cpix+16)-2*miny);  /* down case */
437   }
438   
439   
440   /* handle stop pixel */
441
442   if (thin) { /* step 2a */
443     startpix = coarse(rminx);
444     stoppix = coarse(lmaxx+15); /* one more than needed */
445     
446     for(cpix=startpix; cpix<stoppix; cpix++) {
447       printf("%2d: step2a pixel\n", cpix);
448       ss->line[cpix] += 
449         pixel_coverage(l, cpix*16, cpix*16+16, miny, maxy)
450         +(cpix*16+16-min(cpix*16+16, l->maxx))*(maxy-miny)
451         -pixel_coverage(r, cpix*16, cpix*16+16, miny, maxy);
452     }
453   } else { /* step 2b */
454     stoppix = coarse(rminx);
455     for(/* cpix already correct */; cpix<stoppix; cpix++) {
456       printf("%2d: step2b pixel\n", cpix);
457       ss->line[cpix] += 16.0*(maxy-miny);
458     }
459   }
460   
461   /* step 3 */
462
463   cpix = max(coarse(rminx), coarse(lmaxx+15));
464   stoppix = coarse(rmaxx-15);
465   
466   printf("step3 from %d to %d\n", cpix, stoppix);
467
468   for(; cpix<stoppix; cpix++) {
469     printf("%2d: step3 pixel\n", cpix);
470     ss->line[cpix] += 0+ 
471       (l->updown == 1 ?
472        8.0 * (2*maxy-p_eval_atx(r, 16*cpix)-p_eval_atx(r, 16*cpix+16))  /* up case */
473        :
474        8.0 * (p_eval_atx(r, 16*cpix)+p_eval_atx(r, 16*cpix+16)-2*miny));  /* down case */
475   }
476   
477   ss->line[cpix] += (16.0)*(maxy-miny) - pixel_coverage(r, cpix*16, cpix*16+16, miny, maxy);
478 }
479
480
481
482
483
484
485 /* Antialiasing polygon algorithm 
486    specs:
487    1. only nice polygons - no crossovers
488    2. 1/16 pixel resolution
489    3. full antialiasing ( complete spectrum of blends )
490    4. uses hardly any memory
491    5. no subsampling phase
492    
493
494    Algorithm outline:
495    1. Split into vertical intervals.
496    2. handle each interval 
497
498    For each interval we must: 
499    1. find which lines are in it
500    2. order the lines from in increasing x order.
501       since we are assuming no crossovers it is sufficent
502       to check a single point on each line.
503 */
504
505 /*
506   Definitions:
507   
508   1. Interval:  A vertical segment in which no lines cross nor end.
509   2. Scanline:  A physical line, contains 16 subpixels in the horizontal direction
510   3. Slice:     A start stop line pair.
511   
512  */
513
514
515 void
516 i_poly_aa(i_img *im, int l, double *x, double *y, i_color *val) {
517   int i ,k;                     /* Index variables */
518   int clc;                      /* Lines inside current interval */
519   pcord miny ,maxy;             /* Min and max values of the current slice in the subcord system */
520   pcord tempy;
521   int cscl;                     /* Current scanline */
522
523   ss_scanline templine;         /* scanline accumulator */
524   p_point *pset;                /* List of points in polygon */
525   p_line  *lset;                /* List of lines in polygon */
526   p_slice *tllist;              /* List of slices */
527
528   mm_log((1, "i_poly_aa(im %p, l %d, x %p, y %p, val %p)\n", im, l, x, y, val));
529
530   for(i=0; i<l; i++) {
531     mm_log((2, "(%.2f, %.2f)\n", x[i], y[i]));
532   }
533
534
535   POLY_DEB(
536            fflush(stdout);
537            setbuf(stdout, NULL);
538            );
539
540   tllist   = mymalloc(sizeof(p_slice)*l);
541   
542   ss_scanline_init(&templine, im->xsize, l);
543
544   pset     = point_set_new(x, y, l);
545   lset     = line_set_new(x, y, l);
546
547
548   qsort(pset, l, sizeof(p_point), (int(*)(const void *,const void *))p_compy);
549   
550   POLY_DEB(
551            for(i=0;i<l;i++) {
552              printf("%d [ %d ] (%d , %d) -> (%d , %d) yspan ( %d , %d )\n",
553                     i, lset[i].n, lset[i].x1, lset[i].y1, lset[i].x2, lset[i].y2, lset[i].miny, lset[i].maxy);
554            }
555            printf("MAIN LOOP\n\n");
556            );
557   
558
559   /* loop on intervals */
560   for(i=0; i<l-1; i++) {
561     int startscan = max( coarse(pset[i].y), 0);
562     int stopscan = min( coarse(pset[i+1].y+15), im->ysize-1);
563     pcord cc = (pset[i].y + pset[i+1].y)/2;
564
565     POLY_DEB(
566              printf("current slice is %d: %d to %d ( cpoint %d ) scanlines %d to %d\n", 
567                     i, pset[i].y, pset[i+1].y, cc, startscan, stopscan)
568              );
569     
570     if (pset[i].y == pset[i+1].y) {
571       POLY_DEB( printf("current slice thickness = 0 => skipping\n") );
572       continue;
573     }
574     
575     clc = lines_in_interval(lset, l, tllist, cc);
576     qsort(tllist, clc, sizeof(p_slice), (int(*)(const void *,const void *))p_compx);
577
578     mark_updown_slices(lset, tllist, clc);
579
580     POLY_DEB( printf("Interval contains %d lines\n", clc) );
581
582     for(k=0; k<clc; k++) {
583       int lno = tllist[k].n;
584       p_line *ln = lset+lno;
585       POLY_DEB(
586                printf("%d:  line #%2d: (%2d, %2d)->(%2d, %2d) (%2d/%2d, %2d/%2d) -> (%2d/%2d, %2d/%2d) alignment=%s\n",
587                       k, lno, ln->x1, ln->y1, ln->x2, ln->y2, 
588                       coarse(ln->x1), fine(ln->x1), 
589                       coarse(ln->y1), fine(ln->y1), 
590                       coarse(ln->x2), fine(ln->x2), 
591                       coarse(ln->y2), fine(ln->y2),
592                       ln->updown == 0 ? "vert" : ln->updown == 1 ? "up" : "down")
593                );
594     }
595     for(cscl=startscan; cscl<stopscan; cscl++) {
596       tempy = min(cscl*16+16, pset[i+1].y);
597       POLY_DEB( printf("evaluating scan line %d \n", cscl) );
598       for(k=0; k<clc-1; k+=2) {
599         render_slice_scanline(&templine, cscl, lset+tllist[k].n, lset+tllist[k+1].n);
600       }
601       if (16*coarse(tempy) == tempy) {
602         POLY_DEB( printf("flushing scan line %d\n", cscl) );
603         scanline_flush(im, &templine, cscl, val);
604         ss_scanline_reset(&templine);
605       }
606       /*
607         else {
608         scanline_flush(im, &templine, cscl, val);
609         ss_scanline_reset(&templine);
610         return 0;
611         }
612       */
613     }
614   } /* Intervals */
615   if (16*coarse(tempy) != tempy) 
616     scanline_flush(im, &templine, cscl-1, val);
617
618   ss_scanline_exorcise(&templine);
619   myfree(pset);
620   myfree(lset);
621   myfree(tllist);
622   
623 } /* Function */