rfxswf cleanups: TAG structure and ResetWriteBits/ResetReadBits
[swftools.git] / pdf2swf / swfoutput.cc
1 /* swfoutput.cc
2    Implements generation of swf files using the rfxswf lib. The routines
3    in this file are called from pdf2swf.
4
5    This file is part of swftools.
6
7    Swftools is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    Swftools is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with swftools; if not, write to the Free Software
19    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
20
21 #include <string.h>
22 #include <fcntl.h>
23 #include <unistd.h>
24 #include "swfoutput.h"
25 #include "spline.h"
26 extern "C" {
27 #include "../lib/log.h"
28 #include "../lib/rfxswf.h"
29 }
30
31 int ignoredraworder=0;
32 int drawonlyshapes=0;
33 int jpegquality=85;
34 static int flag_protected = 0;
35
36 typedef unsigned char u8;
37 typedef unsigned short int u16;
38 typedef unsigned long int u32;
39
40 static int fi;
41 static char* filename = 0;
42 static SWF swf;
43 static TAG *tag;
44 static int currentswfid = 0;
45 static int depth = 1;
46 static int startdepth = 1;
47
48 static SHAPE* shape;
49 static int shapeid = -1;
50 static int textid = -1;
51
52 static int drawmode = -1;
53 static char storefont = 0;
54 static int fillstyleid;
55 static int linestyleid;
56 static int swflastx=0;
57 static int swflasty=0;
58 static int lastwasfill = 0;
59 static char fill = 0;
60 static int sizex;
61 static int sizey;
62 TAG* cliptags[128];
63 int clipshapes[128];
64 u32 clipdepths[128];
65 int clippos = 0;
66
67 int CHARMIDX = 0;
68 int CHARMIDY = 0;
69
70 void startshape(struct swfoutput* obj);
71 void starttext(struct swfoutput* obj);
72 void endshape();
73 void endtext();
74
75 // matrix multiplication. changes p0
76 void transform (plotxy*p0,struct swfmatrix*m)
77 {
78     double x,y;
79     x = m->m11*p0->x+m->m12*p0->y;
80     y = m->m21*p0->x+m->m22*p0->y;
81     p0->x = x + m->m13;
82     p0->y = y + m->m23;
83 }
84
85 // write a move-to command into the swf
86 void moveto(TAG*tag, plotxy p0)
87 {
88     int rx = (int)(p0.x*20);
89     int ry = (int)(p0.y*20);
90     if(rx!=swflastx || ry!=swflasty) {
91       swf_ShapeSetMove (tag, shape, rx,ry);
92     }
93     swflastx=rx;
94     swflasty=ry;
95 }
96
97 // write a line-to command into the swf
98 void lineto(TAG*tag, plotxy p0)
99 {
100     int rx = ((int)(p0.x*20)-swflastx);
101     int ry = ((int)(p0.y*20)-swflasty);
102     /* we can't skip this for rx=0,ry=0, those
103        are plots */
104     swf_ShapeSetLine (tag, shape, rx,ry);
105     swflastx+=rx;
106     swflasty+=ry;
107 }
108
109 // write a spline-to command into the swf
110 void splineto(TAG*tag, plotxy control,plotxy end)
111 {
112     int cx = ((int)(control.x*20)-swflastx);
113     int cy = ((int)(control.y*20)-swflasty);
114     swflastx += cx;
115     swflasty += cy;
116     int ex = ((int)(end.x*20)-swflastx);
117     int ey = ((int)(end.y*20)-swflasty);
118     swflastx += ex;
119     swflasty += ey;
120     swf_ShapeSetCurve(tag, shape, cx,cy,ex,ey);
121 }
122
123 /* write a line, given two points and the transformation
124    matrix. */
125 void line(TAG*tag, plotxy p0, plotxy p1, struct swfmatrix*m)
126 {
127     transform(&p0,m);
128     transform(&p1,m);
129     moveto(tag, p0);
130     lineto(tag, p1);
131 }
132
133 /* write a cubic (!) spline. This involves calling the approximate()
134    function out of spline.cc to convert it to a quadratic spline.  */
135 void spline(TAG*tag,plotxy p0,plotxy p1,plotxy p2,plotxy p3,struct swfmatrix*m)
136 {
137     double d;
138     struct qspline q[16];
139     int num;
140     int t;
141     transform(&p0,m);
142     transform(&p1,m);
143     transform(&p2,m);
144     transform(&p3,m);
145
146     num = approximate(p0,p1,p2,p3,q);
147     for(t=0;t<num;t++) {
148         moveto(tag,q[t].start);
149         splineto(tag,q[t].control, q[t].end);
150     }
151 }
152
153 /* draw a T1 outline. These are generated by pdf2swf and by t1lib.
154    (representing characters) */
155 void drawpath(TAG*tag, T1_OUTLINE*outline, struct swfmatrix*m)
156 {
157     if(tag->id != ST_DEFINEFONT &&
158         tag->id != ST_DEFINESHAPE &&
159         tag->id != ST_DEFINESHAPE2 &&
160         tag->id != ST_DEFINESHAPE3)
161     {
162         logf("<error> internal error: drawpath needs a shape tag, not %d\n",tag->id);
163         exit(1);
164     }
165     int log = 0;
166
167     double x=0,y=0;
168     double lastx=0,lasty=0;
169     double firstx=0,firsty=0;
170     int init=1;
171
172     while (outline)
173     {
174         x += (outline->dest.x/(float)0xffff);
175         y += (outline->dest.y/(float)0xffff);
176         if(outline->type == T1_PATHTYPE_MOVE)
177         {
178             if(((int)(lastx*20) != (int)(firstx*20) ||
179                 (int)(lasty*20) != (int)(firsty*20)) &&
180                      fill && !init)
181             {
182                 plotxy p0;
183                 plotxy p1;
184                 p0.x=lastx;
185                 p0.y=lasty;
186                 p1.x=firstx;
187                 p1.y=firsty;
188                 if(log) printf("fix: %f,%f -> %f,%f\n",p0.x,p0.y,p1.x,p1.y);
189                 line(tag, p0, p1, m);
190             }
191             firstx=x;
192             firsty=y;
193             init = 0;
194         }
195         else if(outline->type == T1_PATHTYPE_LINE) 
196         {
197             plotxy p0;
198             plotxy p1;
199             p0.x=lastx;
200             p0.y=lasty;
201             p1.x=x;
202             p1.y=y;
203             if(log) printf("line: %f,%f -> %f,%f\n",p0.x,p0.y,p1.x,p1.y);
204             line(tag, p0,p1,m);
205         }
206         else if(outline->type == T1_PATHTYPE_BEZIER)
207         {
208             plotxy p0;
209             plotxy p1;
210             plotxy p2;
211             plotxy p3;
212             T1_BEZIERSEGMENT*o2 = (T1_BEZIERSEGMENT*)outline;
213             p0.x=x; 
214             p0.y=y;
215             p1.x=o2->C.x/(float)0xffff+lastx;
216             p1.y=o2->C.y/(float)0xffff+lasty;
217             p2.x=o2->B.x/(float)0xffff+lastx;
218             p2.y=o2->B.y/(float)0xffff+lasty;
219             p3.x=lastx;
220             p3.y=lasty;
221             if(log) printf("spline: %f,%f -> %f,%f\n",p3.x,p3.y,p0.x,p0.y);
222             spline(tag,p0,p1,p2,p3,m);
223         } 
224         else {
225          logf("<error> drawpath: unknown outline type:%d\n", outline->type);
226         }
227         lastx=x;
228         lasty=y;
229         outline = outline->link;
230     }
231     if(((int)(lastx*20) != (int)(firstx*20) ||
232         (int)(lasty*20) != (int)(firsty*20)) &&
233              fill)
234     {
235         plotxy p0;
236         plotxy p1;
237         p0.x=lastx;
238         p0.y=lasty;
239         p1.x=firstx;
240         p1.y=firsty;
241         if(log) printf("fix: %f,%f -> %f,%f\n",p0.x,p0.y,p1.x,p1.y);
242         line(tag, p0, p1, m);
243     }
244 }
245
246 int colorcompare(RGBA*a,RGBA*b)
247 {
248
249     if(a->r!=b->r ||
250        a->g!=b->g ||
251        a->b!=b->b ||
252        a->a!=b->a) {
253         return 0;
254     }
255     return 1;
256 }
257
258 static const int CHARDATAMAX = 1024;
259 struct chardata {
260     int charid;
261     int fontid;
262     int x;
263     int y;
264     int size;
265     RGBA color;
266 } chardata[CHARDATAMAX];
267 int chardatapos = 0;
268
269 void putcharacters(TAG*tag)
270 {
271     int t;
272     SWFFONT font;
273     RGBA color;
274     color.r = chardata[0].color.r^255;
275     color.g = 0;
276     color.b = 0;
277     color.a = 0;
278     int lastfontid;
279     int lastx;
280     int lasty;
281     int lastsize;
282     int charids[128];
283     int charadvance[128];
284     int charstorepos;
285     int pass;
286     int glyphbits=1; //TODO: can this be zero?
287     int advancebits=1;
288
289     if(tag->id != ST_DEFINETEXT &&
290         tag->id != ST_DEFINETEXT2) {
291         logf("<error> internal error: putcharacters needs an text tag, not %d\n",tag->id);
292         exit(1);
293     }
294     if(!chardatapos) {
295         logf("<warning> putcharacters called with zero characters");
296     }
297
298     for(pass = 0; pass < 2; pass++)
299     {
300         charstorepos = 0;
301         lastfontid = -1;
302         lastx = CHARMIDX;
303         lasty = CHARMIDY;
304         lastsize = -1;
305
306         if(pass==1)
307         {
308             advancebits++; // add sign bit
309             swf_SetU8(tag, glyphbits);
310             swf_SetU8(tag, advancebits);
311         }
312
313         for(t=0;t<=chardatapos;t++)
314         {
315             if(lastfontid != chardata[t].fontid || 
316                     lastx!=chardata[t].x ||
317                     lasty!=chardata[t].y ||
318                     !colorcompare(&color, &chardata[t].color) ||
319                     charstorepos==127 ||
320                     lastsize != chardata[t].size ||
321                     t == chardatapos)
322             {
323                 if(charstorepos && pass==0)
324                 {
325                     int s;
326                     for(s=0;s<charstorepos;s++)
327                     {
328                         while(charids[s]>=(1<<glyphbits))
329                             glyphbits++;
330                         while(charadvance[s]>=(1<<advancebits))
331                             advancebits++;
332                     }
333                 }
334                 if(charstorepos && pass==1)
335                 {
336                     tag->writeBit = 0; // Q&D
337                     swf_SetBits(tag, 0, 1); // GLYPH Record
338                     swf_SetBits(tag, charstorepos, 7); // number of glyphs
339                     int s;
340                     for(s=0;s<charstorepos;s++)
341                     {
342                         swf_SetBits(tag, charids[s], glyphbits);
343                         swf_SetBits(tag, charadvance[s], advancebits);
344                     }
345                 }
346                 charstorepos = 0;
347
348                 if(pass == 1 && t<chardatapos)
349                 {
350                     RGBA*newcolor=0;
351                     SWFFONT*newfont=0;
352                     int newx = 0;
353                     int newy = 0;
354                     if(lastx != chardata[t].x ||
355                        lasty != chardata[t].y)
356                     {
357                         newx=chardata[t].x;
358                         newy=chardata[t].y;
359                     }
360                     if(!colorcompare(&color, &chardata[t].color)) 
361                     {
362                         color = chardata[t].color;
363                         newcolor = &color;
364                     }
365                     font.id = chardata[t].fontid;
366                     if(lastfontid != chardata[t].fontid || lastsize != chardata[t].size)
367                         newfont = &font;
368
369                     tag->writeBit = 0; // Q&D
370                     swf_TextSetInfoRecord(tag, newfont, chardata[t].size, newcolor, newx,newy);
371                 }
372
373                 lastfontid = chardata[t].fontid;
374                 lastx = chardata[t].x;
375                 lasty = chardata[t].y;
376                 lastsize = chardata[t].size;
377             }
378
379             if(t==chardatapos)
380                     break;
381
382             int advance;
383             int nextt = t==chardatapos-1?t:t+1;
384             int rel = chardata[nextt].x-chardata[t].x;
385             if(rel>=0 && (rel<(1<<(advancebits-1)) || pass==0)) {
386                advance = rel;
387                lastx=chardata[nextt].x;
388             }
389             else {
390                advance = 0;
391                lastx=chardata[t].x;
392             }
393             charids[charstorepos] = chardata[t].charid;
394             charadvance[charstorepos] = advance;
395             charstorepos ++;
396         }
397     }
398     chardatapos = 0;
399 }
400
401 void putcharacter(struct swfoutput*obj, int fontid, int charid, 
402                     int x,int y, int size)
403 {
404     if(chardatapos == CHARDATAMAX)
405     {
406         endtext();
407         starttext(obj);
408     }
409     chardata[chardatapos].fontid = fontid;
410     chardata[chardatapos].charid = charid;
411     chardata[chardatapos].x = x;
412     chardata[chardatapos].y = y;
413     chardata[chardatapos].color = obj->fillrgb;
414     chardata[chardatapos].size = size;
415     chardatapos++;
416 }
417
418
419 /* process a character. */
420 void drawchar(struct swfoutput*obj, SWFFont*font, char*character, swfmatrix*m)
421 {
422     int usefonts=1;
423     if(m->m12!=0 || m->m21!=0)
424         usefonts=0;
425     if(m->m11 != m->m22)
426         usefonts=0;
427
428     if(usefonts && ! drawonlyshapes)
429     {
430         int charid = font->getSWFCharID(character);
431         if(shapeid>=0)
432             endshape();
433         if(textid<0)
434             starttext(obj);
435         putcharacter(obj, font->swfid, charid,(int)(m->m13*20),(int)(m->m23*20),
436                 (int)(m->m11*20/2+0.5)); //where does the /2 come from?
437     }
438     else
439     {
440         T1_OUTLINE*outline = font->getOutline(character);
441         char* charname = character;
442
443         if(!outline) {
444          logf("<warning> Didn't find %s in current charset (%s)", 
445                  character,font->getName());
446          return;
447         }
448         
449         swfmatrix m2=*m;    
450         m2.m11/=100;
451         m2.m21/=100;
452         m2.m12/=100;
453         m2.m22/=100;
454
455         if(textid>=0)
456             endtext();
457         if(shapeid<0)
458             startshape(obj);
459
460         if(!lastwasfill)
461          swf_ShapeSetStyle(tag,shape,0x8000,fillstyleid,0);
462         lastwasfill = 1;
463
464         int lf = fill;
465         fill = 1;
466         drawpath(tag, outline, &m2);
467         fill = lf;
468     }
469 }
470
471 /* draw a curved polygon. */
472 void swfoutput_drawpath(swfoutput*output, T1_OUTLINE*outline, 
473                             struct swfmatrix*m)
474 {
475     if(textid>=0)
476         endtext();
477     if(shapeid<0)
478         startshape(output);
479
480     if(lastwasfill && !fill)
481     {
482      swf_ShapeSetStyle(tag,shape,linestyleid,0x8000,0);
483      lastwasfill = 0;
484     }
485     if(!lastwasfill && fill)
486     {
487      swf_ShapeSetStyle(tag,shape,0x8000,fillstyleid,0);
488      lastwasfill = 1;
489     }
490
491     drawpath(tag, outline,m); 
492 }
493
494 /* SWFFont: copy all t1 font outlines to a local 
495    array. */
496 SWFFont::SWFFont(char*name, int id, char*filename)
497 {
498     if(!T1_GetFontName(id))
499         T1_LoadFont(id);
500
501     this->name = strdup(T1_GetFontFileName(id));
502     this->fontid = strdup(name);
503     this->t1id = id;
504
505     char**a= T1_GetAllCharNames(id);
506     int t=0, outlinepos=0;
507     char*map[256];
508     while(a[t])
509         t++;
510  
511     this->charnum = t;
512     if(!t) 
513         return;
514     logf("<verbose> Font %s(%d): Storing %d outlines.\n", name, id, t);
515     
516     outline = (T1_OUTLINE**)malloc(t*sizeof(T1_OUTLINE*));
517     charname = (char**)malloc(t*sizeof(char*));
518     used = (char*)malloc(t*sizeof(char));
519     char2swfcharid = (U16*)malloc(t*2);
520     swfcharid2char = (U16*)malloc(t*2);
521     swfcharpos = 0;
522
523     memset(used,0,t*sizeof(char));
524
525     this->swfid = ++currentswfid;
526
527     
528     t=0;
529     while(*a)
530     {
531         map[t] = *a;
532         a++;
533         t++;
534         if(t==256 || !*a) {
535             int s;
536             for(s=t;s<256;s++)
537                 map[s] = ".notdef";
538
539             int ret = T1_ReencodeFont(id, map);
540             if(ret) {
541              T1_DeleteFont(id);
542              T1_LoadFont(id);
543              int ret = T1_ReencodeFont(id, map);
544              if(ret)
545                fprintf(stderr,"Can't reencode font: (%s) ret:%d\n",filename, ret);
546             }
547
548             // parsecharacters
549             for(s=0;s<t;s++)
550             {
551                 this->outline[outlinepos] = T1_CopyOutline(T1_GetCharOutline(id, s, 100.0, 0));
552                 this->charname[outlinepos] = strdup(T1_GetCharName(id, s));
553                 outlinepos++;
554             }
555             t=0;
556         }
557     }
558 }
559
560 /* free all tables, write out definefont tags */
561 SWFFont::~SWFFont()
562 {
563     int t,usednum=0;
564     int*ptr = (int*)malloc(swfcharpos*sizeof(int));
565
566     for(t=0;t<charnum;t++)
567         if(used[t]) usednum++;
568
569     if(usednum && !drawonlyshapes)
570     {
571         logf("<verbose> Font %s has %d used characters",fontid, usednum);
572         TAG*ftag = swf_InsertTag(swf.firstTag,ST_DEFINEFONT);
573         swf_SetU16(ftag, this->swfid);
574         int initpos = swf_GetDataSize(ftag);
575         swfmatrix m;
576         m.m11 = m.m22 = 1;
577         m.m21 = m.m12 = 0;
578         m.m13 = CHARMIDX;
579         m.m23 = CHARMIDY;
580         for(t=0;t<swfcharpos;t++) 
581         {
582             ptr[t] = swf_GetDataSize(ftag);
583             swf_SetU16(ftag, 0x1234);
584         }
585         for(t=0;t<swfcharpos;t++)
586         {
587             *(U16*)&ftag->data[ptr[t]] = swf_GetDataSize(ftag)-initpos;
588             swflastx=0;
589             swflasty=0;
590             swf_SetU8(ftag,0x10); //0 fill bits, 0 linestyle bits
591             SHAPE s;
592             s.bits.fill = 1;
593             s.bits.line = 0;
594             swf_ShapeSetStyle(ftag,&s,0,1,0);
595             int lastfill = fill;
596             fill = 1;
597             storefont = 1;
598             drawpath(ftag, outline[swfcharid2char[t]],&m);
599             storefont = 0;
600             fill = lastfill;
601             swf_ShapeSetEnd(ftag);
602         }
603     }
604
605     free(ptr);
606     free(outline);
607     for(t=0;t<charnum;t++)
608         free(charname[t]);
609     free(charname);
610     free(used);
611     free(swfcharid2char);
612     free(char2swfcharid);
613 }
614
615 T1_OUTLINE*SWFFont::getOutline(char*name)
616 {
617     int t;
618     for(t=0;t<this->charnum;t++) {
619         if(!strcmp(this->charname[t],name)) {
620             if(!used[t])
621             {
622                 swfcharid2char[swfcharpos] = t;
623                 char2swfcharid[t] = swfcharpos;
624                 swfcharpos++;
625                 used[t] = 1;
626             }
627             return outline[t];
628         }
629     }
630     return 0;
631 }
632
633 int SWFFont::getSWFCharID(char*name)
634 {
635     int t;
636     for(t=0;t<this->charnum;t++) {
637         if(!strcmp(this->charname[t],name)) {
638             if(!used[t])
639             {
640                 swfcharid2char[swfcharpos] = t;
641                 char2swfcharid[t] = swfcharpos++;
642                 used[t] = 1;
643             }
644             return char2swfcharid[t];
645         }
646     }
647     logf("<warning> Didn't find character '%s' in font '%s'", name, this->name);
648     return 0;
649 }
650
651 char*SWFFont::getName()
652 {
653     return this->name;
654 }
655
656 struct fontlist_t 
657 {
658     SWFFont * font;
659     fontlist_t*next;
660 } *fontlist = 0;
661
662 /* set's the t1 font index of the font to use for swfoutput_drawchar(). */
663 void swfoutput_setfont(struct swfoutput*obj, char*fontid, int t1id, char*filename)
664 {
665     fontlist_t*last=0,*iterator;
666     if(obj->font && !strcmp(obj->font->fontid,fontid))
667         return;
668
669     iterator = fontlist;
670     while(iterator) {
671         if(!strcmp(iterator->font->fontid,fontid))
672             break;
673         last = iterator;
674         iterator = iterator->next;
675     }
676     if(iterator) 
677     {
678         obj->font = iterator->font;
679         return ;
680     }
681
682     if(t1id<0) {
683         logf("<error> internal error: t1id:%d, fontid:%s\n", t1id,fontid);
684     }
685     
686     SWFFont*font = new SWFFont(fontid, t1id, filename);
687     iterator = new fontlist_t;
688     iterator->font = font;
689     iterator->next = 0;
690
691     if(last) 
692         last->next = iterator;
693     else 
694         fontlist = iterator;
695     obj->font = font;
696 }
697
698 int swfoutput_queryfont(struct swfoutput*obj, char*fontid)
699 {
700     fontlist_t *iterator = fontlist;
701     while(iterator) {
702         if(!strcmp(iterator->font->fontid,fontid))
703             return 1;
704         iterator = iterator->next;
705     }
706     return 0;
707 }
708
709 /* set's the matrix which is to be applied to characters drawn by
710    swfoutput_drawchar() */
711 void swfoutput_setfontmatrix(struct swfoutput*obj,double m11,double m12,
712                                                   double m21,double m22)
713 {
714     if(obj->fontm11 == m11 &&
715        obj->fontm12 == m12 &&
716        obj->fontm21 == m21 &&
717        obj->fontm22 == m22)
718         return;
719 //    if(textid>=0)
720 //      endtext();
721     obj->fontm11 = m11;
722     obj->fontm12 = m12;
723     obj->fontm21 = m21;
724     obj->fontm22 = m22;
725 }
726
727 /* draws a character at x,y. */
728 void swfoutput_drawchar(struct swfoutput* obj,double x,double y,char*character) 
729 {
730     swfmatrix m;
731     m.m11 = obj->fontm11;
732     m.m12 = obj->fontm12;
733     m.m21 = obj->fontm21;
734     m.m22 = obj->fontm22;
735     m.m13 = x;
736     m.m23 = y;
737     drawchar(obj, obj->font, character, &m);
738 }
739
740 /* initialize the swf writer */
741 void swfoutput_init(struct swfoutput* obj, char*_filename, int _sizex, int _sizey) 
742 {
743   GLYPH *glyph;
744   RGBA rgb;
745   SRECT r;
746   memset(obj, 0, sizeof(struct swfoutput));
747   filename = _filename;
748   sizex = _sizex;
749   sizey = _sizey;
750
751   logf("<verbose> initializing swf output for size %d*%d\n", sizex,sizey);
752
753   obj->font = 0;
754   
755   memset(&swf,0x00,sizeof(SWF));
756
757   swf.fileVersion    = 4;
758   swf.frameRate      = 0x0040; // 1 frame per 4 seconds
759   swf.movieSize.xmax = 20*sizex;
760   swf.movieSize.ymax = 20*sizey;
761   
762   swf.firstTag = swf_InsertTag(NULL,ST_SETBACKGROUNDCOLOR);
763   tag = swf.firstTag;
764   rgb.r = 0xff;
765   rgb.g = 0xff;
766   rgb.b = 0xff;
767   swf_SetRGB(tag,&rgb);
768   if(flag_protected)  // good practice! /r
769     tag = swf_InsertTag(tag, ST_PROTECT);
770   depth = 1;
771   startdepth = depth;
772 }
773
774 void swfoutput_setprotected() //write PROTECT tag
775 {
776   flag_protected = 1;
777 }
778
779 void startshape(struct swfoutput*obj)
780 {
781   RGBA rgb;
782   SRECT r;
783
784   if(textid>=0)
785       endtext();
786
787   tag = swf_InsertTag(tag,ST_DEFINESHAPE);
788
789   swf_ShapeNew(&shape);
790   linestyleid = swf_ShapeAddLineStyle(shape,obj->linewidth,&obj->strokergb);
791   rgb.r = obj->fillrgb.r;
792   rgb.g = obj->fillrgb.g;
793   rgb.b = obj->fillrgb.b;
794   fillstyleid = swf_ShapeAddSolidFillStyle(shape,&obj->fillrgb);
795
796   shapeid = ++currentswfid;
797   swf_SetU16(tag,shapeid);  // ID
798
799   r.xmin = 0;
800   r.ymin = 0;
801   r.xmax = 20*sizex;
802   r.ymax = 20*sizey;
803   
804   swf_SetRect(tag,&r);
805
806   swf_SetShapeStyles(tag,shape);
807   swf_ShapeCountBits(shape,NULL,NULL);
808   swf_SetShapeBits(tag,shape);
809
810   swf_ShapeSetAll(tag,shape,/*x*/0,/*y*/0,linestyleid,0,0);
811   swflastx=swflasty=0;
812   lastwasfill = 0;
813 }
814
815 void starttext(struct swfoutput*obj)
816 {
817   SRECT r;
818   MATRIX m;
819   if(shapeid>=0)
820       endshape();
821   tag = swf_InsertTag(tag,ST_DEFINETEXT);
822   textid = ++currentswfid;
823   swf_SetU16(tag, textid);
824
825   r.xmin = 0;
826   r.ymin = 0;
827   r.xmax = 20*sizex;
828   r.ymax = 20*sizey;
829   
830   swf_SetRect(tag,&r);
831
832   m.sx = 65536;
833   m.sy = 65536;
834   m.r0 = 0;
835   m.r1 = 0;
836   m.tx = 0;
837   m.ty = 0;
838  
839   swf_SetMatrix(tag,&m);
840   swflastx=swflasty=0;
841 }
842
843 void endshape()
844 {
845     if(shapeid<0) 
846         return;
847     swf_ShapeSetEnd(tag);
848     tag = swf_InsertTag(tag,ST_PLACEOBJECT2);
849     swf_ObjectPlace(tag,shapeid,/*depth*/depth++,NULL,NULL,NULL);
850     shapeid = -1;
851 }
852
853 void endtext()
854 {
855     if(textid<0)
856         return;
857     putcharacters(tag);
858     swf_SetU8(tag,0);
859     tag = swf_InsertTag(tag,ST_PLACEOBJECT2);
860     swf_ObjectPlace(tag,textid,/*depth*/depth++,NULL,NULL,NULL);
861     textid = -1;
862 }
863
864 void endpage(struct swfoutput*obj)
865 {
866     if(shapeid>=0)
867       endshape();
868     if(textid>=0)
869       endtext();
870     while(clippos)
871         swfoutput_endclip(obj);
872     tag = swf_InsertTag(tag,ST_SHOWFRAME);
873 }
874
875 void swfoutput_newpage(struct swfoutput*obj)
876 {
877     endpage(obj);
878
879     for(depth--;depth>=startdepth;depth--) {
880         tag = swf_InsertTag(tag,ST_REMOVEOBJECT2);
881         swf_SetU16(tag,depth);
882     }
883
884     depth = 1;
885     startdepth = depth;
886 }
887
888 /* "destroy" like in (oo-terminology) "destructor". Perform cleaning
889    up, complete the swf, and write it out. */
890 void swfoutput_destroy(struct swfoutput* obj) 
891 {
892     endpage(obj);
893     fontlist_t *tmp,*iterator = fontlist;
894     while(iterator) {
895         delete iterator->font;
896         iterator->font = 0;
897         tmp = iterator;
898         iterator = iterator->next;
899         delete tmp;
900     }
901
902     T1_CloseLib();
903     if(!filename) 
904         return;
905     if(filename)
906      fi = open(filename, O_CREAT|O_TRUNC|O_WRONLY, 0777);
907     else
908      fi = 1; // stdout
909     
910     if(fi<=0) {
911      logf("<fatal> Could not create \"%s\". ", filename);
912      exit(1);
913     }
914  
915     tag = swf_InsertTag(tag,ST_END);
916
917     if FAILED(swf_WriteSWF(fi,&swf)) 
918      logf("<error> WriteSWF() failed.\n");
919     if(filename)
920      close(fi);
921     logf("<notice> SWF written\n");
922 }
923
924 void swfoutput_setdrawmode(swfoutput* obj, int mode)
925 {
926     drawmode = mode;
927     if(mode == DRAWMODE_FILL)
928      fill = 1;
929     else if(mode == DRAWMODE_EOFILL)
930      fill = 1;
931     else if(mode == DRAWMODE_STROKE)
932      fill = 0;
933     else if(mode == DRAWMODE_CLIP)
934      fill = 1;
935     else if(mode == DRAWMODE_EOCLIP)
936      fill = 1;
937 }
938
939 void swfoutput_setfillcolor(swfoutput* obj, u8 r, u8 g, u8 b, u8 a)
940 {
941     if(obj->fillrgb.r == r &&
942        obj->fillrgb.g == g &&
943        obj->fillrgb.b == b &&
944        obj->fillrgb.a == a) return;
945
946     if(shapeid>=0)
947      endshape();
948     obj->fillrgb.r = r;
949     obj->fillrgb.g = g;
950     obj->fillrgb.b = b;
951     obj->fillrgb.a = a;
952 }
953
954 void swfoutput_setstrokecolor(swfoutput* obj, u8 r, u8 g, u8 b, u8 a)
955 {
956     if(obj->strokergb.r == r &&
957        obj->strokergb.g == g &&
958        obj->strokergb.b == b &&
959        obj->strokergb.a == a) return;
960
961     if(shapeid>=0)
962      endshape();
963     obj->strokergb.r = r;
964     obj->strokergb.g = g;
965     obj->strokergb.b = b;
966     obj->strokergb.a = a;
967 }
968
969 void swfoutput_setlinewidth(struct swfoutput*obj, double linewidth)
970 {
971     if(obj->linewidth == (u16)(linewidth*20))
972         return;
973
974     if(shapeid>=0)
975      endshape();
976     obj->linewidth = (u16)(linewidth*20);
977 }
978
979
980 void swfoutput_startclip(swfoutput*obj, T1_OUTLINE*outline, struct swfmatrix*m)
981 {
982     if(textid>=0)
983      endtext();
984     if(shapeid>=0)
985      endshape();
986
987     if(clippos >= 127)
988     {
989         logf("<warning> Too many clip levels.");
990         clippos --;
991     } 
992     
993     startshape(obj);
994     int olddrawmode = drawmode;
995     swfoutput_setdrawmode(obj, DRAWMODE_CLIP);
996     swfoutput_drawpath(obj, outline, m);
997     swf_ShapeSetEnd(tag);
998     swfoutput_setdrawmode(obj, olddrawmode);
999
1000     tag = swf_InsertTag(tag,ST_PLACEOBJECT2);
1001     cliptags[clippos] = tag;
1002     clipshapes[clippos] = shapeid;
1003     clipdepths[clippos] = depth++;
1004     clippos++;
1005     shapeid = -1;
1006 }
1007
1008 void swfoutput_endclip(swfoutput*obj)
1009 {
1010     if(textid>=0)
1011      endtext();
1012     if(shapeid>=0)
1013      endshape();
1014
1015     if(!clippos) {
1016         logf("<error> Invalid end of clipping region");
1017         return;
1018     }
1019     clippos--;
1020     swf_ObjectPlaceClip(cliptags[clippos],clipshapes[clippos],clipdepths[clippos],NULL,NULL,NULL,depth++);
1021 }
1022
1023
1024 void drawimage(struct swfoutput*obj, int bitid, int sizex,int sizey, 
1025         double x1,double y1,
1026         double x2,double y2,
1027         double x3,double y3,
1028         double x4,double y4)
1029 {
1030     RGBA rgb;
1031     SRECT r;
1032     int lsid=0;
1033     int fsid;
1034     struct plotxy p1,p2,p3,p4;
1035     int myshapeid;
1036     double xmax=x1,ymax=y1,xmin=x1,ymin=y1;
1037     if(x2>xmax) xmax=x2;
1038     if(y2>ymax) ymax=y2;
1039     if(x2<xmin) xmin=x2;
1040     if(y2<ymin) ymin=y2;
1041     if(x3>xmax) xmax=x3;
1042     if(y3>ymax) ymax=y3;
1043     if(x3<xmin) xmin=x3;
1044     if(y3<ymin) ymin=y3;
1045     if(x4>xmax) xmax=x4;
1046     if(y4>ymax) ymax=y4;
1047     if(x4<xmin) xmin=x4;
1048     if(y4<ymin) ymin=y4;
1049     p1.x=x1;
1050     p1.y=y1;
1051     p2.x=x2;
1052     p2.y=y2;
1053     p3.x=x3;
1054     p3.y=y3;
1055     p4.x=x4;
1056     p4.y=y4;
1057     
1058     MATRIX m;
1059     m.sx = (int)(65536*20*(x4-x1))/sizex;
1060     m.r1 = -(int)(65536*20*(y4-y1))/sizex;
1061     m.r0 = (int)(65536*20*(x1-x2))/sizey;
1062     m.sy = -(int)(65536*20*(y1-y2))/sizey;
1063
1064     m.tx = (int)(x1*20);
1065     m.ty = (int)(y1*20);
1066   
1067     /* shape */
1068     myshapeid = ++currentswfid;
1069     tag = swf_InsertTag(tag,ST_DEFINESHAPE);
1070     swf_ShapeNew(&shape);
1071     //lsid = ShapeAddLineStyle(shape,obj->linewidth,&obj->strokergb);
1072     //fsid = ShapeAddSolidFillStyle(shape,&obj->fillrgb);
1073     fsid = swf_ShapeAddBitmapFillStyle(shape,&m,bitid,0);
1074     swf_SetU16(tag, myshapeid);
1075     r.xmin = (int)(xmin*20);
1076     r.ymin = (int)(ymin*20);
1077     r.xmax = (int)(xmax*20);
1078     r.ymax = (int)(ymax*20);
1079     swf_SetRect(tag,&r);
1080     swf_SetShapeStyles(tag,shape);
1081     swf_ShapeCountBits(shape,NULL,NULL);
1082     swf_SetShapeBits(tag,shape);
1083     swf_ShapeSetAll(tag,shape,/*x*/0,/*y*/0,lsid,fsid,0);
1084     swflastx = swflasty = 0;
1085     moveto(tag, p1);
1086     lineto(tag, p2);
1087     lineto(tag, p3);
1088     lineto(tag, p4);
1089     lineto(tag, p1);
1090     /*
1091     ShapeMoveTo  (tag, shape, (int)(x1*20),(int)(y1*20));
1092     ShapeSetLine (tag, shape, (int)(x1*20);
1093     ShapeSetLine (tag, shape, x*20,0);
1094     ShapeSetLine (tag, shape, 0,-y*20);
1095     ShapeSetLine (tag, shape, -x*20,0);*/
1096     swf_ShapeSetEnd(tag);
1097
1098     /* instance */
1099     tag = swf_InsertTag(tag,ST_PLACEOBJECT2);
1100     swf_ObjectPlace(tag,myshapeid,/*depth*/depth++,NULL,NULL,NULL);
1101 }
1102
1103 int swfoutput_drawimagejpeg(struct swfoutput*obj, char*filename, int sizex,int sizey, 
1104         double x1,double y1,
1105         double x2,double y2,
1106         double x3,double y3,
1107         double x4,double y4)
1108 {
1109     if(shapeid>=0)
1110      endshape();
1111     if(textid>=0)
1112      endtext();
1113
1114     int bitid = ++currentswfid;
1115     tag = swf_InsertTag(tag,ST_DEFINEBITSJPEG2);
1116     swf_SetU16(tag, bitid);
1117     swf_SetJPEGBits(tag, filename, jpegquality);
1118
1119     drawimage(obj, bitid, sizex, sizey, x1,y1,x2,y2,x3,y3,x4,y4);
1120     return bitid;
1121 }
1122
1123 int swfoutput_drawimagelossless(struct swfoutput*obj, RGBA*mem, int sizex,int sizey, 
1124         double x1,double y1,
1125         double x2,double y2,
1126         double x3,double y3,
1127         double x4,double y4)
1128 {
1129     if(shapeid>=0)
1130      endshape();
1131     if(textid>=0)
1132      endtext();
1133
1134     int bitid = ++currentswfid;
1135     tag = swf_InsertTag(tag,ST_DEFINEBITSLOSSLESS);
1136     swf_SetU16(tag, bitid);
1137     swf_SetLosslessBits(tag,sizex,sizey,mem, BMF_32BIT);
1138     
1139     drawimage(obj, bitid, sizex, sizey, x1,y1,x2,y2,x3,y3,x4,y4);
1140     return bitid;
1141 }
1142
1143 int swfoutput_drawimagelossless256(struct swfoutput*obj, U8*mem, RGBA*pal, int sizex,int sizey, 
1144         double x1,double y1,
1145         double x2,double y2,
1146         double x3,double y3,
1147         double x4,double y4)
1148 {
1149     if(shapeid>=0)
1150      endshape();
1151     if(textid>=0)
1152      endtext();
1153
1154     int bitid = ++currentswfid;
1155     tag = swf_InsertTag(tag,ST_DEFINEBITSLOSSLESS2);
1156     swf_SetU16(tag, bitid);
1157     swf_SetLosslessBitsIndexed(tag,sizex,sizey,mem, pal, 256);
1158   
1159     drawimage(obj, bitid, sizex, sizey, x1,y1,x2,y2,x3,y3,x4,y4);
1160     return bitid;
1161 }
1162
1163 void swfoutput_drawimageagain(struct swfoutput*obj, int id, int sizex,int sizey, 
1164         double x1,double y1,
1165         double x2,double y2,
1166         double x3,double y3,
1167         double x4,double y4)
1168 {
1169     if(shapeid>=0)
1170      endshape();
1171     if(textid>=0)
1172      endtext();
1173
1174     drawimage(obj, id, sizex, sizey, x1,y1,x2,y2,x3,y3,x4,y4);
1175 }
1176