BasicStroke.java 26.8 KB
Newer Older
1
/* BasicStroke.java --
2
   Copyright (C) 2002, 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
Tom Tromey committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package java.awt;

41 42 43 44 45
import gnu.java.awt.java2d.CubicSegment;
import gnu.java.awt.java2d.LineSegment;
import gnu.java.awt.java2d.QuadSegment;
import gnu.java.awt.java2d.Segment;

46
import java.awt.geom.FlatteningPathIterator;
47 48 49
import java.awt.geom.GeneralPath;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
Tom Tromey committed
50 51 52
import java.util.Arrays;

/**
53 54 55
 * A general purpose {@link Stroke} implementation that can represent a wide
 * variety of line styles for use with subclasses of {@link Graphics2D}.
 * <p>
56
 * The line cap and join styles can be set using the options illustrated
57 58 59 60 61 62 63
 * here:
 * <p>
 * <img src="doc-files/capjoin.png" width="350" height="180"
 * alt="Illustration of line cap and join styles" />
 * <p>
 * A dash array can be used to specify lines with alternating opaque and
 * transparent sections.
Tom Tromey committed
64 65 66
 */
public class BasicStroke implements Stroke
{
67
  /**
68 69 70
   * Indicates a mitered line join style. See the class overview for an
   * illustration.
   */
Tom Tromey committed
71
  public static final int JOIN_MITER = 0;
72 73

  /**
74 75 76
   * Indicates a rounded line join style. See the class overview for an
   * illustration.
   */
Tom Tromey committed
77
  public static final int JOIN_ROUND = 1;
78 79

  /**
80 81 82
   * Indicates a bevelled line join style. See the class overview for an
   * illustration.
   */
Tom Tromey committed
83 84
  public static final int JOIN_BEVEL = 2;

85
  /**
86 87 88
   * Indicates a flat line cap style. See the class overview for an
   * illustration.
   */
Tom Tromey committed
89
  public static final int CAP_BUTT = 0;
90 91

  /**
92 93 94
   * Indicates a rounded line cap style. See the class overview for an
   * illustration.
   */
Tom Tromey committed
95
  public static final int CAP_ROUND = 1;
96 97

  /**
98 99 100
   * Indicates a square line cap style. See the class overview for an
   * illustration.
   */
Tom Tromey committed
101 102
  public static final int CAP_SQUARE = 2;

103
  /** The stroke width. */
Tom Tromey committed
104
  private final float width;
105

106
  /** The line cap style. */
Tom Tromey committed
107
  private final int cap;
108

109
  /** The line join style. */
Tom Tromey committed
110
  private final int join;
111

112
  /** The miter limit. */
Tom Tromey committed
113
  private final float limit;
114

115
  /** The dash array. */
Tom Tromey committed
116
  private final float[] dash;
117

118
  /** The dash phase. */
Tom Tromey committed
119 120
  private final float phase;

121
  // The inner and outer paths of the stroke
122 123
  private Segment start, end;

Tom Tromey committed
124
  /**
125
   * Creates a new <code>BasicStroke</code> instance with the given attributes.
Tom Tromey committed
126
   *
127
   * @param width  the line width (>= 0.0f).
128
   * @param cap  the line cap style (one of {@link #CAP_BUTT},
129
   *             {@link #CAP_ROUND} or {@link #CAP_SQUARE}).
130
   * @param join  the line join style (one of {@link #JOIN_ROUND},
131 132
   *              {@link #JOIN_BEVEL}, or {@link #JOIN_MITER}).
   * @param miterlimit  the limit to trim the miter join. The miterlimit must be
Tom Tromey committed
133 134 135 136 137
   * greater than or equal to 1.0f.
   * @param dash The array representing the dashing pattern. There must be at
   * least one non-zero entry.
   * @param dashPhase is negative and dash is not null.
   *
138
   * @throws IllegalArgumentException If one input parameter doesn't meet
Tom Tromey committed
139 140 141 142 143 144 145 146 147
   * its needs.
   */
  public BasicStroke(float width, int cap, int join, float miterlimit,
                     float[] dash, float dashPhase)
  {
    if (width < 0.0f )
      throw new IllegalArgumentException("width " + width + " < 0");
    else if (cap < CAP_BUTT || cap > CAP_SQUARE)
      throw new IllegalArgumentException("cap " + cap + " out of range ["
148
                                         + CAP_BUTT + ".." + CAP_SQUARE + "]");
Tom Tromey committed
149 150
    else if (miterlimit < 1.0f && join == JOIN_MITER)
      throw new IllegalArgumentException("miterlimit " + miterlimit
151
                                         + " < 1.0f while join == JOIN_MITER");
Tom Tromey committed
152 153
    else if (join < JOIN_MITER || join > JOIN_BEVEL)
      throw new IllegalArgumentException("join " + join + " out of range ["
154 155
                                         + JOIN_MITER + ".." + JOIN_BEVEL
                                         + "]");
Tom Tromey committed
156 157
    else if (dashPhase < 0.0f && dash != null)
      throw new IllegalArgumentException("dashPhase " + dashPhase
158
                                         + " < 0.0f while dash != null");
Tom Tromey committed
159 160
    else if (dash != null)
      if (dash.length == 0)
161
        throw new IllegalArgumentException("dash.length is 0");
Tom Tromey committed
162
      else
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
        {
          boolean allZero = true;

          for ( int i = 0; i < dash.length; ++i)
            {
              if (dash[i] != 0.0f)
                {
                  allZero = false;
                  break;
                }
            }

          if (allZero)
            throw new IllegalArgumentException("all dashes are 0.0f");
        }
Tom Tromey committed
178 179 180 181 182 183 184 185 186 187

    this.width = width;
    this.cap = cap;
    this.join = join;
    limit = miterlimit;
    this.dash = dash == null ? null : (float[]) dash.clone();
    phase = dashPhase;
  }

