1 /*
   2  * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.marlin;
  27 
  28 import java.util.Arrays;
  29 import com.sun.javafx.geom.PathConsumer2D;
  30 
  31 /**
  32  * The <code>Dasher</code> class takes a series of linear commands
  33  * (<code>moveTo</code>, <code>lineTo</code>, <code>close</code> and
  34  * <code>end</code>) and breaks them into smaller segments according to a
  35  * dash pattern array and a starting dash phase.
  36  *
  37  * <p> Issues: in J2Se, a zero length dash segment as drawn as a very
  38  * short dash, whereas Pisces does not draw anything.  The PostScript
  39  * semantics are unclear.
  40  *
  41  */
  42 public final class Dasher implements PathConsumer2D, MarlinConst {
  43 
  44     static final int REC_LIMIT = 4;
  45     static final float ERR = 0.01f;
  46     static final float MIN_T_INC = 1.0f / (1 << REC_LIMIT);
  47 
  48     // More than 24 bits of mantissa means we can no longer accurately
  49     // measure the number of times cycled through the dash array so we
  50     // punt and override the phase to just be 0 past that point.
  51     static final float MAX_CYCLES = 16000000.0f;
  52 
  53     private PathConsumer2D out;
  54     private float[] dash;
  55     private int dashLen;
  56     private float startPhase;
  57     private boolean startDashOn;
  58     private int startIdx;
  59 
  60     private boolean starting;
  61     private boolean needsMoveTo;
  62 
  63     private int idx;
  64     private boolean dashOn;
  65     private float phase;
  66 
  67     private float sx, sy;
  68     private float x0, y0;
  69 
  70     // temporary storage for the current curve
  71     private final float[] curCurvepts;
  72 
  73     // per-thread renderer context
  74     final RendererContext rdrCtx;
  75 
  76     // flag to recycle dash array copy
  77     boolean recycleDashes;
  78 
  79     // dashes ref (dirty)
  80     final FloatArrayCache.Reference dashes_ref;
  81     // firstSegmentsBuffer ref (dirty)
  82     final FloatArrayCache.Reference firstSegmentsBuffer_ref;
  83 
  84     /**
  85      * Constructs a <code>Dasher</code>.
  86      * @param rdrCtx per-thread renderer context
  87      */
  88     Dasher(final RendererContext rdrCtx) {
  89         this.rdrCtx = rdrCtx;
  90 
  91         dashes_ref = rdrCtx.newDirtyFloatArrayRef(INITIAL_ARRAY); // 1K
  92 
  93         firstSegmentsBuffer_ref = rdrCtx.newDirtyFloatArrayRef(INITIAL_ARRAY); // 1K
  94         firstSegmentsBuffer     = firstSegmentsBuffer_ref.initial;
  95 
  96         // we need curCurvepts to be able to contain 2 curves because when
  97         // dashing curves, we need to subdivide it
  98         curCurvepts = new float[8 * 2];
  99     }
 100 
 101     /**
 102      * Initialize the <code>Dasher</code>.
 103      *
 104      * @param out an output <code>PathConsumer2D</code>.
 105      * @param dash an array of <code>float</code>s containing the dash pattern
 106      * @param dashLen length of the given dash array
 107      * @param phase a <code>float</code> containing the dash phase
 108      * @param recycleDashes true to indicate to recycle the given dash array
 109      * @return this instance
 110      */
 111     public Dasher init(final PathConsumer2D out, final float[] dash, final int dashLen,
 112                        float phase, final boolean recycleDashes)
 113     {
 114         this.out = out;
 115 
 116         // Normalize so 0 <= phase < dash[0]
 117         int sidx = 0;
 118         dashOn = true;
 119 
 120         // note: BasicStroke constructor checks dash elements and sum > 0
 121         float sum = 0.0f;
 122         for (int i = 0; i < dashLen; i++) {
 123             sum += dash[i];
 124         }
 125         float cycles = phase / sum;
 126         if (phase < 0.0f) {
 127             if (-cycles >= MAX_CYCLES) {
 128                 phase = 0.0f;
 129             } else {
 130                 int fullcycles = FloatMath.floor_int(-cycles);
 131                 if ((fullcycles & dashLen & 1) != 0) {
 132                     dashOn = !dashOn;
 133                 }
 134                 phase += fullcycles * sum;
 135                 while (phase < 0.0f) {
 136                     if (--sidx < 0) {
 137                         sidx = dashLen - 1;
 138                     }
 139                     phase += dash[sidx];
 140                     dashOn = !dashOn;
 141                 }
 142             }
 143         } else if (phase > 0.0f) {
 144             if (cycles >= MAX_CYCLES) {
 145                 phase = 0.0f;
 146             } else {
 147                 int fullcycles = FloatMath.floor_int(cycles);
 148                 if ((fullcycles & dashLen & 1) != 0) {
 149                     dashOn = !dashOn;
 150                 }
 151                 phase -= fullcycles * sum;
 152                 float d;
 153                 while (phase >= (d = dash[sidx])) {
 154                     phase -= d;
 155                     sidx = (sidx + 1) % dashLen;
 156                     dashOn = !dashOn;
 157                 }
 158             }
 159         }
 160 
 161         this.dash = dash;
 162         this.dashLen = dashLen;
 163         this.phase = phase;
 164         this.startPhase = phase;
 165         this.startDashOn = dashOn;
 166         this.startIdx = sidx;
 167         this.starting = true;
 168         this.needsMoveTo = false;
 169         this.firstSegidx = 0;
 170 
 171         this.recycleDashes = recycleDashes;
 172 
 173         return this; // fluent API
 174     }
 175 
 176     /**
 177      * Disposes this dasher:
 178      * clean up before reusing this instance
 179      */
 180     void dispose() {
 181         if (DO_CLEAN_DIRTY) {
 182             // Force zero-fill dirty arrays:
 183             Arrays.fill(curCurvepts, 0.0f);
 184         }
 185         // Return arrays:
 186         if (recycleDashes) {
 187             dash = dashes_ref.putArray(dash);
 188         }
 189         firstSegmentsBuffer = firstSegmentsBuffer_ref.putArray(firstSegmentsBuffer);
 190     }
 191 
 192     public float[] copyDashArray(final float[] dashes) {
 193         final int len = dashes.length;
 194         final float[] newDashes;
 195         if (len <= MarlinConst.INITIAL_ARRAY) {
 196             newDashes = dashes_ref.initial;
 197         } else {
 198             if (DO_STATS) {
 199                 rdrCtx.stats.stat_array_dasher_dasher.add(len);
 200             }
 201             newDashes = dashes_ref.getArray(len);
 202         }
 203         System.arraycopy(dashes, 0, newDashes, 0, len);
 204         return newDashes;
 205     }
 206 
 207     @Override
 208     public void moveTo(final float x0, final float y0) {
 209         if (firstSegidx != 0) {
 210             out.moveTo(sx, sy);
 211             emitFirstSegments();
 212         }
 213         needsMoveTo = true;
 214         this.idx = startIdx;
 215         this.dashOn = this.startDashOn;
 216         this.phase = this.startPhase;
 217         this.sx = x0;
 218         this.sy = y0;
 219         this.x0 = x0;
 220         this.y0 = y0;
 221         this.starting = true;
 222     }
 223 
 224     private void emitSeg(float[] buf, int off, int type) {
 225         switch (type) {
 226         case 8:
 227             out.curveTo(buf[off+0], buf[off+1],
 228                         buf[off+2], buf[off+3],
 229                         buf[off+4], buf[off+5]);
 230             return;
 231         case 6:
 232             out.quadTo(buf[off+0], buf[off+1],
 233                        buf[off+2], buf[off+3]);
 234             return;
 235         case 4:
 236             out.lineTo(buf[off], buf[off+1]);
 237             return;
 238         default:
 239         }
 240     }
 241 
 242     private void emitFirstSegments() {
 243         final float[] fSegBuf = firstSegmentsBuffer;
 244 
 245         for (int i = 0, len = firstSegidx; i < len; ) {
 246             int type = (int)fSegBuf[i];
 247             emitSeg(fSegBuf, i + 1, type);
 248             i += (type - 1);
 249         }
 250         firstSegidx = 0;
 251     }
 252     // We don't emit the first dash right away. If we did, caps would be
 253     // drawn on it, but we need joins to be drawn if there's a closePath()
 254     // So, we store the path elements that make up the first dash in the
 255     // buffer below.
 256     private float[] firstSegmentsBuffer; // dynamic array
 257     private int firstSegidx;
 258 
 259     // precondition: pts must be in relative coordinates (relative to x0,y0)
 260     private void goTo(final float[] pts, final int off, final int type,
 261                       final boolean on)
 262     {
 263         final int index = off + type;
 264         final float x = pts[index - 4];
 265         final float y = pts[index - 3];
 266 
 267         if (on) {
 268             if (starting) {
 269                 goTo_starting(pts, off, type);
 270             } else {
 271                 if (needsMoveTo) {
 272                     needsMoveTo = false;
 273                     out.moveTo(x0, y0);
 274                 }
 275                 emitSeg(pts, off, type);
 276             }
 277         } else {
 278             if (starting) {
 279                 // low probability test (hotspot)
 280                 starting = false;
 281             }
 282             needsMoveTo = true;
 283         }
 284         this.x0 = x;
 285         this.y0 = y;
 286     }
 287 
 288     private void goTo_starting(final float[] pts, final int off, final int type) {
 289         int len = type - 1; // - 2 + 1
 290         int segIdx = firstSegidx;
 291         float[] buf = firstSegmentsBuffer;
 292 
 293         if (segIdx + len  > buf.length) {
 294             if (DO_STATS) {
 295                 rdrCtx.stats.stat_array_dasher_firstSegmentsBuffer
 296                     .add(segIdx + len);
 297             }
 298             firstSegmentsBuffer = buf
 299                 = firstSegmentsBuffer_ref.widenArray(buf, segIdx,
 300                                                      segIdx + len);
 301         }
 302         buf[segIdx++] = type;
 303         len--;
 304         // small arraycopy (2, 4 or 6) but with offset:
 305         System.arraycopy(pts, off, buf, segIdx, len);
 306         firstSegidx = segIdx + len;
 307     }
 308 
 309     @Override
 310     public void lineTo(final float x1, final float y1) {
 311         final float dx = x1 - x0;
 312         final float dy = y1 - y0;
 313 
 314         float len = dx*dx + dy*dy;
 315         if (len == 0.0f) {
 316             return;
 317         }
 318         len = (float) Math.sqrt(len);
 319 
 320         // The scaling factors needed to get the dx and dy of the
 321         // transformed dash segments.
 322         final float cx = dx / len;
 323         final float cy = dy / len;
 324 
 325         final float[] _curCurvepts = curCurvepts;
 326         final float[] _dash = dash;
 327         final int _dashLen = this.dashLen;
 328 
 329         int _idx = idx;
 330         boolean _dashOn = dashOn;
 331         float _phase = phase;
 332 
 333         float leftInThisDashSegment;
 334         float d, dashdx, dashdy, p;
 335 
 336         while (true) {
 337             d = _dash[_idx];
 338             leftInThisDashSegment = d - _phase;
 339 
 340             if (len <= leftInThisDashSegment) {
 341                 _curCurvepts[0] = x1;
 342                 _curCurvepts[1] = y1;
 343 
 344                 goTo(_curCurvepts, 0, 4, _dashOn);
 345 
 346                 // Advance phase within current dash segment
 347                 _phase += len;
 348 
 349                 // TODO: compare float values using epsilon:
 350                 if (len == leftInThisDashSegment) {
 351                     _phase = 0.0f;
 352                     _idx = (_idx + 1) % _dashLen;
 353                     _dashOn = !_dashOn;
 354                 }
 355 
 356                 // Save local state:
 357                 idx = _idx;
 358                 dashOn = _dashOn;
 359                 phase = _phase;
 360                 return;
 361             }
 362 
 363             dashdx = d * cx;
 364             dashdy = d * cy;
 365 
 366             if (_phase == 0.0f) {
 367                 _curCurvepts[0] = x0 + dashdx;
 368                 _curCurvepts[1] = y0 + dashdy;
 369             } else {
 370                 p = leftInThisDashSegment / d;
 371                 _curCurvepts[0] = x0 + p * dashdx;
 372                 _curCurvepts[1] = y0 + p * dashdy;
 373             }
 374 
 375             goTo(_curCurvepts, 0, 4, _dashOn);
 376 
 377             len -= leftInThisDashSegment;
 378             // Advance to next dash segment
 379             _idx = (_idx + 1) % _dashLen;
 380             _dashOn = !_dashOn;
 381             _phase = 0.0f;
 382         }
 383     }
 384 
 385     // shared instance in Dasher
 386     private final LengthIterator li = new LengthIterator();
 387 
 388     // preconditions: curCurvepts must be an array of length at least 2 * type,
 389     // that contains the curve we want to dash in the first type elements
 390     private void somethingTo(final int type) {
 391         if (pointCurve(curCurvepts, type)) {
 392             return;
 393         }
 394         final LengthIterator _li = li;
 395         final float[] _curCurvepts = curCurvepts;
 396         final float[] _dash = dash;
 397         final int _dashLen = this.dashLen;
 398 
 399         _li.initializeIterationOnCurve(_curCurvepts, type);
 400 
 401         int _idx = idx;
 402         boolean _dashOn = dashOn;
 403         float _phase = phase;
 404 
 405         // initially the current curve is at curCurvepts[0...type]
 406         int curCurveoff = 0;
 407         float lastSplitT = 0.0f;
 408         float t;
 409         float leftInThisDashSegment = _dash[_idx] - _phase;
 410 
 411         while ((t = _li.next(leftInThisDashSegment)) < 1.0f) {
 412             if (t != 0.0f) {
 413                 Helpers.subdivideAt((t - lastSplitT) / (1.0f - lastSplitT),
 414                                     _curCurvepts, curCurveoff,
 415                                     _curCurvepts, 0,
 416                                     _curCurvepts, type, type);
 417                 lastSplitT = t;
 418                 goTo(_curCurvepts, 2, type, _dashOn);
 419                 curCurveoff = type;
 420             }
 421             // Advance to next dash segment
 422             _idx = (_idx + 1) % _dashLen;
 423             _dashOn = !_dashOn;
 424             _phase = 0.0f;
 425             leftInThisDashSegment = _dash[_idx];
 426         }
 427 
 428         goTo(_curCurvepts, curCurveoff + 2, type, _dashOn);
 429 
 430         _phase += _li.lastSegLen();
 431         if (_phase >= _dash[_idx]) {
 432             _phase = 0.0f;
 433             _idx = (_idx + 1) % _dashLen;
 434             _dashOn = !_dashOn;
 435         }
 436         // Save local state:
 437         idx = _idx;
 438         dashOn = _dashOn;
 439         phase = _phase;
 440 
 441         // reset LengthIterator:
 442         _li.reset();
 443     }
 444 
 445     private static boolean pointCurve(float[] curve, int type) {
 446         for (int i = 2; i < type; i++) {
 447             if (curve[i] != curve[i-2]) {
 448                 return false;
 449             }
 450         }
 451         return true;
 452     }
 453 
 454     // Objects of this class are used to iterate through curves. They return
 455     // t values where the left side of the curve has a specified length.
 456     // It does this by subdividing the input curve until a certain error
 457     // condition has been met. A recursive subdivision procedure would
 458     // return as many as 1<<limit curves, but this is an iterator and we
 459     // don't need all the curves all at once, so what we carry out a
 460     // lazy inorder traversal of the recursion tree (meaning we only move
 461     // through the tree when we need the next subdivided curve). This saves
 462     // us a lot of memory because at any one time we only need to store
 463     // limit+1 curves - one for each level of the tree + 1.
 464     // NOTE: the way we do things here is not enough to traverse a general
 465     // tree; however, the trees we are interested in have the property that
 466     // every non leaf node has exactly 2 children
 467     static final class LengthIterator {
 468         private enum Side {LEFT, RIGHT}
 469         // Holds the curves at various levels of the recursion. The root
 470         // (i.e. the original curve) is at recCurveStack[0] (but then it
 471         // gets subdivided, the left half is put at 1, so most of the time
 472         // only the right half of the original curve is at 0)
 473         private final float[][] recCurveStack; // dirty
 474         // sides[i] indicates whether the node at level i+1 in the path from
 475         // the root to the current leaf is a left or right child of its parent.
 476         private final Side[] sides; // dirty
 477         private int curveType;
 478         // lastT and nextT delimit the current leaf.
 479         private float nextT;
 480         private float lenAtNextT;
 481         private float lastT;
 482         private float lenAtLastT;
 483         private float lenAtLastSplit;
 484         private float lastSegLen;
 485         // the current level in the recursion tree. 0 is the root. limit
 486         // is the deepest possible leaf.
 487         private int recLevel;
 488         private boolean done;
 489 
 490         // the lengths of the lines of the control polygon. Only its first
 491         // curveType/2 - 1 elements are valid. This is an optimization. See
 492         // next() for more detail.
 493         private final float[] curLeafCtrlPolyLengths = new float[3];
 494 
 495         LengthIterator() {
 496             this.recCurveStack = new float[REC_LIMIT + 1][8];
 497             this.sides = new Side[REC_LIMIT];
 498             // if any methods are called without first initializing this object
 499             // on a curve, we want it to fail ASAP.
 500             this.nextT = Float.MAX_VALUE;
 501             this.lenAtNextT = Float.MAX_VALUE;
 502             this.lenAtLastSplit = Float.MIN_VALUE;
 503             this.recLevel = Integer.MIN_VALUE;
 504             this.lastSegLen = Float.MAX_VALUE;
 505             this.done = true;
 506         }
 507 
 508         /**
 509          * Reset this LengthIterator.
 510          */
 511         void reset() {
 512             // keep data dirty
 513             // as it appears not useful to reset data:
 514             if (DO_CLEAN_DIRTY) {
 515                 final int recLimit = recCurveStack.length - 1;
 516                 for (int i = recLimit; i >= 0; i--) {
 517                     Arrays.fill(recCurveStack[i], 0.0f);
 518                 }
 519                 Arrays.fill(sides, Side.LEFT);
 520                 Arrays.fill(curLeafCtrlPolyLengths, 0.0f);
 521                 Arrays.fill(nextRoots, 0.0f);
 522                 Arrays.fill(flatLeafCoefCache, 0.0f);
 523                 flatLeafCoefCache[2] = -1.0f;
 524             }
 525         }
 526 
 527         void initializeIterationOnCurve(float[] pts, int type) {
 528             // optimize arraycopy (8 values faster than 6 = type):
 529             System.arraycopy(pts, 0, recCurveStack[0], 0, 8);
 530             this.curveType = type;
 531             this.recLevel = 0;
 532             this.lastT = 0.0f;
 533             this.lenAtLastT = 0.0f;
 534             this.nextT = 0.0f;
 535             this.lenAtNextT = 0.0f;
 536             goLeft(); // initializes nextT and lenAtNextT properly
 537             this.lenAtLastSplit = 0.0f;
 538             if (recLevel > 0) {
 539                 this.sides[0] = Side.LEFT;
 540                 this.done = false;
 541             } else {
 542                 // the root of the tree is a leaf so we're done.
 543                 this.sides[0] = Side.RIGHT;
 544                 this.done = true;
 545             }
 546             this.lastSegLen = 0.0f;
 547         }
 548 
 549         // 0 == false, 1 == true, -1 == invalid cached value.
 550         private int cachedHaveLowAcceleration = -1;
 551 
 552         private boolean haveLowAcceleration(float err) {
 553             if (cachedHaveLowAcceleration == -1) {
 554                 final float len1 = curLeafCtrlPolyLengths[0];
 555                 final float len2 = curLeafCtrlPolyLengths[1];
 556                 // the test below is equivalent to !within(len1/len2, 1, err).
 557                 // It is using a multiplication instead of a division, so it
 558                 // should be a bit faster.
 559                 if (!Helpers.within(len1, len2, err * len2)) {
 560                     cachedHaveLowAcceleration = 0;
 561                     return false;
 562                 }
 563                 if (curveType == 8) {
 564                     final float len3 = curLeafCtrlPolyLengths[2];
 565                     // if len1 is close to 2 and 2 is close to 3, that probably
 566                     // means 1 is close to 3 so the second part of this test might
 567                     // not be needed, but it doesn't hurt to include it.
 568                     final float errLen3 = err * len3;
 569                     if (!(Helpers.within(len2, len3, errLen3) &&
 570                           Helpers.within(len1, len3, errLen3))) {
 571                         cachedHaveLowAcceleration = 0;
 572                         return false;
 573                     }
 574                 }
 575                 cachedHaveLowAcceleration = 1;
 576                 return true;
 577             }
 578 
 579             return (cachedHaveLowAcceleration == 1);
 580         }
 581 
 582         // we want to avoid allocations/gc so we keep this array so we
 583         // can put roots in it,
 584         private final float[] nextRoots = new float[4];
 585 
 586         // caches the coefficients of the current leaf in its flattened
 587         // form (see inside next() for what that means). The cache is
 588         // invalid when it's third element is negative, since in any
 589         // valid flattened curve, this would be >= 0.
 590         private final float[] flatLeafCoefCache = new float[]{0.0f, 0.0f, -1.0f, 0.0f};
 591 
 592         // returns the t value where the remaining curve should be split in
 593         // order for the left subdivided curve to have length len. If len
 594         // is >= than the length of the uniterated curve, it returns 1.
 595         float next(final float len) {
 596             final float targetLength = lenAtLastSplit + len;
 597             while (lenAtNextT < targetLength) {
 598                 if (done) {
 599                     lastSegLen = lenAtNextT - lenAtLastSplit;
 600                     return 1.0f;
 601                 }
 602                 goToNextLeaf();
 603             }
 604             lenAtLastSplit = targetLength;
 605             final float leaflen = lenAtNextT - lenAtLastT;
 606             float t = (targetLength - lenAtLastT) / leaflen;
 607 
 608             // cubicRootsInAB is a fairly expensive call, so we just don't do it
 609             // if the acceleration in this section of the curve is small enough.
 610             if (!haveLowAcceleration(0.05f)) {
 611                 // We flatten the current leaf along the x axis, so that we're
 612                 // left with a, b, c which define a 1D Bezier curve. We then
 613                 // solve this to get the parameter of the original leaf that
 614                 // gives us the desired length.
 615                 final float[] _flatLeafCoefCache = flatLeafCoefCache;
 616 
 617                 if (_flatLeafCoefCache[2] < 0.0f) {
 618                     float x =     curLeafCtrlPolyLengths[0],
 619                           y = x + curLeafCtrlPolyLengths[1];
 620                     if (curveType == 8) {
 621                         float z = y + curLeafCtrlPolyLengths[2];
 622                         _flatLeafCoefCache[0] = 3.0f * (x - y) + z;
 623                         _flatLeafCoefCache[1] = 3.0f * (y - 2.0f * x);
 624                         _flatLeafCoefCache[2] = 3.0f * x;
 625                         _flatLeafCoefCache[3] = -z;
 626                     } else if (curveType == 6) {
 627                         _flatLeafCoefCache[0] = 0.0f;
 628                         _flatLeafCoefCache[1] = y - 2.0f * x;
 629                         _flatLeafCoefCache[2] = 2.0f * x;
 630                         _flatLeafCoefCache[3] = -y;
 631                     }
 632                 }
 633                 float a = _flatLeafCoefCache[0];
 634                 float b = _flatLeafCoefCache[1];
 635                 float c = _flatLeafCoefCache[2];
 636                 float d = t * _flatLeafCoefCache[3];
 637 
 638                 // we use cubicRootsInAB here, because we want only roots in 0, 1,
 639                 // and our quadratic root finder doesn't filter, so it's just a
 640                 // matter of convenience.
 641                 int n = Helpers.cubicRootsInAB(a, b, c, d, nextRoots, 0, 0.0f, 1.0f);
 642                 if (n == 1 && !Float.isNaN(nextRoots[0])) {
 643                     t = nextRoots[0];
 644                 }
 645             }
 646             // t is relative to the current leaf, so we must make it a valid parameter
 647             // of the original curve.
 648             t = t * (nextT - lastT) + lastT;
 649             if (t >= 1.0f) {
 650                 t = 1.0f;
 651                 done = true;
 652             }
 653             // even if done = true, if we're here, that means targetLength
 654             // is equal to, or very, very close to the total length of the
 655             // curve, so lastSegLen won't be too high. In cases where len
 656             // overshoots the curve, this method will exit in the while
 657             // loop, and lastSegLen will still be set to the right value.
 658             lastSegLen = len;
 659             return t;
 660         }
 661 
 662         float lastSegLen() {
 663             return lastSegLen;
 664         }
 665 
 666         // go to the next leaf (in an inorder traversal) in the recursion tree
 667         // preconditions: must be on a leaf, and that leaf must not be the root.
 668         private void goToNextLeaf() {
 669             // We must go to the first ancestor node that has an unvisited
 670             // right child.
 671             int _recLevel = recLevel;
 672             final Side[] _sides = sides;
 673 
 674             _recLevel--;
 675             while(_sides[_recLevel] == Side.RIGHT) {
 676                 if (_recLevel == 0) {
 677                     recLevel = 0;
 678                     done = true;
 679                     return;
 680                 }
 681                 _recLevel--;
 682             }
 683 
 684             _sides[_recLevel] = Side.RIGHT;
 685             // optimize arraycopy (8 values faster than 6 = type):
 686             System.arraycopy(recCurveStack[_recLevel], 0,
 687                              recCurveStack[_recLevel+1], 0, 8);
 688             _recLevel++;
 689 
 690             recLevel = _recLevel;
 691             goLeft();
 692         }
 693 
 694         // go to the leftmost node from the current node. Return its length.
 695         private void goLeft() {
 696             float len = onLeaf();
 697             if (len >= 0.0f) {
 698                 lastT = nextT;
 699                 lenAtLastT = lenAtNextT;
 700                 nextT += (1 << (REC_LIMIT - recLevel)) * MIN_T_INC;
 701                 lenAtNextT += len;
 702                 // invalidate caches
 703                 flatLeafCoefCache[2] = -1.0f;
 704                 cachedHaveLowAcceleration = -1;
 705             } else {
 706                 Helpers.subdivide(recCurveStack[recLevel], 0,
 707                                   recCurveStack[recLevel+1], 0,
 708                                   recCurveStack[recLevel], 0, curveType);
 709                 sides[recLevel] = Side.LEFT;
 710                 recLevel++;
 711                 goLeft();
 712             }
 713         }
 714 
 715         // this is a bit of a hack. It returns -1 if we're not on a leaf, and
 716         // the length of the leaf if we are on a leaf.
 717         private float onLeaf() {
 718             final float[] curve = recCurveStack[recLevel];
 719             final int _curveType = curveType;
 720             float polyLen = 0.0f;
 721 
 722             float x0 = curve[0], y0 = curve[1];
 723             for (int i = 2; i < _curveType; i += 2) {
 724                 final float x1 = curve[i], y1 = curve[i+1];
 725                 final float len = Helpers.linelen(x0, y0, x1, y1);
 726                 polyLen += len;
 727                 curLeafCtrlPolyLengths[(i >> 1) - 1] = len;
 728                 x0 = x1;
 729                 y0 = y1;
 730             }
 731 
 732             final float lineLen = Helpers.linelen(curve[0], curve[1],
 733                                                   curve[_curveType-2],
 734                                                   curve[_curveType-1]);
 735             if ((polyLen - lineLen) < ERR || recLevel == REC_LIMIT) {
 736                 return (polyLen + lineLen) / 2.0f;
 737             }
 738             return -1.0f;
 739         }
 740     }
 741 
 742     @Override
 743     public void curveTo(final float x1, final float y1,
 744                         final float x2, final float y2,
 745                         final float x3, final float y3)
 746     {
 747         final float[] _curCurvepts = curCurvepts;
 748         _curCurvepts[0] = x0;        _curCurvepts[1] = y0;
 749         _curCurvepts[2] = x1;        _curCurvepts[3] = y1;
 750         _curCurvepts[4] = x2;        _curCurvepts[5] = y2;
 751         _curCurvepts[6] = x3;        _curCurvepts[7] = y3;
 752         somethingTo(8);
 753     }
 754 
 755     @Override
 756     public void quadTo(final float x1, final float y1,
 757                        final float x2, final float y2)
 758     {
 759         final float[] _curCurvepts = curCurvepts;
 760         _curCurvepts[0] = x0;        _curCurvepts[1] = y0;
 761         _curCurvepts[2] = x1;        _curCurvepts[3] = y1;
 762         _curCurvepts[4] = x2;        _curCurvepts[5] = y2;
 763         somethingTo(6);
 764     }
 765 
 766     @Override
 767     public void closePath() {
 768         lineTo(sx, sy);
 769         if (firstSegidx != 0) {
 770             if (!dashOn || needsMoveTo) {
 771                 out.moveTo(sx, sy);
 772             }
 773             emitFirstSegments();
 774         }
 775         moveTo(sx, sy);
 776     }
 777 
 778     @Override
 779     public void pathDone() {
 780         if (firstSegidx != 0) {
 781             out.moveTo(sx, sy);
 782             emitFirstSegments();
 783         }
 784         out.pathDone();
 785 
 786         // Dispose this instance:
 787         dispose();
 788     }
 789 }
 790