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 sun.java2d.marlin;
  27 
  28 import java.util.Arrays;
  29 import sun.awt.geom.PathConsumer2D;
  30 import sun.java2d.marlin.TransformingPathConsumer2D.CurveBasicMonotonizer;
  31 import sun.java2d.marlin.TransformingPathConsumer2D.CurveClipSplitter;
  32 
  33 /**
  34  * The <code>Dasher</code> class takes a series of linear commands
  35  * (<code>moveTo</code>, <code>lineTo</code>, <code>close</code> and
  36  * <code>end</code>) and breaks them into smaller segments according to a
  37  * dash pattern array and a starting dash phase.
  38  *
  39  * <p> Issues: in J2Se, a zero length dash segment as drawn as a very
  40  * short dash, whereas Pisces does not draw anything.  The PostScript
  41  * semantics are unclear.
  42  *
  43  */
  44 final class Dasher implements PathConsumer2D, MarlinConst {
  45 
  46     /* huge circle with radius ~ 2E9 only needs 12 subdivision levels */
  47     static final int REC_LIMIT = 16;
  48     static final float CURVE_LEN_ERR = MarlinProperties.getCurveLengthError(); // 0.01
  49     static final float MIN_T_INC = 1.0f / (1 << REC_LIMIT);
  50 
  51     static final float EPS = 1e-6f;
  52 
  53     // More than 24 bits of mantissa means we can no longer accurately
  54     // measure the number of times cycled through the dash array so we
  55     // punt and override the phase to just be 0 past that point.
  56     static final float MAX_CYCLES = 16000000.0f;
  57 
  58     private PathConsumer2D out;
  59     private float[] dash;
  60     private int dashLen;
  61     private float startPhase;
  62     private boolean startDashOn;
  63     private int startIdx;
  64 
  65     private boolean starting;
  66     private boolean needsMoveTo;
  67 
  68     private int idx;
  69     private boolean dashOn;
  70     private float phase;
  71 
  72     // The starting point of the path
  73     private float sx0, sy0;
  74     // the current point
  75     private float cx0, cy0;
  76 
  77     // temporary storage for the current curve
  78     private final float[] curCurvepts;
  79 
  80     // per-thread renderer context
  81     final RendererContext rdrCtx;
  82 
  83     // flag to recycle dash array copy
  84     boolean recycleDashes;
  85 
  86     // We don't emit the first dash right away. If we did, caps would be
  87     // drawn on it, but we need joins to be drawn if there's a closePath()
  88     // So, we store the path elements that make up the first dash in the
  89     // buffer below.
  90     private float[] firstSegmentsBuffer; // dynamic array
  91     private int firstSegidx;
  92 
  93     // dashes ref (dirty)
  94     final FloatArrayCache.Reference dashes_ref;
  95     // firstSegmentsBuffer ref (dirty)
  96     final FloatArrayCache.Reference firstSegmentsBuffer_ref;
  97 
  98     // Bounds of the drawing region, at pixel precision.
  99     private float[] clipRect;
 100 
 101     // the outcode of the current point
 102     private int cOutCode = 0;
 103 
 104     private boolean subdivide = DO_CLIP_SUBDIVIDER;
 105 
 106     private final LengthIterator li = new LengthIterator();
 107 
 108     private final CurveClipSplitter curveSplitter;
 109 
 110     private float cycleLen;
 111     private boolean outside;
 112     private float totalSkipLen;
 113 
 114     /**
 115      * Constructs a <code>Dasher</code>.
 116      * @param rdrCtx per-thread renderer context
 117      */
 118     Dasher(final RendererContext rdrCtx) {
 119         this.rdrCtx = rdrCtx;
 120 
 121         dashes_ref = rdrCtx.newDirtyFloatArrayRef(INITIAL_ARRAY); // 1K
 122 
 123         firstSegmentsBuffer_ref = rdrCtx.newDirtyFloatArrayRef(INITIAL_ARRAY); // 1K
 124         firstSegmentsBuffer     = firstSegmentsBuffer_ref.initial;
 125 
 126         // we need curCurvepts to be able to contain 2 curves because when
 127         // dashing curves, we need to subdivide it
 128         curCurvepts = new float[8 * 2];
 129 
 130         this.curveSplitter = rdrCtx.curveClipSplitter;
 131     }
 132 
 133     /**
 134      * Initialize the <code>Dasher</code>.
 135      *
 136      * @param out an output <code>PathConsumer2D</code>.
 137      * @param dash an array of <code>float</code>s containing the dash pattern
 138      * @param dashLen length of the given dash array
 139      * @param phase a <code>float</code> containing the dash phase
 140      * @param recycleDashes true to indicate to recycle the given dash array
 141      * @return this instance
 142      */
 143     Dasher init(final PathConsumer2D out, final float[] dash, final int dashLen,
 144                 float phase, final boolean recycleDashes)
 145     {
 146         this.out = out;
 147 
 148         // Normalize so 0 <= phase < dash[0]
 149         int sidx = 0;
 150         dashOn = true;
 151 
 152         // note: BasicStroke constructor checks dash elements and sum > 0
 153         float sum = 0.0f;
 154         for (int i = 0; i < dashLen; i++) {
 155             sum += dash[i];
 156         }
 157         this.cycleLen = sum;
 158 
 159         float cycles = phase / sum;
 160         if (phase < 0.0f) {
 161             if (-cycles >= MAX_CYCLES) {
 162                 phase = 0.0f;
 163             } else {
 164                 int fullcycles = FloatMath.floor_int(-cycles);
 165                 if ((fullcycles & dashLen & 1) != 0) {
 166                     dashOn = !dashOn;
 167                 }
 168                 phase += fullcycles * sum;
 169                 while (phase < 0.0f) {
 170                     if (--sidx < 0) {
 171                         sidx = dashLen - 1;
 172                     }
 173                     phase += dash[sidx];
 174                     dashOn = !dashOn;
 175                 }
 176             }
 177         } else if (phase > 0.0f) {
 178             if (cycles >= MAX_CYCLES) {
 179                 phase = 0.0f;
 180             } else {
 181                 int fullcycles = FloatMath.floor_int(cycles);
 182                 if ((fullcycles & dashLen & 1) != 0) {
 183                     dashOn = !dashOn;
 184                 }
 185                 phase -= fullcycles * sum;
 186                 float d;
 187                 while (phase >= (d = dash[sidx])) {
 188                     phase -= d;
 189                     sidx = (sidx + 1) % dashLen;
 190                     dashOn = !dashOn;
 191                 }
 192             }
 193         }
 194 
 195         this.dash = dash;
 196         this.dashLen = dashLen;
 197         this.phase = phase;
 198         this.startPhase = phase;
 199         this.startDashOn = dashOn;
 200         this.startIdx = sidx;
 201         this.starting = true;
 202         this.needsMoveTo = false;
 203         this.firstSegidx = 0;
 204 
 205         this.recycleDashes = recycleDashes;
 206 
 207         if (rdrCtx.doClip) {
 208             this.clipRect = rdrCtx.clipRect;
 209         } else {
 210             this.clipRect = null;
 211             this.cOutCode = 0;
 212         }
 213         return this; // fluent API
 214     }
 215 
 216     /**
 217      * Disposes this dasher:
 218      * clean up before reusing this instance
 219      */
 220     void dispose() {
 221         if (DO_CLEAN_DIRTY) {
 222             // Force zero-fill dirty arrays:
 223             Arrays.fill(curCurvepts, 0.0f);
 224         }
 225         // Return arrays:
 226         if (recycleDashes) {
 227             dash = dashes_ref.putArray(dash);
 228         }
 229         firstSegmentsBuffer = firstSegmentsBuffer_ref.putArray(firstSegmentsBuffer);
 230     }
 231 
 232     float[] copyDashArray(final float[] dashes) {
 233         final int len = dashes.length;
 234         final float[] newDashes;
 235         if (len <= MarlinConst.INITIAL_ARRAY) {
 236             newDashes = dashes_ref.initial;
 237         } else {
 238             if (DO_STATS) {
 239                 rdrCtx.stats.stat_array_dasher_dasher.add(len);
 240             }
 241             newDashes = dashes_ref.getArray(len);
 242         }
 243         System.arraycopy(dashes, 0, newDashes, 0, len);
 244         return newDashes;
 245     }
 246 
 247     @Override
 248     public void moveTo(final float x0, final float y0) {
 249         if (firstSegidx != 0) {
 250             out.moveTo(sx0, sy0);
 251             emitFirstSegments();
 252         }
 253         this.needsMoveTo = true;
 254         this.idx = startIdx;
 255         this.dashOn = this.startDashOn;
 256         this.phase = this.startPhase;
 257         this.cx0 = x0;
 258         this.cy0 = y0;
 259 
 260         // update starting point:
 261         this.sx0 = x0;
 262         this.sy0 = y0;
 263         this.starting = true;
 264 
 265         if (clipRect != null) {
 266             final int outcode = Helpers.outcode(x0, y0, clipRect);
 267             this.cOutCode = outcode;
 268             this.outside = false;
 269             this.totalSkipLen = 0.0f;
 270         }
 271     }
 272 
 273     private void emitSeg(float[] buf, int off, int type) {
 274         switch (type) {
 275         case 4:
 276             out.lineTo(buf[off], buf[off + 1]);
 277             return;
 278         case 8:
 279             out.curveTo(buf[off    ], buf[off + 1],
 280                         buf[off + 2], buf[off + 3],
 281                         buf[off + 4], buf[off + 5]);
 282             return;
 283         case 6:
 284             out.quadTo(buf[off    ], buf[off + 1],
 285                        buf[off + 2], buf[off + 3]);
 286             return;
 287         default:
 288         }
 289     }
 290 
 291     private void emitFirstSegments() {
 292         final float[] fSegBuf = firstSegmentsBuffer;
 293 
 294         for (int i = 0, len = firstSegidx; i < len; ) {
 295             int type = (int)fSegBuf[i];
 296             emitSeg(fSegBuf, i + 1, type);
 297             i += (type - 1);
 298         }
 299         firstSegidx = 0;
 300     }
 301 
 302     // precondition: pts must be in relative coordinates (relative to x0,y0)
 303     private void goTo(final float[] pts, final int off, final int type,
 304                       final boolean on)
 305     {
 306         final int index = off + type;
 307         final float x = pts[index - 4];
 308         final float y = pts[index - 3];
 309 
 310         if (on) {
 311             if (starting) {
 312                 goTo_starting(pts, off, type);
 313             } else {
 314                 if (needsMoveTo) {
 315                     needsMoveTo = false;
 316                     out.moveTo(cx0, cy0);
 317                 }
 318                 emitSeg(pts, off, type);
 319             }
 320         } else {
 321             if (starting) {
 322                 // low probability test (hotspot)
 323                 starting = false;
 324             }
 325             needsMoveTo = true;
 326         }
 327         this.cx0 = x;
 328         this.cy0 = y;
 329     }
 330 
 331     private void goTo_starting(final float[] pts, final int off, final int type) {
 332         int len = type - 1; // - 2 + 1
 333         int segIdx = firstSegidx;
 334         float[] buf = firstSegmentsBuffer;
 335 
 336         if (segIdx + len  > buf.length) {
 337             if (DO_STATS) {
 338                 rdrCtx.stats.stat_array_dasher_firstSegmentsBuffer
 339                     .add(segIdx + len);
 340             }
 341             firstSegmentsBuffer = buf
 342                 = firstSegmentsBuffer_ref.widenArray(buf, segIdx,
 343                                                      segIdx + len);
 344         }
 345         buf[segIdx++] = type;
 346         len--;
 347         // small arraycopy (2, 4 or 6) but with offset:
 348         System.arraycopy(pts, off, buf, segIdx, len);
 349         firstSegidx = segIdx + len;
 350     }
 351 
 352     @Override
 353     public void lineTo(final float x1, final float y1) {
 354         final int outcode0 = this.cOutCode;
 355 
 356         if (clipRect != null) {
 357             final int outcode1 = Helpers.outcode(x1, y1, clipRect);
 358 
 359             // Should clip
 360             final int orCode = (outcode0 | outcode1);
 361 
 362             if (orCode != 0) {
 363                 final int sideCode = outcode0 & outcode1;
 364 
 365                 // basic rejection criteria:
 366                 if (sideCode == 0) {
 367                     // overlap clip:
 368                     if (subdivide) {
 369                         // avoid reentrance
 370                         subdivide = false;
 371                         // subdivide curve => callback with subdivided parts:
 372                         boolean ret = curveSplitter.splitLine(cx0, cy0, x1, y1,
 373                                                               orCode, this);
 374                         // reentrance is done:
 375                         subdivide = true;
 376                         if (ret) {
 377                             return;
 378                         }
 379                     }
 380                     // already subdivided so render it
 381                 } else {
 382                     this.cOutCode = outcode1;
 383                     skipLineTo(x1, y1);
 384                     return;
 385                 }
 386             }
 387 
 388             this.cOutCode = outcode1;
 389 
 390             if (this.outside) {
 391                 this.outside = false;
 392                 // Adjust current index, phase & dash:
 393                 skipLen();
 394             }
 395         }
 396         _lineTo(x1, y1);
 397     }
 398 
 399     private void _lineTo(final float x1, final float y1) {
 400         final float dx = x1 - cx0;
 401         final float dy = y1 - cy0;
 402 
 403         float len = dx * dx + dy * dy;
 404         if (len == 0.0f) {
 405             return;
 406         }
 407         len = (float) Math.sqrt(len);
 408 
 409         // The scaling factors needed to get the dx and dy of the
 410         // transformed dash segments.
 411         final float cx = dx / len;
 412         final float cy = dy / len;
 413 
 414         final float[] _curCurvepts = curCurvepts;
 415         final float[] _dash = dash;
 416         final int _dashLen = this.dashLen;
 417 
 418         int _idx = idx;
 419         boolean _dashOn = dashOn;
 420         float _phase = phase;
 421 
 422         float leftInThisDashSegment, rem;
 423 
 424         while (true) {
 425             leftInThisDashSegment = _dash[_idx] - _phase;
 426             rem = len - leftInThisDashSegment;
 427 
 428             if (rem <= EPS) {
 429                 _curCurvepts[0] = x1;
 430                 _curCurvepts[1] = y1;
 431 
 432                 goTo(_curCurvepts, 0, 4, _dashOn);
 433 
 434                 // Advance phase within current dash segment
 435                 _phase += len;
 436 
 437                 // compare values using epsilon:
 438                 if (Math.abs(rem) <= EPS) {
 439                     _phase = 0.0f;
 440                     _idx = (_idx + 1) % _dashLen;
 441                     _dashOn = !_dashOn;
 442                 }
 443                 break;
 444             }
 445 
 446             _curCurvepts[0] = cx0 + leftInThisDashSegment * cx;
 447             _curCurvepts[1] = cy0 + leftInThisDashSegment * cy;
 448 
 449             goTo(_curCurvepts, 0, 4, _dashOn);
 450 
 451             len = rem;
 452             // Advance to next dash segment
 453             _idx = (_idx + 1) % _dashLen;
 454             _dashOn = !_dashOn;
 455             _phase = 0.0f;
 456         }
 457         // Save local state:
 458         idx = _idx;
 459         dashOn = _dashOn;
 460         phase = _phase;
 461     }
 462 
 463     private void skipLineTo(final float x1, final float y1) {
 464         final float dx = x1 - cx0;
 465         final float dy = y1 - cy0;
 466 
 467         float len = dx * dx + dy * dy;
 468         if (len != 0.0f) {
 469             len = (float)Math.sqrt(len);
 470         }
 471 
 472         // Accumulate skipped length:
 473         this.outside = true;
 474         this.totalSkipLen += len;
 475 
 476         // Fix initial move:
 477         this.needsMoveTo = true;
 478         this.starting = false;
 479 
 480         this.cx0 = x1;
 481         this.cy0 = y1;
 482     }
 483 
 484     public void skipLen() {
 485         float len = this.totalSkipLen;
 486         this.totalSkipLen = 0.0f;
 487 
 488         final float[] _dash = dash;
 489         final int _dashLen = this.dashLen;
 490 
 491         int _idx = idx;
 492         boolean _dashOn = dashOn;
 493         float _phase = phase;
 494 
 495         // -2 to ensure having 2 iterations of the post-loop
 496         // to compensate the remaining phase
 497         final long fullcycles = (long)Math.floor(len / cycleLen) - 2L;
 498 
 499         if (fullcycles > 0L) {
 500             len -= cycleLen * fullcycles;
 501 
 502             final long iterations = fullcycles * _dashLen;
 503             _idx = (int) (iterations + _idx) % _dashLen;
 504             _dashOn = (iterations + (_dashOn ? 1L : 0L) & 1L) == 1L;
 505         }
 506 
 507         float leftInThisDashSegment, rem;
 508 
 509         while (true) {
 510             leftInThisDashSegment = _dash[_idx] - _phase;
 511             rem = len - leftInThisDashSegment;
 512 
 513             if (rem <= EPS) {
 514                 // Advance phase within current dash segment
 515                 _phase += len;
 516 
 517                 // compare values using epsilon:
 518                 if (Math.abs(rem) <= EPS) {
 519                     _phase = 0.0f;
 520                     _idx = (_idx + 1) % _dashLen;
 521                     _dashOn = !_dashOn;
 522                 }
 523                 break;
 524             }
 525 
 526             len = rem;
 527             // Advance to next dash segment
 528             _idx = (_idx + 1) % _dashLen;
 529             _dashOn = !_dashOn;
 530             _phase = 0.0f;
 531         }
 532         // Save local state:
 533         idx = _idx;
 534         dashOn = _dashOn;
 535         phase = _phase;
 536     }
 537 
 538     // preconditions: curCurvepts must be an array of length at least 2 * type,
 539     // that contains the curve we want to dash in the first type elements
 540     private void somethingTo(final int type) {
 541         final float[] _curCurvepts = curCurvepts;
 542         if (pointCurve(_curCurvepts, type)) {
 543             return;
 544         }
 545         final LengthIterator _li = li;
 546         final float[] _dash = dash;
 547         final int _dashLen = this.dashLen;
 548 
 549         _li.initializeIterationOnCurve(_curCurvepts, type);
 550 
 551         int _idx = idx;
 552         boolean _dashOn = dashOn;
 553         float _phase = phase;
 554 
 555         // initially the current curve is at curCurvepts[0...type]
 556         int curCurveoff = 0;
 557         float prevT = 0.0f;
 558         float t;
 559         float leftInThisDashSegment = _dash[_idx] - _phase;
 560 
 561         while ((t = _li.next(leftInThisDashSegment)) < 1.0f) {
 562             if (t != 0.0f) {
 563                 Helpers.subdivideAt((t - prevT) / (1.0f - prevT),
 564                                     _curCurvepts, curCurveoff,
 565                                     _curCurvepts, 0, type);
 566                 prevT = t;
 567                 goTo(_curCurvepts, 2, type, _dashOn);
 568                 curCurveoff = type;
 569             }
 570             // Advance to next dash segment
 571             _idx = (_idx + 1) % _dashLen;
 572             _dashOn = !_dashOn;
 573             _phase = 0.0f;
 574             leftInThisDashSegment = _dash[_idx];
 575         }
 576 
 577         goTo(_curCurvepts, curCurveoff + 2, type, _dashOn);
 578 
 579         _phase += _li.lastSegLen();
 580 
 581         // compare values using epsilon:
 582         if (_phase + EPS >= _dash[_idx]) {
 583             _phase = 0.0f;
 584             _idx = (_idx + 1) % _dashLen;
 585             _dashOn = !_dashOn;
 586         }
 587         // Save local state:
 588         idx = _idx;
 589         dashOn = _dashOn;
 590         phase = _phase;
 591 
 592         // reset LengthIterator:
 593         _li.reset();
 594     }
 595 
 596     private void skipSomethingTo(final int type) {
 597         final float[] _curCurvepts = curCurvepts;
 598         if (pointCurve(_curCurvepts, type)) {
 599             return;
 600         }
 601         final LengthIterator _li = li;
 602 
 603         _li.initializeIterationOnCurve(_curCurvepts, type);
 604 
 605         // In contrary to somethingTo(),
 606         // just estimate properly the curve length:
 607         final float len = _li.totalLength();
 608 
 609         // Accumulate skipped length:
 610         this.outside = true;
 611         this.totalSkipLen += len;
 612 
 613         // Fix initial move:
 614         this.needsMoveTo = true;
 615         this.starting = false;
 616     }
 617 
 618     private static boolean pointCurve(final float[] curve, final int type) {
 619         for (int i = 2; i < type; i++) {
 620             if (curve[i] != curve[i-2]) {
 621                 return false;
 622             }
 623         }
 624         return true;
 625     }
 626 
 627     // Objects of this class are used to iterate through curves. They return
 628     // t values where the left side of the curve has a specified length.
 629     // It does this by subdividing the input curve until a certain error
 630     // condition has been met. A recursive subdivision procedure would
 631     // return as many as 1<<limit curves, but this is an iterator and we
 632     // don't need all the curves all at once, so what we carry out a
 633     // lazy inorder traversal of the recursion tree (meaning we only move
 634     // through the tree when we need the next subdivided curve). This saves
 635     // us a lot of memory because at any one time we only need to store
 636     // limit+1 curves - one for each level of the tree + 1.
 637     // NOTE: the way we do things here is not enough to traverse a general
 638     // tree; however, the trees we are interested in have the property that
 639     // every non leaf node has exactly 2 children
 640     static final class LengthIterator {
 641         // Holds the curves at various levels of the recursion. The root
 642         // (i.e. the original curve) is at recCurveStack[0] (but then it
 643         // gets subdivided, the left half is put at 1, so most of the time
 644         // only the right half of the original curve is at 0)
 645         private final float[][] recCurveStack; // dirty
 646         // sidesRight[i] indicates whether the node at level i+1 in the path from
 647         // the root to the current leaf is a left or right child of its parent.
 648         private final boolean[] sidesRight; // dirty
 649         private int curveType;
 650         // lastT and nextT delimit the current leaf.
 651         private float nextT;
 652         private float lenAtNextT;
 653         private float lastT;
 654         private float lenAtLastT;
 655         private float lenAtLastSplit;
 656         private float lastSegLen;
 657         // the current level in the recursion tree. 0 is the root. limit
 658         // is the deepest possible leaf.
 659         private int recLevel;
 660         private boolean done;
 661 
 662         // the lengths of the lines of the control polygon. Only its first
 663         // curveType/2 - 1 elements are valid. This is an optimization. See
 664         // next() for more detail.
 665         private final float[] curLeafCtrlPolyLengths = new float[3];
 666 
 667         LengthIterator() {
 668             this.recCurveStack = new float[REC_LIMIT + 1][8];
 669             this.sidesRight = new boolean[REC_LIMIT];
 670             // if any methods are called without first initializing this object
 671             // on a curve, we want it to fail ASAP.
 672             this.nextT = Float.MAX_VALUE;
 673             this.lenAtNextT = Float.MAX_VALUE;
 674             this.lenAtLastSplit = Float.MIN_VALUE;
 675             this.recLevel = Integer.MIN_VALUE;
 676             this.lastSegLen = Float.MAX_VALUE;
 677             this.done = true;
 678         }
 679 
 680         /**
 681          * Reset this LengthIterator.
 682          */
 683         void reset() {
 684             // keep data dirty
 685             // as it appears not useful to reset data:
 686             if (DO_CLEAN_DIRTY) {
 687                 final int recLimit = recCurveStack.length - 1;
 688                 for (int i = recLimit; i >= 0; i--) {
 689                     Arrays.fill(recCurveStack[i], 0.0f);
 690                 }
 691                 Arrays.fill(sidesRight, false);
 692                 Arrays.fill(curLeafCtrlPolyLengths, 0.0f);
 693                 Arrays.fill(nextRoots, 0.0f);
 694                 Arrays.fill(flatLeafCoefCache, 0.0f);
 695                 flatLeafCoefCache[2] = -1.0f;
 696             }
 697         }
 698 
 699         void initializeIterationOnCurve(final float[] pts, final int type) {
 700             // optimize arraycopy (8 values faster than 6 = type):
 701             System.arraycopy(pts, 0, recCurveStack[0], 0, 8);
 702             this.curveType = type;
 703             this.recLevel = 0;
 704             this.lastT = 0.0f;
 705             this.lenAtLastT = 0.0f;
 706             this.nextT = 0.0f;
 707             this.lenAtNextT = 0.0f;
 708             goLeft(); // initializes nextT and lenAtNextT properly
 709             this.lenAtLastSplit = 0.0f;
 710             if (recLevel > 0) {
 711                 this.sidesRight[0] = false;
 712                 this.done = false;
 713             } else {
 714                 // the root of the tree is a leaf so we're done.
 715                 this.sidesRight[0] = true;
 716                 this.done = true;
 717             }
 718             this.lastSegLen = 0.0f;
 719         }
 720 
 721         // 0 == false, 1 == true, -1 == invalid cached value.
 722         private int cachedHaveLowAcceleration = -1;
 723 
 724         private boolean haveLowAcceleration(final float err) {
 725             if (cachedHaveLowAcceleration == -1) {
 726                 final float len1 = curLeafCtrlPolyLengths[0];
 727                 final float len2 = curLeafCtrlPolyLengths[1];
 728                 // the test below is equivalent to !within(len1/len2, 1, err).
 729                 // It is using a multiplication instead of a division, so it
 730                 // should be a bit faster.
 731                 if (!Helpers.within(len1, len2, err * len2)) {
 732                     cachedHaveLowAcceleration = 0;
 733                     return false;
 734                 }
 735                 if (curveType == 8) {
 736                     final float len3 = curLeafCtrlPolyLengths[2];
 737                     // if len1 is close to 2 and 2 is close to 3, that probably
 738                     // means 1 is close to 3 so the second part of this test might
 739                     // not be needed, but it doesn't hurt to include it.
 740                     final float errLen3 = err * len3;
 741                     if (!(Helpers.within(len2, len3, errLen3) &&
 742                           Helpers.within(len1, len3, errLen3))) {
 743                         cachedHaveLowAcceleration = 0;
 744                         return false;
 745                     }
 746                 }
 747                 cachedHaveLowAcceleration = 1;
 748                 return true;
 749             }
 750 
 751             return (cachedHaveLowAcceleration == 1);
 752         }
 753 
 754         // we want to avoid allocations/gc so we keep this array so we
 755         // can put roots in it,
 756         private final float[] nextRoots = new float[4];
 757 
 758         // caches the coefficients of the current leaf in its flattened
 759         // form (see inside next() for what that means). The cache is
 760         // invalid when it's third element is negative, since in any
 761         // valid flattened curve, this would be >= 0.
 762         private final float[] flatLeafCoefCache = new float[]{0.0f, 0.0f, -1.0f, 0.0f};
 763 
 764         // returns the t value where the remaining curve should be split in
 765         // order for the left subdivided curve to have length len. If len
 766         // is >= than the length of the uniterated curve, it returns 1.
 767         float next(final float len) {
 768             final float targetLength = lenAtLastSplit + len;
 769             while (lenAtNextT < targetLength) {
 770                 if (done) {
 771                     lastSegLen = lenAtNextT - lenAtLastSplit;
 772                     return 1.0f;
 773                 }
 774                 goToNextLeaf();
 775             }
 776             lenAtLastSplit = targetLength;
 777             final float leaflen = lenAtNextT - lenAtLastT;
 778             float t = (targetLength - lenAtLastT) / leaflen;
 779 
 780             // cubicRootsInAB is a fairly expensive call, so we just don't do it
 781             // if the acceleration in this section of the curve is small enough.
 782             if (!haveLowAcceleration(0.05f)) {
 783                 // We flatten the current leaf along the x axis, so that we're
 784                 // left with a, b, c which define a 1D Bezier curve. We then
 785                 // solve this to get the parameter of the original leaf that
 786                 // gives us the desired length.
 787                 final float[] _flatLeafCoefCache = flatLeafCoefCache;
 788 
 789                 if (_flatLeafCoefCache[2] < 0.0f) {
 790                     float x =     curLeafCtrlPolyLengths[0],
 791                           y = x + curLeafCtrlPolyLengths[1];
 792                     if (curveType == 8) {
 793                         float z = y + curLeafCtrlPolyLengths[2];
 794                         _flatLeafCoefCache[0] = 3.0f * (x - y) + z;
 795                         _flatLeafCoefCache[1] = 3.0f * (y - 2.0f * x);
 796                         _flatLeafCoefCache[2] = 3.0f * x;
 797                         _flatLeafCoefCache[3] = -z;
 798                     } else if (curveType == 6) {
 799                         _flatLeafCoefCache[0] = 0.0f;
 800                         _flatLeafCoefCache[1] = y - 2.0f * x;
 801                         _flatLeafCoefCache[2] = 2.0f * x;
 802                         _flatLeafCoefCache[3] = -y;
 803                     }
 804                 }
 805                 float a = _flatLeafCoefCache[0];
 806                 float b = _flatLeafCoefCache[1];
 807                 float c = _flatLeafCoefCache[2];
 808                 float d = t * _flatLeafCoefCache[3];
 809 
 810                 // we use cubicRootsInAB here, because we want only roots in 0, 1,
 811                 // and our quadratic root finder doesn't filter, so it's just a
 812                 // matter of convenience.
 813                 final int n = Helpers.cubicRootsInAB(a, b, c, d, nextRoots, 0, 0.0f, 1.0f);
 814                 if (n == 1 && !Float.isNaN(nextRoots[0])) {
 815                     t = nextRoots[0];
 816                 }
 817             }
 818             // t is relative to the current leaf, so we must make it a valid parameter
 819             // of the original curve.
 820             t = t * (nextT - lastT) + lastT;
 821             if (t >= 1.0f) {
 822                 t = 1.0f;
 823                 done = true;
 824             }
 825             // even if done = true, if we're here, that means targetLength
 826             // is equal to, or very, very close to the total length of the
 827             // curve, so lastSegLen won't be too high. In cases where len
 828             // overshoots the curve, this method will exit in the while
 829             // loop, and lastSegLen will still be set to the right value.
 830             lastSegLen = len;
 831             return t;
 832         }
 833 
 834         float totalLength() {
 835             while (!done) {
 836                 goToNextLeaf();
 837             }
 838             // reset LengthIterator:
 839             reset();
 840 
 841             return lenAtNextT;
 842         }
 843 
 844         float lastSegLen() {
 845             return lastSegLen;
 846         }
 847 
 848         // go to the next leaf (in an inorder traversal) in the recursion tree
 849         // preconditions: must be on a leaf, and that leaf must not be the root.
 850         private void goToNextLeaf() {
 851             // We must go to the first ancestor node that has an unvisited
 852             // right child.
 853             final boolean[] _sides = sidesRight;
 854             int _recLevel = recLevel;
 855             _recLevel--;
 856 
 857             while(_sides[_recLevel]) {
 858                 if (_recLevel == 0) {
 859                     recLevel = 0;
 860                     done = true;
 861                     return;
 862                 }
 863                 _recLevel--;
 864             }
 865 
 866             _sides[_recLevel] = true;
 867             // optimize arraycopy (8 values faster than 6 = type):
 868             System.arraycopy(recCurveStack[_recLevel++], 0,
 869                              recCurveStack[_recLevel], 0, 8);
 870             recLevel = _recLevel;
 871             goLeft();
 872         }
 873 
 874         // go to the leftmost node from the current node. Return its length.
 875         private void goLeft() {
 876             final float len = onLeaf();
 877             if (len >= 0.0f) {
 878                 lastT = nextT;
 879                 lenAtLastT = lenAtNextT;
 880                 nextT += (1 << (REC_LIMIT - recLevel)) * MIN_T_INC;
 881                 lenAtNextT += len;
 882                 // invalidate caches
 883                 flatLeafCoefCache[2] = -1.0f;
 884                 cachedHaveLowAcceleration = -1;
 885             } else {
 886                 Helpers.subdivide(recCurveStack[recLevel],
 887                                   recCurveStack[recLevel + 1],
 888                                   recCurveStack[recLevel], curveType);
 889 
 890                 sidesRight[recLevel] = false;
 891                 recLevel++;
 892                 goLeft();
 893             }
 894         }
 895 
 896         // this is a bit of a hack. It returns -1 if we're not on a leaf, and
 897         // the length of the leaf if we are on a leaf.
 898         private float onLeaf() {
 899             final float[] curve = recCurveStack[recLevel];
 900             final int _curveType = curveType;
 901             float polyLen = 0.0f;
 902 
 903             float x0 = curve[0], y0 = curve[1];
 904             for (int i = 2; i < _curveType; i += 2) {
 905                 final float x1 = curve[i], y1 = curve[i + 1];
 906                 final float len = Helpers.linelen(x0, y0, x1, y1);
 907                 polyLen += len;
 908                 curLeafCtrlPolyLengths[(i >> 1) - 1] = len;
 909                 x0 = x1;
 910                 y0 = y1;
 911             }
 912 
 913             final float lineLen = Helpers.linelen(curve[0], curve[1], x0, y0);
 914 
 915             if ((polyLen - lineLen) < CURVE_LEN_ERR || recLevel == REC_LIMIT) {
 916                 return (polyLen + lineLen) / 2.0f;
 917             }
 918             return -1.0f;
 919         }
 920     }
 921 
 922     @Override
 923     public void curveTo(final float x1, final float y1,
 924                         final float x2, final float y2,
 925                         final float x3, final float y3)
 926     {
 927         final int outcode0 = this.cOutCode;
 928 
 929         if (clipRect != null) {
 930             final int outcode1 = Helpers.outcode(x1, y1, clipRect);
 931             final int outcode2 = Helpers.outcode(x2, y2, clipRect);
 932             final int outcode3 = Helpers.outcode(x3, y3, clipRect);
 933 
 934             // Should clip
 935             final int orCode = (outcode0 | outcode1 | outcode2 | outcode3);
 936             if (orCode != 0) {
 937                 final int sideCode = outcode0 & outcode1 & outcode2 & outcode3;
 938 
 939                 // basic rejection criteria:
 940                 if (sideCode == 0) {
 941                     // overlap clip:
 942                     if (subdivide) {
 943                         // avoid reentrance
 944                         subdivide = false;
 945                         // subdivide curve => callback with subdivided parts:
 946                         boolean ret = curveSplitter.splitCurve(cx0, cy0, x1, y1, x2, y2, x3, y3,
 947                                                                orCode, this);
 948                         // reentrance is done:
 949                         subdivide = true;
 950                         if (ret) {
 951                             return;
 952                         }
 953                     }
 954                     // already subdivided so render it
 955                 } else {
 956                     this.cOutCode = outcode3;
 957                     skipCurveTo(x1, y1, x2, y2, x3, y3);
 958                     return;
 959                 }
 960             }
 961 
 962             this.cOutCode = outcode3;
 963 
 964             if (this.outside) {
 965                 this.outside = false;
 966                 // Adjust current index, phase & dash:
 967                 skipLen();
 968             }
 969         }
 970         _curveTo(x1, y1, x2, y2, x3, y3);
 971     }
 972 
 973     private void _curveTo(final float x1, final float y1,
 974                           final float x2, final float y2,
 975                           final float x3, final float y3)
 976     {
 977         final float[] _curCurvepts = curCurvepts;
 978 
 979         // monotonize curve:
 980         final CurveBasicMonotonizer monotonizer
 981             = rdrCtx.monotonizer.curve(cx0, cy0, x1, y1, x2, y2, x3, y3);
 982 
 983         final int nSplits = monotonizer.nbSplits;
 984         final float[] mid = monotonizer.middle;
 985 
 986         for (int i = 0, off = 0; i <= nSplits; i++, off += 6) {
 987             // optimize arraycopy (8 values faster than 6 = type):
 988             System.arraycopy(mid, off, _curCurvepts, 0, 8);
 989 
 990             somethingTo(8);
 991         }
 992     }
 993 
 994     private void skipCurveTo(final float x1, final float y1,
 995                              final float x2, final float y2,
 996                              final float x3, final float y3)
 997     {
 998         final float[] _curCurvepts = curCurvepts;
 999         _curCurvepts[0] = cx0; _curCurvepts[1] = cy0;
1000         _curCurvepts[2] = x1;  _curCurvepts[3] = y1;
1001         _curCurvepts[4] = x2;  _curCurvepts[5] = y2;
1002         _curCurvepts[6] = x3;  _curCurvepts[7] = y3;
1003 
1004         skipSomethingTo(8);
1005 
1006         this.cx0 = x3;
1007         this.cy0 = y3;
1008     }
1009 
1010     @Override
1011     public void quadTo(final float x1, final float y1,
1012                        final float x2, final float y2)
1013     {
1014         final int outcode0 = this.cOutCode;
1015 
1016         if (clipRect != null) {
1017             final int outcode1 = Helpers.outcode(x1, y1, clipRect);
1018             final int outcode2 = Helpers.outcode(x2, y2, clipRect);
1019 
1020             // Should clip
1021             final int orCode = (outcode0 | outcode1 | outcode2);
1022             if (orCode != 0) {
1023                 final int sideCode = outcode0 & outcode1 & outcode2;
1024 
1025                 // basic rejection criteria:
1026                 if (sideCode == 0) {
1027                     // overlap clip:
1028                     if (subdivide) {
1029                         // avoid reentrance
1030                         subdivide = false;
1031                         // subdivide curve => call lineTo() with subdivided curves:
1032                         boolean ret = curveSplitter.splitQuad(cx0, cy0, x1, y1,
1033                                                               x2, y2, orCode, this);
1034                         // reentrance is done:
1035                         subdivide = true;
1036                         if (ret) {
1037                             return;
1038                         }
1039                     }
1040                     // already subdivided so render it
1041                 } else {
1042                     this.cOutCode = outcode2;
1043                     skipQuadTo(x1, y1, x2, y2);
1044                     return;
1045                 }
1046             }
1047 
1048             this.cOutCode = outcode2;
1049 
1050             if (this.outside) {
1051                 this.outside = false;
1052                 // Adjust current index, phase & dash:
1053                 skipLen();
1054             }
1055         }
1056         _quadTo(x1, y1, x2, y2);
1057     }
1058 
1059     private void _quadTo(final float x1, final float y1,
1060                          final float x2, final float y2)
1061     {
1062         final float[] _curCurvepts = curCurvepts;
1063 
1064         // monotonize quad:
1065         final CurveBasicMonotonizer monotonizer
1066             = rdrCtx.monotonizer.quad(cx0, cy0, x1, y1, x2, y2);
1067 
1068         final int nSplits = monotonizer.nbSplits;
1069         final float[] mid = monotonizer.middle;
1070 
1071         for (int i = 0, off = 0; i <= nSplits; i++, off += 4) {
1072             // optimize arraycopy (8 values faster than 6 = type):
1073             System.arraycopy(mid, off, _curCurvepts, 0, 8);
1074 
1075             somethingTo(6);
1076         }
1077     }
1078 
1079     private void skipQuadTo(final float x1, final float y1,
1080                             final float x2, final float y2)
1081     {
1082         final float[] _curCurvepts = curCurvepts;
1083         _curCurvepts[0] = cx0; _curCurvepts[1] = cy0;
1084         _curCurvepts[2] = x1;  _curCurvepts[3] = y1;
1085         _curCurvepts[4] = x2;  _curCurvepts[5] = y2;
1086 
1087         skipSomethingTo(6);
1088 
1089         this.cx0 = x2;
1090         this.cy0 = y2;
1091     }
1092 
1093     @Override
1094     public void closePath() {
1095         if (cx0 != sx0 || cy0 != sy0) {
1096             lineTo(sx0, sy0);
1097         }
1098         if (firstSegidx != 0) {
1099             if (!dashOn || needsMoveTo) {
1100                 out.moveTo(sx0, sy0);
1101             }
1102             emitFirstSegments();
1103         }
1104         moveTo(sx0, sy0);
1105     }
1106 
1107     @Override
1108     public void pathDone() {
1109         if (firstSegidx != 0) {
1110             out.moveTo(sx0, sy0);
1111             emitFirstSegments();
1112         }
1113         out.pathDone();
1114 
1115         // Dispose this instance:
1116         dispose();
1117     }
1118 
1119     @Override
1120     public long getNativeConsumer() {
1121         throw new InternalError("Dasher does not use a native consumer");
1122     }
1123 }
1124