  /**
188
   * Creates a new <code>BasicStroke</code> instance with the given attributes.
Tom Tromey committed
189
   *
190
   * @param width  the line width (>= 0.0f).
191
   * @param cap  the line cap style (one of {@link #CAP_BUTT},
192
   *             {@link #CAP_ROUND} or {@link #CAP_SQUARE}).
193
   * @param join  the line join style (one of {@link #JOIN_ROUND},
194
   *              {@link #JOIN_BEVEL}, or {@link #JOIN_MITER}).
Tom Tromey committed
195 196
   * @param miterlimit the limit to trim the miter join. The miterlimit must be
   * greater than or equal to 1.0f.
197
   *
198
   * @throws IllegalArgumentException If one input parameter doesn't meet
Tom Tromey committed
199 200 201 202 203 204 205 206
   * its needs.
   */
  public BasicStroke(float width, int cap, int join, float miterlimit)
  {
    this(width, cap, join, miterlimit, null, 0);
  }

  /**
207 208
   * Creates a new <code>BasicStroke</code> instance with the given attributes.
   * The miter limit defaults to <code>10.0</code>.
Tom Tromey committed
209
   *
210
   * @param width  the line width (>= 0.0f).
211
   * @param cap  the line cap style (one of {@link #CAP_BUTT},
212
   *             {@link #CAP_ROUND} or {@link #CAP_SQUARE}).
213
   * @param join  the line join style (one of {@link #JOIN_ROUND},
214
   *              {@link #JOIN_BEVEL}, or {@link #JOIN_MITER}).
215
   *
216
   * @throws IllegalArgumentException If one input parameter doesn't meet
Tom Tromey committed
217 218 219 220 221 222 223 224
   * its needs.
   */
  public BasicStroke(float width, int cap, int join)
  {
    this(width, cap, join, 10, null, 0);
  }

  /**
225 226 227 228 229 230 231
   * Creates a new <code>BasicStroke</code> instance with the given line
   * width.  The default values are:
   * <ul>
   * <li>line cap style: {@link #CAP_SQUARE};</li>
   * <li>line join style: {@link #JOIN_MITER};</li>
   * <li>miter limit: <code>10.0f</code>.
   * </ul>
232
   *
233
   * @param width  the line width (>= 0.0f).
234
   *
235
   * @throws IllegalArgumentException If <code>width</code> is negative.
Tom Tromey committed
236 237 238 239 240 241 242
   */
  public BasicStroke(float width)
  {
    this(width, CAP_SQUARE, JOIN_MITER, 10, null, 0);
  }

