< prev index next >

src/java.desktop/share/classes/sun/java2d/marlin/DDasher.java

Print this page


   1 /*
   2  * Copyright (c) 2007, 2017, 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 
  30 /**
  31  * The <code>DDasher</code> class takes a series of linear commands
  32  * (<code>moveTo</code>, <code>lineTo</code>, <code>close</code> and
  33  * <code>end</code>) and breaks them into smaller segments according to a
  34  * dash pattern array and a starting dash phase.
  35  *
  36  * <p> Issues: in J2Se, a zero length dash segment as drawn as a very
  37  * short dash, whereas Pisces does not draw anything.  The PostScript
  38  * semantics are unclear.
  39  *
  40  */
  41 final class DDasher implements DPathConsumer2D, MarlinConst {
  42 
  43     static final int REC_LIMIT = 4;
  44     static final double ERR = 0.01d;

  45     static final double MIN_T_INC = 1.0d / (1 << REC_LIMIT);
  46 
  47     // More than 24 bits of mantissa means we can no longer accurately
  48     // measure the number of times cycled through the dash array so we
  49     // punt and override the phase to just be 0 past that point.
  50     static final double MAX_CYCLES = 16000000.0d;
  51 
  52     private DPathConsumer2D out;
  53     private double[] dash;
  54     private int dashLen;
  55     private double startPhase;
  56     private boolean startDashOn;
  57     private int startIdx;
  58 
  59     private boolean starting;
  60     private boolean needsMoveTo;
  61 
  62     private int idx;
  63     private boolean dashOn;
  64     private double phase;
  65 
  66     private double sx, sy;
  67     private double x0, y0;


  68 
  69     // temporary storage for the current curve
  70     private final double[] curCurvepts;
  71 
  72     // per-thread renderer context
  73     final DRendererContext rdrCtx;
  74 
  75     // flag to recycle dash array copy
  76     boolean recycleDashes;
  77 







  78     // dashes ref (dirty)
  79     final DoubleArrayCache.Reference dashes_ref;
  80     // firstSegmentsBuffer ref (dirty)
  81     final DoubleArrayCache.Reference firstSegmentsBuffer_ref;
  82 
















  83     /**
  84      * Constructs a <code>DDasher</code>.
  85      * @param rdrCtx per-thread renderer context
  86      */
  87     DDasher(final DRendererContext rdrCtx) {
  88         this.rdrCtx = rdrCtx;
  89 
  90         dashes_ref = rdrCtx.newDirtyDoubleArrayRef(INITIAL_ARRAY); // 1K
  91 
  92         firstSegmentsBuffer_ref = rdrCtx.newDirtyDoubleArrayRef(INITIAL_ARRAY); // 1K
  93         firstSegmentsBuffer     = firstSegmentsBuffer_ref.initial;
  94 
  95         // we need curCurvepts to be able to contain 2 curves because when
  96         // dashing curves, we need to subdivide it
  97         curCurvepts = new double[8 * 2];


  98     }
  99 
 100     /**
 101      * Initialize the <code>DDasher</code>.
 102      *
 103      * @param out an output <code>DPathConsumer2D</code>.
 104      * @param dash an array of <code>double</code>s containing the dash pattern
 105      * @param dashLen length of the given dash array
 106      * @param phase a <code>double</code> containing the dash phase
 107      * @param recycleDashes true to indicate to recycle the given dash array
 108      * @return this instance
 109      */
 110     DDasher init(final DPathConsumer2D out, double[] dash, int dashLen,
 111                 double phase, boolean recycleDashes)
 112     {
 113         this.out = out;
 114 
 115         // Normalize so 0 <= phase < dash[0]
 116         int sidx = 0;
 117         dashOn = true;

 118         double sum = 0.0d;
 119         for (double d : dash) {
 120             sum += d;
 121         }


 122         double cycles = phase / sum;
 123         if (phase < 0.0d) {
 124             if (-cycles >= MAX_CYCLES) {
 125                 phase = 0.0d;
 126             } else {
 127                 int fullcycles = FloatMath.floor_int(-cycles);
 128                 if ((fullcycles & dash.length & 1) != 0) {
 129                     dashOn = !dashOn;
 130                 }
 131                 phase += fullcycles * sum;
 132                 while (phase < 0.0d) {
 133                     if (--sidx < 0) {
 134                         sidx = dash.length - 1;
 135                     }
 136                     phase += dash[sidx];
 137                     dashOn = !dashOn;
 138                 }
 139             }
 140         } else if (phase > 0.0d) {
 141             if (cycles >= MAX_CYCLES) {


 150                 while (phase >= (d = dash[sidx])) {
 151                     phase -= d;
 152                     sidx = (sidx + 1) % dash.length;
 153                     dashOn = !dashOn;
 154                 }
 155             }
 156         }
 157 
 158         this.dash = dash;
 159         this.dashLen = dashLen;
 160         this.phase = phase;
 161         this.startPhase = phase;
 162         this.startDashOn = dashOn;
 163         this.startIdx = sidx;
 164         this.starting = true;
 165         this.needsMoveTo = false;
 166         this.firstSegidx = 0;
 167 
 168         this.recycleDashes = recycleDashes;
 169 






 170         return this; // fluent API
 171     }
 172 
 173     /**
 174      * Disposes this dasher:
 175      * clean up before reusing this instance
 176      */
 177     void dispose() {
 178         if (DO_CLEAN_DIRTY) {
 179             // Force zero-fill dirty arrays:
 180             Arrays.fill(curCurvepts, 0.0d);
 181         }
 182         // Return arrays:
 183         if (recycleDashes) {
 184             dash = dashes_ref.putArray(dash);
 185         }
 186         firstSegmentsBuffer = firstSegmentsBuffer_ref.putArray(firstSegmentsBuffer);
 187     }
 188 
 189     double[] copyDashArray(final float[] dashes) {
 190         final int len = dashes.length;
 191         final double[] newDashes;
 192         if (len <= MarlinConst.INITIAL_ARRAY) {
 193             newDashes = dashes_ref.initial;
 194         } else {
 195             if (DO_STATS) {
 196                 rdrCtx.stats.stat_array_dasher_dasher.add(len);
 197             }
 198             newDashes = dashes_ref.getArray(len);
 199         }
 200         for (int i = 0; i < len; i++) { newDashes[i] = dashes[i]; }
 201         return newDashes;
 202     }
 203 
 204     @Override
 205     public void moveTo(final double x0, final double y0) {
 206         if (firstSegidx != 0) {
 207             out.moveTo(sx, sy);
 208             emitFirstSegments();
 209         }
 210         needsMoveTo = true;
 211         this.idx = startIdx;
 212         this.dashOn = this.startDashOn;
 213         this.phase = this.startPhase;
 214         this.sx = x0;
 215         this.sy = y0;
 216         this.x0 = x0;
 217         this.y0 = y0;


 218         this.starting = true;







 219     }
 220 
 221     private void emitSeg(double[] buf, int off, int type) {
 222         switch (type) {
 223         case 8:
 224             out.curveTo(buf[off+0], buf[off+1],
 225                         buf[off+2], buf[off+3],
 226                         buf[off+4], buf[off+5]);
 227             return;
 228         case 6:
 229             out.quadTo(buf[off+0], buf[off+1],
 230                        buf[off+2], buf[off+3]);
 231             return;
 232         case 4:
 233             out.lineTo(buf[off], buf[off+1]);
 234             return;
 235         default:
 236         }
 237     }
 238 
 239     private void emitFirstSegments() {
 240         final double[] fSegBuf = firstSegmentsBuffer;
 241 
 242         for (int i = 0, len = firstSegidx; i < len; ) {
 243             int type = (int)fSegBuf[i];
 244             emitSeg(fSegBuf, i + 1, type);
 245             i += (type - 1);
 246         }
 247         firstSegidx = 0;
 248     }
 249     // We don't emit the first dash right away. If we did, caps would be
 250     // drawn on it, but we need joins to be drawn if there's a closePath()
 251     // So, we store the path elements that make up the first dash in the
 252     // buffer below.
 253     private double[] firstSegmentsBuffer; // dynamic array
 254     private int firstSegidx;
 255 
 256     // precondition: pts must be in relative coordinates (relative to x0,y0)
 257     private void goTo(final double[] pts, final int off, final int type,
 258                       final boolean on)
 259     {
 260         final int index = off + type;
 261         final double x = pts[index - 4];
 262         final double y = pts[index - 3];
 263 
 264         if (on) {
 265             if (starting) {
 266                 goTo_starting(pts, off, type);
 267             } else {
 268                 if (needsMoveTo) {
 269                     needsMoveTo = false;
 270                     out.moveTo(x0, y0);
 271                 }
 272                 emitSeg(pts, off, type);
 273             }
 274         } else {
 275             if (starting) {
 276                 // low probability test (hotspot)
 277                 starting = false;
 278             }
 279             needsMoveTo = true;
 280         }
 281         this.x0 = x;
 282         this.y0 = y;
 283     }
 284 
 285     private void goTo_starting(final double[] pts, final int off, final int type) {
 286         int len = type - 1; // - 2 + 1
 287         int segIdx = firstSegidx;
 288         double[] buf = firstSegmentsBuffer;
 289 
 290         if (segIdx + len  > buf.length) {
 291             if (DO_STATS) {
 292                 rdrCtx.stats.stat_array_dasher_firstSegmentsBuffer
 293                     .add(segIdx + len);
 294             }
 295             firstSegmentsBuffer = buf
 296                 = firstSegmentsBuffer_ref.widenArray(buf, segIdx,
 297                                                      segIdx + len);
 298         }
 299         buf[segIdx++] = type;
 300         len--;
 301         // small arraycopy (2, 4 or 6) but with offset:
 302         System.arraycopy(pts, off, buf, segIdx, len);
 303         firstSegidx = segIdx + len;
 304     }
 305 
 306     @Override
 307     public void lineTo(final double x1, final double y1) {
 308         final double dx = x1 - x0;
 309         final double dy = y1 - y0;





 310 
 311         double len = dx*dx + dy*dy;









































 312         if (len == 0.0d) {
 313             return;
 314         }
 315         len = Math.sqrt(len);
 316 
 317         // The scaling factors needed to get the dx and dy of the
 318         // transformed dash segments.
 319         final double cx = dx / len;
 320         final double cy = dy / len;
 321 
 322         final double[] _curCurvepts = curCurvepts;
 323         final double[] _dash = dash;
 324         final int _dashLen = this.dashLen;
 325 
 326         int _idx = idx;
 327         boolean _dashOn = dashOn;
 328         double _phase = phase;
 329 
 330         double leftInThisDashSegment;
 331         double d, dashdx, dashdy, p;
 332 
 333         while (true) {
 334             d = _dash[_idx];
 335             leftInThisDashSegment = d - _phase;
 336 
 337             if (len <= leftInThisDashSegment) {
 338                 _curCurvepts[0] = x1;
 339                 _curCurvepts[1] = y1;
 340 
 341                 goTo(_curCurvepts, 0, 4, _dashOn);
 342 
 343                 // Advance phase within current dash segment
 344                 _phase += len;
 345 
 346                 // TODO: compare double values using epsilon:
 347                 if (len == leftInThisDashSegment) {
 348                     _phase = 0.0d;
 349                     _idx = (_idx + 1) % _dashLen;
 350                     _dashOn = !_dashOn;
 351                 }
 352 
 353                 // Save local state:
 354                 idx = _idx;
 355                 dashOn = _dashOn;
 356                 phase = _phase;
 357                 return;
 358             }
 359 
 360             dashdx = d * cx;
 361             dashdy = d * cy;
 362 
 363             if (_phase == 0.0d) {
 364                 _curCurvepts[0] = x0 + dashdx;
 365                 _curCurvepts[1] = y0 + dashdy;
 366             } else {
 367                 p = leftInThisDashSegment / d;
 368                 _curCurvepts[0] = x0 + p * dashdx;
 369                 _curCurvepts[1] = y0 + p * dashdy;
 370             }
 371 
 372             goTo(_curCurvepts, 0, 4, _dashOn);
 373 
 374             len -= leftInThisDashSegment;
 375             // Advance to next dash segment
 376             _idx = (_idx + 1) % _dashLen;
 377             _dashOn = !_dashOn;
 378             _phase = 0.0d;
 379         }




 380     }
 381 
 382     // shared instance in DDasher
 383     private final LengthIterator li = new LengthIterator();








































































 384 
 385     // preconditions: curCurvepts must be an array of length at least 2 * type,
 386     // that contains the curve we want to dash in the first type elements
 387     private void somethingTo(final int type) {
 388         if (pointCurve(curCurvepts, type)) {

 389             return;
 390         }
 391         final LengthIterator _li = li;
 392         final double[] _curCurvepts = curCurvepts;
 393         final double[] _dash = dash;
 394         final int _dashLen = this.dashLen;
 395 
 396         _li.initializeIterationOnCurve(_curCurvepts, type);
 397 
 398         int _idx = idx;
 399         boolean _dashOn = dashOn;
 400         double _phase = phase;
 401 
 402         // initially the current curve is at curCurvepts[0...type]
 403         int curCurveoff = 0;
 404         double lastSplitT = 0.0d;
 405         double t;
 406         double leftInThisDashSegment = _dash[_idx] - _phase;
 407 
 408         while ((t = _li.next(leftInThisDashSegment)) < 1.0d) {
 409             if (t != 0.0d) {
 410                 DHelpers.subdivideAt((t - lastSplitT) / (1.0d - lastSplitT),
 411                                     _curCurvepts, curCurveoff,
 412                                     _curCurvepts, 0,
 413                                     _curCurvepts, type, type);
 414                 lastSplitT = t;
 415                 goTo(_curCurvepts, 2, type, _dashOn);
 416                 curCurveoff = type;
 417             }
 418             // Advance to next dash segment
 419             _idx = (_idx + 1) % _dashLen;
 420             _dashOn = !_dashOn;
 421             _phase = 0.0d;
 422             leftInThisDashSegment = _dash[_idx];
 423         }
 424 
 425         goTo(_curCurvepts, curCurveoff + 2, type, _dashOn);
 426 
 427         _phase += _li.lastSegLen();
 428         if (_phase >= _dash[_idx]) {
 429             _phase = 0.0d;
 430             _idx = (_idx + 1) % _dashLen;
 431             _dashOn = !_dashOn;
 432         }
 433         // Save local state:
 434         idx = _idx;
 435         dashOn = _dashOn;
 436         phase = _phase;
 437 
 438         // reset LengthIterator:
 439         _li.reset();
 440     }
 441 
 442     private static boolean pointCurve(double[] curve, int type) {






















 443         for (int i = 2; i < type; i++) {
 444             if (curve[i] != curve[i-2]) {
 445                 return false;
 446             }
 447         }
 448         return true;
 449     }
 450 
 451     // Objects of this class are used to iterate through curves. They return
 452     // t values where the left side of the curve has a specified length.
 453     // It does this by subdividing the input curve until a certain error
 454     // condition has been met. A recursive subdivision procedure would
 455     // return as many as 1<<limit curves, but this is an iterator and we
 456     // don't need all the curves all at once, so what we carry out a
 457     // lazy inorder traversal of the recursion tree (meaning we only move
 458     // through the tree when we need the next subdivided curve). This saves
 459     // us a lot of memory because at any one time we only need to store
 460     // limit+1 curves - one for each level of the tree + 1.
 461     // NOTE: the way we do things here is not enough to traverse a general
 462     // tree; however, the trees we are interested in have the property that
 463     // every non leaf node has exactly 2 children
 464     static final class LengthIterator {
 465         private enum Side {LEFT, RIGHT}
 466         // Holds the curves at various levels of the recursion. The root
 467         // (i.e. the original curve) is at recCurveStack[0] (but then it
 468         // gets subdivided, the left half is put at 1, so most of the time
 469         // only the right half of the original curve is at 0)
 470         private final double[][] recCurveStack; // dirty
 471         // sides[i] indicates whether the node at level i+1 in the path from
 472         // the root to the current leaf is a left or right child of its parent.
 473         private final Side[] sides; // dirty
 474         private int curveType;
 475         // lastT and nextT delimit the current leaf.
 476         private double nextT;
 477         private double lenAtNextT;
 478         private double lastT;
 479         private double lenAtLastT;
 480         private double lenAtLastSplit;
 481         private double lastSegLen;
 482         // the current level in the recursion tree. 0 is the root. limit
 483         // is the deepest possible leaf.
 484         private int recLevel;
 485         private boolean done;
 486 
 487         // the lengths of the lines of the control polygon. Only its first
 488         // curveType/2 - 1 elements are valid. This is an optimization. See
 489         // next() for more detail.
 490         private final double[] curLeafCtrlPolyLengths = new double[3];
 491 
 492         LengthIterator() {
 493             this.recCurveStack = new double[REC_LIMIT + 1][8];
 494             this.sides = new Side[REC_LIMIT];
 495             // if any methods are called without first initializing this object
 496             // on a curve, we want it to fail ASAP.
 497             this.nextT = Double.MAX_VALUE;
 498             this.lenAtNextT = Double.MAX_VALUE;
 499             this.lenAtLastSplit = Double.MIN_VALUE;
 500             this.recLevel = Integer.MIN_VALUE;
 501             this.lastSegLen = Double.MAX_VALUE;
 502             this.done = true;
 503         }
 504 
 505         /**
 506          * Reset this LengthIterator.
 507          */
 508         void reset() {
 509             // keep data dirty
 510             // as it appears not useful to reset data:
 511             if (DO_CLEAN_DIRTY) {
 512                 final int recLimit = recCurveStack.length - 1;
 513                 for (int i = recLimit; i >= 0; i--) {
 514                     Arrays.fill(recCurveStack[i], 0.0d);
 515                 }
 516                 Arrays.fill(sides, Side.LEFT);
 517                 Arrays.fill(curLeafCtrlPolyLengths, 0.0d);
 518                 Arrays.fill(nextRoots, 0.0d);
 519                 Arrays.fill(flatLeafCoefCache, 0.0d);
 520                 flatLeafCoefCache[2] = -1.0d;
 521             }
 522         }
 523 
 524         void initializeIterationOnCurve(double[] pts, int type) {
 525             // optimize arraycopy (8 values faster than 6 = type):
 526             System.arraycopy(pts, 0, recCurveStack[0], 0, 8);
 527             this.curveType = type;
 528             this.recLevel = 0;
 529             this.lastT = 0.0d;
 530             this.lenAtLastT = 0.0d;
 531             this.nextT = 0.0d;
 532             this.lenAtNextT = 0.0d;
 533             goLeft(); // initializes nextT and lenAtNextT properly
 534             this.lenAtLastSplit = 0.0d;
 535             if (recLevel > 0) {
 536                 this.sides[0] = Side.LEFT;
 537                 this.done = false;
 538             } else {
 539                 // the root of the tree is a leaf so we're done.
 540                 this.sides[0] = Side.RIGHT;
 541                 this.done = true;
 542             }
 543             this.lastSegLen = 0.0d;
 544         }
 545 
 546         // 0 == false, 1 == true, -1 == invalid cached value.
 547         private int cachedHaveLowAcceleration = -1;
 548 
 549         private boolean haveLowAcceleration(double err) {
 550             if (cachedHaveLowAcceleration == -1) {
 551                 final double len1 = curLeafCtrlPolyLengths[0];
 552                 final double len2 = curLeafCtrlPolyLengths[1];
 553                 // the test below is equivalent to !within(len1/len2, 1, err).
 554                 // It is using a multiplication instead of a division, so it
 555                 // should be a bit faster.
 556                 if (!DHelpers.within(len1, len2, err * len2)) {
 557                     cachedHaveLowAcceleration = 0;
 558                     return false;
 559                 }
 560                 if (curveType == 8) {
 561                     final double len3 = curLeafCtrlPolyLengths[2];
 562                     // if len1 is close to 2 and 2 is close to 3, that probably
 563                     // means 1 is close to 3 so the second part of this test might
 564                     // not be needed, but it doesn't hurt to include it.
 565                     final double errLen3 = err * len3;
 566                     if (!(DHelpers.within(len2, len3, errLen3) &&
 567                           DHelpers.within(len1, len3, errLen3))) {
 568                         cachedHaveLowAcceleration = 0;
 569                         return false;


 596                     lastSegLen = lenAtNextT - lenAtLastSplit;
 597                     return 1.0d;
 598                 }
 599                 goToNextLeaf();
 600             }
 601             lenAtLastSplit = targetLength;
 602             final double leaflen = lenAtNextT - lenAtLastT;
 603             double t = (targetLength - lenAtLastT) / leaflen;
 604 
 605             // cubicRootsInAB is a fairly expensive call, so we just don't do it
 606             // if the acceleration in this section of the curve is small enough.
 607             if (!haveLowAcceleration(0.05d)) {
 608                 // We flatten the current leaf along the x axis, so that we're
 609                 // left with a, b, c which define a 1D Bezier curve. We then
 610                 // solve this to get the parameter of the original leaf that
 611                 // gives us the desired length.
 612                 final double[] _flatLeafCoefCache = flatLeafCoefCache;
 613 
 614                 if (_flatLeafCoefCache[2] < 0.0d) {
 615                     double x =     curLeafCtrlPolyLengths[0],
 616                           y = x + curLeafCtrlPolyLengths[1];
 617                     if (curveType == 8) {
 618                         double z = y + curLeafCtrlPolyLengths[2];
 619                         _flatLeafCoefCache[0] = 3.0d * (x - y) + z;
 620                         _flatLeafCoefCache[1] = 3.0d * (y - 2.0d * x);
 621                         _flatLeafCoefCache[2] = 3.0d * x;
 622                         _flatLeafCoefCache[3] = -z;
 623                     } else if (curveType == 6) {
 624                         _flatLeafCoefCache[0] = 0.0d;
 625                         _flatLeafCoefCache[1] = y - 2.0d * x;
 626                         _flatLeafCoefCache[2] = 2.0d * x;
 627                         _flatLeafCoefCache[3] = -y;
 628                     }
 629                 }
 630                 double a = _flatLeafCoefCache[0];
 631                 double b = _flatLeafCoefCache[1];
 632                 double c = _flatLeafCoefCache[2];
 633                 double d = t * _flatLeafCoefCache[3];
 634 
 635                 // we use cubicRootsInAB here, because we want only roots in 0, 1,
 636                 // and our quadratic root finder doesn't filter, so it's just a
 637                 // matter of convenience.
 638                 int n = DHelpers.cubicRootsInAB(a, b, c, d, nextRoots, 0, 0.0d, 1.0d);

 639                 if (n == 1 && !Double.isNaN(nextRoots[0])) {
 640                     t = nextRoots[0];
 641                 }
 642             }
 643             // t is relative to the current leaf, so we must make it a valid parameter
 644             // of the original curve.
 645             t = t * (nextT - lastT) + lastT;
 646             if (t >= 1.0d) {
 647                 t = 1.0d;
 648                 done = true;
 649             }
 650             // even if done = true, if we're here, that means targetLength
 651             // is equal to, or very, very close to the total length of the
 652             // curve, so lastSegLen won't be too high. In cases where len
 653             // overshoots the curve, this method will exit in the while
 654             // loop, and lastSegLen will still be set to the right value.
 655             lastSegLen = len;
 656             return t;
 657         }
 658 










 659         double lastSegLen() {
 660             return lastSegLen;
 661         }
 662 
 663         // go to the next leaf (in an inorder traversal) in the recursion tree
 664         // preconditions: must be on a leaf, and that leaf must not be the root.
 665         private void goToNextLeaf() {
 666             // We must go to the first ancestor node that has an unvisited
 667             // right child.

 668             int _recLevel = recLevel;
 669             final Side[] _sides = sides;
 670 
 671             _recLevel--;
 672             while(_sides[_recLevel] == Side.RIGHT) {

 673                 if (_recLevel == 0) {
 674                     recLevel = 0;
 675                     done = true;
 676                     return;
 677                 }
 678                 _recLevel--;
 679             }
 680 
 681             _sides[_recLevel] = Side.RIGHT;
 682             // optimize arraycopy (8 values faster than 6 = type):
 683             System.arraycopy(recCurveStack[_recLevel], 0,
 684                              recCurveStack[_recLevel+1], 0, 8);
 685             _recLevel++;
 686 
 687             recLevel = _recLevel;
 688             goLeft();
 689         }
 690 
 691         // go to the leftmost node from the current node. Return its length.
 692         private void goLeft() {
 693             double len = onLeaf();
 694             if (len >= 0.0d) {
 695                 lastT = nextT;
 696                 lenAtLastT = lenAtNextT;
 697                 nextT += (1 << (REC_LIMIT - recLevel)) * MIN_T_INC;
 698                 lenAtNextT += len;
 699                 // invalidate caches
 700                 flatLeafCoefCache[2] = -1.0d;
 701                 cachedHaveLowAcceleration = -1;
 702             } else {
 703                 DHelpers.subdivide(recCurveStack[recLevel], 0,
 704                                   recCurveStack[recLevel+1], 0,
 705                                   recCurveStack[recLevel], 0, curveType);
 706                 sides[recLevel] = Side.LEFT;

 707                 recLevel++;
 708                 goLeft();
 709             }
 710         }
 711 
 712         // this is a bit of a hack. It returns -1 if we're not on a leaf, and
 713         // the length of the leaf if we are on a leaf.
 714         private double onLeaf() {
 715             final double[] curve = recCurveStack[recLevel];
 716             final int _curveType = curveType;
 717             double polyLen = 0.0d;
 718 
 719             double x0 = curve[0], y0 = curve[1];
 720             for (int i = 2; i < _curveType; i += 2) {
 721                 final double x1 = curve[i], y1 = curve[i+1];
 722                 final double len = DHelpers.linelen(x0, y0, x1, y1);
 723                 polyLen += len;
 724                 curLeafCtrlPolyLengths[(i >> 1) - 1] = len;
 725                 x0 = x1;
 726                 y0 = y1;
 727             }
 728 
 729             final double lineLen = DHelpers.linelen(curve[0], curve[1],
 730                                                     curve[_curveType-2],
 731                                                     curve[_curveType-1]);
 732             if ((polyLen - lineLen) < ERR || recLevel == REC_LIMIT) {
 733                 return (polyLen + lineLen) / 2.0d;
 734             }
 735             return -1.0d;
 736         }
 737     }
 738 
 739     @Override
 740     public void curveTo(final double x1, final double y1,
 741                         final double x2, final double y2,
 742                         final double x3, final double y3)
 743     {


















































 744         final double[] _curCurvepts = curCurvepts;
 745         _curCurvepts[0] = x0;        _curCurvepts[1] = y0;
 746         _curCurvepts[2] = x1;        _curCurvepts[3] = y1;
 747         _curCurvepts[4] = x2;        _curCurvepts[5] = y2;
 748         _curCurvepts[6] = x3;        _curCurvepts[7] = y3;
 749         somethingTo(8);

























 750     }
 751 
 752     @Override
 753     public void quadTo(final double x1, final double y1,
 754                        final double x2, final double y2)
 755     {




































































 756         final double[] _curCurvepts = curCurvepts;
 757         _curCurvepts[0] = x0;        _curCurvepts[1] = y0;
 758         _curCurvepts[2] = x1;        _curCurvepts[3] = y1;
 759         _curCurvepts[4] = x2;        _curCurvepts[5] = y2;
 760         somethingTo(6);




 761     }
 762 
 763     @Override
 764     public void closePath() {
 765         lineTo(sx, sy);


 766         if (firstSegidx != 0) {
 767             if (!dashOn || needsMoveTo) {
 768                 out.moveTo(sx, sy);
 769             }
 770             emitFirstSegments();
 771         }
 772         moveTo(sx, sy);
 773     }
 774 
 775     @Override
 776     public void pathDone() {
 777         if (firstSegidx != 0) {
 778             out.moveTo(sx, sy);
 779             emitFirstSegments();
 780         }
 781         out.pathDone();
 782 
 783         // Dispose this instance:
 784         dispose();
 785     }
 786 
 787     @Override
 788     public long getNativeConsumer() {
 789         throw new InternalError("DDasher does not use a native consumer");
 790     }
 791 }
 792 
   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.java2d.marlin.DTransformingPathConsumer2D.CurveBasicMonotonizer;
  30 import sun.java2d.marlin.DTransformingPathConsumer2D.CurveClipSplitter;
  31 
  32 /**
  33  * The <code>DDasher</code> class takes a series of linear commands
  34  * (<code>moveTo</code>, <code>lineTo</code>, <code>close</code> and
  35  * <code>end</code>) and breaks them into smaller segments according to a
  36  * dash pattern array and a starting dash phase.
  37  *
  38  * <p> Issues: in J2Se, a zero length dash segment as drawn as a very
  39  * short dash, whereas Pisces does not draw anything.  The PostScript
  40  * semantics are unclear.
  41  *
  42  */
  43 final class DDasher implements DPathConsumer2D, MarlinConst {
  44 
  45     /* huge circle with radius ~ 2E9 only needs 12 subdivision levels */
  46     static final int REC_LIMIT = 16;
  47     static final double CURVE_LEN_ERR = MarlinProperties.getCurveLengthError(); // 0.01 initial
  48     static final double MIN_T_INC = 1.0d / (1 << REC_LIMIT);
  49 
  50     // More than 24 bits of mantissa means we can no longer accurately
  51     // measure the number of times cycled through the dash array so we
  52     // punt and override the phase to just be 0 past that point.
  53     static final double MAX_CYCLES = 16000000.0d;
  54 
  55     private DPathConsumer2D out;
  56     private double[] dash;
  57     private int dashLen;
  58     private double startPhase;
  59     private boolean startDashOn;
  60     private int startIdx;
  61 
  62     private boolean starting;
  63     private boolean needsMoveTo;
  64 
  65     private int idx;
  66     private boolean dashOn;
  67     private double phase;
  68 
  69     // The starting point of the path
  70     private double sx0, sy0;
  71     // the current point
  72     private double cx0, cy0;
  73 
  74     // temporary storage for the current curve
  75     private final double[] curCurvepts;
  76 
  77     // per-thread renderer context
  78     final DRendererContext rdrCtx;
  79 
  80     // flag to recycle dash array copy
  81     boolean recycleDashes;
  82 
  83     // We don't emit the first dash right away. If we did, caps would be
  84     // drawn on it, but we need joins to be drawn if there's a closePath()
  85     // So, we store the path elements that make up the first dash in the
  86     // buffer below.
  87     private double[] firstSegmentsBuffer; // dynamic array
  88     private int firstSegidx;
  89 
  90     // dashes ref (dirty)
  91     final DoubleArrayCache.Reference dashes_ref;
  92     // firstSegmentsBuffer ref (dirty)
  93     final DoubleArrayCache.Reference firstSegmentsBuffer_ref;
  94 
  95     // Bounds of the drawing region, at pixel precision.
  96     private double[] clipRect;
  97 
  98     // the outcode of the current point
  99     private int cOutCode = 0;
 100 
 101     private boolean subdivide = DO_CLIP_SUBDIVIDER;
 102 
 103     private final LengthIterator li = new LengthIterator();
 104 
 105     private final CurveClipSplitter curveSplitter;
 106 
 107     private double cycleLen;
 108     private boolean outside;
 109     private double totalSkipLen;
 110 
 111     /**
 112      * Constructs a <code>DDasher</code>.
 113      * @param rdrCtx per-thread renderer context
 114      */
 115     DDasher(final DRendererContext rdrCtx) {
 116         this.rdrCtx = rdrCtx;
 117 
 118         dashes_ref = rdrCtx.newDirtyDoubleArrayRef(INITIAL_ARRAY); // 1K
 119 
 120         firstSegmentsBuffer_ref = rdrCtx.newDirtyDoubleArrayRef(INITIAL_ARRAY); // 1K
 121         firstSegmentsBuffer     = firstSegmentsBuffer_ref.initial;
 122 
 123         // we need curCurvepts to be able to contain 2 curves because when
 124         // dashing curves, we need to subdivide it
 125         curCurvepts = new double[8 * 2];
 126 
 127         this.curveSplitter = rdrCtx.curveClipSplitter;
 128     }
 129 
 130     /**
 131      * Initialize the <code>DDasher</code>.
 132      *
 133      * @param out an output <code>DPathConsumer2D</code>.
 134      * @param dash an array of <code>double</code>s containing the dash pattern
 135      * @param dashLen length of the given dash array
 136      * @param phase a <code>double</code> containing the dash phase
 137      * @param recycleDashes true to indicate to recycle the given dash array
 138      * @return this instance
 139      */
 140     DDasher init(final DPathConsumer2D out, double[] dash, int dashLen,
 141                 double phase, boolean recycleDashes)
 142     {
 143         this.out = out;
 144 
 145         // Normalize so 0 <= phase < dash[0]
 146         int sidx = 0;
 147         dashOn = true;
 148 
 149         double sum = 0.0d;
 150         for (double d : dash) {
 151             sum += d;
 152         }
 153         this.cycleLen = sum;
 154 
 155         double cycles = phase / sum;
 156         if (phase < 0.0d) {
 157             if (-cycles >= MAX_CYCLES) {
 158                 phase = 0.0d;
 159             } else {
 160                 int fullcycles = FloatMath.floor_int(-cycles);
 161                 if ((fullcycles & dash.length & 1) != 0) {
 162                     dashOn = !dashOn;
 163                 }
 164                 phase += fullcycles * sum;
 165                 while (phase < 0.0d) {
 166                     if (--sidx < 0) {
 167                         sidx = dash.length - 1;
 168                     }
 169                     phase += dash[sidx];
 170                     dashOn = !dashOn;
 171                 }
 172             }
 173         } else if (phase > 0.0d) {
 174             if (cycles >= MAX_CYCLES) {


 183                 while (phase >= (d = dash[sidx])) {
 184                     phase -= d;
 185                     sidx = (sidx + 1) % dash.length;
 186                     dashOn = !dashOn;
 187                 }
 188             }
 189         }
 190 
 191         this.dash = dash;
 192         this.dashLen = dashLen;
 193         this.phase = phase;
 194         this.startPhase = phase;
 195         this.startDashOn = dashOn;
 196         this.startIdx = sidx;
 197         this.starting = true;
 198         this.needsMoveTo = false;
 199         this.firstSegidx = 0;
 200 
 201         this.recycleDashes = recycleDashes;
 202 
 203         if (rdrCtx.doClip) {
 204             this.clipRect = rdrCtx.clipRect;
 205         } else {
 206             this.clipRect = null;
 207             this.cOutCode = 0;
 208         }
 209         return this; // fluent API
 210     }
 211 
 212     /**
 213      * Disposes this dasher:
 214      * clean up before reusing this instance
 215      */
 216     void dispose() {
 217         if (DO_CLEAN_DIRTY) {
 218             // Force zero-fill dirty arrays:
 219             Arrays.fill(curCurvepts, 0.0d);
 220         }
 221         // Return arrays:
 222         if (recycleDashes) {
 223             dash = dashes_ref.putArray(dash);
 224         }
 225         firstSegmentsBuffer = firstSegmentsBuffer_ref.putArray(firstSegmentsBuffer);
 226     }
 227 
 228     double[] copyDashArray(final float[] dashes) {
 229         final int len = dashes.length;
 230         final double[] newDashes;
 231         if (len <= MarlinConst.INITIAL_ARRAY) {
 232             newDashes = dashes_ref.initial;
 233         } else {
 234             if (DO_STATS) {
 235                 rdrCtx.stats.stat_array_dasher_dasher.add(len);
 236             }
 237             newDashes = dashes_ref.getArray(len);
 238         }
 239         for (int i = 0; i < len; i++) { newDashes[i] = dashes[i]; }
 240         return newDashes;
 241     }
 242 
 243     @Override
 244     public void moveTo(final double x0, final double y0) {
 245         if (firstSegidx != 0) {
 246             out.moveTo(sx0, sy0);
 247             emitFirstSegments();
 248         }
 249         this.needsMoveTo = true;
 250         this.idx = startIdx;
 251         this.dashOn = this.startDashOn;
 252         this.phase = this.startPhase;
 253         this.cx0 = x0;
 254         this.cy0 = y0;
 255 
 256         // update starting point:
 257         this.sx0 = x0;
 258         this.sy0 = y0;
 259         this.starting = true;
 260 
 261         if (clipRect != null) {
 262             final int outcode = DHelpers.outcode(x0, y0, clipRect);
 263             this.cOutCode = outcode;
 264             this.outside = false;
 265             this.totalSkipLen = 0.0d;
 266         }
 267     }
 268 
 269     private void emitSeg(double[] buf, int off, int type) {
 270         switch (type) {
 271         case 8:
 272             out.curveTo(buf[off    ], buf[off + 1],
 273                         buf[off + 2], buf[off + 3],
 274                         buf[off + 4], buf[off + 5]);
 275             return;
 276         case 6:
 277             out.quadTo(buf[off    ], buf[off + 1],
 278                        buf[off + 2], buf[off + 3]);
 279             return;
 280         case 4:
 281             out.lineTo(buf[off], buf[off + 1]);
 282             return;
 283         default:
 284         }
 285     }
 286 
 287     private void emitFirstSegments() {
 288         final double[] fSegBuf = firstSegmentsBuffer;
 289 
 290         for (int i = 0, len = firstSegidx; i < len; ) {
 291             int type = (int)fSegBuf[i];
 292             emitSeg(fSegBuf, i + 1, type);
 293             i += (type - 1);
 294         }
 295         firstSegidx = 0;
 296     }






 297 
 298     // precondition: pts must be in relative coordinates (relative to x0,y0)
 299     private void goTo(final double[] pts, final int off, final int type,
 300                       final boolean on)
 301     {
 302         final int index = off + type;
 303         final double x = pts[index - 4];
 304         final double y = pts[index - 3];
 305 
 306         if (on) {
 307             if (starting) {
 308                 goTo_starting(pts, off, type);
 309             } else {
 310                 if (needsMoveTo) {
 311                     needsMoveTo = false;
 312                     out.moveTo(cx0, cy0);
 313                 }
 314                 emitSeg(pts, off, type);
 315             }
 316         } else {
 317             if (starting) {
 318                 // low probability test (hotspot)
 319                 starting = false;
 320             }
 321             needsMoveTo = true;
 322         }
 323         this.cx0 = x;
 324         this.cy0 = y;
 325     }
 326 
 327     private void goTo_starting(final double[] pts, final int off, final int type) {
 328         int len = type - 1; // - 2 + 1
 329         int segIdx = firstSegidx;
 330         double[] buf = firstSegmentsBuffer;
 331 
 332         if (segIdx + len  > buf.length) {
 333             if (DO_STATS) {
 334                 rdrCtx.stats.stat_array_dasher_firstSegmentsBuffer
 335                     .add(segIdx + len);
 336             }
 337             firstSegmentsBuffer = buf
 338                 = firstSegmentsBuffer_ref.widenArray(buf, segIdx,
 339                                                      segIdx + len);
 340         }
 341         buf[segIdx++] = type;
 342         len--;
 343         // small arraycopy (2, 4 or 6) but with offset:
 344         System.arraycopy(pts, off, buf, segIdx, len);
 345         firstSegidx = segIdx + len;
 346     }
 347 
 348     @Override
 349     public void lineTo(final double x1, final double y1) {
 350         final int outcode0 = this.cOutCode;
 351 
 352         if (clipRect != null) {
 353             final int outcode1 = DHelpers.outcode(x1, y1, clipRect);
 354 
 355             // Should clip
 356             final int orCode = (outcode0 | outcode1);
 357 
 358             if (orCode != 0) {
 359                 final int sideCode = outcode0 & outcode1;
 360 
 361                 // basic rejection criteria:
 362                 if (sideCode == 0) {
 363                     // ovelap clip:
 364                     if (subdivide) {
 365                         // avoid reentrance
 366                         subdivide = false;
 367                         // subdivide curve => callback with subdivided parts:
 368                         boolean ret = curveSplitter.splitLine(cx0, cy0, x1, y1,
 369                                                               orCode, this);
 370                         // reentrance is done:
 371                         subdivide = true;
 372                         if (ret) {
 373                             return;
 374                         }
 375                     }
 376                     // already subdivided so render it
 377                 } else {
 378                     this.cOutCode = outcode1;
 379                     skipLineTo(x1, y1);
 380                     return;
 381                 }
 382             }
 383 
 384             this.cOutCode = outcode1;
 385 
 386             if (this.outside) {
 387                 this.outside = false;
 388                 // Adjust current index, phase & dash:
 389                 skipLen();
 390             }
 391         }
 392         _lineTo(x1, y1);
 393     }
 394 
 395     private void _lineTo(final double x1, final double y1) {
 396         final double dx = x1 - cx0;
 397         final double dy = y1 - cy0;
 398 
 399         double len = dx * dx + dy * dy;
 400         if (len == 0.0d) {
 401             return;
 402         }
 403         len = Math.sqrt(len);
 404 
 405         // The scaling factors needed to get the dx and dy of the
 406         // transformed dash segments.
 407         final double cx = dx / len;
 408         final double cy = dy / len;
 409 
 410         final double[] _curCurvepts = curCurvepts;
 411         final double[] _dash = dash;
 412         final int _dashLen = this.dashLen;
 413 
 414         int _idx = idx;
 415         boolean _dashOn = dashOn;
 416         double _phase = phase;
 417 
 418         double leftInThisDashSegment, d;

 419 
 420         while (true) {
 421             d = _dash[_idx];
 422             leftInThisDashSegment = d - _phase;
 423 
 424             if (len <= leftInThisDashSegment) {
 425                 _curCurvepts[0] = x1;
 426                 _curCurvepts[1] = y1;
 427 
 428                 goTo(_curCurvepts, 0, 4, _dashOn);
 429 
 430                 // Advance phase within current dash segment
 431                 _phase += len;
 432 
 433                 // TODO: compare double values using epsilon:
 434                 if (len == leftInThisDashSegment) {
 435                     _phase = 0.0d;
 436                     _idx = (_idx + 1) % _dashLen;
 437                     _dashOn = !_dashOn;
 438                 }
 439                 break;





 440             }
 441 



 442             if (_phase == 0.0d) {
 443                 _curCurvepts[0] = cx0 + d * cx;
 444                 _curCurvepts[1] = cy0 + d * cy;
 445             } else {
 446                 _curCurvepts[0] = cx0 + leftInThisDashSegment * cx;
 447                 _curCurvepts[1] = cy0 + leftInThisDashSegment * cy;

 448             }
 449 
 450             goTo(_curCurvepts, 0, 4, _dashOn);
 451 
 452             len -= leftInThisDashSegment;
 453             // Advance to next dash segment
 454             _idx = (_idx + 1) % _dashLen;
 455             _dashOn = !_dashOn;
 456             _phase = 0.0d;
 457         }
 458         // Save local state:
 459         idx = _idx;
 460         dashOn = _dashOn;
 461         phase = _phase;
 462     }
 463 
 464     private void skipLineTo(final double x1, final double y1) {
 465         final double dx = x1 - cx0;
 466         final double dy = y1 - cy0;
 467 
 468         double len = dx * dx + dy * dy;
 469         if (len != 0.0d) {
 470             len = Math.sqrt(len);
 471         }
 472 
 473         // Accumulate skipped length:
 474         this.outside = true;
 475         this.totalSkipLen += len;
 476 
 477         // Fix initial move:
 478         this.needsMoveTo = true;
 479         this.starting = false;
 480 
 481         this.cx0 = x1;
 482         this.cy0 = y1;
 483     }
 484 
 485     public void skipLen() {
 486         double len = this.totalSkipLen;
 487         this.totalSkipLen = 0.0d;
 488 
 489         final double[] _dash = dash;
 490         final int _dashLen = this.dashLen;
 491 
 492         int _idx = idx;
 493         boolean _dashOn = dashOn;
 494         double _phase = phase;
 495 
 496         // -2 to ensure having 2 iterations of the post-loop
 497         // to compensate the remaining phase
 498         final long fullcycles = (long)Math.floor(len / cycleLen) - 2L;
 499 
 500         if (fullcycles > 0L) {
 501             len -= cycleLen * fullcycles;
 502 
 503             final long iterations = fullcycles * _dashLen;
 504             _idx = (int) (iterations + _idx) % _dashLen;
 505             _dashOn = (iterations + (_dashOn ? 1L : 0L) & 1L) == 1L;
 506         }
 507 
 508         double leftInThisDashSegment, d;
 509 
 510         while (true) {
 511             d = _dash[_idx];
 512             leftInThisDashSegment = d - _phase;
 513 
 514             if (len <= leftInThisDashSegment) {
 515                 // Advance phase within current dash segment
 516                 _phase += len;
 517 
 518                 // TODO: compare double values using epsilon:
 519                 if (len == leftInThisDashSegment) {
 520                     _phase = 0.0d;
 521                     _idx = (_idx + 1) % _dashLen;
 522                     _dashOn = !_dashOn;
 523                 }
 524                 break;
 525             }
 526 
 527             len -= leftInThisDashSegment;
 528             // Advance to next dash segment
 529             _idx = (_idx + 1) % _dashLen;
 530             _dashOn = !_dashOn;
 531             _phase = 0.0d;
 532         }
 533         // Save local state:
 534         idx = _idx;
 535         dashOn = _dashOn;
 536         phase = _phase;
 537     }
 538 
 539     // preconditions: curCurvepts must be an array of length at least 2 * type,
 540     // that contains the curve we want to dash in the first type elements
 541     private void somethingTo(final int type) {
 542         final double[] _curCurvepts = curCurvepts;
 543         if (pointCurve(_curCurvepts, type)) {
 544             return;
 545         }
 546         final LengthIterator _li = li;

 547         final double[] _dash = dash;
 548         final int _dashLen = this.dashLen;
 549 
 550         _li.initializeIterationOnCurve(_curCurvepts, type);
 551 
 552         int _idx = idx;
 553         boolean _dashOn = dashOn;
 554         double _phase = phase;
 555 
 556         // initially the current curve is at curCurvepts[0...type]
 557         int curCurveoff = 0;
 558         double prevT = 0.0d;
 559         double t;
 560         double leftInThisDashSegment = _dash[_idx] - _phase;
 561 
 562         while ((t = _li.next(leftInThisDashSegment)) < 1.0d) {
 563             if (t != 0.0d) {
 564                 DHelpers.subdivideAt((t - prevT) / (1.0d - prevT),
 565                                     _curCurvepts, curCurveoff,
 566                                     _curCurvepts, 0, type);
 567                 prevT = t;

 568                 goTo(_curCurvepts, 2, type, _dashOn);
 569                 curCurveoff = type;
 570             }
 571             // Advance to next dash segment
 572             _idx = (_idx + 1) % _dashLen;
 573             _dashOn = !_dashOn;
 574             _phase = 0.0d;
 575             leftInThisDashSegment = _dash[_idx];
 576         }
 577 
 578         goTo(_curCurvepts, curCurveoff + 2, type, _dashOn);
 579 
 580         _phase += _li.lastSegLen();
 581         if (_phase >= _dash[_idx]) {
 582             _phase = 0.0d;
 583             _idx = (_idx + 1) % _dashLen;
 584             _dashOn = !_dashOn;
 585         }
 586         // Save local state:
 587         idx = _idx;
 588         dashOn = _dashOn;
 589         phase = _phase;
 590 
 591         // reset LengthIterator:
 592         _li.reset();
 593     }
 594 
 595     private void skipSomethingTo(final int type) {
 596         final double[] _curCurvepts = curCurvepts;
 597         if (pointCurve(_curCurvepts, type)) {
 598             return;
 599         }
 600         final LengthIterator _li = li;
 601 
 602         _li.initializeIterationOnCurve(_curCurvepts, type);
 603 
 604         // In contrary to somethingTo(),
 605         // just estimate properly the curve length:
 606         final double len = _li.totalLength();
 607 
 608         // Accumulate skipped length:
 609         this.outside = true;
 610         this.totalSkipLen += len;
 611 
 612         // Fix initial move:
 613         this.needsMoveTo = true;
 614         this.starting = false;
 615     }
 616 
 617     private static boolean pointCurve(final double[] curve, final int type) {
 618         for (int i = 2; i < type; i++) {
 619             if (curve[i] != curve[i-2]) {
 620                 return false;
 621             }
 622         }
 623         return true;
 624     }
 625 
 626     // Objects of this class are used to iterate through curves. They return
 627     // t values where the left side of the curve has a specified length.
 628     // It does this by subdividing the input curve until a certain error
 629     // condition has been met. A recursive subdivision procedure would
 630     // return as many as 1<<limit curves, but this is an iterator and we
 631     // don't need all the curves all at once, so what we carry out a
 632     // lazy inorder traversal of the recursion tree (meaning we only move
 633     // through the tree when we need the next subdivided curve). This saves
 634     // us a lot of memory because at any one time we only need to store
 635     // limit+1 curves - one for each level of the tree + 1.
 636     // NOTE: the way we do things here is not enough to traverse a general
 637     // tree; however, the trees we are interested in have the property that
 638     // every non leaf node has exactly 2 children
 639     static final class LengthIterator {

 640         // Holds the curves at various levels of the recursion. The root
 641         // (i.e. the original curve) is at recCurveStack[0] (but then it
 642         // gets subdivided, the left half is put at 1, so most of the time
 643         // only the right half of the original curve is at 0)
 644         private final double[][] recCurveStack; // dirty
 645         // sidesRight[i] indicates whether the node at level i+1 in the path from
 646         // the root to the current leaf is a left or right child of its parent.
 647         private final boolean[] sidesRight; // dirty
 648         private int curveType;
 649         // lastT and nextT delimit the current leaf.
 650         private double nextT;
 651         private double lenAtNextT;
 652         private double lastT;
 653         private double lenAtLastT;
 654         private double lenAtLastSplit;
 655         private double lastSegLen;
 656         // the current level in the recursion tree. 0 is the root. limit
 657         // is the deepest possible leaf.
 658         private int recLevel;
 659         private boolean done;
 660 
 661         // the lengths of the lines of the control polygon. Only its first
 662         // curveType/2 - 1 elements are valid. This is an optimization. See
 663         // next() for more detail.
 664         private final double[] curLeafCtrlPolyLengths = new double[3];
 665 
 666         LengthIterator() {
 667             this.recCurveStack = new double[REC_LIMIT + 1][8];
 668             this.sidesRight = new boolean[REC_LIMIT];
 669             // if any methods are called without first initializing this object
 670             // on a curve, we want it to fail ASAP.
 671             this.nextT = Double.MAX_VALUE;
 672             this.lenAtNextT = Double.MAX_VALUE;
 673             this.lenAtLastSplit = Double.MIN_VALUE;
 674             this.recLevel = Integer.MIN_VALUE;
 675             this.lastSegLen = Double.MAX_VALUE;
 676             this.done = true;
 677         }
 678 
 679         /**
 680          * Reset this LengthIterator.
 681          */
 682         void reset() {
 683             // keep data dirty
 684             // as it appears not useful to reset data:
 685             if (DO_CLEAN_DIRTY) {
 686                 final int recLimit = recCurveStack.length - 1;
 687                 for (int i = recLimit; i >= 0; i--) {
 688                     Arrays.fill(recCurveStack[i], 0.0d);
 689                 }
 690                 Arrays.fill(sidesRight, false);
 691                 Arrays.fill(curLeafCtrlPolyLengths, 0.0d);
 692                 Arrays.fill(nextRoots, 0.0d);
 693                 Arrays.fill(flatLeafCoefCache, 0.0d);
 694                 flatLeafCoefCache[2] = -1.0d;
 695             }
 696         }
 697 
 698         void initializeIterationOnCurve(final double[] pts, final int type) {
 699             // optimize arraycopy (8 values faster than 6 = type):
 700             System.arraycopy(pts, 0, recCurveStack[0], 0, 8);
 701             this.curveType = type;
 702             this.recLevel = 0;
 703             this.lastT = 0.0d;
 704             this.lenAtLastT = 0.0d;
 705             this.nextT = 0.0d;
 706             this.lenAtNextT = 0.0d;
 707             goLeft(); // initializes nextT and lenAtNextT properly
 708             this.lenAtLastSplit = 0.0d;
 709             if (recLevel > 0) {
 710                 this.sidesRight[0] = false;
 711                 this.done = false;
 712             } else {
 713                 // the root of the tree is a leaf so we're done.
 714                 this.sidesRight[0] = true;
 715                 this.done = true;
 716             }
 717             this.lastSegLen = 0.0d;
 718         }
 719 
 720         // 0 == false, 1 == true, -1 == invalid cached value.
 721         private int cachedHaveLowAcceleration = -1;
 722 
 723         private boolean haveLowAcceleration(final double err) {
 724             if (cachedHaveLowAcceleration == -1) {
 725                 final double len1 = curLeafCtrlPolyLengths[0];
 726                 final double len2 = curLeafCtrlPolyLengths[1];
 727                 // the test below is equivalent to !within(len1/len2, 1, err).
 728                 // It is using a multiplication instead of a division, so it
 729                 // should be a bit faster.
 730                 if (!DHelpers.within(len1, len2, err * len2)) {
 731                     cachedHaveLowAcceleration = 0;
 732                     return false;
 733                 }
 734                 if (curveType == 8) {
 735                     final double len3 = curLeafCtrlPolyLengths[2];
 736                     // if len1 is close to 2 and 2 is close to 3, that probably
 737                     // means 1 is close to 3 so the second part of this test might
 738                     // not be needed, but it doesn't hurt to include it.
 739                     final double errLen3 = err * len3;
 740                     if (!(DHelpers.within(len2, len3, errLen3) &&
 741                           DHelpers.within(len1, len3, errLen3))) {
 742                         cachedHaveLowAcceleration = 0;
 743                         return false;


 770                     lastSegLen = lenAtNextT - lenAtLastSplit;
 771                     return 1.0d;
 772                 }
 773                 goToNextLeaf();
 774             }
 775             lenAtLastSplit = targetLength;
 776             final double leaflen = lenAtNextT - lenAtLastT;
 777             double t = (targetLength - lenAtLastT) / leaflen;
 778 
 779             // cubicRootsInAB is a fairly expensive call, so we just don't do it
 780             // if the acceleration in this section of the curve is small enough.
 781             if (!haveLowAcceleration(0.05d)) {
 782                 // We flatten the current leaf along the x axis, so that we're
 783                 // left with a, b, c which define a 1D Bezier curve. We then
 784                 // solve this to get the parameter of the original leaf that
 785                 // gives us the desired length.
 786                 final double[] _flatLeafCoefCache = flatLeafCoefCache;
 787 
 788                 if (_flatLeafCoefCache[2] < 0.0d) {
 789                     double x =     curLeafCtrlPolyLengths[0],
 790                            y = x + curLeafCtrlPolyLengths[1];
 791                     if (curveType == 8) {
 792                         double z = y + curLeafCtrlPolyLengths[2];
 793                         _flatLeafCoefCache[0] = 3.0d * (x - y) + z;
 794                         _flatLeafCoefCache[1] = 3.0d * (y - 2.0d * x);
 795                         _flatLeafCoefCache[2] = 3.0d * x;
 796                         _flatLeafCoefCache[3] = -z;
 797                     } else if (curveType == 6) {
 798                         _flatLeafCoefCache[0] = 0.0d;
 799                         _flatLeafCoefCache[1] = y - 2.0d * x;
 800                         _flatLeafCoefCache[2] = 2.0d * x;
 801                         _flatLeafCoefCache[3] = -y;
 802                     }
 803                 }
 804                 double a = _flatLeafCoefCache[0];
 805                 double b = _flatLeafCoefCache[1];
 806                 double c = _flatLeafCoefCache[2];
 807                 double d = t * _flatLeafCoefCache[3];
 808 
 809                 // we use cubicRootsInAB here, because we want only roots in 0, 1,
 810                 // and our quadratic root finder doesn't filter, so it's just a
 811                 // matter of convenience.
 812                 final int n = DHelpers.cubicRootsInAB(a, b, c, d, nextRoots, 0, 0.0d, 1.0d);
 813 // TODO: check NaN is impossible
 814                 if (n == 1 && !Double.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.0d) {
 822                 t = 1.0d;
 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         double totalLength() {
 835             while (!done) {
 836                 goToNextLeaf();
 837             }
 838             // reset LengthIterator:
 839             reset();
 840 
 841             return lenAtNextT;
 842         }
 843 
 844         double 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 double len = onLeaf();
 877             if (len >= 0.0d) {
 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.0d;
 884                 cachedHaveLowAcceleration = -1;
 885             } else {
 886                 DHelpers.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 double onLeaf() {
 899             final double[] curve = recCurveStack[recLevel];
 900             final int _curveType = curveType;
 901             double polyLen = 0.0d;
 902 
 903             double x0 = curve[0], y0 = curve[1];
 904             for (int i = 2; i < _curveType; i += 2) {
 905                 final double x1 = curve[i], y1 = curve[i + 1];
 906                 final double len = DHelpers.linelen(x0, y0, x1, y1);
 907                 polyLen += len;
 908                 curLeafCtrlPolyLengths[(i >> 1) - 1] = len;
 909                 x0 = x1;
 910                 y0 = y1;
 911             }
 912 
 913             final double lineLen = DHelpers.linelen(curve[0], curve[1], x0, y0);
 914 
 915             if ((polyLen - lineLen) < CURVE_LEN_ERR || recLevel == REC_LIMIT) {

 916                 return (polyLen + lineLen) / 2.0d;
 917             }
 918             return -1.0d;
 919         }
 920     }
 921 
 922     @Override
 923     public void curveTo(final double x1, final double y1,
 924                         final double x2, final double y2,
 925                         final double x3, final double y3)
 926     {
 927         final int outcode0 = this.cOutCode;
 928 
 929         if (clipRect != null) {
 930             final int outcode1 = DHelpers.outcode(x1, y1, clipRect);
 931             final int outcode2 = DHelpers.outcode(x2, y2, clipRect);
 932             final int outcode3 = DHelpers.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                     // ovelap 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 double x1, final double y1,
 974                           final double x2, final double y2,
 975                           final double x3, final double y3)
 976     {
 977         final double[] _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 double[] 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 double x1, final double y1,
 995                              final double x2, final double y2,
 996                              final double x3, final double y3)
 997     {
 998         final double[] _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 double x1, final double y1,
1012                        final double x2, final double y2)
1013     {
1014         final int outcode0 = this.cOutCode;
1015 
1016         if (clipRect != null) {
1017             final int outcode1 = DHelpers.outcode(x1, y1, clipRect);
1018             final int outcode2 = DHelpers.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                     // ovelap 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 double x1, final double y1,
1060                          final double x2, final double y2)
1061     {
1062         final double[] _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 double[] 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 double x1, final double y1,
1080                             final double x2, final double y2)
1081     {
1082         final double[] _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("DDasher does not use a native consumer");
1122     }
1123 }
1124 
< prev index next >