resolve darcs stupidity
[org.ibex.core.git] / src / org / ibex / VectorGraphics.java
1 // FIXME
2 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
3 package org.ibex;
4 import java.util.*;
5
6 // FIXME: offer a "subpixel" mode where we pass floats to the Platform and don't do any snapping
7 // FIXME: fracture when realizing instead of when parsing?
8
9 /*
10     v1.0
11     - textpath
12     - gradients
13     - patterns
14     - clipping/masking
15     - filters (filtering of a group must be performed AFTER the group is assembled; sep. canvas)
16
17     v1.1
18     - bump caps [requires Paint that can fill circles...] [remember to distinguish between closed/unclosed]
19     - line joins
20         - mitre    (hard)
21         - bevel    (easy)
22         - bump     (easy, but requires 'round' Paint)
23     - subtree sharing? otherwise the memory consumption might be outrageous... clone="" attribute?
24     - better clipping
25         - intersect clip regions (linearity)
26         - clip on trapezoids, not pixels
27     - faster gradients and patterns:
28         - transform each corner of the trapezoid and then interpolate
29 */
30
31 /** Ibex's fully conformant Static SVG Viewer; see SVG spec, section G.7 */
32 public final class VectorGraphics {
33
34     // Private Constants ///////////////////////////////////////////////////////////////////
35
36     private static final int DEFAULT_PATHLEN = 1000;
37     private static final float PI = (float)Math.PI;
38
39
40     // Public entry points /////////////////////////////////////////////////////////////////
41
42     public static VectorPath parseVectorPath(String s) {
43         if (s == null) return null;
44         PathTokenizer t = new PathTokenizer(s);
45         VectorPath ret = new VectorPath();
46         char last_command = 'M';
47         boolean first = true;
48         while(t.hasMoreTokens()) {
49             char command = t.parseCommand();
50             if (first && command != 'M') throw new RuntimeException("the first command of a path must be 'M'");
51             first = false;
52             boolean relative = Character.toLowerCase(command) == command;
53             command = Character.toLowerCase(command);
54             ret.parseSingleCommandAndArguments(t, command, relative);
55             last_command = command;
56         }
57         return ret;
58     }
59
60
61     // Affine //////////////////////////////////////////////////////////////////////////////
62
63     /** an affine transform; all operations are destructive */
64     public static final class Affine {
65
66         //  [ a b e ]
67         //  [ c d f ]
68         //  [ 0 0 1 ]
69         public float a, b, c, d, e, f;
70
71         Affine(float _a, float _b, float _c, float _d, float _e, float _f) { a = _a; b = _b; c = _c; d = _d; e = _e; f = _f; }
72         public String toString() { return "[ " + a + ", " + b + ", " + c + ", " + d + ", " + e + ", " + f + " ]"; }
73         public Affine copy() { return new Affine(a, b, c, d, e, f); }
74         public static Affine identity() { return new Affine(1, 0, 0, 1, 0, 0); }
75         public static Affine scale(float sx, float sy) { return new Affine(sx, 0, 0, sy, 0, 0); }
76         public static Affine shear(float degrees) {
77             return new Affine(1, 0, (float)Math.tan(degrees * (float)(Math.PI / 180.0)), 1, 0, 0); }
78         public static Affine translate(float tx, float ty) { return new Affine(1, 0, 0, 1, tx, ty); }
79         public static Affine flip(boolean horiz, boolean vert) { return new Affine(horiz ? -1 : 1, 0, 0, vert ? -1 : 1, 0, 0); }
80         public float multiply_px(float x, float y) { return x * a + y * c + e; }
81         public float multiply_py(float x, float y) { return x * b + y * d + f; }
82         public boolean equalsIgnoringTranslation(Affine x) { return a == x.a && b == x.b && c == x.c && d == x.d; }
83
84         public boolean equals(Object o) {
85             if (!(o instanceof Affine)) return false;
86             Affine x = (Affine)o;
87             return a == x.a && b == x.b && c == x.c && d == x.d && e == x.e && f == x.f;
88         }
89
90         public static Affine rotate(float degrees) {
91             float s = (float)Math.sin(degrees * (float)(Math.PI / 180.0));
92             float c = (float)Math.cos(degrees * (float)(Math.PI / 180.0));
93             return new Affine(c, s, -s, c, 0, 0);
94         }
95
96         /** this = this * a */
97         public Affine multiply(Affine A) {
98             float _a = this.a * A.a + this.b * A.c;
99             float _b = this.a * A.b + this.b * A.d;
100             float _c = this.c * A.a + this.d * A.c;
101             float _d = this.c * A.b + this.d * A.d;
102             float _e = this.e * A.a + this.f * A.c + A.e;
103             float _f = this.e * A.b + this.f * A.d + A.f;
104             a = _a; b = _b; c = _c; d = _d; e = _e; f = _f;
105             return this;
106         }
107
108         public void invert() {
109             float det = 1 / (a * d - b * c);
110             float _a = d * det;
111             float _b = -1 * b * det;
112             float _c = -1 * c * det;
113             float _d = a * det;
114             float _e = -1 * e * a - f * c;
115             float _f = -1 * e * b - f * d;
116             a = _a; b = _b; c = _c; d = _d; e = _e; f = _f;
117         }
118     }
119
120
121     // PathTokenizer //////////////////////////////////////////////////////////////////////////////
122
123     public static Affine parseTransform(String t) {
124         if (t == null) return null;
125         t = t.trim();
126         Affine ret = VectorGraphics.Affine.identity();
127         while (t.length() > 0) {
128             if (t.startsWith("skewX(")) {
129                 // FIXME
130                 
131             } else if (t.startsWith("shear(")) {
132                 // FIXME: nonstandard; remove this
133                 ret.multiply(VectorGraphics.Affine.shear(Float.parseFloat(t.substring(t.indexOf('(') + 1, t.indexOf(')')))));
134                 
135             } else if (t.startsWith("skewY(")) {
136                 // FIXME
137                 
138             } else if (t.startsWith("rotate(")) {
139                 String sub = t.substring(t.indexOf('(') + 1, t.indexOf(')'));
140                 if (sub.indexOf(',') != -1) {
141                     float angle = Float.parseFloat(sub.substring(0, sub.indexOf(',')));
142                     sub = sub.substring(sub.indexOf(',') + 1);
143                     float cx = Float.parseFloat(sub.substring(0, sub.indexOf(',')));
144                     sub = sub.substring(sub.indexOf(',') + 1);
145                     float cy = Float.parseFloat(sub);
146                     ret.multiply(VectorGraphics.Affine.translate(cx, cy));
147                     ret.multiply(VectorGraphics.Affine.rotate(angle));
148                     ret.multiply(VectorGraphics.Affine.translate(-1 * cx, -1 * cy));
149                 } else {
150                     ret.multiply(VectorGraphics.Affine.rotate(Float.parseFloat(t.substring(t.indexOf('(') + 1, t.indexOf(')')))));
151                 }
152                 
153             } else if (t.startsWith("translate(")) {
154                 String sub = t.substring(t.indexOf('(') + 1, t.indexOf(')'));
155                 if (sub.indexOf(',') > -1) {
156                     ret.multiply(VectorGraphics.Affine.translate(Float.parseFloat(t.substring(t.indexOf('(') + 1, t.indexOf(','))),
157                                                                  Float.parseFloat(t.substring(t.indexOf(',') + 1, t.indexOf(')')))));
158                 } else {
159                     ret.multiply(VectorGraphics.Affine.translate(Float.parseFloat(t.substring(t.indexOf('(') + 1, t.indexOf(','))), 0));
160                 }
161                 
162             } else if (t.startsWith("flip(")) {
163                 String which = t.substring(t.indexOf('(') + 1, t.indexOf(')'));
164                 ret.multiply(VectorGraphics.Affine.flip(which.equals("horizontal"), which.equals("vertical")));
165                 
166             } else if (t.startsWith("scale(")) {
167                 String sub = t.substring(t.indexOf('(') + 1, t.indexOf(')'));
168                 if (sub.indexOf(',') > -1) {
169                     ret.multiply(VectorGraphics.Affine.scale(Float.parseFloat(t.substring(t.indexOf('(') + 1, t.indexOf(','))),
170                                                              Float.parseFloat(t.substring(t.indexOf(',') + 1, t.indexOf(')')))));
171                 } else {
172                     ret.multiply(VectorGraphics.Affine.scale(Float.parseFloat(t.substring(t.indexOf('(') + 1, t.indexOf(','))),
173                                                              Float.parseFloat(t.substring(t.indexOf('(') + 1, t.indexOf(',')))));
174                 }
175                 
176             } else if (t.startsWith("matrix(")) {
177                 // FIXME: is this mapped right?
178                 float d[] = new float[6];
179                 StringTokenizer st = new StringTokenizer(t, ",", false);
180                 for(int i=0; i<6; i++)
181                     d[i] = Float.parseFloat(st.nextToken());
182                 ret.multiply(new VectorGraphics.Affine(d[0], d[1], d[2], d[3], d[4], d[5]));
183             }
184             t = t.substring(t.indexOf(')') + 1).trim();
185         }
186         return ret;
187     }
188     
189     public static final float PX_PER_INCH = 72;
190     public static final float INCHES_PER_CM = (float)0.3937;
191     public static final float INCHES_PER_MM = INCHES_PER_CM / 10;
192
193     public static class PathTokenizer {
194         // FIXME: check array bounds exception for improperly terminated string
195         String s;
196         int i = 0;
197         char lastCommand = 'M';
198         public PathTokenizer(String s) { this.s = s; }
199         private void consumeWhitespace() {
200             while(i < s.length() && (Character.isWhitespace(s.charAt(i)))) i++;
201             if (i < s.length() && s.charAt(i) == ',') i++;
202             while(i < s.length() && (Character.isWhitespace(s.charAt(i)))) i++;
203         }
204         public boolean hasMoreTokens() { consumeWhitespace(); return i < s.length(); }
205         public char parseCommand() {
206             consumeWhitespace();
207             char c = s.charAt(i);
208             if (!Character.isLetter(c)) return lastCommand;
209             i++;
210             return lastCommand = c;
211         }
212         public float parseFloat() {
213             consumeWhitespace();
214             int start = i;
215             float multiplier = 1;
216             for(; i < s.length(); i++) {
217                 char c = s.charAt(i);
218                 if (Character.isWhitespace(c) || c == ',' || (c == '-' && i != start)) break;
219                 if (!((c >= '0' && c <= '9') || c == '.' || c == 'e' || c == 'E' || c == '-')) {
220                     if (c == '%') {                                // FIXME
221                     } else if (s.regionMatches(i, "pt", 0, i+2)) { // FIXME
222                     } else if (s.regionMatches(i, "em", 0, i+2)) { // FIXME
223                     } else if (s.regionMatches(i, "pc", 0, i+2)) { // FIXME
224                     } else if (s.regionMatches(i, "ex", 0, i+2)) { // FIXME
225                     } else if (s.regionMatches(i, "mm", 0, i+2)) { i += 2; multiplier = INCHES_PER_MM * PX_PER_INCH; break;
226                     } else if (s.regionMatches(i, "cm", 0, i+2)) { i += 2; multiplier = INCHES_PER_CM * PX_PER_INCH; break;
227                     } else if (s.regionMatches(i, "in", 0, i+2)) { i += 2; multiplier = PX_PER_INCH; break;
228                     } else if (s.regionMatches(i, "px", 0, i+2)) { i += 2; break;
229                     } else if (Character.isLetter(c)) break;
230                     throw new RuntimeException("didn't expect character \"" + c + "\" in a numeric constant");
231                 }
232             }
233             if (start == i) throw new RuntimeException("FIXME");
234             return Float.parseFloat(s.substring(start, i)) * multiplier;
235         }
236     }
237
238
239     // Abstract Path //////////////////////////////////////////////////////////////////////////////
240
241     /** an abstract path; may contain splines and arcs */
242     public static class VectorPath {
243
244         // the number of vertices on this path
245         int numvertices = 0;
246
247         // the vertices of the path
248         float[] x = new float[DEFAULT_PATHLEN];
249         float[] y = new float[DEFAULT_PATHLEN];
250
251         // the type of each edge; type[i] is the type of the edge from x[i],y[i] to x[i+1],y[i+1]
252         byte[] type = new byte[DEFAULT_PATHLEN];
253
254         // bezier control points
255         float[] c1x = new float[DEFAULT_PATHLEN];  // or rx (arcto)
256         float[] c1y = new float[DEFAULT_PATHLEN];  // or ry (arcto)
257         float[] c2x = new float[DEFAULT_PATHLEN];  // or x-axis-rotation (arcto)
258         float[] c2y = new float[DEFAULT_PATHLEN];  // or large-arc << 1 | sweep (arcto)
259
260         boolean closed = false;
261
262         static final byte TYPE_MOVETO = 0;
263         static final byte TYPE_LINETO = 1;
264         static final byte TYPE_ARCTO = 2;
265         static final byte TYPE_CUBIC = 3;
266         static final byte TYPE_QUADRADIC = 4;
267
268         /** Creates a concrete vector path transformed through the given matrix. */
269         public RasterPath realize(Affine a) {
270
271             RasterPath ret = new RasterPath();
272             int NUMSTEPS = 5;  // FIXME
273             ret.numvertices = 1;
274             ret.x[0] = (int)Math.round(a.multiply_px(x[0], y[0]));
275             ret.y[0] = (int)Math.round(a.multiply_py(x[0], y[0]));
276
277             for(int i=1; i<numvertices; i++) {
278                 if (type[i] == TYPE_LINETO) {
279                     float rx = x[i];
280                     float ry = y[i];
281                     ret.x[ret.numvertices] = (int)Math.round(a.multiply_px(rx, ry));
282                     ret.y[ret.numvertices] = (int)Math.round(a.multiply_py(rx, ry));
283                     ret.edges[ret.numedges++] = ret.numvertices - 1; ret.numvertices++;
284
285                 } else if (type[i] == TYPE_MOVETO) {
286                     float rx = x[i];
287                     float ry = y[i];
288                     ret.x[ret.numvertices] = (int)Math.round(a.multiply_px(rx, ry));
289                     ret.y[ret.numvertices] = (int)Math.round(a.multiply_py(rx, ry));
290                     ret.numvertices++;
291
292                 } else if (type[i] == TYPE_ARCTO) {
293                     float rx = c1x[i];
294                     float ry = c1y[i];
295                     float phi = c2x[i];
296                     float fa = ((int)c2y[i]) >> 1;
297                     float fs = ((int)c2y[i]) & 1;
298                     float x1 = x[i];
299                     float y1 = y[i];
300                     float x2 = x[i+1];
301                     float y2 = y[i+1];
302
303                     // F.6.5: given x1,y1,x2,y2,fa,fs, compute cx,cy,theta1,dtheta
304                     float x1_ = (float)Math.cos(phi) * (x1 - x2) / 2 + (float)Math.sin(phi) * (y1 - y2) / 2;
305                     float y1_ = -1 * (float)Math.sin(phi) * (x1 - x2) / 2 + (float)Math.cos(phi) * (y1 - y2) / 2;
306                     float tmp = (float)Math.sqrt((rx * rx * ry * ry - rx * rx * y1_ * y1_ - ry * ry * x1_ * x1_) /
307                                                  (rx * rx * y1_ * y1_ + ry * ry * x1_ * x1_));
308                     float cx_ = (fa == fs ? -1 : 1) * tmp * (rx * y1_ / ry);
309                     float cy_ = (fa == fs ? -1 : 1) * -1 * tmp * (ry * x1_ / rx);
310                     float cx = (float)Math.cos(phi) * cx_ - (float)Math.sin(phi) * cy_ + (x1 + x2) / 2;
311                     float cy = (float)Math.sin(phi) * cx_ + (float)Math.cos(phi) * cy_ + (y1 + y2) / 2;
312
313                     // F.6.4 Conversion from center to endpoint parameterization
314                     float ux = 1, uy = 0, vx = (x1_ - cx_) / rx, vy = (y1_ - cy_) / ry;
315                     float det = ux * vy - uy * vx;
316                     float theta1 = (det < 0 ? -1 : 1) *
317                         (float)Math.acos((ux * vx + uy * vy) / 
318                                   ((float)Math.sqrt(ux * ux + uy * uy) * (float)Math.sqrt(vx * vx + vy * vy)));
319                     ux = (x1_ - cx_) / rx; uy = (y1_ - cy_) / ry;
320                     vx = (-1 * x1_ - cx_) / rx; vy = (-1 * y1_ - cy_) / ry;
321                     det = ux * vy - uy * vx;
322                     float dtheta = (det < 0 ? -1 : 1) *
323                         (float)Math.acos((ux * vx + uy * vy) / 
324                                   ((float)Math.sqrt(ux * ux + uy * uy) * (float)Math.sqrt(vx * vx + vy * vy)));
325                     dtheta = dtheta % (float)(2 * Math.PI);
326
327                     if (fs == 0 && dtheta > 0) theta1 -= 2 * PI; 
328                     if (fs == 1 && dtheta < 0) theta1 += 2 * PI;
329
330                     if (fa == 1 && dtheta < 0) dtheta = 2 * PI + dtheta;
331                     else if (fa == 1 && dtheta > 0) dtheta = -1 * (2 * PI - dtheta);
332
333                     // FIXME: integrate F.6.6
334                     // FIXME: isn't quite ending where it should...
335
336                     // F.6.3: Parameterization alternatives
337                     float theta = theta1;
338                     for(int j=0; j<NUMSTEPS; j++) {
339                         float rasterx = rx * (float)Math.cos(theta) * (float)Math.cos(phi) -
340                             ry * (float)Math.sin(theta) * (float)Math.sin(phi) + cx;
341                         float rastery = rx * (float)Math.cos(theta) * (float)Math.sin(phi) +
342                             ry * (float)Math.cos(phi) * (float)Math.sin(theta) + cy;
343                         ret.x[ret.numvertices] = (int)Math.round(a.multiply_px(rasterx, rastery));
344                         ret.y[ret.numvertices] = (int)Math.round(a.multiply_py(rasterx, rastery));
345                         ret.edges[ret.numedges++] = ret.numvertices - 1; ret.numvertices++;
346                         theta += dtheta / NUMSTEPS;
347                     }
348
349                 } else if (type[i] == TYPE_CUBIC) {
350
351                     float ax = x[i+1] - 3 * c2x[i] + 3 * c1x[i] - x[i];
352                     float bx = 3 * c2x[i] - 6 * c1x[i] + 3 * x[i];
353                     float cx = 3 * c1x[i] - 3 * x[i];
354                     float dx = x[i];
355                     float ay = y[i+1] - 3 * c2y[i] + 3 * c1y[i] - y[i];
356                     float by = 3 * c2y[i] - 6 * c1y[i] + 3 * y[i];
357                     float cy = 3 * c1y[i] - 3 * y[i];
358                     float dy = y[i];
359                     
360                     for(float t=0; t<1; t += 1 / (float)NUMSTEPS) {
361                         float rx = ax * t * t * t + bx * t * t + cx * t + dx;
362                         float ry = ay * t * t * t + by * t * t + cy * t + dy;
363                         ret.x[ret.numvertices] = (int)Math.round(a.multiply_px(rx, ry));
364                         ret.y[ret.numvertices] = (int)Math.round(a.multiply_py(rx, ry));
365                         ret.edges[ret.numedges++] = ret.numvertices - 1; ret.numvertices++;
366                     }
367
368
369                 } else if (type[i] == TYPE_QUADRADIC) {
370
371                     float bx = x[i+1] - 2 * c1x[i] + x[i];
372                     float cx = 2 * c1x[i] - 2 * x[i];
373                     float dx = x[i];
374                     float by = y[i+1] - 2 * c1y[i] + y[i];
375                     float cy = 2 * c1y[i] - 2 * y[i];
376                     float dy = y[i];
377                         
378                     for(float t=0; t<1; t += 1 / (float)NUMSTEPS) {
379                         float rx = bx * t * t + cx * t + dx;
380                         float ry = by * t * t + cy * t + dy;
381                         ret.x[ret.numvertices] = (int)Math.round(a.multiply_px(rx, ry));
382                         ret.y[ret.numvertices] = (int)Math.round(a.multiply_py(rx, ry));
383                         ret.edges[ret.numedges++] = ret.numvertices - 1; ret.numvertices++;
384                     }
385
386                 }
387
388             }
389             
390             if (ret.numedges > 0) ret.sort(0, ret.numedges - 1, false);
391             return ret;
392         }
393
394         protected void parseSingleCommandAndArguments(PathTokenizer t, char command, boolean relative) {
395             if (numvertices == 0 && command != 'm') throw new RuntimeException("first command MUST be an 'm'");
396             if (numvertices > x.length - 2) {
397                 float[] new_x = new float[x.length * 2]; System.arraycopy(x, 0, new_x, 0, x.length); x = new_x;
398                 float[] new_y = new float[y.length * 2]; System.arraycopy(y, 0, new_y, 0, y.length); y = new_y;
399             }
400             switch(command) {
401             case 'z': {
402                 int where;
403                 type[numvertices-1] = TYPE_LINETO;
404                 for(where = numvertices - 1; where > 0; where--)
405                     if (type[where - 1] == TYPE_MOVETO) break;
406                 x[numvertices] = x[where];
407                 y[numvertices] = y[where];
408                 numvertices++;
409                 closed = true;
410                 break;
411             }
412
413             case 'm': {
414                 if (numvertices > 0) type[numvertices-1] = TYPE_MOVETO;
415                 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
416                 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
417                 numvertices++;
418                 break;
419             }
420
421             case 'l': case 'h': case 'v': {
422                 type[numvertices-1] = TYPE_LINETO;
423                 float first = t.parseFloat(), second;
424                 if (command == 'h') {
425                     second = relative ? 0 : y[numvertices - 1];
426                 } else if (command == 'v') {
427                     second = first; first = relative ? 0 : x[numvertices - 1];
428                 } else {
429                     second = t.parseFloat();
430                 }
431                 x[numvertices] = first + (relative ? x[numvertices - 1] : 0);
432                 y[numvertices] = second + (relative ? y[numvertices - 1] : 0);
433                 numvertices++;
434                 break;
435             }
436             
437             case 'a': {
438                 type[numvertices-1] = TYPE_ARCTO;
439                 c1x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
440                 c1y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
441                 c2x[numvertices-1] = (t.parseFloat() / 360) * 2 * PI;
442                 c2y[numvertices-1] = (((int)t.parseFloat()) << 1) | (int)t.parseFloat();
443                 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
444                 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
445                 numvertices++;
446                 break;
447             }
448
449             case 's': case 'c': {
450                 type[numvertices-1] = TYPE_CUBIC;
451                 if (command == 'c') {
452                     c1x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
453                     c1y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
454                 } else if (numvertices > 1 && type[numvertices-2] == TYPE_CUBIC) {
455                     c1x[numvertices-1] = 2 * x[numvertices - 1] - c2x[numvertices-2];
456                     c1y[numvertices-1] = 2 * y[numvertices - 1] - c2y[numvertices-2];
457                 } else {
458                     c1x[numvertices-1] = x[numvertices-1];
459                     c1y[numvertices-1] = y[numvertices-1];
460                 }
461                 c2x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
462                 c2y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
463                 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
464                 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
465                 numvertices++;
466                 break;
467             }
468
469             case 't': case 'q': {
470                 type[numvertices-1] = TYPE_QUADRADIC;
471                 if (command == 'q') {
472                     c1x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
473                     c1y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
474                 } else if (numvertices > 1 && type[numvertices-2] == TYPE_QUADRADIC) {
475                     c1x[numvertices-1] = 2 * x[numvertices - 1] - c1x[numvertices-2];
476                     c1y[numvertices-1] = 2 * y[numvertices - 1] - c1y[numvertices-2];
477                 } else {
478                     c1x[numvertices-1] = x[numvertices-1];
479                     c1y[numvertices-1] = y[numvertices-1];
480                 }
481                 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
482                 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
483                 numvertices++;
484                 break;
485             }
486
487             default:
488                 // FIXME
489             }
490
491             /*
492             // invariant: after this loop, no two lines intersect other than at a vertex
493             // FIXME: cleanup
494             int index = numvertices - 2;
495             for(int i=0; i<Math.min(numvertices - 3, index); i++) {
496                 for(int j = index; j < numvertices - 1; j++) {
497
498                     // I'm not sure how to deal with vertical lines...
499                     if (x[i+1] == x[i] || x[j+1] == x[j]) continue;
500                         
501                     float islope = (y[i+1] - y[i]) / (x[i+1] - x[i]);
502                     float jslope = (y[j+1] - y[j]) / (x[j+1] - x[j]);
503                     if (islope == jslope) continue;   // parallel lines can't intersect
504                         
505                     float _x = (islope * x[i] - jslope * x[j] + y[j] - y[i]) / (islope - jslope);
506                     float _y = islope * (_x - x[i]) + y[i];
507                         
508                     if (_x > Math.min(x[i+1], x[i]) && _x < Math.max(x[i+1], x[i]) &&
509                         _x > Math.min(x[j+1], x[j]) && _x < Math.max(x[j+1], x[j])) {
510                         // FIXME: something's not right in here.  See if we can do without fracturing line 'i'.
511                         for(int k = ++numvertices; k>i; k--) { x[k] = x[k - 1]; y[k] = y[k - 1]; }
512                         x[i+1] = _x;
513                         y[i+1] = _y;
514                         x[numvertices] = x[numvertices - 1];  x[numvertices - 1] = _x;
515                         y[numvertices] = y[numvertices - 1];  y[numvertices - 1] = _y;
516                         edges[numedges++] = numvertices - 1; numvertices++;
517                         index++;
518                         break;  // actually 'continue' the outermost loop
519                     }
520                 }
521             }
522             */
523
524         }
525     }
526
527
528
529
530     // Rasterized Vector Path //////////////////////////////////////////////////////////////////////////////
531     
532     /** a vector path */
533     public static class RasterPath {
534
535         // the vertices of this path
536         int[] x = new int[DEFAULT_PATHLEN];
537         int[] y = new int[DEFAULT_PATHLEN];
538         int numvertices = 0;
539
540         /**
541          *  A list of the vertices on this path which *start* an *edge* (rather than a moveto), sorted by increasing y.
542          *  example: x[edges[1]],y[edges[1]] - x[edges[i]+1],y[edges[i]+1] is the second-topmost edge
543          *  note that if x[i],y[i] - x[i+1],y[i+1] is a MOVETO, then no element in edges will be equal to i
544          */
545         int[] edges = new int[DEFAULT_PATHLEN];
546         int numedges = 0;
547
548         /** translate a rasterized path */
549         public void translate(int dx, int dy) { for(int i=0; i<numvertices; i++) { x[i] += dx; y[i] += dy; } }
550
551         /** simple quicksort, from http://sourceforge.net/snippet/detail.php?type=snippet&id=100240 */
552         int sort(int left, int right, boolean partition) {
553             if (partition) {
554                 int i, j, middle;
555                 middle = (left + right) / 2;
556                 int s = edges[right]; edges[right] = edges[middle]; edges[middle] = s;
557                 for (i = left - 1, j = right; ; ) {
558                     while (y[edges[++i]] < y[edges[right]]);
559                     while (j > left && y[edges[--j]] > y[edges[right]]);
560                     if (i >= j) break;
561                     s = edges[i]; edges[i] = edges[j]; edges[j] = s;
562                 }
563                 s = edges[right]; edges[right] = edges[i]; edges[i] = s;
564                 return i;
565             } else {
566                 if (left >= right) return 0;
567                 int p = sort(left, right, true);
568                 sort(left, p - 1, false);
569                 sort(p + 1, right, false);
570                 return 0;
571             }
572         }
573
574         /** finds the x value at which the line intercepts the line y=_y */
575         private int intercept(int i, float _y, boolean includeTop, boolean includeBottom) {
576             if (includeTop ? (_y < Math.min(y[i], y[i+1])) : (_y <= Math.min(y[i], y[i+1])))
577                 return Integer.MIN_VALUE;
578             if (includeBottom ? (_y > Math.max(y[i], y[i+1])) : (_y >= Math.max(y[i], y[i+1])))
579                 return Integer.MIN_VALUE;
580             return (int)Math.round((((float)(x[i + 1] - x[i])) /
581                                     ((float)(y[i + 1] - y[i])) ) * ((float)(_y - y[i])) + x[i]);
582         }
583
584         /** fill the interior of the path */
585         public void fill(PixelBuffer buf, Paint paint) {
586             if (numedges == 0) return;
587             int y0 = y[edges[0]], y1 = y0;
588             boolean useEvenOdd = false;
589
590             // we iterate over all endpoints in increasing y-coordinate order
591             for(int index = 1; index<numedges; index++) {
592                 int count = 0;
593
594                 // we now examine the horizontal band between y=y0 and y=y1
595                 y0 = y1;
596                 y1 = y[edges[index]];
597                 if (y0 == y1) continue;
598  
599                 // within this band, we iterate over all edges
600                 int x0 = Integer.MIN_VALUE;
601                 int leftSegment = -1;
602                 while(true) {
603                     int x1 = Integer.MAX_VALUE;
604                     int rightSegment = Integer.MAX_VALUE;
605                     for(int i=0; i<numedges; i++) {
606                         if (y[edges[i]] == y[edges[i]+1]) continue; // ignore horizontal lines; they are irrelevant.
607                         // we order the segments by the x-coordinate of their midpoint;
608                         // since segments cannot intersect, this is a well-ordering
609                         int i0 = intercept(edges[i], y0, true, false);
610                         int i1 = intercept(edges[i], y1, false, true);
611                         if (i0 == Integer.MIN_VALUE || i1 == Integer.MIN_VALUE) continue;
612                         int midpoint = i0 + i1;
613                         if (midpoint < x0) continue;
614                         if (midpoint == x0 && i <= leftSegment) continue;
615                         if (midpoint > x1) continue;
616                         if (midpoint == x1 && i >= rightSegment) continue;
617                         rightSegment = i;
618                         x1 = midpoint;
619                     }
620                     if (leftSegment == rightSegment || rightSegment == Integer.MAX_VALUE) break;
621                     if (leftSegment != -1)
622                         if ((useEvenOdd && count % 2 != 0) || (!useEvenOdd && count != 0))
623                             paint.fillTrapezoid(intercept(edges[leftSegment], y0, true, true),
624                                                 intercept(edges[rightSegment], y0, true, true), y0,
625                                                 intercept(edges[leftSegment], y1, true, true),
626                                                 intercept(edges[rightSegment], y1, true, true), y1,
627                                                 buf);
628                     if (useEvenOdd) count++;
629                     else count += (y[edges[rightSegment]] < y[edges[rightSegment]+1]) ? -1 : 1;
630                     leftSegment = rightSegment; x0 = x1;
631                 }
632             }
633         }
634         
635         /** stroke the outline of the path */
636         public void stroke(PixelBuffer buf, int width, int color) { stroke(buf, width, color, null, 0, 0); }
637         public void stroke(PixelBuffer buf, int width, int color, String dashArray, int dashOffset, float segLength) {
638
639             if (dashArray == null) {
640                 for(int i=0; i<numedges; i++)
641                     buf.drawLine((int)x[edges[i]],
642                                  (int)y[edges[i]], (int)x[edges[i]+1], (int)y[edges[i]+1], width, color, false);
643                 return;
644             }
645
646             float ratio = 1;
647             if (segLength > 0) {
648                 float actualLength = 0;
649                 for(int i=0; i<numvertices; i++) {
650                     // skip over MOVETOs -- they do not contribute to path length
651                     if (x[i] == x[i+1] && y[i] == y[i+1]) continue;
652                     if (x[i+1] == x[i+2] && y[i+1] == y[i+2]) continue;
653                     int x1 = x[i];
654                     int x2 = x[i + 1];
655                     int y1 = y[i];
656                     int y2 = y[i + 1];
657                     actualLength += java.lang.Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
658                 }
659                 ratio = actualLength / segLength;
660             }
661             PathTokenizer pt = new PathTokenizer(dashArray);
662             Vector v = new Vector();
663             while (pt.hasMoreTokens()) v.addElement(new Float(pt.parseFloat()));
664             float[] dashes = new float[v.size() % 2 == 0 ? v.size() : 2 * v.size()];
665             for(int i=0; i<dashes.length; i++) dashes[i] = ((Float)v.elementAt(i % v.size())).floatValue();
666             int dashpos = dashOffset;
667             boolean on = dashpos % 2 == 0;
668             for(int i=0; i<numvertices; i++) {
669                 // skip over MOVETOs -- they do not contribute to path length
670                 if (x[i] == x[i+1] && y[i] == y[i+1]) continue;
671                 if (x[i+1] == x[i+2] && y[i+1] == y[i+2]) continue;
672                 int x1 = (int)x[i];
673                 int x2 = (int)x[i + 1];
674                 int y1 = (int)y[i];
675                 int y2 = (int)y[i + 1];
676                 float segmentLength = (float)java.lang.Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
677                 int _x1 = x1, _y1 = y1;
678                 float pos = 0;
679                 do {
680                     pos = Math.min(segmentLength, pos + dashes[dashpos] * ratio);
681                     if (pos != segmentLength) dashpos = (dashpos + 1) % dashes.length;
682                     int _x2 = (int)((x2 * pos + x1 * (segmentLength - pos)) / segmentLength);
683                     int _y2 = (int)((y2 * pos + y1 * (segmentLength - pos)) / segmentLength);
684                     if (on) buf.drawLine(_x1, _y1, _x2, _y2, width, color, false);
685                     on = !on;
686                     _x1 = _x2; _y1 = _y2;
687                 } while(pos < segmentLength);
688             }
689         }
690
691         // FEATURE: make this faster and cache it; also deal with negative coordinates
692         public int boundingBoxWidth() {
693             int ret = 0;
694             for(int i=0; i<numvertices; i++) ret = Math.max(ret, x[i]);
695             return ret;
696         }
697
698         // FEATURE: make this faster and cache it; also deal with negative coordinates
699         public int boundingBoxHeight() {
700             int ret = 0;
701             for(int i=0; i<numvertices; i++) ret = Math.max(ret, y[i]);
702             return ret;
703         }
704     }
705     
706     
707     // Paint //////////////////////////////////////////////////////////////////////////////
708
709     public static interface Paint {
710         public abstract void
711             fillTrapezoid(int tx1, int tx2, int ty1, int tx3, int tx4, int ty2, PixelBuffer buf);
712     }
713
714     public static class SingleColorPaint implements Paint {
715         int color;
716         public SingleColorPaint(int color) { this.color = color; }
717         public void fillTrapezoid(int x1, int x2, int y1, int x3, int x4, int y2, PixelBuffer buf) {
718             buf.fillTrapezoid(x1, x2, y1, x3, x4, y2, color);
719         }
720     }
721
722 }
723
724
725
726
727
728
729
730
731
732     /*
733     public static abstract class GradientPaint extends Paint {
734         public GradientPaint(boolean reflect, boolean repeat, Affine gradientTransform,
735                              int[] stop_colors, float[] stop_offsets) {
736             this.reflect = reflect; this.repeat = repeat;
737             this.gradientTransform = gradientTransform;
738             this.stop_colors = stop_colors;
739             this.stop_offsets = stop_offsets;
740         }
741         Affine gradientTransform = Affine.identity();
742         boolean useBoundingBox = false;            // FIXME not supported
743         boolean patternUseBoundingBox = false;     // FIXME not supported
744
745         // it's invalid for both of these to be true
746         boolean reflect = false;                   // FIXME not supported
747         boolean repeat = false;                    // FIXME not supported
748         int[] stop_colors;
749         float[] stop_offsets;
750
751         public void fillTrapezoid(float tx1, float tx2, float ty1, float tx3, float tx4, float ty2, PixelBuffer buf) {
752             Affine a = buf.a;
753             Affine inverse = a.copy().invert();
754             float slope1 = (tx3 - tx1) / (ty2 - ty1);
755             float slope2 = (tx4 - tx2) / (ty2 - ty1);
756             for(float y=ty1; y<ty2; y++) {
757                 float _x1 = (y - ty1) * slope1 + tx1;
758                 float _x2 = (y - ty1) * slope2 + tx2;
759                 if (_x1 > _x2) { float _x0 = _x1; _x1 = _x2; _x2 = _x0; }
760
761                 for(float x=_x1; x<_x2; x++) {
762                     
763                     float distance = isLinear ?
764                         // length of projection of <x,y> onto the gradient vector == {<x,y> \dot {grad \over |grad|}}
765                         (x * (x2 - x1) + y * (y2 - y1)) / (float)Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) :
766                         
767                         // radial form is simple! FIXME, not quite right
768                         (float)Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy));
769                         
770                     // FIXME: offsets are 0..1, not 0..length(gradient)
771                     int i = 0; for(; i<stop_offsets.length; i++) if (distance < stop_offsets[i]) break;
772
773                     // FIXME: handle points beyond the bounds
774                     if (i < 0 || i >= stop_offsets.length) continue;
775
776                     // gradate from offsets[i - 1] to offsets[i]
777                     float percentage = ((distance - stop_offsets[i - 1]) / (stop_offsets[i] - stop_offsets[i - 1]));
778
779                     int a = (int)((((stop_colors[i] >> 24) & 0xff) - ((stop_colors[i - 1] >> 24) & 0xff)) * percentage) +
780                         ((stop_colors[i - 1] >> 24) & 0xff);
781                     int r = (int)((((stop_colors[i] >> 16) & 0xff) - ((stop_colors[i - 1] >> 16) & 0xff)) * percentage) +
782                         ((stop_colors[i - 1] >> 16) & 0xff);
783                     int g = (int)((((stop_colors[i] >> 8) & 0xff)  - ((stop_colors[i - 1] >> 8) & 0xff)) * percentage) +
784                         ((stop_colors[i - 1] >> 8) & 0xff);
785                     int b = (int)((((stop_colors[i] >> 0) & 0xff)  - ((stop_colors[i - 1] >> 0) & 0xff)) * percentage) +
786                         ((stop_colors[i - 1] >> 0) & 0xff);
787                     int argb = (a << 24) | (r << 16) | (g << 8) | b;
788                     buf.drawPoint((int)x, (int)Math.floor(y), argb);
789                 }
790             }
791         }
792     }
793
794     public static class LinearGradientPaint extends GradientPaint {
795         public LinearGradientPaint(float x1, float y1, float x2, float y2, boolean reflect, boolean repeat,
796                                    Affine gradientTransform,  int[] stop_colors, float[] stop_offsets) {
797             super(reflect, repeat, gradientTransform, stop_colors, stop_offsets);
798             this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2;
799         }
800         float x1 = 0, y1 = 0, x2 = 300, y2 = 300;
801     }
802
803     public static class RadialGradientPaint extends GradientPaint {
804         public RadialGradientPaint(float cx, float cy, float fx, float fy, float r, boolean reflect, boolean repeat,
805                              Affine gradientTransform, int[] stop_colors, float[] stop_offsets) {
806             super(reflect, repeat, gradientTransform, stop_colors, stop_offsets);
807             this.cx = cx; this.cy = cy; this.fx = fx; this.fy = fy; this.r = r;
808         }
809             
810         float cx, cy, r, fx, fy;
811
812     }
813     */
814