  /**
243 244 245 246 247 248 249
   * Creates a new <code>BasicStroke</code> instance.  The default values are:
   * <ul>
   * <li>line width: <code>1.0f</code>;</li>
   * <li>line cap style: {@link #CAP_SQUARE};</li>
   * <li>line join style: {@link #JOIN_MITER};</li>
   * <li>miter limit: <code>10.0f</code>.
   * </ul>
Tom Tromey committed
250 251 252 253 254
   */
  public BasicStroke()
  {
    this(1, CAP_SQUARE, JOIN_MITER, 10, null, 0);
  }
255

256 257 258
  /**
   * Creates a shape representing the stroked outline of the given shape.
   * THIS METHOD IS NOT YET IMPLEMENTED.
259
   *
260 261
   * @param s  the shape.
   */
Tom Tromey committed
262 263
  public Shape createStrokedShape(Shape s)
  {
264
    PathIterator pi = s.getPathIterator(null);
265 266 267 268 269

    if( dash == null )
      return solidStroke( pi );

    return dashedStroke( pi );
Tom Tromey committed
270 271
  }

272 273
  /**
   * Returns the line width.
274
   *
275 276
   * @return The line width.
   */
Tom Tromey committed
277 278 279 280 281
  public float getLineWidth()
  {
    return width;
  }

282 283 284
  /**
   * Returns a code indicating the line cap style (one of {@link #CAP_BUTT},
   * {@link #CAP_ROUND}, {@link #CAP_SQUARE}).
285
   *
286 287
   * @return A code indicating the line cap style.
   */
Tom Tromey committed
288 289 290 291 292
  public int getEndCap()
  {
    return cap;
  }

293 294 295
  /**
   * Returns a code indicating the line join style (one of {@link #JOIN_BEVEL},
   * {@link #JOIN_MITER} or {@link #JOIN_ROUND}).
296
   *
297 298
   * @return A code indicating the line join style.
   */
Tom Tromey committed
299 300 301 302 303
  public int getLineJoin()
  {
    return join;
  }

304 305
  /**
   * Returns the miter limit.
306
   *
307 308
   * @return The miter limit.
   */
Tom Tromey committed
309 310 311 312 313
  public float getMiterLimit()
  {
    return limit;
  }

314
  /**
315 316
   * Returns the dash array, which defines the length of alternate opaque and
   * transparent sections in lines drawn with this stroke.  If
317
   * <code>null</code>, a continuous line will be drawn.
318
   *
319 320
   * @return The dash array (possibly <code>null</code>).
   */
Tom Tromey committed
321 322 323 324 325
  public float[] getDashArray()
  {
    return dash;
  }

326 327
  /**
   * Returns the dash phase for the stroke.  This is the offset from the start
328
   * of a path at which the pattern defined by {@link #getDashArray()} is
329
   * rendered.
330
   *
331 332
   * @return The dash phase.
   */
Tom Tromey committed
333 334 335 336 337 338 339 340 341 342 343
  public float getDashPhase()
  {
    return phase;
  }

  /**
   * Returns the hash code for this object. The hash is calculated by
   * xoring the hash, cap, join, limit, dash array and phase values
   * (converted to <code>int</code> first with
   * <code>Float.floatToIntBits()</code> if the value is a
   * <code>float</code>).
344
   *
345
   * @return The hash code.
Tom Tromey committed
346 347 348 349 350 351 352
   */
  public int hashCode()
  {
    int hash = Float.floatToIntBits(width);
    hash ^= cap;
    hash ^= join;
    hash ^= Float.floatToIntBits(limit);
353

Tom Tromey committed
354 355
    if (dash != null)
      for (int i = 0; i < dash.length; i++)
356
        hash ^=  Float.floatToIntBits(dash[i]);
Tom Tromey committed
357 358 359 360 361 362 363

    hash ^= Float.floatToIntBits(phase);

    return hash;
  }

