added alpha and font filter drafts
[swftools.git] / lib / gfxtools.c
1 /* gfxtools.c
2
3    Various utility functions for dealing with gfxdevices.
4
5    Part of the swftools package.
6
7    Copyright (c) 2005 Matthias Kramm <kramm@quiss.org>
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <memory.h>
26 #include <math.h>
27 #include <string.h>
28 #include <assert.h>
29 #include "gfxtools.h"
30 #include "gfxfont.h"
31 #include "jpeg.h"
32 #include "q.h"
33
34 typedef struct _linedraw_internal
35 {
36     gfxline_t*start;
37     gfxline_t*next;
38     gfxcoord_t x0,y0;
39     char has_moveto;
40 } linedraw_internal_t;
41
42 static void linedraw_moveTo(gfxdrawer_t*d, gfxcoord_t x, gfxcoord_t y)
43 {
44     linedraw_internal_t*i = (linedraw_internal_t*)d->internal;
45     gfxline_t*l = (gfxline_t*)rfx_alloc(sizeof(gfxline_t));
46     l->type = gfx_moveTo;
47     i->has_moveto = 1;
48     i->x0 = x;
49     i->y0 = y;
50     l->sx = l->sy = 0;
51     d->x = l->x = x;
52     d->y = l->y = y;
53     l->next = 0;
54     if(i->next)
55         i->next->next = l;
56     i->next = l;
57     if(!i->start)
58         i->start = l;
59 }
60 static void linedraw_lineTo(gfxdrawer_t*d, gfxcoord_t x, gfxcoord_t y)
61 {
62     linedraw_internal_t*i = (linedraw_internal_t*)d->internal;
63     if(!i->has_moveto) {
64         /* starts with a line, not with a moveto. As this is the first
65            entry in the list, this is probably *meant* to be a moveto */
66         linedraw_moveTo(d, x, y);
67         return;
68     }
69     
70     gfxline_t*l = (gfxline_t*)rfx_alloc(sizeof(gfxline_t));
71     l->type = gfx_lineTo;
72     d->x = l->x = x;
73     d->y = l->y = y;
74
75     l->next = 0;
76     if(i->next)
77         i->next->next = l;
78     i->next = l;
79     if(!i->start)
80         i->start = l;
81 }
82 static void linedraw_splineTo(gfxdrawer_t*d, gfxcoord_t sx, gfxcoord_t sy, gfxcoord_t x, gfxcoord_t y)
83 {
84     linedraw_internal_t*i = (linedraw_internal_t*)d->internal;
85     if(!i->has_moveto) {
86         linedraw_moveTo(d, x, y);
87         return;
88     }
89
90     gfxline_t*l = (gfxline_t*)rfx_alloc(sizeof(gfxline_t));
91     l->type = gfx_splineTo;
92     d->x = l->x = x;
93     d->y = l->y = y;
94     l->sx = sx;
95     l->sy = sy;
96     l->next = 0;
97     if(i->next)
98         i->next->next = l;
99     i->next = l;
100     if(!i->start)
101         i->start = l;
102 }
103 static void linedraw_close(gfxdrawer_t*d)
104 {
105     linedraw_internal_t*i = (linedraw_internal_t*)d->internal;
106     if(!i->has_moveto) 
107         return;
108     linedraw_lineTo(d, i->x0, i->y0);
109     i->has_moveto = 0;
110     i->x0 = 0;
111     i->y0 = 0;
112 }
113 static void* linedraw_result(gfxdrawer_t*d)
114 {
115     linedraw_internal_t*i = (linedraw_internal_t*)d->internal;
116     void*result = (void*)i->start;
117     rfx_free(i);
118     memset(d, 0, sizeof(gfxdrawer_t));
119     return result;
120 }
121
122 void gfxdrawer_target_gfxline(gfxdrawer_t*d)
123 {
124     linedraw_internal_t*i = (linedraw_internal_t*)rfx_calloc(sizeof(linedraw_internal_t));
125     d->x = 0x7fffffff;
126     d->y = 0x7fffffff;
127     d->internal = i;
128     d->moveTo = linedraw_moveTo;
129     d->lineTo = linedraw_lineTo;
130     d->splineTo = linedraw_splineTo;
131     d->close = linedraw_close;
132     d->result = linedraw_result;
133 }
134
135 typedef struct _qspline_abc
136 {
137     double ax,bx,cx;
138     double ay,by,cy;
139 } qspline_abc_t;
140
141 typedef struct qspline_t
142 {
143     gfxpoint_t start;
144     gfxpoint_t control;
145     gfxpoint_t end;
146 } qspline_t;
147
148 typedef struct cspline_t
149 {
150     gfxpoint_t start;
151     gfxpoint_t control1;
152     gfxpoint_t control2;
153     gfxpoint_t end;
154 } cspline_t;
155
156 static void mkspline(qspline_abc_t*s, double x, double y, gfxline_t*l)
157 {
158     /*
159        Form 1: x = t*t*l->x + 2*t*(1-t)*l->sx + (1-t)*(1-t)*x;
160        Form 2: x = a*t*t + b*t + c
161     */
162     s->cx = x; s->bx = 2*l->sx - 2*x; s->ax = l->x - 2*l->sx + x;
163     s->cy = y; s->by = 2*l->sy - 2*y; s->ay = l->y - 2*l->sy + y;
164 }
165
166 static void spline_get_controlpoint(qspline_abc_t*q, double t1, double t2, double*dx, double*dy)
167 {
168     double dt = t2-t1;
169     double nax = q->ax*dt*dt;
170     double nay = q->ay*dt*dt;
171     double nbx = 2*q->ax*dt*t1 + q->bx*dt;
172     double nby = 2*q->ay*dt*t1 + q->by*dt;
173     double ncx = q->ax*t1*t1 + q->bx*t1 + q->cx;
174     double ncy = q->ay*t1*t1 + q->by*t1 + q->cy;
175     *dx = ncx + nbx/2;
176     *dy = ncy + nby/2;
177 }
178
179 static double get_spline_len(qspline_abc_t*s)
180 {
181     int parts = (int)(sqrt(fabs(s->ax) + fabs(s->ay))*3);
182     int i;
183     double len = 0;
184     double r;
185     double r2;
186     if(parts < 3) parts = 3;
187     r = 1.0/parts;
188     r2 = 1.0/(parts*parts);
189     for(i=0;i<parts;i++)
190     {
191         double dx = s->ax*(2*i+1)*r2 + s->bx*r;
192         double dy = s->ay*(2*i+1)*r2 + s->by*r;
193         len += sqrt(dx*dx+dy*dy);
194     }
195     /*printf("Spline from %f,%f to %f,%f has len %f (%f)\n", s->cx, s->cy,
196             s->cx + s->bx + s->ax,
197             s->cy + s->by + s->ay, len,
198             sqrt((s->bx + s->ax)*(s->bx + s->ax) + (s->by + s->ay)*(s->by + s->ay))
199             );
200     assert(len+0.5 >= sqrt((s->bx + s->ax)*(s->bx + s->ax) + (s->by + s->ay)*(s->by + s->ay)));
201      */
202     return len;
203 }
204
205 void gfxtool_draw_dashed_line(gfxdrawer_t*d, gfxline_t*line, float*r, float phase)
206 {
207     double x=0,y=0;
208     double linepos,nextpos;
209     char on;
210     int apos=0;
211
212     if(line && line->type != gfx_moveTo) {
213         fprintf(stderr, "gfxtool: outline doesn't start with a moveTo");
214         return;
215     }
216     
217     int i;
218     double dashlen=0;
219     for(i=0;r[i]>=0;i++) {
220         dashlen+=r[i];
221     }
222     if(!r || (r[0]<=0 && r[0]>-0.01) || dashlen<0.001) {
223         // no dashing. just draw the thing
224         while(line) {
225             if(line->type == gfx_moveTo) {
226                 d->moveTo(d, line->x, line->y);
227             } else if(line->type == gfx_lineTo) {
228                 d->lineTo(d, line->x, line->y);
229             } else if(line->type == gfx_splineTo) {
230                 d->splineTo(d, line->sx, line->sy, line->x, line->y);
231             }
232             line = line->next;
233         }
234         return;
235     }
236     if(r[0]<0 || phase<0) {
237         fprintf(stderr, "gfxtool: invalid (negative) dashes: %f, phase=%f\n", r[0], phase);
238         return;
239     }
240
241     for(;line;line=line->next) {
242         if(line->type == gfx_moveTo) {
243             d->moveTo(d, line->x, line->y);
244             on = 1; nextpos = r[0]; apos = 0; linepos = 0;
245             x = line->x; y = line->y;
246             while(linepos < phase) {
247                 //printf("[+] linepos: %f, phase: %f, on:%d, apos:%d nextpos:%f\n", linepos, phase, on, apos, nextpos);
248                 linepos += r[apos];
249                 if(linepos < phase) {
250                     on ^= 1;
251                     if(r[++apos]<0)
252                         apos = 0;
253                     nextpos += r[apos];
254                 }
255             }
256             linepos = phase;
257             //printf("[k] linepos: %f, phase: %f, on:%d, apos:%d nextpos:%f \n", linepos, phase, on, apos, nextpos);
258         } else if(line->type == gfx_lineTo) {
259             double dx = line->x - x;
260             double dy = line->y - y;
261             double len = sqrt(dx*dx+dy*dy);
262             double vx;
263             double vy;
264             double lineend = linepos+len;
265             if(len==0)
266                 continue;
267             vx = dx/len;
268             vy = dy/len;
269             assert(nextpos>=linepos);
270             //printf("(line) on:%d apos: %d nextpos: %f, line pos: %f, line end: %f\n", on, apos, nextpos, linepos, linepos+len);
271             while(nextpos<lineend) {
272                 double nx = x + vx*(nextpos-linepos);
273                 double ny = y + vy*(nextpos-linepos);
274                 if(on) {d->lineTo(d, nx,ny);/*printf("lineTo %f\n", nextpos);*/}
275                 else   {d->moveTo(d, nx,ny);/*printf("moveTo %f\n", nextpos);*/}
276                 on^=1;
277                 if(r[++apos]<0)
278                     apos = 0;
279                 nextpos+=r[apos];
280             }
281             linepos = lineend;
282             if(on) {
283                 //printf("lineTo %f\n", 1.0);
284                 d->lineTo(d, line->x,line->y);
285             }
286             x = line->x; y = line->y;
287         } else if(line->type == gfx_splineTo) {
288             qspline_abc_t q;
289             double len, lineend,lastt;
290             mkspline(&q, x, y, line);
291
292             len = get_spline_len(&q);
293             //printf("%f %f -> %f %f, len: %f\n", x, y, line->x, line->y, len);
294             if(len==0)
295                 continue;
296             lineend = linepos+len;
297             lastt = 0;
298             if(nextpos<linepos)
299                 printf("%f !< %f\n", nextpos, linepos);
300             assert(nextpos>=linepos);
301             //printf("(spline) on:%d apos: %d nextpos: %f, line pos: %f, line end: %f\n", on, apos, nextpos, linepos, linepos+len);
302             while(nextpos<lineend) {
303                 double t = (nextpos-linepos)/len;
304                 //printf("%f (%f-%f) apos=%d r[apos]=%f\n", t, nextpos, linepos, apos, r[apos]);
305                 double nx = q.ax*t*t+q.bx*t+q.cx;
306                 double ny = q.ay*t*t+q.by*t+q.cy;
307                 if(on) {
308                     double sx,sy;
309                     spline_get_controlpoint(&q, lastt, t, &sx, &sy);
310                     d->splineTo(d, sx, sy, nx,ny);
311                     //printf("splineTo %f\n", nextpos);
312                 } else  {
313                     d->moveTo(d, nx,ny);
314                     //printf("moveTo %f\n", nextpos);
315                 }
316                 lastt =  t;
317                 on^=1;
318                 if(r[++apos]<0)
319                     apos = 0;
320                 nextpos+=r[apos];
321             }
322             linepos = lineend;
323             if(on) {
324                 double sx,sy;
325                 spline_get_controlpoint(&q, lastt, 1, &sx, &sy);
326                 d->splineTo(d, sx, sy, line->x,line->y);
327                 //printf("splineTo %f\n", 1.0);
328             }
329             x = line->x; y = line->y;
330         }
331     }
332 }
333
334 gfxline_t * gfxline_clone(gfxline_t*line)
335 {
336     gfxline_t*dest = 0;
337     gfxline_t*pos = 0;
338     while(line) {
339         gfxline_t*n = (gfxline_t*)rfx_calloc(sizeof(gfxline_t));
340         *n = *line;
341         n->next = 0;
342         if(!pos) {
343             dest = pos = n;
344         } else {
345             pos->next = n;
346             pos = n;
347         }
348         line = line->next;
349     }
350     return dest;
351 }
352
353 static char splineIsStraight(double x, double y, gfxline_t*l)
354 {
355     if(l->type == gfx_moveTo)
356         return 0;
357     if(l->type == gfx_lineTo)
358         return 1;
359     double dx = l->x-x;
360     double dy = l->y-y;
361     double sx = l->sx-x;
362     double sy = l->sy-y;
363     if(fabs(dx*sy - dy*sx) < 0.000001 && (dx*sx + dy*sy) >= 0) {
364         return 1;
365     }
366     return 0;
367 }
368
369 void gfxline_optimize(gfxline_t*line)
370 {
371     gfxline_t*l = line;
372     /* step 1: convert splines to lines, where possible */
373     double x=0,y=0;
374     while(l) {
375         if(l->type == gfx_splineTo && splineIsStraight(x,y,l)) {
376             l->type = gfx_lineTo;
377         }
378         x = l->x;
379         y = l->y;
380         l = l->next;
381     }
382     /* step 2: combine adjacent lines and splines, where possible */
383     l = line;
384     while(l && l->next) {
385         gfxline_t*next = l->next;
386         char combine = 0;
387         double sx=0,sy=0;
388         if(l->type == gfx_lineTo && next->type == gfx_lineTo) {
389             double dx = l->x-x;
390             double dy = l->y-y;
391             double nx = next->x-l->x;
392             double ny = next->y-l->y;
393             if(fabs(dx*ny - dy*nx) < 0.000001 && (dx*nx + dy*ny) >= 0) {
394                 combine = 1;
395             }
396         } else if(l->type == gfx_splineTo && next->type == gfx_splineTo) {
397             /* TODO */
398         }
399         if(combine) {
400             l->next = next->next;
401             next->next = 0;
402             l->x = next->x;
403             l->y = next->y;
404             l->sx = sx;
405             l->sy = sy;
406             rfx_free(next);
407         } else {
408             x = l->x;
409             y = l->y;
410             l = l->next;
411         }
412     }
413 }
414
415 gfxline_t* gfxtool_dash_line(gfxline_t*line, float*dashes, float phase)
416 {
417     gfxdrawer_t d;
418     gfxline_t*result;
419     gfxdrawer_target_gfxline(&d);
420     gfxtool_draw_dashed_line(&d, line, dashes, phase);
421     result= (gfxline_t*)d.result(&d);
422     return result;
423 }
424
425 void gfxline_show(gfxline_t*l, FILE*fi)
426 {
427     while(l) {
428         if(l->type == gfx_moveTo) {
429             fprintf(fi, "moveTo %.2f,%.2f\n", l->x, l->y);
430         }
431         if(l->type == gfx_lineTo) {
432             fprintf(fi, "lineTo %.2f,%.2f\n", l->x, l->y);
433         }
434         if(l->type == gfx_splineTo) {
435             fprintf(fi, "splineTo %.2f,%.2f %.2f,%.2f\n", l->sx, l->sy, l->x, l->y);
436         }
437         l = l->next;
438     }
439 }
440
441 void gfxline_free(gfxline_t*l)
442 {
443     if(l && (l+1) == l->next) {
444         /* flattened */
445         rfx_free(l);
446     } else {
447         gfxline_t*next;
448         while(l) {
449             next = l->next;
450             l->next = 0;
451             rfx_free(l);
452             l = next;
453         }
454     }
455 }
456
457 static inline gfxpoint_t cspline_getpoint(const struct cspline_t*s, double t)
458 {
459     gfxpoint_t p;
460     double tt = t*t;
461     double ttt = tt*t;
462     double mt = (1-t);
463     double mtmt = mt*(1-t);
464     double mtmtmt = mtmt*(1-t);
465     p.x= s->end.x*ttt + 3*s->control2.x*tt*mt
466             + 3*s->control1.x*t*mtmt + s->start.x*mtmtmt;
467     p.y= s->end.y*ttt + 3*s->control2.y*tt*mt
468             + 3*s->control1.y*t*mtmt + s->start.y*mtmtmt;
469     return p;
470 }
471 static gfxpoint_t qspline_getpoint(const qspline_t*s, double t)
472 {
473     gfxpoint_t p;
474     p.x= s->end.x*t*t + 2*s->control.x*t*(1-t) + s->start.x*(1-t)*(1-t);
475     p.y= s->end.y*t*t + 2*s->control.y*t*(1-t) + s->start.y*(1-t)*(1-t);
476     return p;
477 }
478
479 static int approximate3(const cspline_t*s, qspline_t*q, int size, double quality2)
480 {
481     unsigned int gran = 0;
482     unsigned int istep = 0x80000000;
483     unsigned int istart = 0;
484     int num = 0;
485     int level = 0;
486
487     while(istart<0x80000000)
488     {
489         unsigned int iend = istart + istep;
490         double start = istart/(double)0x80000000;
491         double end = iend/(double)0x80000000;
492         qspline_t test;
493         double pos,qpos;
494         char left = 0,recurse=0;
495         int t;
496         int probes = 15;
497         double dx,dy;
498
499         /* create simple approximation: a qspline_t which run's through the
500            qspline_t point at 0.5 */
501         test.start = cspline_getpoint(s, start);
502         test.control = cspline_getpoint(s, (start+end)/2);
503         test.end = cspline_getpoint(s, end);
504         /* fix the control point:
505            move it so that the new spline does runs through it */
506         test.control.x = -(test.end.x + test.start.x)/2 + 2*(test.control.x);
507         test.control.y = -(test.end.y + test.start.y)/2 + 2*(test.control.y);
508
509         /* depending on where we are in the spline, we either try to match
510            the left or right tangent */
511         if(start<0.5)
512             left=1;
513         /* get derivative */
514         pos = left?start:end;
515         qpos = pos*pos;
516         test.control.x = s->end.x*(3*qpos) + 3*s->control2.x*(2*pos-3*qpos) +
517                     3*s->control1.x*(1-4*pos+3*qpos) + s->start.x*(-3+6*pos-3*qpos);
518         test.control.y = s->end.y*(3*qpos) + 3*s->control2.y*(2*pos-3*qpos) +
519                     3*s->control1.y*(1-4*pos+3*qpos) + s->start.y*(-3+6*pos-3*qpos);
520         if(left) {
521             test.control.x *= (end-start)/2;
522             test.control.y *= (end-start)/2;
523             test.control.x += test.start.x;
524             test.control.y += test.start.y;
525         } else {
526             test.control.x *= -(end-start)/2;
527             test.control.y *= -(end-start)/2;
528             test.control.x += test.end.x;
529             test.control.y += test.end.y;
530         }
531
532 //#define PROBES
533 #ifdef PROBES
534         /* measure the spline's accurancy, by taking a number of probes */
535         for(t=0;t<probes;t++) {
536             gfxpoint_t qr1,qr2,cr1,cr2;
537             double pos = 0.5/(probes*2)*(t*2+1);
538             double dx,dy;
539             double dist1,dist2;
540             qr1 = qspline_getpoint(&test, pos);
541             cr1 = cspline_getpoint(s, start+pos*(end-start));
542
543             dx = qr1.x - cr1.x;
544             dy = qr1.y - cr1.y;
545             dist1 = dx*dx+dy*dy;
546
547             if(dist1>quality2) {
548                 recurse=1;break;
549             }
550             qr2 = qspline_getpoint(&test, (1-pos));
551             cr2 = cspline_getpoint(s, start+(1-pos)*(end-start));
552
553             dx = qr2.x - cr2.x;
554             dy = qr2.y - cr2.y;
555             dist2 = dx*dx+dy*dy;
556
557             if(dist2>quality2) {
558                 recurse=1;break;
559             }
560         }
561 #else // quadratic error: *much* faster!
562
563         /* convert control point representation to
564            d*x^3 + c*x^2 + b*x + a */
565         dx= s->end.x  - s->control2.x*3 + s->control1.x*3 - s->start.x;
566         dy= s->end.y  - s->control2.y*3 + s->control1.y*3 - s->start.y;
567
568         /* we need to do this for the subspline between [start,end], not [0,1]
569            as a transformation of t->a*t+b does nothing to highest coefficient
570            of the spline except multiply it with a^3, we just need to modify
571            d here. */
572         {double m = end-start;
573          dx*=m*m*m;
574          dy*=m*m*m;
575         }
576
577         /* use the integral over (f(x)-g(x))^2 between 0 and 1
578            to measure the approximation quality.
579            (it boils down to const*d^2) */
580         recurse = (dx*dx + dy*dy > quality2);
581 #endif
582
583         if(recurse && istep>1 && size-level > num) {
584             istep >>= 1;
585             level++;
586         } else {
587             *q++ = test;
588             num++;
589             istart += istep;
590             while(!(istart & istep)) {
591                 level--;
592                 istep <<= 1;
593             }
594         }
595     }
596     return num;
597 }
598
599 void gfxdraw_conicTo(gfxdrawer_t*draw, double cx, double cy, double tox, double toy, double quality)
600 {
601     double c1x = (draw->x + 2 * cx) / 3;
602     double c1y = (draw->y + 2 * cy) / 3;
603     double c2x = (2 * cx + tox) / 3;
604     double c2y = (2 * cy + toy) / 3;
605     gfxdraw_cubicTo(draw, c1x, c1y, c2x, c2y, tox, toy, quality);
606 }
607
608
609 void gfxdraw_cubicTo(gfxdrawer_t*draw, double c1x, double c1y, double c2x, double c2y, double x, double y, double quality)
610 {
611     qspline_t q[128];
612     cspline_t c;
613     double maxerror = quality>0 ? quality : 1.0;
614     int t,num;
615
616     c.start.x = draw->x;
617     c.start.y = draw->y;
618     c.control1.x = c1x;
619     c.control1.y = c1y;
620     c.control2.x = c2x;
621     c.control2.y = c2y;
622     c.end.x = x;
623     c.end.y = y;
624
625     num = approximate3(&c, q, 128, maxerror);
626
627     for(t=0;t<num;t++) {
628         gfxpoint_t mid;
629         gfxpoint_t to;
630         mid.x = q[t].control.x;
631         mid.y = q[t].control.y;
632         to.x = q[t].end.x;
633         to.y = q[t].end.y;
634         draw->splineTo(draw, mid.x, mid.y, to.x, to.y);
635     }
636 }
637
638 gfxbbox_t gfxbbox_expand_to_point(gfxbbox_t box, gfxcoord_t x, gfxcoord_t y)
639 {
640     if(box.xmin==0 && box.ymin==0 && box.xmax==0 && box.ymax==0) {
641         box.xmin = x;
642         box.ymin = y;
643         box.xmax = x;
644         box.ymax = y;
645         if(x==0 && y==0) box.xmax = 0.0000001;
646         return box;
647     }
648     if(x < box.xmin)
649         box.xmin = x;
650     if(x > box.xmax)
651         box.xmax = x;
652     if(y < box.ymin)
653         box.ymin = y;
654     if(y > box.ymax)
655         box.ymax = y;
656     return box;
657 }
658
659 void gfxbbox_intersect(gfxbbox_t*box1, gfxbbox_t*box2)
660 {
661     if(box2->xmin > box1->xmin)
662         box1->xmin = box2->xmin;
663     if(box2->ymin > box1->ymin)
664         box1->ymin = box2->ymin;
665     if(box2->xmax < box1->xmax)
666         box1->xmax = box2->xmax;
667     if(box2->ymax > box1->ymax)
668         box1->ymax = box2->ymax;
669     if(box1->xmin > box1->xmax)
670         box1->xmax = box1->xmin;
671     if(box1->ymin > box1->ymax)
672         box1->ymax = box1->ymin;
673 }
674
675 gfxbbox_t gfxline_getbbox(gfxline_t*line)
676 {
677     gfxcoord_t x=0,y=0;
678     gfxbbox_t bbox = {0,0,0,0};
679     char last = 0;
680     while(line) {
681         if(line->type == gfx_moveTo) {
682             last = 1;
683         } else if(line->type == gfx_lineTo) {
684             if(last) bbox = gfxbbox_expand_to_point(bbox, x, y);
685             bbox = gfxbbox_expand_to_point(bbox, line->x, line->y);
686             last = 0;
687         } else if(line->type == gfx_splineTo) {
688             if(last) bbox = gfxbbox_expand_to_point(bbox, x, y);
689             bbox = gfxbbox_expand_to_point(bbox, line->sx, line->sy);
690             bbox = gfxbbox_expand_to_point(bbox, line->x, line->y);
691             last = 0;
692         }
693         x = line->x;
694         y = line->y;
695         line = line->next;
696     }
697     return bbox;
698 }
699
700 gfxline_t* gfxline_append(gfxline_t*line1, gfxline_t*line2)
701 {
702     gfxline_t*l = line1;;
703     if(!l)
704         return line2;
705     while(l->next) {
706         l = l->next;
707     }
708     l->next = line2;
709     return line1;
710 }
711
712 void gfxline_transform(gfxline_t*line, gfxmatrix_t*matrix)
713 {
714     while(line) {
715         double x = matrix->m00*line->x + matrix->m10*line->y + matrix->tx;
716         double y = matrix->m01*line->x + matrix->m11*line->y + matrix->ty;
717         line->x = x;
718         line->y = y;
719         if(line->type == gfx_splineTo) {
720             double sx = matrix->m00*line->sx + matrix->m10*line->sy + matrix->tx;
721             double sy = matrix->m01*line->sx + matrix->m11*line->sy + matrix->ty;
722             line->sx = sx;
723             line->sy = sy;
724         }
725         line = line->next;
726     }
727 }
728
729 void gfxmatrix_dump(gfxmatrix_t*m, FILE*fi, char*prefix)
730 {
731     fprintf(fi, "%s%f %f | %f\n", prefix, m->m00, m->m10, m->tx);
732     fprintf(fi, "%s%f %f | %f\n", prefix, m->m01, m->m11, m->ty);
733 }
734
735 void gfxmatrix_transform(gfxmatrix_t*m, double* v, double*dest)
736 {
737     dest[0] = m->m00*v[0] + m->m10*v[1] + m->tx;
738     dest[1] = m->m01*v[0] + m->m11*v[1] + m->ty;
739 }
740 void gfxmatrix_invert(gfxmatrix_t*m, gfxmatrix_t*dest)
741 {
742     double det = m->m00 * m->m11 - m->m10 * m->m01;
743     if(!det) {
744         memset(dest, 0, sizeof(gfxmatrix_t));
745         return;
746     }
747     det = 1/det;
748     dest->m00 = m->m11 * det;
749     dest->m01 = -m->m01 * det;
750     dest->m10 = -m->m10 * det;
751     dest->m11 = m->m00 * det;
752     dest->tx = -(dest->m00 * m->tx + dest->m10 * m->ty);
753     dest->ty = -(dest->m01 * m->tx + dest->m11 * m->ty);
754 }
755 void gfxmatrix_unit(gfxmatrix_t*m)
756 {
757     memset(m, 0, sizeof(gfxmatrix_t));
758     m->m00 = 1.0;
759     m->m11 = 1.0;
760 }
761 void gfxmatrix_multiply(gfxmatrix_t*m1, gfxmatrix_t*m2, gfxmatrix_t*dest)
762 {
763     dest->m00 = m1->m00*m2->m00 + m1->m10*m2->m01;
764     dest->m01 = m1->m01*m2->m00 + m1->m11*m2->m01;
765     dest->m10 = m1->m00*m2->m10 + m1->m10*m2->m11;
766     dest->m11 = m1->m01*m2->m10 + m1->m11*m2->m11;
767     dest->tx = m1->m00*m2->tx + m1->m10*m2->ty + m1->tx;
768     dest->ty = m1->m01*m2->tx + m1->m11*m2->ty + m1->ty;
769 }
770
771 gfxfontlist_t* gfxfontlist_create()
772 {
773     /* Initial list ist empty */
774     return 0;
775 }
776
777 gfxfont_t*gfxfontlist_findfont(gfxfontlist_t*list, char*id)
778 {
779     gfxfontlist_t*l = list;
780     while(l) {
781         if(!strcmp((char*)l->font->id, id)) {
782             return l->font;
783         }
784         l = l->next;
785     }
786     return 0;
787 }
788 char gfxfontlist_hasfont(gfxfontlist_t*list, gfxfont_t*font)
789 {
790     gfxfontlist_t*l = list;
791     while(l) {
792         if(!strcmp((char*)l->font->id, font->id)) {
793             return 1;
794         }
795         l = l->next;
796     }
797     return 0;
798 }
799 void*gfxfontlist_getuserdata(gfxfontlist_t*list, const char*id)
800 {
801     gfxfontlist_t*l = list;
802     while(l) {
803         if(!strcmp((char*)l->font->id, id)) {
804             return l->user;
805         }
806         l = l->next;
807     }
808     return 0;
809 }
810 gfxfontlist_t*gfxfontlist_addfont2(gfxfontlist_t*list, gfxfont_t*font, void*user)
811 {
812     gfxfontlist_t*last=0,*l = list;
813     while(l) {
814         last = l;
815         if(l->font == font) {
816             return list; // we already know this font
817         }
818         l = l->next;
819     }
820     if(!font) {
821         fprintf(stderr, "Tried to add zero font\n");
822     }
823     l = (gfxfontlist_t*)rfx_calloc(sizeof(gfxfontlist_t));
824     l->font = font;
825     l->user = user;
826     l->next = 0;
827     if(last) {
828         last->next = l;
829         return list;
830     } else {
831         return l;
832     }
833 }
834 gfxfontlist_t*gfxfontlist_addfont(gfxfontlist_t*list, gfxfont_t*font)
835 {
836     return gfxfontlist_addfont2(list, font, 0);
837 }
838 void gfxfontlist_free(gfxfontlist_t*list, char deletefonts)
839 {
840     gfxfontlist_t*l = list;
841     while(l) {
842         gfxfontlist_t*next = l->next;
843         if(deletefonts && l->font) {
844             gfxfont_free(l->font);l->font=0;
845         }
846         l->next = 0;
847         free(l);
848         l = next;
849     }
850 }
851
852 gfxline_t*gfxline_makerectangle(double x1,double y1,double x2, double y2)
853 {
854     gfxline_t* line = (gfxline_t*)rfx_calloc(sizeof(gfxline_t)*5);
855     line[0].x = x1;line[0].y = y1;line[0].type = gfx_moveTo;line[0].next = &line[1];
856     line[1].x = x2;line[1].y = y1;line[1].type = gfx_lineTo;line[1].next = &line[2];
857     line[2].x = x2;line[2].y = y2;line[2].type = gfx_lineTo;line[2].next = &line[3];
858     line[3].x = x1;line[3].y = y2;line[3].type = gfx_lineTo;line[3].next = &line[4];
859     line[4].x = x1;line[4].y = y1;line[4].type = gfx_lineTo;
860     return line;
861 }
862
863 gfxline_t*gfxline_makecircle(double x,double y,double rx, double ry)
864 {
865     double C1 = 0.2930;    
866     double C2 = 0.4140;   
867     double begin = 0.7070; 
868     gfxline_t** line = (gfxline_t**)rfx_calloc(sizeof(gfxline_t*)*9);
869     int t;
870     for(t=0;t<9;t++) {
871         line[t] = rfx_calloc(sizeof(gfxline_t));
872     }
873     line[0]->type = gfx_moveTo;
874     line[0]->x = x+begin*rx;
875     line[0]->y = y+begin*ry;
876     for(t=1;t<9;t++) {
877         line[t-1]->next = line[t];
878         line[t]->type = gfx_splineTo;
879     }
880     line[8]->next = 0;
881 #define R(nr,cx,cy,mx,my) \
882     line[nr]->sx = line[nr-1]->x + (cx); \
883     line[nr]->sy = line[nr-1]->y + (cy); \
884     line[nr]->x = line[nr]->sx + (mx); \
885     line[nr]->y = line[nr]->sy + (my);
886     R(1, -C1*rx,  C1*ry, -C2*rx,      0);
887     R(2, -C2*rx,      0, -C1*rx, -C1*ry);
888     R(3, -C1*rx, -C1*ry,      0, -C2*ry);
889     R(4,      0, -C2*ry,  C1*rx, -C1*ry);
890     R(5,  C1*rx, -C1*ry,  C2*rx,      0);
891     R(6,  C2*rx,      0,  C1*rx,  C1*ry);
892     R(7,  C1*rx,  C1*ry,      0,  C2*ry);
893     R(8,      0,  C2*ry, -C1*rx,  C1*ry);
894     gfxline_t*l = line[0];
895     free(line);
896     return l;
897 }
898
899 gfxbbox_t* gfxline_isrectangle(gfxline_t*_l)
900 {
901     if(!_l)
902         return 0;
903
904     gfxline_t*l = gfxline_clone(_l);
905     gfxline_optimize(l);
906
907     double x1,x2,y1,y2;
908     int xc=0,yc=0;
909     char corners=0;
910
911     char prev=0;
912     char fail=0;
913     for(;l; l=l->next) {
914         double x = l->x;
915         double y = l->y;
916
917         char top=0,left=0;
918
919         if(xc==2 && x!=x1 && x!=x2) {fail=1;break;}
920         else if(xc>=1 && x==x1) {left=0;}
921         else if(xc==2 && x==x2) {left=1;}
922         else if(xc==1 && x!=x1) {x2 = x; xc=2; left=1;}
923         else if(xc==0) {x1 = x; xc=1;left=0;}
924         else {fprintf(stderr, "Internal error in rectangle detection\n");}
925
926         if(yc==2 && y!=y1 && y!=y2) {fail=1;break;}
927         else if(yc>=1 && y==y1) {top=0;}
928         else if(yc==2 && y==y2) {top=1;}
929         else if(yc==1 && y!=y1) {y2 = y; yc=2; top=1;}
930         else if(yc==0) {y1 = y; yc=1;top=0;}
931         else {fprintf(stderr, "Internal error in rectangle detection\n");}
932
933         char pos=top<<1|left;
934
935         if((pos^prev)==3) {
936             /* diagonal lines not allowed */
937             fail=1;break;
938         }
939         prev = pos;
940
941         /* no corner except the first one may be touched twice */
942         if(pos && (corners & 1<<pos)) {
943             fail=1;break;
944         }
945         /* mark which corners have been touched so far */
946         corners |= 1<<pos;
947     }
948     if(fail) {
949         gfxline_free(l);
950         return 0;
951     }
952
953     if(corners!=0x0f) return 0; // not all 4 corners reached
954
955     if(x2<x1) {double x = x2;x2=x1;x1=x;}
956     if(y2<y1) {double y = y2;y2=y1;y1=y;}
957
958     gfxbbox_t*r = malloc(sizeof(gfxbbox_t));
959     r->xmin = x1; r->ymin = y1;
960     r->xmax = x2; r->ymax = y2;
961     return r;
962 }
963
964 void gfximage_transform(gfximage_t*img, gfxcxform_t*cxform)
965 {
966     int t;
967     int size = img->width*img->height;
968
969     int rr,rg,rb,ra, tr;
970     int gr,gg,gb,ga, tg;
971     int br,bg,bb,ba, tb;
972     int ar,ag,ab,aa, ta;
973     rr = (int)(cxform->rr*256);gr = (int)(cxform->gr*256);
974     rg = (int)(cxform->rg*256);gg = (int)(cxform->gg*256);
975     rb = (int)(cxform->rb*256);gb = (int)(cxform->gb*256);
976     ra = (int)(cxform->ra*256);ga = (int)(cxform->ga*256);
977     br = (int)(cxform->br*256);ar = (int)(cxform->ar*256);tr = (int)(cxform->tr*256);
978     bg = (int)(cxform->bg*256);ag = (int)(cxform->ag*256);tg = (int)(cxform->tg*256);
979     bb = (int)(cxform->bb*256);ab = (int)(cxform->ab*256);tb = (int)(cxform->tb*256);
980     ba = (int)(cxform->ba*256);aa = (int)(cxform->aa*256);ta = (int)(cxform->ta*256);
981
982     for(t=0;t<size;t++) {
983         gfxcolor_t*pixel = &img->data[t];
984         unsigned char r = (pixel->r * rr + pixel->g * rg + pixel->b * rb + pixel->a * ra + tr) / 256;
985         unsigned char g = (pixel->r * gr + pixel->g * gg + pixel->b * gb + pixel->a * ga + tg) / 256;
986         unsigned char b = (pixel->r * br + pixel->g * bg + pixel->b * bb + pixel->a * ba + tb) / 256;
987         unsigned char a = (pixel->r * ar + pixel->g * ag + pixel->b * ab + pixel->a * aa + ta) / 256;
988         pixel->r = r;
989         pixel->g = g;
990         pixel->b = b;
991         pixel->a = a;
992     }
993 }
994 void gfxline_dump(gfxline_t*line, FILE*fi, char*prefix)
995 {
996     while(line) {
997         if(line->type == gfx_moveTo) {
998             fprintf(fi, "%smoveTo %.2f %.2f\n", prefix, line->x, line->y);
999         } else if(line->type == gfx_lineTo) {
1000             fprintf(fi, "%slineTo %.2f %.2f\n", prefix, line->x, line->y);
1001         } else if(line->type == gfx_splineTo) {
1002             fprintf(fi, "%ssplineTo (%.2f %.2f) %.2f %.2f\n", prefix, line->sx, line->sy, line->x, line->y);
1003         }
1004         line = line->next;
1005     }
1006 }
1007
1008 static char gfxpoint_equals(void*c1, void*c2)
1009 {
1010     return !memcmp(c1, c2, sizeof(gfxpoint_t));
1011 }
1012 static unsigned int gfxpoint_hash(void*c)
1013 {
1014     return string_hash3(c, sizeof(gfxpoint_t));
1015 }
1016 static void* gfxpoint_clone(void*c)
1017 {
1018     void*n = malloc(sizeof(gfxpoint_t));
1019     memcpy(n, c, sizeof(gfxpoint_t));
1020     return n;
1021 }
1022 static void gfxpoint_destroy(void*c)
1023 {
1024     free(c);
1025 }
1026 static type_t gfxpoint_type = {
1027     hash: (hash_func)gfxpoint_hash,
1028     equals: (equals_func)gfxpoint_equals,
1029     dup: (dup_func)gfxpoint_clone,
1030     free: (free_func)gfxpoint_destroy,
1031 };
1032
1033 gfxline_t* gfxline_restitch(gfxline_t*line)
1034 {
1035     dict_t*ff = dict_new2(&gfxpoint_type);
1036     dict_t*rev = dict_new2(&gfxpoint_type);
1037     
1038     gfxline_t*prev=0;
1039     while(line) {
1040         gfxline_t*next = line->next;
1041         if(line->type == gfx_moveTo && (line->next && line->next->type != gfx_moveTo)) {
1042             gfxpoint_t xy = {line->x, line->y};
1043             dict_put(ff, &xy, line);
1044             prev = line;
1045         } else if(!line->next || line->next->type == gfx_moveTo) {
1046             if(prev) {
1047                 gfxpoint_t xy = {line->x, line->y};
1048                 dict_put(rev, &xy, prev);
1049                 line->next = 0;
1050             }
1051         }
1052         line = next;
1053     }
1054    
1055     gfxpoint_t pos = {0,0};
1056
1057     gfxline_t*result = 0;
1058     gfxline_t*last = 0;
1059    
1060     char first = 1;
1061     while(dict_count(ff)) {
1062         char reverse = 0, stitch = 1;
1063         gfxline_t*l = dict_lookup(ff, &pos);
1064         if(l) {
1065             char d = dict_del2(ff,&pos,l);assert(d);
1066         } else {
1067             l = dict_lookup(rev, &pos);
1068             if(l) {
1069                 reverse = 1;
1070                 char d = dict_del2(rev,&pos,l);assert(d);
1071             }
1072         }
1073         if(!l) {
1074             /* try to find *any* entry. this is costly, but
1075                doesn't happen too often */
1076             stitch = 0;
1077             DICT_ITERATE_DATA(ff, gfxline_t*, l2) {
1078                 l = l2;
1079                 break;
1080             }
1081             assert(l);
1082             gfxpoint_t xy = {l->x,l->y};
1083             char d = dict_del2(ff,&xy,l);assert(d);
1084         }
1085         
1086         gfxline_t*end = l;
1087         if(!reverse) {
1088             while(end->next) end = end->next;
1089             pos.x = end->x;
1090             pos.y = end->y;
1091             char d = dict_del2(rev,&pos,l);assert(d);
1092         } else {
1093             l = gfxline_reverse(l);
1094             pos.x = end->x;
1095             pos.y = end->y;
1096             char d = dict_del2(ff,&pos,end);assert(d);
1097         }
1098
1099         assert(l->type == gfx_moveTo);
1100         if(stitch && !first) {
1101             /* cut away the moveTo */
1102             gfxline_t*next = l->next;
1103             free(l);
1104             l = next;
1105         }
1106
1107         if(!last) {
1108             result = l;
1109             last = end;
1110         } else {
1111             last->next = l;
1112             last = end;
1113         }
1114         first = 0;
1115     }
1116     dict_destroy(ff);
1117     dict_destroy(rev);
1118     return result;
1119 }
1120
1121 gfxline_t* gfxline_reverse(gfxline_t*line)
1122 {
1123     gfxline_t*b = 0;
1124     while(line) {
1125         gfxline_t*next = line->next;
1126         if(next && next->type != gfx_moveTo) {
1127             line->type = next->type;
1128             line->sx = next->sx;
1129             line->sy = next->sy;
1130         } else {
1131             line->type = gfx_moveTo;
1132         }
1133         line->next = b;
1134         b = line;
1135         line = next;
1136     }
1137     return b;
1138 }
1139
1140 void gfxgradient_destroy(gfxgradient_t*gradient)
1141 {
1142     while(gradient) {
1143         gfxgradient_t*next = gradient->next;
1144         free(gradient);
1145         gradient = next;
1146     }
1147 }
1148
1149 gfxparams_t* gfxparams_new()
1150 {
1151     return (gfxparams_t*)rfx_calloc(sizeof(gfxparams_t));
1152 }
1153
1154 void gfxparams_store(gfxparams_t*params, const char*key, const char*value)
1155 {
1156     gfxparam_t*o = params->params;
1157     while(o) {
1158         if(!strcmp(key, o->key)) {
1159             /* overwrite old value */
1160             free((void*)o->value);
1161             o->value = strdup(value);
1162             return;
1163         }
1164         o = o->next;
1165     }
1166     gfxparam_t*p = (gfxparam_t*)malloc(sizeof(gfxparam_t));
1167     p->key = strdup(key);
1168     p->value = strdup(value);
1169     p->next = 0;
1170
1171     if(params->last) {
1172         params->last->next = p;
1173         params->last = p;
1174     } else {
1175         params->params = p;
1176         params->last = p;
1177     }
1178 }
1179
1180 void gfxparams_free(gfxparams_t*params)
1181 {
1182     gfxparam_t*p = params->params;
1183     while(p) {
1184         gfxparam_t*next = p->next;
1185         free((void*)p->key);
1186         if(p->value) free((void*)p->value);
1187         free(p);
1188         p = next;
1189     }
1190     free(params);
1191 }
1192