dc6f937828e7dd0326aff601ffeb54d6992b627d
[synfig.git] / synfig-core / trunk / src / synfig / layer_shape.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file layer_shape.cpp
3 **      \brief Implementation of the "Shape" layer
4 **
5 **      $Id$
6 **
7 **      \legal
8 **      Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
9 **      Copyright (c) 2007 Chris Moore
10 **
11 **      This package is free software; you can redistribute it and/or
12 **      modify it under the terms of the GNU General Public License as
13 **      published by the Free Software Foundation; either version 2 of
14 **      the License, or (at your option) any later version.
15 **
16 **      This package is distributed in the hope that it will be useful,
17 **      but WITHOUT ANY WARRANTY; without even the implied warranty of
18 **      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 **      General Public License for more details.
20 **      \endlegal
21 */
22 /* ========================================================================= */
23
24 /* === H E A D E R S ======================================================= */
25
26 #ifdef USING_PCH
27 #       include "pch.h"
28 #else
29 #ifdef HAVE_CONFIG_H
30 #       include <config.h>
31 #endif
32
33 #include "layer_shape.h"
34 #include "string.h"
35 #include "time.h"
36 #include "context.h"
37 #include "paramdesc.h"
38 #include "renddesc.h"
39 #include "surface.h"
40 #include "value.h"
41 #include "valuenode.h"
42 #include "float.h"
43 #include "blur.h"
44
45 #include "curve_helper.h"
46
47 #include <vector>
48
49 #include <deque>
50
51 #endif
52
53 /* === U S I N G =========================================================== */
54
55 using namespace synfig;
56 using namespace std;
57 using namespace etl;
58
59 /* === G L O B A L S ======================================================= */
60
61 SYNFIG_LAYER_INIT(Layer_Shape);
62 SYNFIG_LAYER_SET_NAME(Layer_Shape,"shape");
63 SYNFIG_LAYER_SET_LOCAL_NAME(Layer_Shape,N_("Shape"));
64 SYNFIG_LAYER_SET_CATEGORY(Layer_Shape,N_("Internal"));
65 SYNFIG_LAYER_SET_VERSION(Layer_Shape,"0.1");
66 SYNFIG_LAYER_SET_CVS_ID(Layer_Shape,"$Id$");
67
68 #define EPSILON 1e-12
69
70 template < class T >
71 inline bool IsZero(const T &n)
72 {
73         return (n < EPSILON) && (n > -EPSILON);
74 }
75
76 /* === C L A S S E S ======================================================= */
77
78 //Assumes 64 byte aligned structures if at all
79 struct Primitive
80 {
81         int             operation;
82         int             number;
83
84         //Point data[0];
85
86         enum Operations
87         {
88                 NONE = -1,
89                 MOVE_TO = 0,            //(x,y)+                                after first point treated as line_to
90                 CLOSE,                          //                                              NOT RUNLENGTH enabled
91                 LINE_TO,                        //(x,y)+                                continuous func
92                 CONIC_TO,                       //(x1,y1,x,y)+                  "   "
93                 CONIC_TO_SMOOTH,        //(x,y)+                                "   "
94                 CUBIC_TO,                       //(x1,y1,x2,y2,x,y)+    "   "
95                 CUBIC_TO_SMOOTH,        //(x2,y2,x,y)+                  "   "
96                 END
97         };
98 };
99
100 //******** CURVE FUNCTIONS *****************
101 const int       MAX_SUBDIVISION_SIZE = 64;
102 const int       MIN_SUBDIVISION_DRAW_LEVELS = 4;
103
104 static void Subd_Conic_Stack(Point *arc)
105 {
106         /*
107
108         b0
109         *               0+1 a
110         b1 b    *               1+2*1+2 a
111         *               1+2     b       *
112         b2              *
113         *
114
115         0.1.2 ->        0.1 2 3.4
116
117         */
118
119         Real a,b;
120
121
122         arc[4][0] = arc[2][0];
123         b = arc[1][0];
124
125         a = arc[1][0] = (arc[0][0] + b)/2;
126         b = arc[3][0] = (arc[4][0] + b)/2;
127         arc[2][0] = (a + b)/2;
128
129
130         arc[4][1] = arc[2][1];
131         b = arc[1][1];
132
133         a = arc[1][1] = (arc[0][1] + b)/2;
134         b = arc[3][1] = (arc[4][1] + b)/2;
135         arc[2][1] = (a + b)/2;
136
137         /* //USING SIMD
138
139         arc[4] = arc[2];
140
141         arc[3] = (arc[2] + arc[1])/2;
142         arc[1] = (arc[0] + arc[1])/2;
143
144         arc[2] = (arc[1] + arc[3])/2;
145
146         */
147
148 }
149
150 static void Subd_Cubic_Stack(Point *arc)
151 {
152         Real a,b,c;
153
154         /*
155
156         b0
157         *               0+1 a
158         b1 b    *               1+2*1+2 a
159         *               1+2     b       *                       0+3*1+3*2+3
160         b2 c    *               1+2*2+2 b       *
161         *               2+3     c       *
162         b3              *
163         *
164
165         0.1 2.3 ->      0.1 2 3 4 5.6
166
167         */
168
169         arc[6][0] = arc[3][0];
170
171         b = arc[1][0];
172         c = arc[2][0];
173
174         a = arc[1][0] = (arc[0][0] + b)/2;
175         b = (b + c)/2;
176         c = arc[5][0] = (arc[6][0] + c)/2;
177
178         a = arc[2][0] = (a + b)/2;
179         b = arc[4][0] = (b + c)/2;
180
181         arc[3][0] = (a + b)/2;
182
183
184         arc[6][1] = arc[3][1];
185
186         b = arc[1][1];
187         c = arc[2][1];
188
189         a = arc[1][1] = (arc[0][1] + b)/2;
190         b = (b + c)/2;
191         c = arc[5][1] = (arc[6][1] + c)/2;
192
193         a = arc[2][1] = (a + b)/2;
194         b = arc[4][1] = (b + c)/2;
195
196         arc[3][1] = (a + b)/2;
197
198         /* //USING SIMD
199         temp
200
201         arc[6] = arc[3];
202
203         //backwards to avoid overwriting
204         arc[5] = (arc[2] + arc[3])/2;
205         temp = (arc[1] + arc[2])/2;
206         arc[1] = (arc[0] + arc[1])/2;
207
208         arc[4] = (temp + arc[5])/2;
209         arc[2] = (arc[1] + temp)/2;
210
211         arc[3] = (arc[2] + arc[4])/2;
212
213         */
214 }
215
216 //************** PARAMETRIC RENDERER SUPPORT STRUCTURES ****************
217
218 // super segment
219 struct MonoSegment
220 {
221         Rect    aabb;
222         int             ydir;
223         vector<Point>   pointlist;
224
225         MonoSegment(int dir = 0, Real x0 = 0, Real x1 = 0, Real y0 = 0, Real y1 = 0)
226         {
227                 aabb.minx = x0;
228                 aabb.maxx = x1;
229                 aabb.miny = y0;
230                 aabb.maxy = y1;
231
232                 ydir = dir;
233         }
234
235         int intersect(Real x,Real y) const
236         {
237                 if((y < aabb.miny+EPSILON) || (y > aabb.maxy) || (x < aabb.minx)) return 0;
238                 if(x > aabb.maxx) return ydir;
239
240                 //int i = 0;
241                 //int size = pointlist.size();
242                 //vector<Point>::const_iterator end = pointlist.end();
243                 vector<Point>::const_iterator p = pointlist.begin();
244
245                 //assumes that the rect culled away anything that would be beyond the edges
246                 if(ydir > 0)
247                 {
248                         while(y > (*++p)[1])
249                                 ;
250                 }
251                 else
252                 {
253                         while(y < (*++p)[1])
254                                 ;
255                 }
256
257                 //for the loop to break there must have been a slope (straight line would do nothing)
258                 //vector<Point>::const_iterator p1 = p-1;
259                 Real dy = p[-1][1] - p[0][1];
260                 Real dx = p[-1][0] - p[0][0];
261
262                 assert(dy != 0);
263
264                 Real xi = p[0][0] + (y - p[0][1]) * dx / dy;
265                 return (x > xi)*ydir;
266         }
267 };
268
269 struct CurveArray
270 {
271         Rect    aabb;   //not necessarily as effective - can only reject values
272         vector<Point>   pointlist;      //run length - p0, p1, p2, p3 = p10, p11, p12, p13 = p20 ...
273         vector<char>    degrees;
274
275         CurveArray(Real x0 = 0, Real x1 = 0, Real y0 = 0, Real y1 = 0)
276         {
277                 aabb.set(x0,y0,x1,y1);
278         }
279
280         void reset(Real x0 = 0, Real x1 = 0, Real y0 = 0, Real y1 = 0)
281         {
282                 aabb.set(x0,y0,x1,y1);
283                 pointlist.clear();
284                 degrees.clear();
285         }
286
287         int size () const
288         {
289                 return degrees.size();
290         }
291
292         void Start(Point m)
293         {
294                 reset(m[0],m[0],m[1],m[1]);
295                 pointlist.push_back(m);
296         }
297
298         void AddCubic(Point p1, Point p2, Point dest)
299         {
300                 aabb.expand(p1[0],p1[1]);
301                 aabb.expand(p2[0],p2[1]);
302                 aabb.expand(dest[0],dest[1]);
303
304                 pointlist.push_back(p1);
305                 pointlist.push_back(p2);
306                 pointlist.push_back(dest);
307
308                 degrees.push_back(3);
309         }
310
311         void AddConic(Point p1, Point dest)
312         {
313                 aabb.expand(p1[0],p1[1]);
314                 aabb.expand(dest[0],dest[1]);
315
316                 pointlist.push_back(p1);
317                 pointlist.push_back(dest);
318
319                 degrees.push_back(2);
320         }
321
322         static int intersect_conic(Real x, Real y, Point *p, int /*level*/ = 0)
323         {
324                 Real ymin,ymax,xmin,xmax;
325                 int intersects = 0;
326
327                 //sort the overall curve ys - degenerate detection
328                 ymin = min(p[0][1],p[2][1]);
329                 ymax = max(p[0][1],p[2][1]);
330
331                 xmin = min(min(p[0][0],p[1][0]),p[2][0]);
332                 xmax = max(max(p[0][0],p[1][0]),p[2][0]);
333
334                 //to the left, to the right and out of range y, or completely out of range y
335                 if( x < xmin ) return 0;
336                 if( x > xmax  && (y > ymax || y < ymin) ) return 0;
337                 if( (y > ymax && y > p[1][1]) || (y < ymin && y < p[1][1]) ) return 0;
338
339                 //degenerate line max
340                 if(ymin == ymax && ymax == p[1][1])
341                         return 0;
342
343                 //degenerate accept - to the right and crossing the base line
344                 if(x > xmax)
345                 {
346                         return (y <= ymax && y >= ymin);
347                 }
348
349                 //solve for curve = y
350
351                 //real roots:
352                 //0 roots       - 0 intersection
353                 //1 root        - get x, and figure out x
354                 //2 roots (non-double root)     - get 2 xs, and count xs to the left
355
356                 //for conic we can assume 1 intersection for monotonic curve
357                 Real    a = p[2][1] -   2*p[1][1] +     p[0][1],
358                                 b =                     2*p[1][1] -     2*p[0][1],
359                                 c =                                                     p[0][1]         -       y;
360
361                 Real t1 = -1, t2 = -1;
362
363                 if(a == 0)
364                 {
365                         //linear - easier :)
366                         if(b == 0) return 0; //may not need this check
367
368                         t1 = - c / b; //bt + c = 0 solved
369                 }else
370                 {
371                         //2 degree polynomial
372                         Real b2_4ac = b*b - 4*a*c;
373
374                         //if there are double/no roots - no intersections (in real #s that is)
375                         if(b2_4ac <= 0)
376                         {
377                                 return 0;
378                         }
379
380                         b2_4ac = sqrt(b2_4ac);
381
382                         t1 = (-b - b2_4ac) / 2*a,
383                         t2 = (-b + b2_4ac) / 2*a;
384                 }
385
386                 //calculate number of intersections
387                 if(t1 >= 0 && t1 <= 1)
388                 {
389                         const Real t = t1;
390                         const Real invt = 1 - t;
391
392                         //find x val and it counts if it's to the left of the point
393                         const Real xi = invt*invt*p[0][0] + 2*t*invt*p[1][0] + t*t*p[2][0];
394                         const Real dy_t = 2*a*t + b;
395
396                         if(dy_t)
397                         {
398                                 intersects += (x >= xi) * ( dy_t > 0 ? 1 : -1);
399                         }
400                 }
401
402                 if(t2 >= 0 && t2 <= 1)
403                 {
404                         const Real t = t2;
405                         const Real invt = 1 - t;
406
407                         //find x val and it counts if it's to the left of the point
408                         const Real xi = invt*invt*p[0][0] + 2*t*invt*p[1][0] + t*t*p[2][0];
409                         const Real dy_t = 2*a*t + b;
410
411                         if(dy_t)
412                         {
413                                 intersects += (x >= xi) * ( dy_t > 0 ? 1 : -1);
414                         }
415                 }
416
417                 return intersects;
418         }
419
420         static int      quadratic_eqn(Real a, Real b, Real c, Real *t0, Real *t1)
421         {
422                 const Real b2_4ac = b*b - 4*a*c;
423
424                 //degenerate reject (can't take sqrt)
425                 if(b2_4ac < 0)
426                 {
427                         return 0;
428                 }
429
430                 const Real sqrtb2_4ac = sqrt(b2_4ac);
431                 const Real signb = b < 0 ? -1 : 1;
432                 const Real q = - 0.5 * (b + signb * sqrtb2_4ac);
433
434                 *t0 = q/a;
435                 *t1 = c/q;
436
437                 return sqrtb2_4ac == 0 ? 1 : 2;
438         }
439
440         //Newton-Raphson root polishing (we don't care about bounds, assumes very near the desired root)
441         static Real polish_cubicroot(Real a, Real b, Real c, Real d, Real t, Real *dpdt)
442         {
443                 const Real cn[4] = {a,b,c,d};
444                 Real p,dp,newt,oldpmag=FLT_MAX;
445
446                 //eval cubic eqn and its derivative
447                 for(;;)
448                 {
449                         p = cn[0]*t + cn[1];
450                         dp = cn[0];
451
452                         for(int i = 2; i < 4; i++)
453                         {
454                                 dp = p + dp*t;
455                                 p = cn[i] + p*t;
456                         }
457
458                         if(dp == 0)
459                         {
460                                 synfig::warning("polish_cubicroot: Derivative should not vanish!!!");
461                                 return t;
462                         }
463
464                         newt = t - p/dp;
465
466                         if(newt == t || fabs(p) >= oldpmag)
467                         {
468                                 *dpdt = dp;
469                                 return t;
470                         }
471
472                         t = newt;
473                         oldpmag = fabs(p);
474                 }
475         }
476
477         static int intersect_cubic(Real x, Real y, Point *p, int /*level*/ = 0)
478         {
479                 const Real INVALIDROOT = -FLT_MAX;
480                 Real ymin,ymax,xmin,xmax;
481                 Real ymin2,ymax2,ymintot,ymaxtot;
482                 int intersects = 0;
483
484                 //sort the overall curve ys and xs - degenerate detection
485
486                 //open span for the two end points
487                 ymin = min(p[0][1],p[3][1]);
488                 ymax = max(p[0][1],p[3][1]);
489
490                 //other points etc.
491                 ymin2 = min(p[1][1],p[2][1]);
492                 ymax2 = max(p[1][1],p[2][1]);
493
494                 ymintot = min(ymin,ymin2);
495                 ymaxtot = max(ymax,ymax2);
496
497                 //the entire curve control polygon is in this x range
498                 xmin = min(min(p[0][0],p[1][0]),min(p[2][0],p[3][0]));
499                 xmax = max(max(p[0][0],p[1][0]),max(p[2][0],p[3][0]));
500
501                 //outside all y boundaries (no intersect)
502                 if( (y > ymaxtot) || (y < ymintot) ) return 0;
503
504                 //left of curve (no intersect)
505                 if(x < xmin) return 0;
506
507                 //right of curve (and outside base range)
508                 if( x > xmax )
509                 {
510                         if( (y > ymax) || (y < ymin) ) return 0;
511
512                         //degenerate accept - to the right and inside the [ymin,ymax] range (already rejected if out of range)
513                         const Real n = p[3][1] - p[0][1];
514
515                         //extract the sign from the value (we need valid data)
516                         return n < 0 ? -1 : 1;
517                 }
518
519                 //degenerate horizontal line max -- doesn't happen enough to check for
520                 if( ymintot == ymaxtot ) return 0;
521
522                 //calculate roots:
523                 // can have 0,1,2, or 3 real roots
524                 // if any of them are double then reject the two...
525
526                 // y-coefficients for f_y(t) - y = 0
527                 Real    a = p[3][1]     - 3*p[2][1]     + 3*p[1][1]     -   p[0][1],
528                                 b =                       3*p[2][1]     - 6*p[1][1]     + 3*p[0][1],
529                                 c =                                                       3*p[1][1]     - 3*p[0][1],
530                                 d =                                                                             p[0][1] - y;
531
532                 Real    ax = p[3][0]    - 3*p[2][0]     + 3*p[1][0]     -   p[0][0],
533                                 bx =                      3*p[2][0]     - 6*p[1][0]     + 3*p[0][0],
534                                 cx =                                              3*p[1][0]     - 3*p[0][0],
535                                 dx =                                                                            p[0][0];
536
537                 Real t1 = INVALIDROOT, t2 = INVALIDROOT, t3 = INVALIDROOT, t, dydt;
538
539                 if(a == 0)
540                 {
541                         //only 2nd degree
542                         if(b == 0)
543                         {
544                                 //linear
545                                 if(c == 0) return 0;
546
547                                 t1 = - d / c; //equation devolved into: ct + d = 0 - solve...
548                         }else
549                         {
550                                 //0 roots = 0 intersections, 1 root = 2 intersections at the same place (0 effective)
551                                 if(quadratic_eqn(a,b,c,&t1,&t2) != 2) return 0;
552                         }
553                 }else
554                 {
555                         //cubic - sigh....
556
557                         //algorithm courtesy of Numerical Recipes in C (algorithm copied from pg. 184/185)
558                         Real an = b / a,
559                                  bn = c / a,
560                                  cn = d / a;
561
562                         //if cn is 0 (or really really close), then we can simplify this...
563                         if(IsZero(cn))
564                         {
565                                 t3 = 0;
566
567                                 //0 roots = 0 intersections, 1 root = 2 intersections at the same place (0 effective)
568                                 if(quadratic_eqn(a,b,c,&t1,&t2) != 2)
569                                 {
570                                         t1 = t2 = INVALIDROOT;
571                                 }
572                         }
573                         else
574                         {
575                                 //otherwise run the normal cubic root equation
576                                 Real Q = (an*an - 3.0*bn) / 9.0;
577                                 Real R = ((2.0*an*an - 9.0*bn)*an + 27.0*cn)/54.0;
578
579                                 if(R*R < Q*Q*Q)
580                                 {
581                                         Real theta = acos(R / sqrt(Q*Q*Q));
582
583                                         t1 = -2.0*sqrt(Q)*cos(theta/3) - an/3.0;
584                                         t2 = -2.0*sqrt(Q)*cos((theta+2*PI)/3.0) - an/3.0;
585                                         t3 = -2.0*sqrt(Q)*cos((theta-2*PI)/3.0) - an/3.0;
586
587                                         //don't need to reorder,l just need to eliminate double/triple roots
588                                         //if(t3 == t2 && t1 == t2) t2 = t3 = INVALIDROOT;
589                                         if(t3 == t2) t2 = t3 = INVALIDROOT;
590                                         if(t1 == t2) t1 = t2 = INVALIDROOT;
591                                         if(t1 == t3) t1 = t3 = INVALIDROOT;
592                                 }else
593                                 {
594                                         Real signR = R < 0 ? -1 : 1;
595                                         Real A = - signR * pow(signR*R + sqrt(R*R - Q*Q*Q),1/3.0);
596
597                                         Real B;
598                                         if(A == 0) B = 0;
599                                         else B = Q / A;
600
601                                         //single real root in this case
602                                         t1 = (A + B) - an/3.0;
603                                 }
604                         }
605                 }
606
607                 //if(t1 != INVALIDROOT)
608                 {
609                         t = t1;//polish_cubicroot(a,b,c,d,t1,&dydt);
610                         if(t >= 0 && t < 1)
611                         {
612                                 //const Real invt = 1 - t;
613
614                                 //find x val and it counts if it's to the left of the point
615                                 const Real xi = ((ax*t + bx)*t + cx)*t + dx;
616                                 dydt = (3*a*t + 2*b)*t + c;
617
618                                 if(dydt)
619                                 {
620                                         intersects += (x >= xi) * ( dydt > 0 ? 1 : -1);
621                                 }
622                         }
623                 }
624
625                 //if(t2 != INVALIDROOT)
626                 {
627                         t = t2;//polish_cubicroot(a,b,c,d,t2,&dydt);
628                         if(t >= 0 && t < 1)
629                         {
630                                 //const Real invt = 1 - t;
631
632                                 //find x val and it counts if it's to the left of the point
633                                 const Real xi = ((ax*t + bx)*t + cx)*t + dx;
634                                 dydt = (3*a*t + 2*b)*t + c;
635
636                                 if(dydt)
637                                 {
638                                         intersects += (x >= xi) * ( dydt > 0 ? 1 : -1);
639                                 }
640                         }
641                 }
642
643                 //if(t3 != INVALIDROOT)
644                 {
645                         t = t3;//polish_cubicroot(a,b,c,d,t3,&dydt);
646                         if(t >= 0 && t < 1)
647                         {
648                                 //const Real invt = 1 - t;
649
650                                 //find x val and it counts if it's to the left of the point
651                                 const Real xi = ((ax*t + bx)*t + cx)*t + dx;
652                                 dydt = (3*a*t + 2*b)*t + c;
653
654                                 if(dydt)
655                                 {
656                                         intersects += (x >= xi) * ( dydt > 0 ? 1 : -1);
657                                 }
658                         }
659                 }
660
661                 return intersects;
662         }
663
664         int intersect(Real x,Real y, Point *table) const
665         {
666                 if((y < aabb.miny) || (y > aabb.maxy) || (x < aabb.minx)) return 0;
667
668                 int i, curdeg, intersects = 0;
669                 const int numcurves = degrees.size();
670
671                 vector<Point>::const_iterator   p = pointlist.begin();
672
673                 for(i=0; i < numcurves; i++)
674                 {
675                         curdeg = degrees[i];
676
677                         switch(curdeg)
678                         {
679                                 case 2:
680                                 {
681                                         table[0] = *p++;
682                                         table[1] = *p++;
683                                         table[2] = *p;  //we want to include the last point for the next curve
684
685                                         intersects += intersect_conic(x,y,table);
686
687                                         break;
688                                 }
689
690                                 case 3:
691                                 {
692                                         table[0] = *p++;
693                                         table[1] = *p++;
694                                         table[2] = *p++;
695                                         table[3] = *p;  //we want to include the last point for the next curve
696
697                                         intersects += intersect_cubic(x,y,table);
698
699                                         break;
700                                 }
701
702                                 default:
703                                 {
704                                         warning("Invalid degree (%d) inserted into the list (index: %d)\n", curdeg, i);
705                                         return 0;
706                                 }
707                         }
708                 }
709
710                 return intersects;
711         }
712 };
713
714 struct Layer_Shape::Intersector
715 {
716         Rect    aabb;
717
718         //! true iff aabb hasn't been initialized yet
719         bool    initaabb;
720
721         int     flags;
722
723         enum IntersectorFlags
724         {
725                 NotClosed = 0x8000
726         };
727
728         enum PrimitiveType
729         {
730                 TYPE_NONE = 0,
731                 TYPE_LINE,
732                 TYPE_CURVE
733         };
734
735         Real    cur_x,cur_y;
736         Real    close_x,close_y;
737
738         vector<MonoSegment>                             segs;   //monotonically increasing
739         vector<CurveArray>                              curves; //big array of consecutive curves
740
741         int                                                             prim;
742         Vector                                                  tangent;
743
744         Intersector()
745         {
746                 clear();
747         }
748
749         bool notclosed()
750         {
751                 return (flags & NotClosed) || (cur_x != close_x) || (cur_y != close_y);
752         }
753
754         void move_to(Real x, Real y)
755         {
756                 close();
757
758                 close_x = cur_x = x;
759                 close_y = cur_y = y;
760
761                 tangent[0] = tangent[1] = 0;
762
763                 if(initaabb)
764                 {
765                         aabb.set_point(x,y);
766                         initaabb = false;
767                 }else aabb.expand(x,y);
768
769                 prim = TYPE_NONE;
770         }
771
772         void line_to(Real x, Real y)
773         {
774                 int dir = (y > cur_y)*1 + (-1)*(y < cur_y);
775
776                 //check for context (if not line start a new segment)
777                 //if we're not in line mode (covers 0 set case), or if directions are different (not valid for 0 direction)
778                 if(prim != TYPE_LINE || (dir && segs.back().ydir != dir))
779                 {
780                         MonoSegment             seg(dir,x,x,y,y);
781
782                         seg.aabb.expand(cur_x,cur_y);
783                         seg.pointlist.push_back(Point(cur_x,cur_y));
784                         seg.pointlist.push_back(Point(x,y));
785                         segs.push_back(seg);
786                 }
787                 //add to the last segment, because it works
788                 else
789                 {
790                         segs.back().pointlist.push_back(Point(x,y));
791                         segs.back().aabb.expand(x,y);
792                 }
793
794
795
796                 cur_x = x;
797                 cur_y = y;
798                 aabb.expand(x,y); //expand the entire thing's bounding box
799
800                 tangent[0] = x - cur_x;
801                 tangent[1] = x - cur_y;
802
803                 flags |= NotClosed;
804                 prim = TYPE_LINE;
805         }
806
807         void conic_to_smooth(Real x, Real y)
808         {
809                 const Real x1 = tangent[0]/2.0 + cur_x;
810                 const Real y1 = tangent[1]/2.0 + cur_y;
811
812                 conic_to(x1,y1,x,y);
813         }
814
815         void conic_to(Real x1, Real y1, Real x, Real y)
816         {
817                 //if we're not already a curve start one
818                 if(prim != TYPE_CURVE)
819                 {
820                         CurveArray      c;
821
822                         c.Start(Point(cur_x,cur_y));
823                         c.AddConic(Point(x1,y1),Point(x,y));
824
825                         curves.push_back(c);
826                 }else
827                 {
828                         curves.back().AddConic(Point(x1,y1),Point(x,y));
829                 }
830
831                 cur_x = x;
832                 cur_y = y;
833
834                 aabb.expand(x1,y1);
835                 aabb.expand(x,y);
836
837                 tangent[0] = 2*(x - x1);
838                 tangent[1] = 2*(y - y1);
839
840                 flags |= NotClosed;
841                 prim = TYPE_CURVE;
842         }
843
844         void curve_to_smooth(Real x2, Real y2, Real x, Real y)
845         {
846                 Real x1 = tangent[0]/3.0 + cur_x;
847                 Real y1 = tangent[1]/3.0 + cur_y;
848
849                 curve_to(x1,y1,x2,y2,x,y);
850         }
851
852         void curve_to(Real x1, Real y1, Real x2, Real y2, Real x, Real y)
853         {
854                 //if we're not already a curve start one
855                 if(prim != TYPE_CURVE)
856                 {
857                         CurveArray      c;
858
859                         c.Start(Point(cur_x,cur_y));
860                         c.AddCubic(Point(x1,y1),Point(x2,y2),Point(x,y));
861
862                         curves.push_back(c);
863                 }else
864                 {
865                         curves.back().AddCubic(Point(x1,y1),Point(x2,y2),Point(x,y));
866                 }
867
868                 cur_x = x;
869                 cur_y = y;
870
871                 //expand bounding box around ALL of it
872                 aabb.expand(x1,y1);
873                 aabb.expand(x2,y2);
874                 aabb.expand(x,y);
875
876                 tangent[0] = 3*(x - x2);
877                 tangent[1] = 3*(y - y2);
878
879                 flags |= NotClosed;
880                 prim = TYPE_CURVE;
881         }
882
883         void close()
884         {
885                 if(flags & NotClosed)
886                 {
887                         if(cur_x != close_x || cur_y != close_y)
888                         {
889                                 line_to(close_x,close_y);
890                         }
891
892                         flags &= ~NotClosed;
893                 }
894         }
895
896         //assumes the line to count the intersections with is (-1,0)
897         int     intersect (Real x, Real y) const
898         {
899                 int inter = 0;
900                 unsigned int i;
901                 vector<MonoSegment>::const_iterator s = segs.begin();
902                 vector<CurveArray>::const_iterator c = curves.begin();
903
904                 Point   memory[3*MAX_SUBDIVISION_SIZE + 1];
905
906                 for(i = 0; i < segs.size(); i++,s++)
907                 {
908                         inter += s->intersect(x,y);
909                 }
910
911                 for(i=0; i < curves.size(); i++,c++)
912                         inter += c->intersect(x,y,memory);
913
914                 return inter;
915         }
916
917         //intersect an arbitrary line
918         //int   intersect (Real x, Real y, Real vx, Real vy) {return 0;}
919
920         void clear()
921         {
922                 segs.clear();
923                 curves.clear();
924
925                 flags = 0;
926                 cur_x = cur_y = close_x = close_y = 0;
927                 prim = TYPE_NONE;
928                 tangent[0] = tangent[1] = 0;
929                 initaabb = true;
930         }
931 };
932
933 //*********** SCANLINE RENDERER SUPPORT STRUCTURES ***************
934 struct PenMark
935 {
936         int y,x;
937         Real cover,area;
938
939         PenMark(){}
940         PenMark(int xin, int yin, Real c, Real a)
941                 :y(yin),x(xin),cover(c),area(a) {}
942
943         void set(int xin, int yin, Real c, Real a)      { y = yin; x = xin; cover = c; area = a;        }
944
945         void setcoord(int xin, int yin)                         { y = yin; x = xin;     }
946
947         void setcover(Real c, Real a)                           { cover = c; area = a; }
948         void addcover(Real c, Real a)                           { cover += c; area += a; }
949
950         bool operator < (const PenMark &rhs) const
951         {
952                 return y == rhs.y ? x < rhs.x : y < rhs.y;
953         }
954 };
955
956 typedef rect<int> ContextRect;
957
958 class Layer_Shape::PolySpan
959 {
960 public:
961         typedef deque<PenMark>  cover_array;
962
963         Point                   arc[3*MAX_SUBDIVISION_SIZE + 1];
964
965         cover_array             covers;
966         PenMark                 current;
967
968         int                             open_index;
969
970         //ending position of last primitive
971         Real                    cur_x;
972         Real                    cur_y;
973
974         //starting position of current primitive list
975         Real                    close_x;
976         Real                    close_y;
977
978         //flags for the current segment
979         int                             flags;
980
981         //the window that will be drawn (used for clipping)
982         ContextRect             window;
983
984         //for assignment to flags value
985         enum PolySpanFlags
986         {
987                 NotSorted = 0x8000,
988                 NotClosed =     0x4000
989         };
990
991         //default constructor - 0 everything
992         PolySpan() :current(0,0,0,0),flags(NotSorted)
993         {
994                 cur_x = cur_y = close_x = close_y = 0;
995                 open_index = 0;
996         }
997
998         bool notclosed() const
999         {
1000                 return (flags & NotClosed) || (cur_x != close_x) || (cur_y != close_y);
1001         }
1002
1003         //0 out all the variables involved in processing
1004         void clear()
1005         {
1006                 covers.clear();
1007                 cur_x = cur_y = close_x = close_y = 0;
1008                 open_index = 0;
1009                 current.set(0,0,0,0);
1010                 flags = NotSorted;
1011         }
1012
1013         //add the current cell, but only if there is information to add
1014         void addcurrent()
1015         {
1016                 if(current.cover || current.area)
1017                 {
1018                         covers.push_back(current);
1019                 }
1020         }
1021
1022         //move to the next cell (cover values 0 initially), keeping the current if necessary
1023         void move_pen(int x, int y)
1024         {
1025                 if(y != current.y || x != current.x)
1026                 {
1027                         addcurrent();
1028                         current.set(x,y,0,0);
1029                 }
1030         }
1031
1032         //close the primitives with a line (or rendering will not work as expected)
1033         void close()
1034         {
1035                 if(flags & NotClosed)
1036                 {
1037                         if(cur_x != close_x || cur_y != close_y)
1038                         {
1039                                 line_to(close_x,close_y);
1040                                 addcurrent();
1041                                 current.setcover(0,0);
1042                         }
1043                         flags &= ~NotClosed;
1044                 }
1045         }
1046
1047         // Not recommended - destroys any separation of spans currently held
1048         void merge_all()
1049         {
1050                 sort(covers.begin(),covers.end());
1051                 open_index = 0;
1052         }
1053
1054         //will sort the marks if they are not sorted
1055         void sort_marks()
1056         {
1057                 if(flags & NotSorted)
1058                 {
1059                         //only sort the open index
1060                         addcurrent();
1061                         current.setcover(0,0);
1062
1063                         sort(covers.begin() + open_index,covers.end());
1064                         flags &= ~NotSorted;
1065                 }
1066         }
1067
1068         //encapsulate the current sublist of marks (used for drawing)
1069         void encapsulate_current()
1070         {
1071                 //sort the current list then reposition the open list section
1072                 sort_marks();
1073                 open_index = covers.size();
1074         }
1075
1076         //move to start a new primitive list (enclose the last primitive if need be)
1077         void move_to(Real x, Real y)
1078         {
1079                 close();
1080                 if(isnan(x))x=0;
1081                 if(isnan(y))y=0;
1082                 move_pen((int)floor(x),(int)floor(y));
1083                 close_y = cur_y = y;
1084                 close_x = cur_x = x;
1085         }
1086
1087         //primitive_to functions
1088         void line_to(Real x, Real y);
1089         void conic_to(Real x1, Real y1, Real x, Real y);
1090         void cubic_to(Real x1, Real y1, Real x2, Real y2, Real x, Real y);
1091
1092         void draw_scanline(int y, Real x1, Real y1, Real x2, Real y2);
1093         void draw_line(Real x1, Real y1, Real x2, Real y2);
1094
1095         Real ExtractAlpha(Real area, WindingStyle winding_style)
1096         {
1097                 if (area < 0)
1098                         area = -area;
1099
1100                 if (winding_style == WINDING_NON_ZERO)
1101                 {
1102                         // non-zero winding style
1103                         if (area > 1)
1104                                 return 1;
1105                 }
1106                 else // if (winding_style == WINDING_EVEN_ODD)
1107                 {
1108                         // even-odd winding style
1109                         while (area > 1)
1110                                 area -= 2;
1111
1112                         // want pyramid like thing
1113                         if (area < 0)
1114                                 area = -area;
1115                 }
1116
1117                 return area;
1118         }
1119 };
1120
1121 /* === M E T H O D S ======================================================= */
1122
1123 Layer_Shape::Layer_Shape(const Real &a, const Color::BlendMethod m):
1124         Layer_Composite (a,m),
1125         edge_table              (new Intersector),
1126         color                   (Color::black()),
1127         offset                  (0,0),
1128         invert                  (false),
1129         antialias               (true),
1130         blurtype                (Blur::FASTGAUSSIAN),
1131         feather                 (0),
1132         winding_style   (WINDING_NON_ZERO),
1133         bytestream              (0),
1134         lastbyteop              (Primitive::NONE),
1135         lastoppos               (-1)
1136 {
1137 }
1138
1139 Layer_Shape::~Layer_Shape()
1140 {
1141         delete edge_table;
1142 }
1143
1144 void
1145 Layer_Shape::clear()
1146 {
1147         edge_table->clear();
1148         bytestream.clear();
1149 }
1150
1151 bool
1152 Layer_Shape::set_param(const String & param, const ValueBase &value)
1153 {
1154         IMPORT_PLUS(color, { if (color.get_a() == 0) { if (converted_blend_) {
1155                                         set_blend_method(Color::BLEND_ALPHA_OVER);
1156                                         color.set_a(1); } else transparent_color_ = true; } });
1157         IMPORT(offset);
1158         IMPORT(invert);
1159         IMPORT(antialias);
1160         IMPORT(feather);
1161         IMPORT(blurtype);
1162         IMPORT(winding_style);
1163
1164         return Layer_Composite::set_param(param,value);
1165 }
1166
1167 ValueBase
1168 Layer_Shape::get_param(const String &param)const
1169 {
1170         EXPORT(color);
1171         EXPORT(offset);
1172         EXPORT(invert);
1173         EXPORT(antialias);
1174         EXPORT(feather);
1175         EXPORT(blurtype);
1176         EXPORT(winding_style);
1177
1178         EXPORT_NAME();
1179         EXPORT_VERSION();
1180
1181         return Layer_Composite::get_param(param);
1182 }
1183
1184 Layer::Vocab
1185 Layer_Shape::get_param_vocab()const
1186 {
1187         Layer::Vocab ret(Layer_Composite::get_param_vocab());
1188
1189         ret.push_back(ParamDesc("color")
1190                 .set_local_name(_("Color"))
1191                 .set_description(_("Layer_Shape Color"))
1192         );
1193         ret.push_back(ParamDesc("offset")
1194                 .set_local_name(_("Offset"))
1195         );
1196         ret.push_back(ParamDesc("invert")
1197                 .set_local_name(_("Invert"))
1198         );
1199         ret.push_back(ParamDesc("antialias")
1200                 .set_local_name(_("Antialiasing"))
1201         );
1202         ret.push_back(ParamDesc("feather")
1203                 .set_local_name(_("Feather"))
1204                 .set_is_distance()
1205         );
1206         ret.push_back(ParamDesc("blurtype")
1207                 .set_local_name(_("Type of Feather"))
1208                 .set_description(_("Type of feathering to use"))
1209                 .set_hint("enum")
1210                 .add_enum_value(Blur::BOX,"box",_("Box Blur"))
1211                 .add_enum_value(Blur::FASTGAUSSIAN,"fastgaussian",_("Fast Gaussian Blur"))
1212                 .add_enum_value(Blur::CROSS,"cross",_("Cross-Hatch Blur"))
1213                 .add_enum_value(Blur::GAUSSIAN,"gaussian",_("Gaussian Blur"))
1214                 .add_enum_value(Blur::DISC,"disc",_("Disc Blur"))
1215         );
1216         ret.push_back(ParamDesc("winding_style")
1217                 .set_local_name(_("Winding Style"))
1218                 .set_description(_("Winding style to use"))
1219                 .set_hint("enum")
1220                 .add_enum_value(WINDING_NON_ZERO,"nonzero",_("Non Zero"))
1221                 .add_enum_value(WINDING_EVEN_ODD,"evenodd",_("Even/Odd"))
1222         );
1223
1224         return ret;
1225 }
1226
1227 synfig::Layer::Handle
1228 Layer_Shape::hit_check(synfig::Context context, const synfig::Point &p)const
1229 {
1230         Point pos(p-offset);
1231
1232         int intercepts = edge_table->intersect(pos[0],pos[1]);
1233
1234         // If we have an odd number of intercepts, we are inside.
1235         // If we have an even number of intercepts, we are outside.
1236         bool intersect = ((!!intercepts) ^ invert);
1237
1238         if(get_amount() == 0 || get_blend_method() == Color::BLEND_ALPHA_OVER)
1239         {
1240                 intersect = false;
1241         }
1242
1243         if(intersect)
1244         {
1245                 synfig::Layer::Handle tmp;
1246                 if(get_blend_method()==Color::BLEND_BEHIND && (tmp=context.hit_check(p)))
1247                         return tmp;
1248                 if(Color::is_onto(get_blend_method()))
1249                 {
1250                         //if there's something in the lower layer then we're set...
1251                         if(!context.hit_check(p).empty())
1252                                 return const_cast<Layer_Shape*>(this);
1253                 }else if(get_blend_method() == Color::BLEND_ALPHA_OVER)
1254                 {
1255                         synfig::info("layer_shape::hit_check - we've got alphaover");
1256                         //if there's something in the lower layer then we're set...
1257                         if(color.get_a() < 0.1 && get_amount() > .9)
1258                         {
1259                                 synfig::info("layer_shape::hit_check - can see through us... so nothing");
1260                                 return Handle();
1261                         }else return context.hit_check(p);
1262                 }else
1263                         return const_cast<Layer_Shape*>(this);
1264         }
1265
1266         return context.hit_check(p);
1267 }
1268
1269 Color
1270 Layer_Shape::get_color(Context context, const Point &p)const
1271 {
1272         Point pp = p;
1273
1274         if(feather)
1275                 pp = Blur(feather,feather,blurtype)(p);
1276
1277         Point pos(pp-offset);
1278
1279         int intercepts = edge_table->intersect(pos[0],pos[1]);
1280
1281         // If we have an odd number of intercepts, we are inside.
1282         // If we have an even number of intercepts, we are outside.
1283         bool intersect = ((!!intercepts) ^ invert);
1284
1285         if(!intersect)
1286                 return context.get_color(pp);
1287
1288         //Ok, we're inside... bummmm ba bum buM...
1289         if(get_blend_method() == Color::BLEND_STRAIGHT && get_amount() == 1)
1290                 return color;
1291         else
1292                 return Color::blend(color,context.get_color(p),get_amount(),get_blend_method());
1293 }
1294
1295 //************** SCANLINE RENDERING *********************
1296 void Layer_Shape::PolySpan::line_to(Real x, Real y)
1297 {
1298         Real n[4] = {0,0,0,0};
1299         bool afterx = false;
1300
1301         const Real xin(x), yin(y);
1302
1303         Real dx = x - cur_x;
1304         Real dy = y - cur_y;
1305
1306         //CLIP IT!!!!
1307         try {
1308         //outside y - ignore entirely
1309         if(      (cur_y >= window.maxy && y >= window.maxy)
1310            ||(cur_y <  window.miny && y <  window.miny) )
1311         {
1312                 cur_x = x;
1313                 cur_y = y;
1314         }
1315         else //not degenerate - more complicated
1316         {
1317                 if(dy > 0) //be sure it's not tooooo small
1318                 {
1319                         // cur_y ... window.miny ... window.maxy ... y
1320
1321                         //initial degenerate - initial clip
1322                         if(cur_y < window.miny)
1323                         {
1324                                 //new clipped start point (must also move pen)
1325                                 n[2] = cur_x + (window.miny - cur_y) * dx / dy;
1326
1327                                 cur_x = n[2];
1328                                 cur_y = window.miny;
1329                                 move_pen((int)floor(cur_x),window.miny);
1330                         }
1331
1332                         //generate data for the ending clipped info
1333                         if(y > window.maxy)
1334                         {
1335                                 //initial line to intersection (and degenerate)
1336                                 n[2] = x + (window.maxy - y) * dx / dy;
1337
1338                                 //intersect coords
1339                                 x = n[2];
1340                                 y = window.maxy;
1341                         }
1342                 }
1343                 else
1344                 {
1345                         //initial degenerate - initial clip
1346                         if(cur_y > window.maxy)
1347                         {
1348                                 //new clipped start point (must also move pen)
1349                                 n[2] = cur_x + (window.maxy - cur_y) * dx / dy;
1350
1351                                 cur_x = n[2];
1352                                 cur_y = window.maxy;
1353                                 move_pen((int)floor(cur_x),window.maxy);
1354                         }
1355
1356                         //generate data for the ending clipped info
1357                         if(y < window.miny)
1358                         {
1359                                 //initial line to intersection (and degenerate)
1360                                 n[2] = x + (window.miny - y) * dx / dy;
1361
1362                                 //intersect coords
1363                                 x = n[2];
1364                                 y = window.miny;
1365                         }
1366                 }
1367
1368                 //all degenerate - but require bounded clipped values
1369                 if(   (cur_x >= window.maxx && x >= window.maxx)
1370                         ||(cur_x <  window.minx && x <  window.minx) )
1371                 {
1372                         //clip both vertices - but only needed in the x direction
1373                         cur_x = max(cur_x,      (Real)window.minx);
1374                         cur_x = min(cur_x,      (Real)window.maxx);
1375
1376                         //clip the dest values - y is already clipped
1377                         x = max(x,(Real)window.minx);
1378                         x = min(x,(Real)window.maxx);
1379
1380                         //must start at new point...
1381                         move_pen((int)floor(cur_x),(int)floor(cur_y));
1382
1383                         draw_line(cur_x,cur_y,x,y);
1384
1385                         cur_x = xin;
1386                         cur_y = yin;
1387                 }
1388                 else
1389                 {
1390                         //clip x
1391                         if(dx > 0)
1392                         {
1393                                 //initial degenerate - initial clip
1394                                 if(cur_x < window.minx)
1395                                 {
1396                                         //need to draw an initial segment from clippedx,cur_y to clippedx,intersecty
1397                                         n[2] = cur_y + (window.minx - cur_x) * dy / dx;
1398
1399                                         move_pen(window.minx,(int)floor(cur_y));
1400                                         draw_line(window.minx,cur_y,window.minx,n[2]);
1401
1402                                         cur_x = window.minx;
1403                                         cur_y = n[2];
1404                                 }
1405
1406                                 //generate data for the ending clipped info
1407                                 if(x > window.maxx)
1408                                 {
1409                                         //initial line to intersection (and degenerate)
1410                                         n[2] = y + (window.maxx - x) * dy / dx;
1411
1412                                         n[0] = window.maxx;
1413                                         n[1] = y;
1414
1415                                         //intersect coords
1416                                         x = window.maxx;
1417                                         y = n[2];
1418                                         afterx = true;
1419                                 }
1420                         }else
1421                         {
1422                                 //initial degenerate - initial clip
1423                                 if(cur_x > window.maxx)
1424                                 {
1425                                         //need to draw an initial segment from clippedx,cur_y to clippedx,intersecty
1426                                         n[2] = cur_y + (window.maxx - cur_x) * dy / dx;
1427
1428                                         move_pen(window.maxx,(int)floor(cur_y));
1429                                         draw_line(window.maxx,cur_y,window.maxx,n[2]);
1430
1431                                         cur_x = window.maxx;
1432                                         cur_y = n[2];
1433                                 }
1434
1435                                 //generate data for the ending clipped info
1436                                 if(x < window.minx)
1437                                 {
1438                                         //initial line to intersection (and degenerate)
1439                                         n[2] = y + (window.minx - x) * dy / dx;
1440
1441                                         n[0] = window.minx;
1442                                         n[1] = y;
1443
1444                                         //intersect coords
1445                                         x = window.minx;
1446                                         y = n[2];
1447                                         afterx = true;
1448                                 }
1449                         }
1450
1451                         move_pen((int)floor(cur_x),(int)floor(cur_y));
1452                         //draw the relevant line (clipped)
1453                         draw_line(cur_x,cur_y,x,y);
1454
1455                         if(afterx)
1456                         {
1457                                 draw_line(x,y,n[0],n[1]);
1458                         }
1459
1460                         cur_x = xin;
1461                         cur_y = yin;
1462                 }
1463         }
1464         } catch(...) { synfig::error("line_to: cur_x=%f, cur_y=%f, x=%f, y=%f", cur_x, cur_y, x, y); throw; }
1465
1466         flags |= NotClosed|NotSorted;
1467 }
1468
1469 static inline bool clip_conic(const Point *const p, const ContextRect &r)
1470 {
1471         const Real minx = min(min(p[0][0],p[1][0]),p[2][0]);
1472         const Real miny = min(min(p[0][1],p[1][1]),p[2][1]);
1473         const Real maxx = max(max(p[0][0],p[1][0]),p[2][0]);
1474         const Real maxy = max(max(p[0][1],p[1][1]),p[2][1]);
1475
1476         return  (minx > r.maxx) ||
1477                         (maxx < r.minx) ||
1478                         (miny > r.maxy) ||
1479                         (maxy < r.miny);
1480 }
1481
1482 static inline bool clip_cubic(const Point *const p, const ContextRect &r)
1483 {
1484         /*const Real minx = min(min(p[0][0],p[1][0]),min(p[2][0],p[3][0]));
1485         const Real miny = min(min(p[0][1],p[1][1]),min(p[2][1],p[3][1]));
1486         const Real maxx = max(max(p[0][0],p[1][0]),max(p[2][0],p[3][1]));
1487         const Real maxy = max(max(p[0][1],p[1][1]),max(p[2][1],p[3][1]));
1488
1489         return  (minx > r.maxx) ||
1490                         (maxx < r.minx) ||
1491                         (miny > r.maxy) ||
1492                         (maxy < r.miny);*/
1493
1494         return  ((p[0][0] > r.maxx) && (p[1][0] > r.maxx) && (p[2][0] > r.maxx) && (p[3][0] > r.maxx)) ||
1495                         ((p[0][0] < r.minx) && (p[1][0] < r.minx) && (p[2][0] < r.minx) && (p[3][0] < r.minx)) ||
1496                         ((p[0][1] > r.maxy) && (p[1][1] > r.maxy) && (p[2][1] > r.maxy) && (p[3][1] > r.maxy)) ||
1497                         ((p[0][1] < r.miny) && (p[1][1] < r.miny) && (p[2][1] < r.miny) && (p[3][1] < r.miny));
1498 }
1499
1500 static inline Real max_edges_cubic(const Point *const p)
1501 {
1502         const Real x1 = p[1][0] - p[0][0];
1503         const Real y1 = p[1][1] - p[0][1];
1504
1505         const Real x2 = p[2][0] - p[1][0];
1506         const Real y2 = p[2][1] - p[1][1];
1507
1508         const Real x3 = p[3][0] - p[2][0];
1509         const Real y3 = p[3][1] - p[2][1];
1510
1511         const Real d1 = x1*x1 + y1*y1;
1512         const Real d2 = x2*x2 + y2*y2;
1513         const Real d3 = x3*x3 + y3*y3;
1514
1515         return max(max(d1,d2),d3);
1516 }
1517
1518 static inline Real max_edges_conic(const Point *const p)
1519 {
1520         const Real x1 = p[1][0] - p[0][0];
1521         const Real y1 = p[1][1] - p[0][1];
1522
1523         const Real x2 = p[2][0] - p[1][0];
1524         const Real y2 = p[2][1] - p[1][1];
1525
1526         const Real d1 = x1*x1 + y1*y1;
1527         const Real d2 = x2*x2 + y2*y2;
1528
1529         return max(d1,d2);
1530 }
1531
1532 void Layer_Shape::PolySpan::conic_to(Real x1, Real y1, Real x, Real y)
1533 {
1534         Point *current = arc;
1535         int             level = 0;
1536         int     num = 0;
1537         bool    onsecond = false;
1538
1539         arc[0] = Point(x,y);
1540         arc[1] = Point(x1,y1);
1541         arc[2] = Point(cur_x,cur_y);
1542
1543         //just draw the line if it's outside
1544         if(clip_conic(arc,window))
1545         {
1546                 line_to(x,y);
1547                 return;
1548         }
1549
1550         //Ok so it's not super degenerate, subdivide and draw (run through minimum subdivision levels first)
1551         while(current >= arc)
1552         {
1553                 if(num >= MAX_SUBDIVISION_SIZE)
1554                 {
1555                         warning("Curve subdivision somehow ran out of space while tessellating!");
1556
1557                         //do something...
1558                         assert(0);
1559                         return;
1560                 }else
1561                 //if the curve is clipping then draw degenerate
1562                 if(clip_conic(current,window))
1563                 {
1564                         line_to(current[0][0],current[0][1]); //backwards so front is destination
1565                         current -= 2;
1566                         if(onsecond) level--;
1567                         onsecond = true;
1568                         num--;
1569                         continue;
1570                 }else
1571                 //if we are not at the level minimum
1572                 if(level < MIN_SUBDIVISION_DRAW_LEVELS)
1573                 {
1574                         Subd_Conic_Stack(current);
1575                         current += 2;           //cursor on second curve
1576                         level ++;
1577                         num ++;
1578                         onsecond = false;
1579                         continue;
1580                 }else
1581                 //split it again, if it's too big
1582                 if(max_edges_conic(current) > 0.25) //distance of .5 (cover no more than half the pixel)
1583                 {
1584                         Subd_Conic_Stack(current);
1585                         current += 2;           //cursor on second curve
1586                         level ++;
1587                         num ++;
1588                         onsecond = false;
1589                 }
1590                 else    //NOT TOO BIG? RENDER!!!
1591                 {
1592                         //cur_x,cur_y = current[2], so we need to go 1,0
1593                         line_to(current[1][0],current[1][1]);
1594                         line_to(current[0][0],current[0][1]);
1595
1596                         current -= 2;
1597                         if(onsecond) level--;
1598                         num--;
1599                         onsecond = true;
1600                 }
1601         }
1602 }
1603
1604 void Layer_Shape::PolySpan::cubic_to(Real x1, Real y1, Real x2, Real y2, Real x, Real y)
1605 {
1606         Point *current = arc;
1607         int             num = 0;
1608         int             level = 0;
1609         bool    onsecond = false;
1610
1611         arc[0] = Point(x,y);
1612         arc[1] = Point(x2,y2);
1613         arc[2] = Point(x1,y1);
1614         arc[3] = Point(cur_x,cur_y);
1615
1616         //just draw the line if it's outside
1617         if(clip_cubic(arc,window))
1618         {
1619                 line_to(x,y);
1620                 return;
1621         }
1622
1623         //Ok so it's not super degenerate, subdivide and draw (run through minimum subdivision levels first)
1624         while(current >= arc) //once current goes below arc, there are no more curves left
1625         {
1626                 if(num >= MAX_SUBDIVISION_SIZE)
1627                 {
1628                         warning("Curve subdivision somehow ran out of space while tessellating!");
1629
1630                         //do something...
1631                         assert(0);
1632                         return;
1633                 }else
1634
1635                 //if we are not at the level minimum
1636                 if(level < MIN_SUBDIVISION_DRAW_LEVELS)
1637                 {
1638                         Subd_Cubic_Stack(current);
1639                         current += 3;           //cursor on second curve
1640                         level ++;
1641                         num ++;
1642                         onsecond = false;
1643                         continue;
1644                 }else
1645                 //if the curve is clipping then draw degenerate
1646                 if(clip_cubic(current,window))
1647                 {
1648                         line_to(current[0][0],current[0][1]); //backwards so front is destination
1649                         current -= 3;
1650                         if(onsecond) level--;
1651                         onsecond = true;
1652                         num --;
1653                         continue;
1654                 }
1655                 else
1656                 //split it again, if it's too big
1657                 if(max_edges_cubic(current) > 0.25) //could use max_edges<3>
1658                 {
1659                         Subd_Cubic_Stack(current);
1660                         current += 3;           //cursor on second curve
1661                         level ++;
1662                         num ++;
1663                         onsecond = false;
1664                 }
1665                 else //NOT TOO BIG? RENDER!!!
1666                 {
1667                         //cur_x,cur_y = current[3], so we need to go 2,1,0
1668                         line_to(current[2][0],current[2][1]);
1669                         line_to(current[1][0],current[1][1]);
1670                         line_to(current[0][0],current[0][1]);
1671
1672                         current -= 3;
1673                         if(onsecond) level--;
1674                         num --;
1675                         onsecond = true;
1676                 }
1677         }
1678 }
1679
1680 //******************** LINE ALGORITHMS ****************************
1681 // THESE CALCULATE THE AREA AND THE COVER FOR THE MARKS, TO THEN SCAN CONVERT
1682 // - BROKEN UP INTO SCANLINES (draw_line - y intersections),
1683 //   THEN THE COVER AND AREA PER TOUCHED PIXEL IS CALCULATED (draw_scanline - x intersections)
1684 void Layer_Shape::PolySpan::draw_scanline(int y, Real x1, Real fy1, Real x2, Real fy2)
1685 {
1686         int     ix1 = (int)floor(x1);
1687         int     ix2 = (int)floor(x2);
1688         Real fx1 = x1 - ix1;
1689         Real fx2 = x2 - ix2;
1690
1691         Real dx,dy,dydx,mult;
1692
1693         dx = x2 - x1;
1694         dy = fy2 - fy1;
1695
1696         //case horizontal line
1697         if(fy1 == fy2)
1698         {
1699                 move_pen(ix2,y); //pen needs to be at the last coord
1700                 return;
1701         }
1702
1703         //case all in same pixel
1704         if(ix1 == ix2)  //impossible for degenerate case (covered by the previous cases)
1705         {
1706                 current.addcover(dy,(fx1 + fx2)*dy/2); //horizontal trapezoid area
1707                 return;
1708         }
1709
1710         if(dx > 0)
1711         {
1712                 // ---->        fx1...1  0...1  ...  0...1  0...fx2
1713                 dydx = dy / dx;
1714
1715                 //set initial values
1716                 //Iterate through the covered pixels
1717                 mult = (1 - fx1)*dydx;  //next y intersection diff value (at 1)
1718
1719                 //first pixel
1720                 current.addcover(mult,(1 + fx1)*mult/2);        // fx1,fy1,1,fy@1 - starting trapezoidal area
1721
1722                 //move to the next pixel
1723                 fy1 += mult;
1724                 ix1++;
1725
1726                 move_pen(ix1,y);
1727
1728                 //set up for whole ones
1729                 while(ix1 != ix2)
1730                 {
1731                         //trapezoid(0,y1,1,y1+dydx);
1732                         current.addcover(dydx,dydx/2);  //accumulated area 1/2 the cover
1733
1734                         //move to next pixel (+1)
1735                         ix1++;
1736                         fy1 += dydx;
1737                         move_pen(ix1,y);
1738                 }
1739
1740                 //last pixel
1741                 //final y-pos - last intersect pos
1742                 mult = fx2 * dydx;
1743                 current.addcover(mult,(0+fx2)*mult/2);
1744         }else
1745         {
1746                 // fx2...1  0...1  ...  0...1  0...fx1   <----
1747                 //mult = (0 - fx1) * dy / dx;
1748                 //neg sign sucked into dydx
1749                 dydx = -dy / dx;
1750
1751                 //set initial values
1752                 //Iterate through the covered pixels
1753                 mult = fx1*dydx;        //next y intersection diff value
1754
1755                 //first pixel
1756                 current.addcover(mult,fx1*mult/2);      // fx1,fy1,0,fy@0 - starting trapezoidal area
1757
1758                 //move to next pixel
1759                 fy1 += mult;
1760                 ix1--;
1761
1762                 move_pen(ix1,y);
1763
1764                 //set up for whole ones
1765                 while(ix1 != ix2)
1766                 {
1767                         //trapezoid(0,y1,1,y1+dydx);
1768                         current.addcover(dydx,dydx/2);  //accumulated area 1/2 the cover
1769
1770                         //move to next pixel (-1)
1771                         fy1 += dydx;
1772                         ix1--;
1773                         move_pen(ix1,y);
1774                 }
1775
1776                 //last pixel
1777                 mult = fy2 - fy1; //final y-pos - last intersect pos
1778
1779                 current.addcover(mult,(fx2+1)*mult/2);
1780         }
1781 }
1782
1783 void Layer_Shape::PolySpan::draw_line(Real x1, Real y1, Real x2, Real y2)
1784 {
1785         int iy1 = (int)floor(y1);
1786         int iy2 = (int)floor(y2);
1787         Real fy1 = y1 - iy1;
1788         Real fy2 = y2 - iy2;
1789
1790         assert(!isnan(fy1));
1791         assert(!isnan(fy2));
1792
1793         Real dx,dy,dxdy,mult,x_from,x_to;
1794
1795         const Real SLOPE_EPSILON = 1e-10;
1796
1797         //case all one scanline
1798         if(iy1 == iy2)
1799         {
1800                 draw_scanline(iy1,x1,y1,x2,y2);
1801                 return;
1802         }
1803
1804         //difference values
1805         dy = y2 - y1;
1806         dx = x2 - x1;
1807
1808         //case vertical line
1809         if(dx < SLOPE_EPSILON && dx > -SLOPE_EPSILON)
1810         {
1811                 //calc area and cover on vertical line
1812                 if(dy > 0)
1813                 {
1814                         // ---->        fx1...1  0...1  ...  0...1  0...fx2
1815                         Real sub;
1816
1817                         int      ix1 = (int)floor(x1);
1818                         Real fx1 = x1 - ix1;
1819
1820                         //current pixel
1821                         sub = 1 - fy1;
1822
1823                         current.addcover(sub,fx1*sub);
1824
1825                         //next pixel
1826                         iy1++;
1827
1828                         //move pen to next pixel
1829                         move_pen(ix1,iy1);
1830
1831                         while(iy1 != iy2)
1832                         {
1833                                 //accumulate cover
1834                                 current.addcover(1,fx1);
1835
1836                                 //next pixel
1837                                 iy1++;
1838                                 move_pen(ix1,iy1);
1839                         }
1840
1841                         //last pixel
1842                         current.addcover(fy2,fy2*fx1);
1843                 }else
1844                 {
1845                         Real sub;
1846
1847                         int      ix1 = (int)floor(x1);
1848                         Real fx1 = x1 - ix1;
1849
1850                         //current pixel
1851                         sub = 0 - fy1;
1852
1853                         current.addcover(sub,fx1*sub);
1854
1855                         //next pixel
1856                         iy1--;
1857
1858                         move_pen(ix1,iy1);
1859
1860                         while(iy1 != iy2)
1861                         {
1862                                 //accumulate in current pixel
1863                                 current.addcover(-1,-fx1);
1864
1865                                 //move to next
1866                                 iy1--;
1867                                 move_pen(ix1,iy1);
1868                         }
1869
1870                         current.addcover(fy2-1,(fy2-1)*fx1);
1871                 }
1872                 return;
1873         }
1874
1875         //case normal line - guaranteed dx != 0 && dy != 0
1876
1877         //calculate the initial intersection with "next" scanline
1878         if(dy > 0)
1879         {
1880                 dxdy = dx / dy;
1881
1882                 mult = (1 - fy1) * dxdy;
1883
1884                 //x intersect scanline
1885                 x_from = x1 + mult;
1886                 draw_scanline(iy1,x1,fy1,x_from,1);
1887
1888                 //move to next line
1889                 iy1++;
1890
1891                 move_pen((int)floor(x_from),iy1);
1892
1893                 while(iy1 != iy2)
1894                 {
1895                         //keep up on the x axis, and render the current scanline
1896                         x_to = x_from + dxdy;
1897                         draw_scanline(iy1,x_from,0,x_to,1);
1898                         x_from = x_to;
1899
1900                         //move to next pixel
1901                         iy1++;
1902                         move_pen((int)floor(x_from),iy1);
1903                 }
1904
1905                 //draw the last one, fractional
1906                 draw_scanline(iy2,x_from,0,x2,fy2);
1907
1908         }else
1909         {
1910                 dxdy = -dx / dy;
1911
1912                 mult = fy1 * dxdy;
1913
1914                 //x intersect scanline
1915                 x_from = x1 + mult;
1916                 draw_scanline(iy1,x1,fy1,x_from,0);
1917
1918                 //each line after
1919                 iy1--;
1920
1921                 move_pen((int)floor(x_from),iy1);
1922
1923                 while(iy1 != iy2)
1924                 {
1925                         x_to = x_from + dxdy;
1926                         draw_scanline(iy1,x_from,1,x_to,0);
1927                         x_from = x_to;
1928
1929                         iy1--;
1930                         move_pen((int)floor(x_from),iy1);
1931                 }
1932                 //draw the last one, fractional
1933                 draw_scanline(iy2,x_from,1,x2,fy2);
1934         }
1935 }
1936
1937 //****** LAYER PEN OPERATIONS (move_to, line_to, etc.) ******
1938 void Layer_Shape::move_to(Real x, Real y)
1939 {
1940         //const int sizeblock = sizeof(Primitive)+sizeof(Point);
1941         Primitive       op;
1942         Point           p(x,y);
1943
1944         op.operation = Primitive::MOVE_TO;
1945         op.number = 1;  //one point for now
1946
1947         if(lastbyteop == Primitive::MOVE_TO)
1948         {
1949                 char *ptr = &bytestream[lastoppos];
1950                 memcpy(ptr,&op,sizeof(op));
1951                 memcpy(ptr+sizeof(op),&p,sizeof(p));
1952         }
1953         else //make a new op
1954         {
1955                 lastbyteop = Primitive::MOVE_TO;
1956                 lastoppos = bytestream.size();
1957
1958                 bytestream.insert(bytestream.end(),(char*)&op,(char*)(&op+1));  //insert the bytes for the header
1959                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));    //insert the bytes for data
1960         }
1961
1962         edge_table->move_to(x,y);
1963 }
1964
1965 void Layer_Shape::close()
1966 {
1967         Primitive op;
1968
1969         op.operation = Primitive::CLOSE;
1970         op.number = 0;
1971
1972         if(lastbyteop == Primitive::CLOSE)
1973         {
1974         }else
1975         {
1976                 lastbyteop = Primitive::CLOSE;
1977                 lastoppos = bytestream.size();
1978
1979                 bytestream.insert(bytestream.end(),(char*)&op,(char*)(&op+1)); //insert header
1980         }
1981
1982         edge_table->close();
1983         //should not affect the bounding box since it would just be returning to old point...
1984 }
1985
1986 void Layer_Shape::endpath()
1987 {
1988         Primitive op;
1989
1990         op.operation = Primitive::END;
1991         op.number = 0;
1992
1993         if(lastbyteop == Primitive::END || lastbyteop == Primitive::NONE)
1994         {
1995         }else
1996         {
1997                 bytestream.insert(bytestream.end(),(char*)&op,(char*)(&op+1));
1998         }
1999         //should not affect the bounding box since it would just be returning to old point... if at all
2000 }
2001
2002 void Layer_Shape::line_to(Real x, Real y)
2003 {
2004         assert(!isnan(x));
2005         assert(!isnan(y));
2006
2007         //const int sizeblock = sizeof(Primitive)+sizeof(Point);
2008         Primitive       op;
2009         Point           p(x,y);
2010
2011         op.operation = Primitive::LINE_TO;
2012         op.number = 1;  //one point for now
2013
2014         if(lastbyteop == Primitive::MOVE_TO || lastbyteop == Primitive::LINE_TO)
2015         {
2016                 //only need to insert the point
2017                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));
2018
2019                 Primitive * prim = (Primitive *)&bytestream[lastoppos];
2020                 prim->number++; //increment number of points in the list
2021         }else
2022         {
2023                 lastbyteop = Primitive::LINE_TO;
2024                 lastoppos = bytestream.size();
2025
2026                 bytestream.insert(bytestream.end(),(char*)&op,(char*)(&op+1));  //insert the bytes for the header
2027                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));    //insert the bytes for data
2028         }
2029
2030         edge_table->line_to(x,y);
2031 }
2032
2033 void Layer_Shape::conic_to(Real x1, Real y1, Real x, Real y)
2034 {
2035         //const int sizeblock = sizeof(Primitive)+sizeof(Point)*2;
2036         Primitive       op;
2037         Point           p(x,y);
2038         Point           p1(x1,y1);
2039
2040         op.operation = Primitive::CONIC_TO;
2041         op.number = 2;  //2 points for now
2042
2043         if(lastbyteop == Primitive::CONIC_TO)
2044         {
2045                 //only need to insert the new points
2046                 bytestream.insert(bytestream.end(),(char*)&p1,(char*)(&p1+1));
2047                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));
2048
2049                 Primitive * prim = (Primitive *)&bytestream[lastoppos];
2050                 prim->number += 2; //increment number of points in the list
2051         }else
2052         {
2053                 lastbyteop = Primitive::CONIC_TO;
2054                 lastoppos = bytestream.size();
2055
2056                 bytestream.insert(bytestream.end(),(char*)&op,(char*)(&op+1));  //insert the bytes for the header
2057                 bytestream.insert(bytestream.end(),(char*)&p1,(char*)(&p1+1));  //insert the bytes for data
2058                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));    //insert the bytes for data
2059         }
2060
2061         edge_table->conic_to(x1,y1,x,y);
2062 }
2063
2064 void Layer_Shape::conic_to_smooth(Real x, Real y)                               //x1,y1 derived from current tangent
2065 {
2066         //const int sizeblock = sizeof(Primitive)+sizeof(Point);
2067         Primitive       op;
2068         Point           p(x,y);
2069
2070         op.operation = Primitive::CONIC_TO_SMOOTH;
2071         op.number = 1;  //2 points for now
2072
2073         if(lastbyteop == Primitive::CONIC_TO_SMOOTH)
2074         {
2075                 //only need to insert the new point
2076                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));
2077
2078                 Primitive * prim = (Primitive *)&bytestream[lastoppos];
2079                 prim->number += 1; //increment number of points in the list
2080         }else
2081         {
2082                 lastbyteop = Primitive::CONIC_TO_SMOOTH;
2083                 lastoppos = bytestream.size();
2084
2085                 bytestream.insert(bytestream.end(),(char*)&op,(char*)(&op+1));  //insert the bytes for the header
2086                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));    //insert the bytes for data
2087         }
2088
2089         edge_table->conic_to_smooth(x,y);
2090 }
2091
2092 void Layer_Shape::curve_to(Real x1, Real y1, Real x2, Real y2, Real x, Real y)
2093 {
2094         //const int sizeblock = sizeof(Primitive)+sizeof(Point)*3;
2095         Primitive       op;
2096         Point           p(x,y);
2097         Point           p1(x1,y1);
2098         Point           p2(x2,y2);
2099
2100         op.operation = Primitive::CUBIC_TO;
2101         op.number = 3;  //3 points for now
2102
2103         if(lastbyteop == Primitive::CUBIC_TO)
2104         {
2105                 //only need to insert the new points
2106                 bytestream.insert(bytestream.end(),(char*)&p1,(char*)(&p1+1));
2107                 bytestream.insert(bytestream.end(),(char*)&p2,(char*)(&p2+1));
2108                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));
2109
2110                 Primitive * prim = (Primitive *)&bytestream[lastoppos];
2111                 prim->number += 3; //increment number of points in the list
2112         }else
2113         {
2114                 lastbyteop = Primitive::CUBIC_TO;
2115                 lastoppos = bytestream.size();
2116
2117                 bytestream.insert(bytestream.end(),(char*)&op,(char*)(&op+1));  //insert the bytes for the header
2118                 bytestream.insert(bytestream.end(),(char*)&p1,(char*)(&p1+1));  //insert the bytes for data
2119                 bytestream.insert(bytestream.end(),(char*)&p2,(char*)(&p2+1));  //insert the bytes for data
2120                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));    //insert the bytes for data
2121         }
2122
2123         edge_table->curve_to(x1,y1,x2,y2,x,y);
2124 }
2125
2126 void Layer_Shape::curve_to_smooth(Real x2, Real y2, Real x, Real y)             //x1,y1 derived from current tangent
2127 {
2128         //const int sizeblock = sizeof(Primitive)+sizeof(Point)*3;
2129         Primitive       op;
2130         Point           p(x,y);
2131         Point           p2(x2,y2);
2132
2133         op.operation = Primitive::CUBIC_TO_SMOOTH;
2134         op.number = 2;  //3 points for now
2135
2136         if(lastbyteop == Primitive::CUBIC_TO_SMOOTH)
2137         {
2138                 //only need to insert the new points
2139                 bytestream.insert(bytestream.end(),(char*)&p2,(char*)(&p2+1));
2140                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));
2141
2142                 Primitive * prim = (Primitive *)&bytestream[lastoppos];
2143                 prim->number += 2; //increment number of points in the list
2144         }else
2145         {
2146                 lastbyteop = Primitive::CUBIC_TO_SMOOTH;
2147                 lastoppos = bytestream.size();
2148
2149                 bytestream.insert(bytestream.end(),(char*)&op,(char*)(&op+1));  //insert the bytes for the header
2150                 bytestream.insert(bytestream.end(),(char*)&p2,(char*)(&p2+1));  //insert the bytes for data
2151                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));    //insert the bytes for data
2152         }
2153 }
2154
2155 // ACCELERATED RENDER FUNCTION - TRANSLATE BYTE CODE INTO FUNCTION CALLS
2156
2157 bool Layer_Shape::render_polyspan(Surface *surface, PolySpan &polyspan,
2158                                                                 Color::BlendMethod got_blend_method, Color::value_type got_amount) const
2159 {
2160         Surface::alpha_pen p(surface->begin(),got_amount,_BlendFunc(got_blend_method));
2161         PolySpan::cover_array::iterator cur_mark = polyspan.covers.begin();
2162         PolySpan::cover_array::iterator end_mark = polyspan.covers.end();
2163
2164         Real cover,area,alpha;
2165
2166         int     y,x;
2167
2168         p.set_value(color);
2169         cover = 0;
2170
2171         if(cur_mark == end_mark)
2172         {
2173                 //no marks at all
2174                 if(invert)
2175                 {
2176                         p.move_to(polyspan.window.minx,polyspan.window.miny);
2177                         p.put_block(polyspan.window.maxy - polyspan.window.miny,polyspan.window.maxx - polyspan.window.minx);
2178                 }
2179                 return true;
2180         }
2181
2182         //fill initial rect / line
2183         if(invert)
2184         {
2185                 //fill all the area above the first vertex
2186                 p.move_to(polyspan.window.minx,polyspan.window.miny);
2187                 y = polyspan.window.miny;
2188                 int l = polyspan.window.maxx - polyspan.window.minx;
2189
2190                 p.put_block(cur_mark->y - polyspan.window.miny,l);
2191
2192                 //fill the area to the left of the first vertex on that line
2193                 l = cur_mark->x - polyspan.window.minx;
2194                 p.move_to(polyspan.window.minx,cur_mark->y);
2195                 if(l) p.put_hline(l);
2196         }
2197
2198         for(;;)
2199         {
2200                 y = cur_mark->y;
2201                 x = cur_mark->x;
2202
2203                 p.move_to(x,y);
2204
2205                 area = cur_mark->area;
2206                 cover += cur_mark->cover;
2207
2208                 //accumulate for the current pixel
2209                 while(++cur_mark != polyspan.covers.end())
2210                 {
2211                         if(y != cur_mark->y || x != cur_mark->x)
2212                                 break;
2213
2214                         area += cur_mark->area;
2215                         cover += cur_mark->cover;
2216                 }
2217
2218                 //draw pixel - based on covered area
2219                 if(area)        //if we're ok, draw the current pixel
2220                 {
2221                         alpha = polyspan.ExtractAlpha(cover - area, winding_style);
2222                         if(invert) alpha = 1 - alpha;
2223
2224                         if(!antialias)
2225                         {
2226                                 if(alpha >= .5) p.put_value();
2227                         }
2228                         else if(alpha) p.put_value_alpha(alpha);
2229
2230                         p.inc_x();
2231                         x++;
2232                 }
2233
2234                 //if we're done, don't use iterator and exit
2235                 if(cur_mark == end_mark) break;
2236
2237                 //if there is no more live pixels on this line, goto next
2238                 if(y != cur_mark->y)
2239                 {
2240                         if(invert)
2241                         {
2242                                 //fill the area at the end of the line
2243                                 p.put_hline(polyspan.window.maxx - x);
2244
2245                                 //fill area at the beginning of the next line
2246                                 p.move_to(polyspan.window.minx,cur_mark->y);
2247                                 p.put_hline(cur_mark->x - polyspan.window.minx);
2248                         }
2249
2250                         cover = 0;
2251
2252                         continue;
2253                 }
2254
2255                 //draw span to next pixel - based on total amount of pixel cover
2256                 if(x < cur_mark->x)
2257                 {
2258                         alpha = polyspan.ExtractAlpha(cover, winding_style);
2259                         if(invert) alpha = 1 - alpha;
2260
2261                         if(!antialias)
2262                         {
2263                                 if(alpha >= .5) p.put_hline(cur_mark->x - x);
2264                         }
2265                         else if(alpha) p.put_hline(cur_mark->x - x,alpha);
2266                 }
2267         }
2268
2269         //fill the after stuff
2270         if(invert)
2271         {
2272                 //fill the area at the end of the line
2273                 p.put_hline(polyspan.window.maxx - x);
2274
2275                 //fill area at the beginning of the next line
2276                 p.move_to(polyspan.window.minx,y+1);
2277                 p.put_block(polyspan.window.maxy - y - 1,polyspan.window.maxx - polyspan.window.minx);
2278         }
2279
2280         return true;
2281 }
2282
2283 bool Layer_Shape::render_polyspan(etl::surface<float> *surface, PolySpan &polyspan) const
2284 {
2285         etl::surface<float>::pen p(surface->begin());
2286         PolySpan::cover_array::iterator cur_mark = polyspan.covers.begin();
2287         PolySpan::cover_array::iterator end_mark = polyspan.covers.end();
2288
2289         Real cover,area,alpha;
2290
2291         int     y,x;
2292
2293         cover = 0;
2294
2295         //the pen always writes 1 (unless told to do otherwise)
2296         p.set_value(1);
2297
2298         if(cur_mark == end_mark)
2299         {
2300                 //no marks at all
2301                 if(invert)
2302                 {
2303                         p.move_to(polyspan.window.minx,polyspan.window.miny);
2304                         p.put_block(polyspan.window.maxy - polyspan.window.miny,polyspan.window.maxx - polyspan.window.minx);
2305                 }
2306                 return true;
2307         }
2308
2309         //fill initial rect / line
2310         if(invert)
2311         {
2312                 //fill all the area above the first vertex
2313                 p.move_to(polyspan.window.minx,polyspan.window.miny);
2314                 y = polyspan.window.miny;
2315                 int l = polyspan.window.maxx - polyspan.window.minx;
2316
2317                 p.put_block(cur_mark->y - polyspan.window.miny,l);
2318
2319                 //fill the area to the left of the first vertex on that line
2320                 l = cur_mark->x - polyspan.window.minx;
2321                 p.move_to(polyspan.window.minx,cur_mark->y);
2322                 if(l) p.put_hline(l);
2323
2324                 for(;;)
2325                 {
2326                         y = cur_mark->y;
2327                         x = cur_mark->x;
2328
2329                         p.move_to(x,y);
2330
2331                         area = cur_mark->area;
2332                         cover += cur_mark->cover;
2333
2334                         //accumulate for the current pixel
2335                         while(++cur_mark != polyspan.covers.end())
2336                         {
2337                                 if(y != cur_mark->y || x != cur_mark->x)
2338                                         break;
2339
2340                                 area += cur_mark->area;
2341                                 cover += cur_mark->cover;
2342                         }
2343
2344                         //draw pixel - based on covered area
2345                         if(area)        //if we're ok, draw the current pixel
2346                         {
2347                                 alpha = 1 - polyspan.ExtractAlpha(cover - area, winding_style);
2348                                 if(!antialias)
2349                                 {
2350                                         if(alpha >= .5) p.put_value();
2351                                 }
2352                                 else if(alpha) p.put_value(alpha);
2353
2354                                 p.inc_x();
2355                                 x++;
2356                         }
2357
2358                         //if we're done, don't use iterator and exit
2359                         if(cur_mark == end_mark) break;
2360
2361                         //if there is no more live pixels on this line, goto next
2362                         if(y != cur_mark->y)
2363                         {
2364                                 //fill the area at the end of the line
2365                                 p.put_hline(polyspan.window.maxx - x);
2366
2367                                 //fill area at the beginning of the next line
2368                                 p.move_to(polyspan.window.minx,cur_mark->y);
2369                                 p.put_hline(cur_mark->x - polyspan.window.minx);
2370
2371                                 cover = 0;
2372
2373                                 continue;
2374                         }
2375
2376                         //draw span to next pixel - based on total amount of pixel cover
2377                         if(x < cur_mark->x)
2378                         {
2379                                 alpha = 1 - polyspan.ExtractAlpha(cover, winding_style);
2380                                 if(!antialias)
2381                                 {
2382                                         if(alpha >= .5) p.put_hline(cur_mark->x - x);
2383                                 }
2384                                 else if(alpha) p.put_hline(cur_mark->x - x,alpha);
2385                         }
2386                 }
2387
2388                 //fill the area at the end of the line
2389                 p.put_hline(polyspan.window.maxx - x);
2390
2391                 //fill area at the beginning of the next line
2392                 p.move_to(polyspan.window.minx,y+1);
2393                 p.put_block(polyspan.window.maxy - y - 1,polyspan.window.maxx - polyspan.window.minx);
2394         }else
2395         {
2396                 for(;;)
2397                 {
2398                         y = cur_mark->y;
2399                         x = cur_mark->x;
2400
2401                         p.move_to(x,y);
2402
2403                         area = cur_mark->area;
2404                         cover += cur_mark->cover;
2405
2406                         //accumulate for the current pixel
2407                         while(++cur_mark != polyspan.covers.end())
2408                         {
2409                                 if(y != cur_mark->y || x != cur_mark->x)
2410                                         break;
2411
2412                                 area += cur_mark->area;
2413                                 cover += cur_mark->cover;
2414                         }
2415
2416                         //draw pixel - based on covered area
2417                         if(area)        //if we're ok, draw the current pixel
2418                         {
2419                                 alpha = polyspan.ExtractAlpha(cover - area, winding_style);
2420                                 if(!antialias)
2421                                 {
2422                                         if(alpha >= .5) p.put_value();
2423                                 }
2424                                 else if(alpha) p.put_value(alpha);
2425
2426                                 p.inc_x();
2427                                 x++;
2428                         }
2429
2430                         //if we're done, don't use iterator and exit
2431                         if(cur_mark == end_mark) break;
2432
2433                         //if there is no more live pixels on this line, goto next
2434                         if(y != cur_mark->y)
2435                         {
2436                                 cover = 0;
2437
2438                                 continue;
2439                         }
2440
2441                         //draw span to next pixel - based on total amount of pixel cover
2442                         if(x < cur_mark->x)
2443                         {
2444                                 alpha = polyspan.ExtractAlpha(cover, winding_style);
2445                                 if(!antialias)
2446                                 {
2447                                         if(alpha >= .5) p.put_hline(cur_mark->x - x);
2448                                 }
2449                                 else if(alpha) p.put_hline(cur_mark->x - x,alpha);
2450                         }
2451                 }
2452         }
2453
2454         return true;
2455 }
2456
2457 bool
2458 Layer_Shape::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
2459 {
2460         const unsigned int w = renddesc.get_w();
2461         const unsigned int h = renddesc.get_h();
2462
2463         const Real pw = abs(renddesc.get_pw());
2464         const Real ph = abs(renddesc.get_ph());
2465
2466         //const Real OFFSET_EPSILON = 1e-8;
2467         SuperCallback stageone(cb,1,10000,15001+renddesc.get_h());
2468         SuperCallback stagetwo(cb,10000,10001+renddesc.get_h(),15001+renddesc.get_h());
2469         SuperCallback stagethree(cb,10001+renddesc.get_h(),15001+renddesc.get_h(),15001+renddesc.get_h());
2470
2471         // Render what is behind us
2472
2473         //clip if it satisfies the invert solid thing
2474         if(is_solid_color() && invert)
2475         {
2476                 Rect aabb = edge_table->aabb;
2477                 Point tl = renddesc.get_tl() - offset;
2478
2479                 Real    pw = renddesc.get_pw(),
2480                                 ph = renddesc.get_ph();
2481
2482                 Rect    nrect;
2483
2484                 Real    pixelfeatherx = quality == 10 ? 0 : abs(feather/pw),
2485                                 pixelfeathery = quality == 10 ? 0 : abs(feather/ph);
2486
2487                 nrect.set_point((aabb.minx - tl[0])/pw,(aabb.miny - tl[1])/ph);
2488                 nrect.expand((aabb.maxx - tl[0])/pw,(aabb.maxy - tl[1])/ph);
2489
2490                 RendDesc        optdesc(renddesc);
2491
2492                 //make sure to expand so we gain subpixels rather than lose them
2493                 nrect.minx = floor(nrect.minx-pixelfeatherx); nrect.miny = floor(nrect.miny-pixelfeathery);
2494                 nrect.maxx = ceil(nrect.maxx+pixelfeatherx); nrect.maxy = ceil(nrect.maxy+pixelfeathery);
2495
2496                 //make sure the subwindow is clipped with our tile window (minimize useless drawing)
2497                 set_intersect(nrect,nrect,Rect(0,0,renddesc.get_w(),renddesc.get_h()));
2498
2499                 //must resize the surface first
2500                 surface->set_wh(renddesc.get_w(),renddesc.get_h());
2501                 surface->clear();
2502
2503                 //only render anything if it's visible from our current tile
2504                 if(nrect.valid())
2505                 {
2506                         //set the subwindow to the viewable pixels and render it to the subsurface
2507                         optdesc.set_subwindow((int)nrect.minx, (int)nrect.miny,
2508                                 (int)(nrect.maxx - nrect.minx), (int)(nrect.maxy - nrect.miny));
2509
2510                         Surface optimizedbacksurf;
2511                         if(!context.accelerated_render(&optimizedbacksurf,quality,optdesc,&stageone))
2512                                 return false;
2513
2514                         //blit that onto the original surface so we can pretend that nothing ever happened
2515                         Surface::pen p = surface->get_pen((int)nrect.minx,(int)nrect.miny);
2516                         optimizedbacksurf.blit_to(p);
2517                 }
2518         }else
2519         {
2520                 if(!context.accelerated_render(surface,quality,renddesc,&stageone))
2521                         return false;
2522         }
2523
2524         if(cb && !cb->amount_complete(10000,10001+renddesc.get_h())) return false;
2525
2526         if(feather && quality != 10)
2527         {
2528                 //we have to blur rather than be crappy
2529
2530                 //so make a separate surface
2531                 RendDesc        workdesc(renddesc);
2532
2533                 etl::surface<float>     shapesurface;
2534
2535                 //the expanded size = 1/2 the size in each direction rounded up
2536                 int     halfsizex = (int) (abs(feather*.5/pw) + 3),
2537                         halfsizey = (int) (abs(feather*.5/ph) + 3);
2538
2539                 //expand by 1/2 size in each direction on either side
2540                 switch(blurtype)
2541                 {
2542                         case Blur::DISC:
2543                         case Blur::BOX:
2544                         case Blur::CROSS:
2545                         {
2546                                 workdesc.set_subwindow(-max(1,halfsizex),-max(1,halfsizey),w+2*max(1,halfsizex),h+2*max(1,halfsizey));
2547                                 break;
2548                         }
2549                         case Blur::FASTGAUSSIAN:
2550                         {
2551                                 if(quality < 4)
2552                                 {
2553                                         halfsizex*=2;
2554                                         halfsizey*=2;
2555                                 }
2556                                 workdesc.set_subwindow(-max(1,halfsizex),-max(1,halfsizey),w+2*max(1,halfsizex),h+2*max(1,halfsizey));
2557                                 break;
2558                         }
2559                         case Blur::GAUSSIAN:
2560                         {
2561                         #define GAUSSIAN_ADJUSTMENT             (0.05)
2562                                 Real    pw = (Real)workdesc.get_w()/(workdesc.get_br()[0]-workdesc.get_tl()[0]);
2563                                 Real    ph = (Real)workdesc.get_h()/(workdesc.get_br()[1]-workdesc.get_tl()[1]);
2564
2565                                 pw=pw*pw;
2566                                 ph=ph*ph;
2567
2568                                 halfsizex = (int)(abs(pw)*feather*GAUSSIAN_ADJUSTMENT+0.5);
2569                                 halfsizey = (int)(abs(ph)*feather*GAUSSIAN_ADJUSTMENT+0.5);
2570
2571                                 halfsizex = (halfsizex + 1)/2;
2572                                 halfsizey = (halfsizey + 1)/2;
2573                                 workdesc.set_subwindow( -halfsizex, -halfsizey, w+2*halfsizex, h+2*halfsizey );
2574
2575                                 break;
2576                         }
2577                 }
2578
2579                 shapesurface.set_wh(workdesc.get_w(),workdesc.get_h());
2580                 shapesurface.clear();
2581
2582                 //render the shape
2583                 if(!render_shape(&shapesurface,quality,workdesc,&stagetwo))return false;
2584
2585                 //blur the image
2586                 Blur(feather,feather,blurtype,&stagethree)(shapesurface,workdesc.get_br()-workdesc.get_tl(),shapesurface);
2587
2588                 //blend with stuff below it...
2589                 unsigned int u = halfsizex, v = halfsizey, x = 0, y = 0;
2590                 for(y = 0; y < h; y++,v++)
2591                 {
2592                         u = halfsizex;
2593                         for(x = 0; x < w; x++,u++)
2594                         {
2595                                 float a = shapesurface[v][u];
2596                                 if(a)
2597                                 {
2598                                         //a = floor(a*255+0.5f)/255;
2599                                         (*surface)[y][x]=Color::blend(color,(*surface)[y][x],a*get_amount(),get_blend_method());
2600                                 }
2601                                 //else (*surface)[y][x] = worksurface[v][u];
2602                         }
2603                 }
2604
2605                 //we are done
2606                 if(cb && !cb->amount_complete(100,100))
2607                 {
2608                         synfig::warning("Layer_Shape: could not set amount complete");
2609                         return false;
2610                 }
2611
2612                 return true;
2613         }else
2614         {
2615                 //might take out to reduce code size
2616                 return render_shape(surface,true,quality,renddesc,&stagetwo);
2617         }
2618
2619 }
2620
2621 bool
2622 Layer_Shape::render_shape(Surface *surface,bool useblend,int /*quality*/,
2623                                                         const RendDesc &renddesc, ProgressCallback *cb)const
2624 {
2625         int tmp(0);
2626
2627         SuperCallback   progress(cb,0,renddesc.get_h(),renddesc.get_h());
2628
2629         // If our amount is set to zero, no need to render anything
2630         if(!get_amount())
2631                 return true;
2632
2633         //test new polygon renderer
2634         // Build edge table
2635         // Width and Height of a pixel
2636         const int       w = renddesc.get_w();
2637         const int       h = renddesc.get_h();
2638         const Real      pw = renddesc.get_w()/(renddesc.get_br()[0]-renddesc.get_tl()[0]);
2639         const Real      ph = renddesc.get_h()/(renddesc.get_br()[1]-renddesc.get_tl()[1]);
2640
2641         const Point     tl = renddesc.get_tl();
2642
2643         Vector tangent (0,0);
2644
2645         PolySpan        span;
2646
2647         // if the pixels are zero sized then we're too zoomed out to see anything
2648         if (pw == 0 || ph == 0)
2649                 return true;
2650
2651         //optimization for tessellating only inside tiles
2652         span.window.minx = 0;
2653         span.window.miny = 0;
2654         span.window.maxx = w;
2655         span.window.maxy = h;
2656
2657         //pointers for processing the bytestream
2658         const char *current     = &bytestream[0];
2659         const char *end                 = &bytestream[bytestream.size()];
2660
2661         int     operation       = Primitive::NONE;
2662         int number              = 0;
2663         int curnum;
2664
2665         Primitive       *curprim;
2666         Point           *data;
2667
2668         Real x,y,x1,y1,x2,y2;
2669
2670
2671         while(current < end)
2672         {
2673                 tmp++;
2674
2675                 try {
2676
2677                 //get the op code safely
2678                 curprim = (Primitive *)current;
2679
2680                 //advance past indices
2681                 current += sizeof(Primitive);
2682                 if(current > end)
2683                 {
2684                         warning("Layer_Shape::accelerated_render - Error in the byte stream, not enough space for next declaration");
2685                         return false;
2686                 }
2687
2688                 //get the relevant data
2689                 operation       = curprim->operation;
2690                 number          = curprim->number;
2691
2692                 if(operation == Primitive::END)
2693                         break;
2694
2695                 if(operation == Primitive::CLOSE)
2696                 {
2697                         if(span.notclosed())
2698                         {
2699                                 tangent[0] = span.close_x - span.cur_x;
2700                                 tangent[1] = span.close_y - span.cur_y;
2701                                 span.close();
2702                         }
2703                         continue;
2704                 }
2705
2706                 data = (Point*)current;
2707                 current += sizeof(Point)*number;
2708
2709                 //check data positioning
2710                 if(current > end)
2711                 {
2712                         warning("Layer_Shape::accelerated_render - Error in the byte stream, in sufficient data space for declared number of points");
2713                         return false;
2714                 }
2715
2716                 } catch(...) { synfig::error("Layer_Shape::render_shape()1: Caught an exception after %d loops, rethrowing...", tmp); throw; }
2717
2718                 //transfer all the data - RLE optimized
2719                 for(curnum=0; curnum < number;)
2720                 {
2721                         switch(operation)
2722                         {
2723                                 case Primitive::MOVE_TO:
2724                                 {
2725                                         x = data[curnum][0];
2726                                         x = (x - tl[0] + offset[0])*pw;
2727                                         y = data[curnum][1];
2728                                         y = (y - tl[1] + offset[1])*ph;
2729
2730                                         if(curnum == 0)
2731                                         {
2732                                                 span.move_to(x,y);
2733
2734                                                 tangent[0] = 0;
2735                                                 tangent[1] = 0;
2736                                         }
2737                                         else
2738                                         {
2739                                                 tangent[0] = x - span.cur_x;
2740                                                 tangent[1] = y - span.cur_y;
2741
2742                                                 span.line_to(x,y);
2743                                         }
2744
2745                                         curnum++; //only advance one point
2746
2747                                         break;
2748                                 }
2749
2750                                 case Primitive::LINE_TO:
2751                                 {
2752                                         x = data[curnum][0];
2753                                         x = (x - tl[0] + offset[0])*pw;
2754                                         y = data[curnum][1];
2755                                         y = (y - tl[1] + offset[1])*ph;
2756
2757                                         tangent[0] = x - span.cur_x;
2758                                         tangent[1] = y - span.cur_y;
2759
2760                                         span.line_to(x,y);
2761                                         curnum++;
2762                                         break;
2763                                 }
2764
2765                                 case Primitive::CONIC_TO:
2766                                 {
2767                                         x = data[curnum+1][0];
2768                                         x = (x - tl[0] + offset[0])*pw;
2769                                         y = data[curnum+1][1];
2770                                         y = (y - tl[1] + offset[1])*ph;
2771
2772                                         x1 = data[curnum][0];
2773                                         x1 = (x1 - tl[0] + offset[0])*pw;
2774                                         y1 = data[curnum][1];
2775                                         y1 = (y1 - tl[1] + offset[1])*ph;
2776
2777                                         tangent[0] = 2*(x - x1);
2778                                         tangent[1] = 2*(y - y1);
2779
2780                                         span.conic_to(x1,y1,x,y);
2781                                         curnum += 2;
2782                                         break;
2783                                 }
2784
2785                                 case Primitive::CONIC_TO_SMOOTH:
2786                                 {
2787                                         x = data[curnum][0];
2788                                         x = (x - tl[0] + offset[0])*pw;
2789                                         y = data[curnum][1];
2790                                         y = (y - tl[1] + offset[1])*ph;
2791
2792                                         x1 = span.cur_x + tangent[0]/2;
2793                                         y1 = span.cur_y + tangent[1]/2;
2794
2795                                         tangent[0] = 2*(x - x1);
2796                                         tangent[1] = 2*(y - y1);
2797
2798                                         span.conic_to(x1,y1,x,y);
2799                                         curnum ++;
2800
2801                                         break;
2802                                 }
2803
2804                                 case Primitive::CUBIC_TO:
2805                                 {
2806                                         x = data[curnum+2][0];
2807                                         x = (x - tl[0] + offset[0])*pw;
2808                                         y = data[curnum+2][1];
2809                                         y = (y - tl[1] + offset[1])*ph;
2810
2811                                         x2 = data[curnum+1][0];
2812                                         x2 = (x2 - tl[0] + offset[0])*pw;
2813                                         y2 = data[curnum+1][1];
2814                                         y2 = (y2 - tl[1] + offset[1])*ph;
2815
2816                                         x1 = data[curnum][0];
2817                                         x1 = (x1 - tl[0] + offset[0])*pw;
2818                                         y1 = data[curnum][1];
2819                                         y1 = (y1 - tl[1] + offset[1])*ph;
2820
2821                                         tangent[0] = 2*(x - x2);
2822                                         tangent[1] = 2*(y - y2);
2823
2824                                         span.cubic_to(x1,y1,x2,y2,x,y);
2825                                         curnum += 3;
2826
2827                                         break;
2828                                 }
2829
2830                                 case Primitive::CUBIC_TO_SMOOTH:
2831                                 {
2832                                         x = data[curnum+1][0];
2833                                         x = (x - tl[0] + offset[0])*pw;
2834                                         y = data[curnum+1][1];
2835                                         y = (y - tl[1] + offset[1])*ph;
2836
2837                                         x2 = data[curnum][0];
2838                                         x2 = (x2 - tl[0] + offset[0])*pw;
2839                                         y2 = data[curnum][1];
2840                                         y2 = (y2 - tl[1] + offset[1])*ph;
2841
2842                                         x1 = span.cur_x + tangent[0]/3.0;
2843                                         y1 = span.cur_y + tangent[1]/3.0;
2844
2845                                         tangent[0] = 2*(x - x2);
2846                                         tangent[1] = 2*(y - y2);
2847
2848                                         span.cubic_to(x1,y1,x2,y2,x,y);
2849                                         curnum += 2;
2850
2851                                         break;
2852                                 }
2853                         }
2854                 }
2855         }
2856
2857         //sort the bastards so we can render everything
2858         span.sort_marks();
2859
2860         return render_polyspan(surface, span,
2861                         useblend?get_blend_method():Color::BLEND_STRAIGHT,
2862                         useblend?get_amount():1.0);
2863 }
2864
2865 bool
2866 Layer_Shape::render_shape(etl::surface<float> *surface,int /*quality*/,
2867                                                         const RendDesc &renddesc, ProgressCallback */*cb*/)const
2868 {
2869         // If our amount is set to zero, no need to render anything
2870         if(!get_amount())
2871                 return true;
2872
2873         //test new polygon renderer
2874         // Build edge table
2875         // Width and Height of a pixel
2876         const int       w = renddesc.get_w();
2877         const int       h = renddesc.get_h();
2878         const Real      pw = renddesc.get_w()/(renddesc.get_br()[0]-renddesc.get_tl()[0]);
2879         const Real      ph = renddesc.get_h()/(renddesc.get_br()[1]-renddesc.get_tl()[1]);
2880
2881         const Point     tl = renddesc.get_tl();
2882
2883         Vector tangent (0,0);
2884
2885         PolySpan        span;
2886
2887         //optimization for tessellating only inside tiles
2888         span.window.minx = 0;
2889         span.window.miny = 0;
2890         span.window.maxx = w;
2891         span.window.maxy = h;
2892
2893         //pointers for processing the bytestream
2894         const char *current     = &bytestream[0];
2895         const char *end                 = &bytestream[bytestream.size()];
2896
2897         int     operation       = Primitive::NONE;
2898         int number              = 0;
2899         int curnum;
2900
2901         Primitive       *curprim;
2902         Point           *data;
2903
2904         Real x,y,x1,y1,x2,y2;
2905
2906         while(current < end)
2907         {
2908                 //get the op code safely
2909                 curprim = (Primitive *)current;
2910
2911                 //advance past indices
2912                 current += sizeof(Primitive);
2913                 if(current > end)
2914                 {
2915                         warning("Layer_Shape::accelerated_render - Error in the byte stream, not enough space for next declaration");
2916                         return false;
2917                 }
2918
2919                 //get the relevant data
2920                 operation       = curprim->operation;
2921                 number          = curprim->number;
2922
2923                 if(operation == Primitive::END)
2924                         break;
2925
2926                 if(operation == Primitive::CLOSE)
2927                 {
2928                         if(span.notclosed())
2929                         {
2930                                 tangent[0] = span.close_x - span.cur_x;
2931                                 tangent[1] = span.close_y - span.cur_y;
2932                                 span.close();
2933                         }
2934                         continue;
2935                 }
2936
2937                 data = (Point*)current;
2938                 current += sizeof(Point)*number;
2939
2940                 //check data positioning
2941                 if(current > end)
2942                 {
2943                         warning("Layer_Shape::accelerated_render - Error in the byte stream, in sufficient data space for declared number of points");
2944                         return false;
2945                 }
2946
2947                 //transfer all the data
2948                 for(curnum=0; curnum < number;)
2949                 {
2950                         switch(operation)
2951                         {
2952                                 case Primitive::MOVE_TO:
2953                                 {
2954                                         x = data[curnum][0];
2955                                         x = (x - tl[0] + offset[0])*pw;
2956                                         y = data[curnum][1];
2957                                         y = (y - tl[1] + offset[1])*ph;
2958
2959                                         if(curnum == 0)
2960                                         {
2961                                                 span.move_to(x,y);
2962
2963                                                 tangent[0] = 0;
2964                                                 tangent[1] = 0;
2965                                         }
2966                                         else
2967                                         {
2968                                                 tangent[0] = x - span.cur_x;
2969                                                 tangent[1] = y - span.cur_y;
2970
2971                                                 span.line_to(x,y);
2972                                         }
2973
2974                                         curnum++; //only advance one point
2975
2976                                         break;
2977                                 }
2978
2979                                 case Primitive::LINE_TO:
2980                                 {
2981                                         x = data[curnum][0];
2982                                         x = (x - tl[0] + offset[0])*pw;
2983                                         y = data[curnum][1];
2984                                         y = (y - tl[1] + offset[1])*ph;
2985
2986                                         tangent[0] = x - span.cur_x;
2987                                         tangent[1] = y - span.cur_y;
2988
2989                                         span.line_to(x,y);
2990                                         curnum++;
2991                                         break;
2992                                 }
2993
2994                                 case Primitive::CONIC_TO:
2995                                 {
2996                                         x = data[curnum+1][0];
2997                                         x = (x - tl[0] + offset[0])*pw;
2998                                         y = data[curnum+1][1];
2999                                         y = (y - tl[1] + offset[1])*ph;
3000
3001                                         x1 = data[curnum][0];
3002                                         x1 = (x1 - tl[0] + offset[0])*pw;
3003                                         y1 = data[curnum][1];
3004                                         y1 = (y1 - tl[1] + offset[1])*ph;
3005
3006                                         tangent[0] = 2*(x - x1);
3007                                         tangent[1] = 2*(y - y1);
3008
3009                                         span.conic_to(x1,y1,x,y);
3010                                         curnum += 2;
3011                                         break;
3012                                 }
3013
3014                                 case Primitive::CONIC_TO_SMOOTH:
3015                                 {
3016                                         x = data[curnum][0];
3017                                         x = (x - tl[0] + offset[0])*pw;
3018                                         y = data[curnum][1];
3019                                         y = (y - tl[1] + offset[1])*ph;
3020
3021                                         x1 = span.cur_x + tangent[0]/2;
3022                                         y1 = span.cur_y + tangent[1]/2;
3023
3024                                         tangent[0] = 2*(x - x1);
3025                                         tangent[1] = 2*(y - y1);
3026
3027                                         span.conic_to(x1,y1,x,y);
3028                                         curnum ++;
3029
3030                                         break;
3031                                 }
3032
3033                                 case Primitive::CUBIC_TO:
3034                                 {
3035                                         x = data[curnum+2][0];
3036                                         x = (x - tl[0] + offset[0])*pw;
3037                                         y = data[curnum+2][1];
3038                                         y = (y - tl[1] + offset[1])*ph;
3039
3040                                         x2 = data[curnum+1][0];
3041                                         x2 = (x2 - tl[0] + offset[0])*pw;
3042                                         y2 = data[curnum+1][1];
3043                                         y2 = (y2 - tl[1] + offset[1])*ph;
3044
3045                                         x1 = data[curnum][0];
3046                                         x1 = (x1 - tl[0] + offset[0])*pw;
3047                                         y1 = data[curnum][1];
3048                                         y1 = (y1 - tl[1] + offset[1])*ph;
3049
3050                                         tangent[0] = 2*(x - x2);
3051                                         tangent[1] = 2*(y - y2);
3052
3053                                         span.cubic_to(x1,y1,x2,y2,x,y);
3054                                         curnum += 3;
3055
3056                                         break;
3057                                 }
3058
3059                                 case Primitive::CUBIC_TO_SMOOTH:
3060                                 {
3061                                         x = data[curnum+1][0];
3062                                         x = (x - tl[0] + offset[0])*pw;
3063                                         y = data[curnum+1][1];
3064                                         y = (y - tl[1] + offset[1])*ph;
3065
3066                                         x2 = data[curnum][0];
3067                                         x2 = (x2 - tl[0] + offset[0])*pw;
3068                                         y2 = data[curnum][1];
3069                                         y2 = (y2 - tl[1] + offset[1])*ph;
3070
3071                                         x1 = span.cur_x + tangent[0]/3.0;
3072                                         y1 = span.cur_y + tangent[1]/3.0;
3073
3074                                         tangent[0] = 2*(x - x2);
3075                                         tangent[1] = 2*(y - y2);
3076
3077                                         span.cubic_to(x1,y1,x2,y2,x,y);
3078                                         curnum += 2;
3079
3080                                         break;
3081                                 }
3082                         }
3083                 }
3084         }
3085
3086         //sort the bastards so we can render everything
3087         span.sort_marks();
3088
3089         return render_polyspan(surface, span);
3090 }
3091
3092 Rect
3093 Layer_Shape::get_bounding_rect()const
3094 {
3095         if(invert)
3096                 return Rect::full_plane();
3097
3098         if (edge_table->initaabb)
3099                 return Rect::zero();
3100
3101         Rect bounds(edge_table->aabb+offset);
3102         bounds.expand(max((bounds.get_min() - bounds.get_max()).mag()*0.01,
3103                                           feather));
3104
3105         return bounds;
3106 }