  /**
364
   * Compares this <code>BasicStroke</code> for equality with an arbitrary
365 366
   * object.  This method returns <code>true</code> if and only if:
   * <ul>
367
   * <li><code>o</code> is an instanceof <code>BasicStroke</code>;</li>
368 369 370
   * <li>this object has the same width, line cap style, line join style,
   * miter limit, dash array and dash phase as <code>o</code>.</li>
   * </ul>
371
   *
372
   * @param o  the object (<code>null</code> permitted).
373
   *
374 375
   * @return <code>true</code> if this stroke is equal to <code>o</code> and
   *         <code>false</code> otherwise.
Tom Tromey committed
376 377 378 379 380 381 382 383 384
   */
  public boolean equals(Object o)
  {
    if (! (o instanceof BasicStroke))
      return false;
    BasicStroke s = (BasicStroke) o;
    return width == s.width && cap == s.cap && join == s.join
      && limit == s.limit && Arrays.equals(dash, s.dash) && phase == s.phase;
  }
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403

  private Shape solidStroke(PathIterator pi)
  {
    double[] coords = new double[6];
    double x, y, x0, y0;
    boolean pathOpen = false;
    GeneralPath output = new GeneralPath( );
    Segment[] p;
    x = x0 = y = y0 = 0;

    while( !pi.isDone() )
      {
        switch( pi.currentSegment(coords) )
          {
          case PathIterator.SEG_MOVETO:
            x0 = x = coords[0];
            y0 = y = coords[1];
            if( pathOpen )
              {
404
                capEnds();
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
                convertPath(output, start);
                start = end = null;
                pathOpen = false;
              }
            break;

          case PathIterator.SEG_LINETO:
            p = (new LineSegment(x, y, coords[0], coords[1])).
              getDisplacedSegments(width/2.0);
            if( !pathOpen )
              {
                start = p[0];
                end = p[1];
                pathOpen = true;
              }
            else
              addSegments(p);

            x = coords[0];
            y = coords[1];
            break;

          case PathIterator.SEG_QUADTO:
428
            p = (new QuadSegment(x, y, coords[0], coords[1], coords[2],
429 430 431 432 433 434 435 436 437 438
                                 coords[3])).getDisplacedSegments(width/2.0);
            if( !pathOpen )
              {
                start = p[0];
                end = p[1];
                pathOpen = true;
              }
            else
              addSegments(p);

439 440
            x = coords[2];
            y = coords[3];
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
            break;

          case PathIterator.SEG_CUBICTO:
            p = new CubicSegment(x, y, coords[0], coords[1],
                                 coords[2], coords[3],
                                 coords[4], coords[5]).getDisplacedSegments(width/2.0);
            if( !pathOpen )
              {
                start = p[0];
                end = p[1];
                pathOpen = true;
              }
            else
              addSegments(p);

456 457
            x = coords[4];
            y = coords[5];
458 459 460
            break;

          case PathIterator.SEG_CLOSE:
461 462 463 464 465 466 467 468 469
            if (x == x0 && y == y0)
              {
                joinSegments(new Segment[] { start.first, end.first });
              }
            else
              {
                p = (new LineSegment(x, y, x0, y0)).getDisplacedSegments(width / 2.0);
                addSegments(p);
              }
470 471 472 473
            convertPath(output, start);
            convertPath(output, end);
            start = end = null;
            pathOpen = false;
474
            output.setWindingRule(GeneralPath.WIND_EVEN_ODD);
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
            break;
          }
        pi.next();
      }

    if( pathOpen )
      {
        capEnds();
        convertPath(output, start);
      }
    return output;
  }

  private Shape dashedStroke(PathIterator pi)
  {
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
    // The choice of (flatnessSq == width / 3) is made to be consistent with
    // the flattening in CubicSegment.getDisplacedSegments
    FlatteningPathIterator flat = new FlatteningPathIterator(pi,
                                                             Math.sqrt(width / 3));

    // Holds the endpoint of the current segment (or piece of a segment)
    double[] coords = new double[2];

    // Holds end of the last segment
    double x, y, x0, y0;
    x = x0 = y = y0 = 0;

    // Various useful flags
    boolean pathOpen = false;
    boolean dashOn = true;
    boolean offsetting = (phase != 0);

    // How far we are into the current dash
    double distance = 0;
    int dashIndex = 0;

    // And variables to hold the final output
    GeneralPath output = new GeneralPath();
    Segment[] p;

    // Iterate over the FlatteningPathIterator
    while (! flat.isDone())
      {
        switch (flat.currentSegment(coords))
          {
          case PathIterator.SEG_MOVETO:
            x0 = x = coords[0];
            y0 = y = coords[1];

            if (pathOpen)
              {
                capEnds();
                convertPath(output, start);
                start = end = null;
                pathOpen = false;
              }

            break;

          case PathIterator.SEG_LINETO:
            boolean segmentConsumed = false;

            while (! segmentConsumed)
              {
                // Find the total remaining length of this segment
                double segLength = Math.sqrt((x - coords[0]) * (x - coords[0])
                                             + (y - coords[1])
                                             * (y - coords[1]));
                boolean spanBoundary = true;
                double[] segmentEnd = null;

                // The current segment fits entirely inside the current dash
                if ((offsetting && distance + segLength <= phase)
                    || distance + segLength <= dash[dashIndex])
                  {
                    spanBoundary = false;
                  }
552

553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
                // Otherwise, we need to split the segment in two, as this
                // segment spans a dash boundry
                else
                  {
                    segmentEnd = (double[]) coords.clone();

                    // Calculate the remaining distance in this dash,
                    // and coordinates of the dash boundary
                    double reqLength;
                    if (offsetting)
                      reqLength = phase - distance;
                    else
                      reqLength = dash[dashIndex] - distance;

                    coords[0] = x + ((coords[0] - x) * reqLength / segLength);
                    coords[1] = y + ((coords[1] - y) * reqLength / segLength);
                  }

                if (offsetting || ! dashOn)
                  {
                    // Dash is off, or we are in offset - treat this as a
                    // moveTo
                    x0 = x = coords[0];
                    y0 = y = coords[1];

                    if (pathOpen)
                      {
                        capEnds();
                        convertPath(output, start);
                        start = end = null;
                        pathOpen = false;
                      }
                  }
                else
                  {
                    // Dash is on - treat this as a lineTo
                    p = (new LineSegment(x, y, coords[0], coords[1])).getDisplacedSegments(width / 2.0);

                    if (! pathOpen)
                      {
                        start = p[0];
                        end = p[1];
                        pathOpen = true;
                      }
                    else
                      addSegments(p);

                    x = coords[0];
                    y = coords[1];
                  }

                // Update variables depending on whether we spanned a
                // dash boundary or not
                if (! spanBoundary)
                  {
                    distance += segLength;
                    segmentConsumed = true;
                  }
                else
                  {
                    if (offsetting)
                      offsetting = false;
                    dashOn = ! dashOn;
                    distance = 0;
                    coords = segmentEnd;

                    if (dashIndex + 1 == dash.length)
                      dashIndex = 0;
                    else
                      dashIndex++;

                    // Since the value of segmentConsumed is still false,
                    // the next run of the while loop will complete the segment
                  }
              }
            break;

          // This is a flattened path, so we don't need to deal with curves
          }
        flat.next();
      }

    if (pathOpen)
      {
        capEnds();
        convertPath(output, start);
      }
    return output;
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
  }

  /**
   * Cap the ends of the path (joining the start and end list of segments)
   */
  private void capEnds()
  {
    Segment returnPath = end.last;

    end.reverseAll(); // reverse the path.
    end = null;
    capEnd(start, returnPath);
    start.last = returnPath.last;
    end = null;

    capEnd(start, start);
  }

  /**
660
   * Append the Segments in s to the GeneralPath p
661 662 663 664 665 666 667 668 669 670 671 672 673
   */
  private void convertPath(GeneralPath p, Segment s)
  {
    Segment v = s;
    p.moveTo((float)s.P1.getX(), (float)s.P1.getY());

    do
      {
        if(v instanceof LineSegment)
          p.lineTo((float)v.P2.getX(), (float)v.P2.getY());
        else if(v instanceof QuadSegment)
          p.quadTo((float)((QuadSegment)v).cp.getX(),
                   (float)((QuadSegment)v).cp.getY(),
674
                   (float)v.P2.getX(),
675 676 677 678 679 680
                   (float)v.P2.getY());
        else if(v instanceof CubicSegment)
          p.curveTo((float)((CubicSegment)v).cp1.getX(),
                    (float)((CubicSegment)v).cp1.getY(),
                    (float)((CubicSegment)v).cp2.getX(),
                    (float)((CubicSegment)v).cp2.getY(),
681
                    (float)v.P2.getX(),
682 683 684 685 686 687
                    (float)v.P2.getY());
        v = v.next;
      } while(v != s && v != null);

    p.closePath();
  }
688

689
  /**
690
   * Add the segments to start and end (the inner and outer edges of the stroke)
691 692 693
   */
  private void addSegments(Segment[] segments)
  {
694 695 696 697 698 699 700 701
    joinSegments(segments);
    start.add(segments[0]);
    end.add(segments[1]);
  }

  private void joinSegments(Segment[] segments)
  {
    double[] p0 = start.last.cp2();
702
    double[] p1 = new double[]{start.last.P2.getX(), start.last.P2.getY()};
703 704
    double[] p2 = new double[]{segments[0].first.P1.getX(), segments[0].first.P1.getY()};
    double[] p3 = segments[0].cp1();
705 706
    Point2D p;

707 708 709
    p = lineIntersection(p0[0],p0[1],p1[0],p1[1],
                                 p2[0],p2[1],p3[0],p3[1], false);

710
    double det = (p1[0] - p0[0])*(p3[1] - p2[1]) -
711 712 713 714
      (p3[0] - p2[0])*(p1[1] - p0[1]);

    if( det > 0 )
      {
715
        // start and segment[0] form the 'inner' part of a join,
716
        // connect the overlapping segments
717 718
        joinInnerSegments(start, segments[0], p);
        joinOuterSegments(end, segments[1], p);
719 720 721
      }
    else
      {
722
        // end and segment[1] form the 'inner' part
723 724
        joinInnerSegments(end, segments[1], p);
        joinOuterSegments(start, segments[0], p);
725 726 727 728
      }
  }

  /**
729
   * Make a cap between a and b segments,
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
   * where a-->b is the direction of iteration.
   */
  private void capEnd(Segment a, Segment b)
  {
    double[] p0, p1;
    double dx, dy, l;
    Point2D c1,c2;

    switch( cap )
      {
      case CAP_BUTT:
        a.add(new LineSegment(a.last.P2, b.P1));
        break;

      case CAP_SQUARE:
745
        p0 = a.last.cp2();
746 747 748 749 750 751 752 753 754 755 756 757 758 759
        p1 = new double[]{a.last.P2.getX(), a.last.P2.getY()};
        dx = p1[0] - p0[0];
        dy = p1[1] - p0[1];
        l = Math.sqrt(dx * dx + dy * dy);
        dx = 0.5*width*dx/l;
        dy = 0.5*width*dy/l;
        c1 = new Point2D.Double(p1[0] + dx, p1[1] + dy);
        c2 = new Point2D.Double(b.P1.getX() + dx, b.P1.getY() + dy);
        a.add(new LineSegment(a.last.P2, c1));
        a.add(new LineSegment(c1, c2));
        a.add(new LineSegment(c2, b.P1));
        break;

      case CAP_ROUND:
760
        p0 = a.last.cp2();
761 762 763
        p1 = new double[]{a.last.P2.getX(), a.last.P2.getY()};
        dx = p1[0] - p0[0];
        dy = p1[1] - p0[1];
764 765 766 767 768 769
        if (dx != 0 && dy != 0)
          {
            l = Math.sqrt(dx * dx + dy * dy);
            dx = (2.0/3.0)*width*dx/l;
            dy = (2.0/3.0)*width*dy/l;
          }
770

771 772 773 774 775 776 777 778 779 780 781 782 783 784
        c1 = new Point2D.Double(p1[0] + dx, p1[1] + dy);
        c2 = new Point2D.Double(b.P1.getX() + dx, b.P1.getY() + dy);
        a.add(new CubicSegment(a.last.P2, c1, c2, b.P1));
        break;
      }
    a.add(b);
  }

  /**
   * Returns the intersection of two lines, or null if there isn't one.
   * @param infinite - true if the lines should be regarded as infinite, false
   * if the intersection must be within the given segments.
   * @return a Point2D or null.
   */
785 786 787
  private Point2D lineIntersection(double X1, double Y1,
                                   double X2, double Y2,
                                   double X3, double Y3,
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
                                   double X4, double Y4,
                                   boolean infinite)
  {
    double x1 = X1;
    double y1 = Y1;
    double rx = X2 - x1;
    double ry = Y2 - y1;

    double x2 = X3;
    double y2 = Y3;
    double sx = X4 - x2;
    double sy = Y4 - y2;

    double determinant = sx * ry - sy * rx;
    double nom = (sx * (y2 - y1) + sy * (x1 - x2));

    // lines can be considered parallel.
    if (Math.abs(determinant) < 1E-6)
      return null;

    nom = nom / determinant;

    // check if lines are within the bounds
    if(!infinite && (nom > 1.0 || nom < 0.0))
      return null;

    return new Point2D.Double(x1 + nom * rx, y1 + nom * ry);
  }

  /**
   * Join a and b segments, where a-->b is the direction of iteration.
   *
   * insideP is the inside intersection point of the join, needed for
   * calculating miter lengths.
   */
823
  private void joinOuterSegments(Segment a, Segment b, Point2D insideP)
824 825 826 827 828 829 830 831
  {
    double[] p0, p1;
    double dx, dy, l;
    Point2D c1,c2;

    switch( join )
      {
      case JOIN_MITER:
832
        p0 = a.last.cp2();
833 834
        p1 = new double[]{a.last.P2.getX(), a.last.P2.getY()};
        double[] p2 = new double[]{b.P1.getX(), b.P1.getY()};
835
        double[] p3 = b.cp1();
836 837 838 839 840 841 842
        Point2D p = lineIntersection(p0[0],p0[1],p1[0],p1[1],p2[0],p2[1],p3[0],p3[1], true);
        if( p == null || insideP == null )
          a.add(new LineSegment(a.last.P2, b.P1));
        else if((p.distance(insideP)/width) < limit)
          {
            a.add(new LineSegment(a.last.P2, p));
            a.add(new LineSegment(p, b.P1));
843
          }
844 845 846 847 848 849 850 851
        else
          {
            // outside miter limit, do a bevel join.
            a.add(new LineSegment(a.last.P2, b.P1));
          }
        break;

      case JOIN_ROUND:
852
        p0 = a.last.cp2();
853 854 855 856 857 858 859 860 861
        p1 = new double[]{a.last.P2.getX(), a.last.P2.getY()};
        dx = p1[0] - p0[0];
        dy = p1[1] - p0[1];
        l = Math.sqrt(dx * dx + dy * dy);
        dx = 0.5*width*dx/l;
        dy = 0.5*width*dy/l;
        c1 = new Point2D.Double(p1[0] + dx, p1[1] + dy);

        p0 = new double[]{b.P1.getX(), b.P1.getY()};
862
        p1 = b.cp1();
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877

        dx = p0[0] - p1[0]; // backwards direction.
        dy = p0[1] - p1[1];
        l = Math.sqrt(dx * dx + dy * dy);
        dx = 0.5*width*dx/l;
        dy = 0.5*width*dy/l;
        c2 = new Point2D.Double(p0[0] + dx, p0[1] + dy);
        a.add(new CubicSegment(a.last.P2, c1, c2, b.P1));
        break;

      case JOIN_BEVEL:
        a.add(new LineSegment(a.last.P2, b.P1));
        break;
      }
  }
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902

  /**
   * Join a and b segments, removing any overlap
   */
  private void joinInnerSegments(Segment a, Segment b, Point2D p)
  {
    double[] p0 = a.last.cp2();
    double[] p1 = new double[] { a.last.P2.getX(), a.last.P2.getY() };
    double[] p2 = new double[] { b.P1.getX(), b.P1.getY() };
    double[] p3 = b.cp1();

    if (p == null)
      {
        // Dodgy.
        a.add(new LineSegment(a.last.P2, b.P1));
        p = new Point2D.Double((b.P1.getX() + a.last.P2.getX()) / 2.0,
                               (b.P1.getY() + a.last.P2.getY()) / 2.0);
      }
    else
      // This assumes segments a and b are single segments, which is
      // incorrect - if they are a linked list of segments (ie, passed in
      // from a flattening operation), this produces strange results!!
      a.last.P2 = b.P1 = p;
  }
}