1 /*
   2  * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.marlin;
  27 
  28 import static com.sun.marlin.OffHeapArray.SIZE_INT;
  29 import sun.misc.Unsafe;
  30 
  31 public final class DRenderer implements DMarlinRenderer, MarlinConst {
  32 
  33     static final boolean DISABLE_RENDER = false;
  34 
  35     private static final int ALL_BUT_LSB = 0xFFFFFFFE;
  36     private static final int ERR_STEP_MAX = 0x7FFFFFFF; // = 2^31 - 1
  37 
  38     private static final double POWER_2_TO_32 = 0x1.0p32d;
  39 
  40     // use double to make tosubpix methods faster (no int to double conversion)
  41     static final double SUBPIXEL_SCALE_X = SUBPIXEL_POSITIONS_X;
  42     static final double SUBPIXEL_SCALE_Y = SUBPIXEL_POSITIONS_Y;
  43     static final int SUBPIXEL_MASK_X = SUBPIXEL_POSITIONS_X - 1;
  44     static final int SUBPIXEL_MASK_Y = SUBPIXEL_POSITIONS_Y - 1;
  45 
  46     private static final double RDR_OFFSET_X = 0.5d / SUBPIXEL_SCALE_X;
  47     private static final double RDR_OFFSET_Y = 0.5d / SUBPIXEL_SCALE_Y;
  48 
  49     // common to all types of input path segments.
  50     // OFFSET as bytes
  51     // only integer values:
  52     public static final long OFF_CURX_OR  = 0;
  53     public static final long OFF_ERROR    = OFF_CURX_OR  + SIZE_INT;
  54     public static final long OFF_BUMP_X   = OFF_ERROR    + SIZE_INT;
  55     public static final long OFF_BUMP_ERR = OFF_BUMP_X   + SIZE_INT;
  56     public static final long OFF_NEXT     = OFF_BUMP_ERR + SIZE_INT;
  57     public static final long OFF_YMAX     = OFF_NEXT     + SIZE_INT;
  58 
  59     // size of one edge in bytes
  60     public static final int SIZEOF_EDGE_BYTES = (int)(OFF_YMAX + SIZE_INT);
  61 
  62     // curve break into lines
  63     // cubic error in subpixels to decrement step
  64     private static final double CUB_DEC_ERR_SUBPIX
  65         = MarlinProperties.getCubicDecD2() * (SUBPIXEL_POSITIONS_X / 8.0d); // 1.0 / 8th pixel
  66     // cubic error in subpixels to increment step
  67     private static final double CUB_INC_ERR_SUBPIX
  68         = MarlinProperties.getCubicIncD1() * (SUBPIXEL_POSITIONS_X / 8.0d); // 0.4 / 8th pixel
  69     // scale factor for Y-axis contribution to quad / cubic errors:
  70     public static final double SCALE_DY = ((double) SUBPIXEL_POSITIONS_X) / SUBPIXEL_POSITIONS_Y;
  71 
  72     // TestNonAARasterization (JDK-8170879): cubics
  73     // bad paths (59294/100000 == 59,29%, 94335 bad pixels (avg = 1,59), 3966 warnings (avg = 0,07)
  74 // 2018
  75     // 1.0 / 0.2: bad paths (67194/100000 == 67,19%, 117394 bad pixels (avg = 1,75 - max =  9), 4042 warnings (avg = 0,06)
  76 
  77     // cubic bind length to decrement step
  78     public static final double CUB_DEC_BND
  79         = 8.0d * CUB_DEC_ERR_SUBPIX;
  80     // cubic bind length to increment step
  81     public static final double CUB_INC_BND
  82         = 8.0d * CUB_INC_ERR_SUBPIX;
  83 
  84     // cubic countlg
  85     public static final int CUB_COUNT_LG = 2;
  86     // cubic count = 2^countlg
  87     private static final int CUB_COUNT = 1 << CUB_COUNT_LG;
  88     // cubic count^2 = 4^countlg
  89     private static final int CUB_COUNT_2 = 1 << (2 * CUB_COUNT_LG);
  90     // cubic count^3 = 8^countlg
  91     private static final int CUB_COUNT_3 = 1 << (3 * CUB_COUNT_LG);
  92     // cubic dt = 1 / count
  93     private static final double CUB_INV_COUNT = 1.0d / CUB_COUNT;
  94     // cubic dt^2 = 1 / count^2 = 1 / 4^countlg
  95     private static final double CUB_INV_COUNT_2 = 1.0d / CUB_COUNT_2;
  96     // cubic dt^3 = 1 / count^3 = 1 / 8^countlg
  97     private static final double CUB_INV_COUNT_3 = 1.0d / CUB_COUNT_3;
  98 
  99     // quad break into lines
 100     // quadratic error in subpixels
 101     private static final double QUAD_DEC_ERR_SUBPIX
 102         = MarlinProperties.getQuadDecD2() * (SUBPIXEL_POSITIONS_X / 8.0d); // 0.5 / 8th pixel
 103 
 104     // TestNonAARasterization (JDK-8170879): quads
 105     // bad paths (62916/100000 == 62,92%, 103818 bad pixels (avg = 1,65), 6514 warnings (avg = 0,10)
 106 // 2018
 107     // 0.50px  = bad paths (62915/100000 == 62,92%, 103810 bad pixels (avg = 1,65), 6512 warnings (avg = 0,10)
 108 
 109     // quadratic bind length to decrement step
 110     public static final double QUAD_DEC_BND
 111         = 8.0d * QUAD_DEC_ERR_SUBPIX;
 112 
 113 //////////////////////////////////////////////////////////////////////////////
 114 //  SCAN LINE
 115 //////////////////////////////////////////////////////////////////////////////
 116     // crossings ie subpixel edge x coordinates
 117     private int[] crossings;
 118     // auxiliary storage for crossings (merge sort)
 119     private int[] aux_crossings;
 120 
 121     // indices into the segment pointer lists. They indicate the "active"
 122     // sublist in the segment lists (the portion of the list that contains
 123     // all the segments that cross the next scan line).
 124     private int edgeCount;
 125     private int[] edgePtrs;
 126     // auxiliary storage for edge pointers (merge sort)
 127     private int[] aux_edgePtrs;
 128 
 129     // max used for both edgePtrs and crossings (stats only)
 130     private int activeEdgeMaxUsed;
 131 
 132     // crossings ref (dirty)
 133     private final IntArrayCache.Reference crossings_ref;
 134     // edgePtrs ref (dirty)
 135     private final IntArrayCache.Reference edgePtrs_ref;
 136     // merge sort initial arrays (large enough to satisfy most usages) (1024)
 137     // aux_crossings ref (dirty)
 138     private final IntArrayCache.Reference aux_crossings_ref;
 139     // aux_edgePtrs ref (dirty)
 140     private final IntArrayCache.Reference aux_edgePtrs_ref;
 141 
 142 //////////////////////////////////////////////////////////////////////////////
 143 //  EDGE LIST
 144 //////////////////////////////////////////////////////////////////////////////
 145     private int edgeMinY = Integer.MAX_VALUE;
 146     private int edgeMaxY = Integer.MIN_VALUE;
 147     private double edgeMinX = Double.POSITIVE_INFINITY;
 148     private double edgeMaxX = Double.NEGATIVE_INFINITY;
 149 
 150     // edges [ints] stored in off-heap memory
 151     private final OffHeapArray edges;
 152 
 153     private int[] edgeBuckets;
 154     private int[] edgeBucketCounts; // 2*newedges + (1 if pruning needed)
 155     // used range for edgeBuckets / edgeBucketCounts
 156     private int buckets_minY;
 157     private int buckets_maxY;
 158 
 159     // edgeBuckets ref (clean)
 160     private final IntArrayCache.Reference edgeBuckets_ref;
 161     // edgeBucketCounts ref (clean)
 162     private final IntArrayCache.Reference edgeBucketCounts_ref;
 163 
 164     boolean useRLE = false;
 165 
 166     // Flattens using adaptive forward differencing. This only carries out
 167     // one iteration of the AFD loop. All it does is update AFD variables (i.e.
 168     // X0, Y0, D*[X|Y], COUNT; not variables used for computing scanline crossings).
 169     private void quadBreakIntoLinesAndAdd(double x0, double y0,
 170                                           final DCurve c,
 171                                           final double x2, final double y2)
 172     {
 173         int count = 1; // dt = 1 / count
 174 
 175         // maximum(ddX|Y) = norm(dbx, dby) * dt^2 (= 1)
 176         double maxDD = Math.abs(c.dbx) + Math.abs(c.dby) * SCALE_DY;
 177 
 178         final double _DEC_BND = QUAD_DEC_BND;
 179 
 180         while (maxDD >= _DEC_BND) {
 181             // divide step by half:
 182             maxDD /= 4.0d; // error divided by 2^2 = 4
 183 
 184             count <<= 1;
 185             if (DO_STATS) {
 186                 rdrCtx.stats.stat_rdr_quadBreak_dec.add(count);
 187             }
 188         }
 189 
 190         final int nL = count; // line count
 191 
 192         if (count > 1) {
 193             final double icount = 1.0d / count; // dt
 194             final double icount2 = icount * icount; // dt^2
 195 
 196             final double ddx = c.dbx * icount2;
 197             final double ddy = c.dby * icount2;
 198             double dx = c.bx * icount2 + c.cx * icount;
 199             double dy = c.by * icount2 + c.cy * icount;
 200 
 201             // we use x0, y0 to walk the line
 202             for (double x1 = x0, y1 = y0; --count > 0; dx += ddx, dy += ddy) {
 203                 x1 += dx;
 204                 y1 += dy;
 205 
 206                 addLine(x0, y0, x1, y1);
 207                 x0 = x1;
 208                 y0 = y1;
 209             }
 210         }
 211         addLine(x0, y0, x2, y2);
 212 
 213         if (DO_STATS) {
 214             rdrCtx.stats.stat_rdr_quadBreak.add(nL);
 215         }
 216     }
 217 
 218     // x0, y0 and x3,y3 are the endpoints of the curve. We could compute these
 219     // using c.xat(0),c.yat(0) and c.xat(1),c.yat(1), but this might introduce
 220     // numerical errors, and our callers already have the exact values.
 221     // Another alternative would be to pass all the control points, and call
 222     // c.set here, but then too many numbers are passed around.
 223     private void curveBreakIntoLinesAndAdd(double x0, double y0,
 224                                            final DCurve c,
 225                                            final double x3, final double y3)
 226     {
 227         int count            = CUB_COUNT;
 228         final double icount  = CUB_INV_COUNT;   // dt
 229         final double icount2 = CUB_INV_COUNT_2; // dt^2
 230         final double icount3 = CUB_INV_COUNT_3; // dt^3
 231 
 232         // the dx and dy refer to forward differencing variables, not the last
 233         // coefficients of the "points" polynomial
 234         double dddx, dddy, ddx, ddy, dx, dy;
 235         dddx = 2.0d * c.dax * icount3;
 236         dddy = 2.0d * c.day * icount3;
 237         ddx = dddx + c.dbx * icount2;
 238         ddy = dddy + c.dby * icount2;
 239         dx = c.ax * icount3 + c.bx * icount2 + c.cx * icount;
 240         dy = c.ay * icount3 + c.by * icount2 + c.cy * icount;
 241 
 242         int nL = 0; // line count
 243 
 244         final double _DEC_BND = CUB_DEC_BND;
 245         final double _INC_BND = CUB_INC_BND;
 246         final double _SCALE_DY = SCALE_DY;
 247 
 248         // we use x0, y0 to walk the line
 249         for (double x1 = x0, y1 = y0; count > 0; ) {
 250             // inc / dec => ratio ~ 5 to minimize upscale / downscale but minimize edges
 251 
 252             // double step:
 253             // can only do this on even "count" values, because we must divide count by 2
 254             while ((count % 2 == 0)
 255                     && ((Math.abs(ddx) + Math.abs(ddy) * _SCALE_DY) <= _INC_BND)) {
 256                 dx = 2.0d * dx + ddx;
 257                 dy = 2.0d * dy + ddy;
 258                 ddx = 4.0d * (ddx + dddx);
 259                 ddy = 4.0d * (ddy + dddy);
 260                 dddx *= 8.0d;
 261                 dddy *= 8.0d;
 262 
 263                 count >>= 1;
 264                 if (DO_STATS) {
 265                     rdrCtx.stats.stat_rdr_curveBreak_inc.add(count);
 266                 }
 267             }
 268 
 269             // divide step by half:
 270             while ((Math.abs(ddx) + Math.abs(ddy) * _SCALE_DY) >= _DEC_BND) {
 271                 dddx /= 8.0d;
 272                 dddy /= 8.0d;
 273                 ddx = ddx / 4.0d - dddx;
 274                 ddy = ddy / 4.0d - dddy;
 275                 dx = (dx - ddx) / 2.0d;
 276                 dy = (dy - ddy) / 2.0d;
 277 
 278                 count <<= 1;
 279                 if (DO_STATS) {
 280                     rdrCtx.stats.stat_rdr_curveBreak_dec.add(count);
 281                 }
 282             }
 283             if (--count == 0) {
 284                 break;
 285             }
 286 
 287             x1 += dx;
 288             y1 += dy;
 289             dx += ddx;
 290             dy += ddy;
 291             ddx += dddx;
 292             ddy += dddy;
 293 
 294             addLine(x0, y0, x1, y1);
 295             x0 = x1;
 296             y0 = y1;
 297         }
 298         addLine(x0, y0, x3, y3);
 299 
 300         if (DO_STATS) {
 301             rdrCtx.stats.stat_rdr_curveBreak.add(nL + 1);
 302         }
 303     }
 304 
 305     private void addLine(double x1, double y1, double x2, double y2) {
 306         if (DO_MONITORS) {
 307             rdrCtx.stats.mon_rdr_addLine.start();
 308         }
 309         if (DO_STATS) {
 310             rdrCtx.stats.stat_rdr_addLine.add(1);
 311         }
 312         int or = 1; // orientation of the line. 1 if y increases, 0 otherwise.
 313         if (y2 < y1) {
 314             or = 0;
 315             double tmp = y2;
 316             y2 = y1;
 317             y1 = tmp;
 318             tmp = x2;
 319             x2 = x1;
 320             x1 = tmp;
 321         }
 322 
 323         // convert subpixel coordinates [double] into pixel positions [int]
 324 
 325         // The index of the pixel that holds the next HPC is at ceil(trueY - 0.5)
 326         // Since y1 and y2 are biased by -0.5 in tosubpixy(), this is simply
 327         // ceil(y1) or ceil(y2)
 328         // upper integer (inclusive)
 329         final int firstCrossing = FloatMath.max(FloatMath.ceil_int(y1), boundsMinY);
 330 
 331         // note: use boundsMaxY (last Y exclusive) to compute correct coverage
 332         // upper integer (exclusive)
 333         final int lastCrossing  = FloatMath.min(FloatMath.ceil_int(y2), boundsMaxY);
 334 
 335         /* skip horizontal lines in pixel space and clip edges
 336            out of y range [boundsMinY; boundsMaxY] */
 337         if (firstCrossing >= lastCrossing) {
 338             if (DO_MONITORS) {
 339                 rdrCtx.stats.mon_rdr_addLine.stop();
 340             }
 341             if (DO_STATS) {
 342                 rdrCtx.stats.stat_rdr_addLine_skip.add(1);
 343             }
 344             return;
 345         }
 346 
 347         // edge min/max X/Y are in subpixel space (half-open interval):
 348         // note: Use integer crossings to ensure consistent range within
 349         // edgeBuckets / edgeBucketCounts arrays in case of NaN values (int = 0)
 350         if (firstCrossing < edgeMinY) {
 351             edgeMinY = firstCrossing;
 352         }
 353         if (lastCrossing > edgeMaxY) {
 354             edgeMaxY = lastCrossing;
 355         }
 356 
 357         final double slope = (x1 - x2) / (y1 - y2);
 358 
 359         if (slope >= 0.0d) { // <==> x1 < x2
 360             if (x1 < edgeMinX) {
 361                 edgeMinX = x1;
 362             }
 363             if (x2 > edgeMaxX) {
 364                 edgeMaxX = x2;
 365             }
 366         } else {
 367             if (x2 < edgeMinX) {
 368                 edgeMinX = x2;
 369             }
 370             if (x1 > edgeMaxX) {
 371                 edgeMaxX = x1;
 372             }
 373         }
 374 
 375         // local variables for performance:
 376         final int _SIZEOF_EDGE_BYTES = SIZEOF_EDGE_BYTES;
 377 
 378         final OffHeapArray _edges = edges;
 379 
 380         // get free pointer (ie length in bytes)
 381         final int edgePtr = _edges.used;
 382 
 383         // use substraction to avoid integer overflow:
 384         if (_edges.length - edgePtr < _SIZEOF_EDGE_BYTES) {
 385             // suppose _edges.length > _SIZEOF_EDGE_BYTES
 386             // so doubling size is enough to add needed bytes
 387             // note: throw IOOB if neededSize > 2Gb:
 388             final long edgeNewSize = ArrayCacheConst.getNewLargeSize(
 389                                         _edges.length,
 390                                         edgePtr + _SIZEOF_EDGE_BYTES);
 391 
 392             if (DO_STATS) {
 393                 rdrCtx.stats.stat_rdr_edges_resizes.add(edgeNewSize);
 394             }
 395             _edges.resize(edgeNewSize);
 396         }
 397 
 398 
 399         final Unsafe _unsafe = OffHeapArray.UNSAFE;
 400         final long SIZE_INT = 4L;
 401         long addr   = _edges.address + edgePtr;
 402 
 403         // The x value must be bumped up to its position at the next HPC we will evaluate.
 404         // "firstcrossing" is the (sub)pixel number where the next crossing occurs
 405         // thus, the actual coordinate of the next HPC is "firstcrossing + 0.5"
 406         // so the Y distance we cover is "firstcrossing + 0.5 - trueY".
 407         // Note that since y1 (and y2) are already biased by -0.5 in tosubpixy(), we have
 408         // y1 = trueY - 0.5
 409         // trueY = y1 + 0.5
 410         // firstcrossing + 0.5 - trueY = firstcrossing + 0.5 - (y1 + 0.5)
 411         //                             = firstcrossing - y1
 412         // The x coordinate at that HPC is then:
 413         // x1_intercept = x1 + (firstcrossing - y1) * slope
 414         // The next VPC is then given by:
 415         // VPC index = ceil(x1_intercept - 0.5), or alternately
 416         // VPC index = floor(x1_intercept - 0.5 + 1 - epsilon)
 417         // epsilon is hard to pin down in floating point, but easy in fixed point, so if
 418         // we convert to fixed point then these operations get easier:
 419         // long x1_fixed = x1_intercept * 2^32;  (fixed point 32.32 format)
 420         // curx = next VPC = fixed_floor(x1_fixed - 2^31 + 2^32 - 1)
 421         //                 = fixed_floor(x1_fixed + 2^31 - 1)
 422         //                 = fixed_floor(x1_fixed + 0x7FFFFFFF)
 423         // and error       = fixed_fract(x1_fixed + 0x7FFFFFFF)
 424         final double x1_intercept = x1 + (firstCrossing - y1) * slope;
 425 
 426         // inlined scalb(x1_intercept, 32):
 427         final long x1_fixed_biased = ((long) (POWER_2_TO_32 * x1_intercept))
 428                                      + 0x7FFFFFFFL;
 429         // curx:
 430         // last bit corresponds to the orientation
 431         _unsafe.putInt(addr, (((int) (x1_fixed_biased >> 31L)) & ALL_BUT_LSB) | or);
 432         addr += SIZE_INT;
 433         _unsafe.putInt(addr,  ((int)  x1_fixed_biased) >>> 1);
 434         addr += SIZE_INT;
 435 
 436         // inlined scalb(slope, 32):
 437         final long slope_fixed = (long) (POWER_2_TO_32 * slope);
 438 
 439         // last bit set to 0 to keep orientation:
 440         _unsafe.putInt(addr, (((int) (slope_fixed >> 31L)) & ALL_BUT_LSB));
 441         addr += SIZE_INT;
 442         _unsafe.putInt(addr,  ((int)  slope_fixed) >>> 1);
 443         addr += SIZE_INT;
 444 
 445         final int[] _edgeBuckets      = edgeBuckets;
 446         final int[] _edgeBucketCounts = edgeBucketCounts;
 447 
 448         final int _boundsMinY = boundsMinY;
 449 
 450         // each bucket is a linked list. this method adds ptr to the
 451         // start of the "bucket"th linked list.
 452         final int bucketIdx = firstCrossing - _boundsMinY;
 453 
 454         // pointer from bucket
 455         _unsafe.putInt(addr, _edgeBuckets[bucketIdx]);
 456         addr += SIZE_INT;
 457         // y max (exclusive)
 458         _unsafe.putInt(addr,  lastCrossing);
 459 
 460         // Update buckets:
 461         // directly the edge struct "pointer"
 462         _edgeBuckets[bucketIdx]       = edgePtr;
 463         _edgeBucketCounts[bucketIdx] += 2; // 1 << 1
 464         // last bit means edge end
 465         _edgeBucketCounts[lastCrossing - _boundsMinY] |= 0x1;
 466 
 467         // update free pointer (ie length in bytes)
 468         _edges.used += _SIZEOF_EDGE_BYTES;
 469 
 470         if (DO_MONITORS) {
 471             rdrCtx.stats.mon_rdr_addLine.stop();
 472         }
 473     }
 474 
 475 // END EDGE LIST
 476 //////////////////////////////////////////////////////////////////////////////
 477 
 478     // Bounds of the drawing region, at subpixel precision.
 479     private int boundsMinX, boundsMinY, boundsMaxX, boundsMaxY;
 480 
 481     // Current winding rule
 482     private int windingRule;
 483 
 484     // Current drawing position, i.e., final point of last segment
 485     private double x0, y0;
 486 
 487     // Position of most recent 'moveTo' command
 488     private double sx0, sy0;
 489 
 490     // per-thread renderer context
 491     final DRendererContext rdrCtx;
 492     // dirty curve
 493     private final DCurve curve;
 494 
 495     // clean alpha array (zero filled)
 496     private int[] alphaLine;
 497 
 498     // alphaLine ref (clean)
 499     private final IntArrayCache.Reference alphaLine_ref;
 500 
 501     private boolean enableBlkFlags = false;
 502     private boolean prevUseBlkFlags = false;
 503 
 504     /* block flags (0|1) */
 505     private int[] blkFlags;
 506 
 507     // blkFlags ref (clean)
 508     private final IntArrayCache.Reference blkFlags_ref;
 509 
 510     DRenderer(final DRendererContext rdrCtx) {
 511         this.rdrCtx = rdrCtx;
 512         this.curve = rdrCtx.curve;
 513 
 514         this.edges = rdrCtx.rdrMem.edges;
 515 
 516         edgeBuckets_ref      = rdrCtx.rdrMem.edgeBuckets_ref;
 517         edgeBucketCounts_ref = rdrCtx.rdrMem.edgeBucketCounts_ref;
 518 
 519         edgeBuckets      = edgeBuckets_ref.initial;
 520         edgeBucketCounts = edgeBucketCounts_ref.initial;
 521 
 522         alphaLine_ref = rdrCtx.rdrMem.alphaLine_ref;
 523         alphaLine     = alphaLine_ref.initial;
 524 
 525         crossings_ref     = rdrCtx.rdrMem.crossings_ref;
 526         aux_crossings_ref = rdrCtx.rdrMem.aux_crossings_ref;
 527         edgePtrs_ref      = rdrCtx.rdrMem.edgePtrs_ref;
 528         aux_edgePtrs_ref  = rdrCtx.rdrMem.aux_edgePtrs_ref;
 529 
 530         crossings     = crossings_ref.initial;
 531         aux_crossings = aux_crossings_ref.initial;
 532         edgePtrs      = edgePtrs_ref.initial;
 533         aux_edgePtrs  = aux_edgePtrs_ref.initial;
 534 
 535         blkFlags_ref = rdrCtx.rdrMem.blkFlags_ref;
 536         blkFlags     = blkFlags_ref.initial;
 537     }
 538 
 539     public DRenderer init(final int pix_boundsX, final int pix_boundsY,
 540                   final int pix_boundsWidth, final int pix_boundsHeight,
 541                   final int windingRule)
 542     {
 543         this.windingRule = windingRule;
 544 
 545         // bounds as half-open intervals: minX <= x < maxX and minY <= y < maxY
 546         this.boundsMinX =  pix_boundsX << SUBPIXEL_LG_POSITIONS_X;
 547         this.boundsMaxX =
 548             (pix_boundsX + pix_boundsWidth) << SUBPIXEL_LG_POSITIONS_X;
 549         this.boundsMinY =  pix_boundsY << SUBPIXEL_LG_POSITIONS_Y;
 550         this.boundsMaxY =
 551             (pix_boundsY + pix_boundsHeight) << SUBPIXEL_LG_POSITIONS_Y;
 552 
 553         if (DO_LOG_BOUNDS) {
 554             MarlinUtils.logInfo("boundsXY = [" + boundsMinX + " ... "
 555                                 + boundsMaxX + "[ [" + boundsMinY + " ... "
 556                                 + boundsMaxY + "[");
 557         }
 558 
 559         // see addLine: ceil(boundsMaxY) => boundsMaxY + 1
 560         // +1 for edgeBucketCounts
 561         final int edgeBucketsLength = (boundsMaxY - boundsMinY) + 1;
 562 
 563         if (edgeBucketsLength > INITIAL_BUCKET_ARRAY) {
 564             if (DO_STATS) {
 565                 rdrCtx.stats.stat_array_renderer_edgeBuckets
 566                     .add(edgeBucketsLength);
 567                 rdrCtx.stats.stat_array_renderer_edgeBucketCounts
 568                     .add(edgeBucketsLength);
 569             }
 570             edgeBuckets = edgeBuckets_ref.getArray(edgeBucketsLength);
 571             edgeBucketCounts = edgeBucketCounts_ref.getArray(edgeBucketsLength);
 572         }
 573 
 574         edgeMinY = Integer.MAX_VALUE;
 575         edgeMaxY = Integer.MIN_VALUE;
 576         edgeMinX = Double.POSITIVE_INFINITY;
 577         edgeMaxX = Double.NEGATIVE_INFINITY;
 578 
 579         // reset used mark:
 580         edgeCount = 0;
 581         activeEdgeMaxUsed = 0;
 582         edges.used = 0;
 583 
 584         // reset bbox:
 585         bboxX0 = 0;
 586         bboxX1 = 0;
 587 
 588         return this; // fluent API
 589     }
 590 
 591     /**
 592      * Disposes this renderer and recycle it clean up before reusing this instance
 593      */
 594     public void dispose() {
 595         if (DO_STATS) {
 596             rdrCtx.stats.stat_rdr_activeEdges.add(activeEdgeMaxUsed);
 597             rdrCtx.stats.stat_rdr_edges.add(edges.used);
 598             rdrCtx.stats.stat_rdr_edges_count.add(edges.used / SIZEOF_EDGE_BYTES);
 599             rdrCtx.stats.hist_rdr_edges_count.add(edges.used / SIZEOF_EDGE_BYTES);
 600             rdrCtx.stats.totalOffHeap += edges.length;
 601         }
 602         // Return arrays:
 603         crossings = crossings_ref.putArray(crossings);
 604         aux_crossings = aux_crossings_ref.putArray(aux_crossings);
 605 
 606         edgePtrs = edgePtrs_ref.putArray(edgePtrs);
 607         aux_edgePtrs = aux_edgePtrs_ref.putArray(aux_edgePtrs);
 608 
 609         alphaLine = alphaLine_ref.putArray(alphaLine, 0, 0); // already zero filled
 610         blkFlags  = blkFlags_ref.putArray(blkFlags, 0, 0); // already zero filled
 611 
 612         if (edgeMinY != Integer.MAX_VALUE) {
 613             // if context is maked as DIRTY:
 614             if (rdrCtx.dirty) {
 615                 // may happen if an exception if thrown in the pipeline processing:
 616                 // clear completely buckets arrays:
 617                 buckets_minY = 0;
 618                 buckets_maxY = boundsMaxY - boundsMinY;
 619             }
 620             // clear only used part
 621             edgeBuckets = edgeBuckets_ref.putArray(edgeBuckets, buckets_minY,
 622                                                                 buckets_maxY);
 623             edgeBucketCounts = edgeBucketCounts_ref.putArray(edgeBucketCounts,
 624                                                              buckets_minY,
 625                                                              buckets_maxY + 1);
 626         } else {
 627             // unused arrays
 628             edgeBuckets = edgeBuckets_ref.putArray(edgeBuckets, 0, 0);
 629             edgeBucketCounts = edgeBucketCounts_ref.putArray(edgeBucketCounts, 0, 0);
 630         }
 631 
 632         // At last: resize back off-heap edges to initial size
 633         if (edges.length != INITIAL_EDGES_CAPACITY) {
 634             // note: may throw OOME:
 635             edges.resize(INITIAL_EDGES_CAPACITY);
 636         }
 637         if (DO_CLEAN_DIRTY) {
 638             // Force zero-fill dirty arrays:
 639             edges.fill(BYTE_0);
 640         }
 641         if (DO_MONITORS) {
 642             rdrCtx.stats.mon_rdr_endRendering.stop();
 643         }
 644     }
 645 
 646     private static double tosubpixx(final double pix_x) {
 647         return SUBPIXEL_SCALE_X * pix_x;
 648     }
 649 
 650     private static double tosubpixy(final double pix_y) {
 651         // shift y by -0.5 for fast ceil(y - 0.5):
 652         return SUBPIXEL_SCALE_Y * pix_y - 0.5d;
 653     }
 654 
 655     @Override
 656     public void moveTo(final double pix_x0, final double pix_y0) {
 657         closePath();
 658         final double sx = tosubpixx(pix_x0);
 659         final double sy = tosubpixy(pix_y0);
 660         this.sx0 = sx;
 661         this.sy0 = sy;
 662         this.x0 = sx;
 663         this.y0 = sy;
 664     }
 665 
 666     @Override
 667     public void lineTo(final double pix_x1, final double pix_y1) {
 668         final double x1 = tosubpixx(pix_x1);
 669         final double y1 = tosubpixy(pix_y1);
 670         addLine(x0, y0, x1, y1);
 671         x0 = x1;
 672         y0 = y1;
 673     }
 674 
 675     @Override
 676     public void curveTo(final double pix_x1, final double pix_y1,
 677                         final double pix_x2, final double pix_y2,
 678                         final double pix_x3, final double pix_y3)
 679     {
 680         final double xe = tosubpixx(pix_x3);
 681         final double ye = tosubpixy(pix_y3);
 682         curve.set(x0, y0,
 683                 tosubpixx(pix_x1), tosubpixy(pix_y1),
 684                 tosubpixx(pix_x2), tosubpixy(pix_y2),
 685                 xe, ye);
 686         curveBreakIntoLinesAndAdd(x0, y0, curve, xe, ye);
 687         x0 = xe;
 688         y0 = ye;
 689     }
 690 
 691     @Override
 692     public void quadTo(final double pix_x1, final double pix_y1,
 693                        final double pix_x2, final double pix_y2)
 694     {
 695         final double xe = tosubpixx(pix_x2);
 696         final double ye = tosubpixy(pix_y2);
 697         curve.set(x0, y0,
 698                 tosubpixx(pix_x1), tosubpixy(pix_y1),
 699                 xe, ye);
 700         quadBreakIntoLinesAndAdd(x0, y0, curve, xe, ye);
 701         x0 = xe;
 702         y0 = ye;
 703     }
 704 
 705     @Override
 706     public void closePath() {
 707         if (x0 != sx0 || y0 != sy0) {
 708             addLine(x0, y0, sx0, sy0);
 709             x0 = sx0;
 710             y0 = sy0;
 711         }
 712     }
 713 
 714     @Override
 715     public void pathDone() {
 716         closePath();
 717 
 718         // call endRendering() to determine the boundaries:
 719         endRendering();
 720     }
 721 
 722     private void _endRendering(final int ymin, final int ymax,
 723                                final MarlinAlphaConsumer ac)
 724     {
 725         if (DISABLE_RENDER) {
 726             return;
 727         }
 728 
 729         // Get X bounds as true pixel boundaries to compute correct pixel coverage:
 730         final int bboxx0 = bbox_spminX;
 731         final int bboxx1 = bbox_spmaxX;
 732 
 733         final boolean windingRuleEvenOdd = (windingRule == WIND_EVEN_ODD);
 734 
 735         // Useful when processing tile line by tile line
 736         final int[] _alpha = alphaLine;
 737 
 738         // local vars (performance):
 739         final OffHeapArray _edges = edges;
 740         final int[] _edgeBuckets = edgeBuckets;
 741         final int[] _edgeBucketCounts = edgeBucketCounts;
 742 
 743         int[] _crossings = this.crossings;
 744         int[] _edgePtrs  = this.edgePtrs;
 745 
 746         // merge sort auxiliary storage:
 747         int[] _aux_crossings = this.aux_crossings;
 748         int[] _aux_edgePtrs  = this.aux_edgePtrs;
 749 
 750         // copy constants:
 751         final long _OFF_ERROR    = OFF_ERROR;
 752         final long _OFF_BUMP_X   = OFF_BUMP_X;
 753         final long _OFF_BUMP_ERR = OFF_BUMP_ERR;
 754 
 755         final long _OFF_NEXT     = OFF_NEXT;
 756         final long _OFF_YMAX     = OFF_YMAX;
 757 
 758         final int _ALL_BUT_LSB   = ALL_BUT_LSB;
 759         final int _ERR_STEP_MAX  = ERR_STEP_MAX;
 760 
 761         // unsafe I/O:
 762         final Unsafe _unsafe = OffHeapArray.UNSAFE;
 763         final long    addr0  = _edges.address;
 764         long addr;
 765         final int _SUBPIXEL_LG_POSITIONS_X = SUBPIXEL_LG_POSITIONS_X;
 766         final int _SUBPIXEL_LG_POSITIONS_Y = SUBPIXEL_LG_POSITIONS_Y;
 767         final int _SUBPIXEL_MASK_X = SUBPIXEL_MASK_X;
 768         final int _SUBPIXEL_MASK_Y = SUBPIXEL_MASK_Y;
 769         final int _SUBPIXEL_POSITIONS_X = SUBPIXEL_POSITIONS_X;
 770 
 771         final int _MIN_VALUE = Integer.MIN_VALUE;
 772         final int _MAX_VALUE = Integer.MAX_VALUE;
 773 
 774         // Now we iterate through the scanlines. We must tell emitRow the coord
 775         // of the first non-transparent pixel, so we must keep accumulators for
 776         // the first and last pixels of the section of the current pixel row
 777         // that we will emit.
 778         // We also need to accumulate pix_bbox, but the iterator does it
 779         // for us. We will just get the values from it once this loop is done
 780         int minX = _MAX_VALUE;
 781         int maxX = _MIN_VALUE;
 782 
 783         int y = ymin;
 784         int bucket = y - boundsMinY;
 785 
 786         int numCrossings = this.edgeCount;
 787         int edgePtrsLen = _edgePtrs.length;
 788         int crossingsLen = _crossings.length;
 789         int _arrayMaxUsed = activeEdgeMaxUsed;
 790         int ptrLen = 0, newCount, ptrEnd;
 791 
 792         int bucketcount, i, j, ecur;
 793         int cross, lastCross;
 794         int x0, x1, tmp, sum, prev, curx, curxo, crorientation, err;
 795         int pix_x, pix_xmaxm1, pix_xmax;
 796 
 797         int low, high, mid, prevNumCrossings;
 798         boolean useBinarySearch;
 799 
 800         final int[] _blkFlags = blkFlags;
 801         final int _BLK_SIZE_LG = BLOCK_SIZE_LG;
 802         final int _BLK_SIZE = BLOCK_SIZE;
 803 
 804         final boolean _enableBlkFlagsHeuristics = ENABLE_BLOCK_FLAGS_HEURISTICS && this.enableBlkFlags;
 805 
 806         // Use block flags if large pixel span and few crossings:
 807         // ie mean(distance between crossings) is high
 808         boolean useBlkFlags = this.prevUseBlkFlags;
 809 
 810         final int stroking = rdrCtx.stroking;
 811 
 812         int lastY = -1; // last emited row
 813 
 814 
 815         // Iteration on scanlines
 816         for (; y < ymax; y++, bucket++) {
 817             // --- from former ScanLineIterator.next()
 818             bucketcount = _edgeBucketCounts[bucket];
 819 
 820             // marker on previously sorted edges:
 821             prevNumCrossings = numCrossings;
 822 
 823             // bucketCount indicates new edge / edge end:
 824             if (bucketcount != 0) {
 825                 if (DO_STATS) {
 826                     rdrCtx.stats.stat_rdr_activeEdges_updates.add(numCrossings);
 827                 }
 828 
 829                 // last bit set to 1 means that edges ends
 830                 if ((bucketcount & 0x1) != 0) {
 831                     // eviction in active edge list
 832                     // cache edges[] address + offset
 833                     addr = addr0 + _OFF_YMAX;
 834 
 835                     for (i = 0, newCount = 0; i < numCrossings; i++) {
 836                         // get the pointer to the edge
 837                         ecur = _edgePtrs[i];
 838                         // random access so use unsafe:
 839                         if (_unsafe.getInt(addr + ecur) > y) {
 840                             _edgePtrs[newCount++] = ecur;
 841                         }
 842                     }
 843                     // update marker on sorted edges minus removed edges:
 844                     prevNumCrossings = numCrossings = newCount;
 845                 }
 846 
 847                 ptrLen = bucketcount >> 1; // number of new edge
 848 
 849                 if (ptrLen != 0) {
 850                     if (DO_STATS) {
 851                         rdrCtx.stats.stat_rdr_activeEdges_adds.add(ptrLen);
 852                         if (ptrLen > 10) {
 853                             rdrCtx.stats.stat_rdr_activeEdges_adds_high.add(ptrLen);
 854                         }
 855                     }
 856                     ptrEnd = numCrossings + ptrLen;
 857 
 858                     if (edgePtrsLen < ptrEnd) {
 859                         if (DO_STATS) {
 860                             rdrCtx.stats.stat_array_renderer_edgePtrs.add(ptrEnd);
 861                         }
 862                         this.edgePtrs = _edgePtrs
 863                             = edgePtrs_ref.widenArray(_edgePtrs, numCrossings,
 864                                                       ptrEnd);
 865 
 866                         edgePtrsLen = _edgePtrs.length;
 867                         // Get larger auxiliary storage:
 868                         aux_edgePtrs_ref.putArray(_aux_edgePtrs);
 869 
 870                         // use ArrayCache.getNewSize() to use the same growing
 871                         // factor than widenArray():
 872                         if (DO_STATS) {
 873                             rdrCtx.stats.stat_array_renderer_aux_edgePtrs.add(ptrEnd);
 874                         }
 875                         this.aux_edgePtrs = _aux_edgePtrs
 876                             = aux_edgePtrs_ref.getArray(
 877                                 ArrayCacheConst.getNewSize(numCrossings, ptrEnd)
 878                             );
 879                     }
 880 
 881                     // cache edges[] address + offset
 882                     addr = addr0 + _OFF_NEXT;
 883 
 884                     // add new edges to active edge list:
 885                     for (ecur = _edgeBuckets[bucket];
 886                          numCrossings < ptrEnd; numCrossings++)
 887                     {
 888                         // store the pointer to the edge
 889                         _edgePtrs[numCrossings] = ecur;
 890                         // random access so use unsafe:
 891                         ecur = _unsafe.getInt(addr + ecur);
 892                     }
 893 
 894                     if (crossingsLen < numCrossings) {
 895                         // Get larger array:
 896                         crossings_ref.putArray(_crossings);
 897 
 898                         if (DO_STATS) {
 899                             rdrCtx.stats.stat_array_renderer_crossings
 900                                 .add(numCrossings);
 901                         }
 902                         this.crossings = _crossings
 903                             = crossings_ref.getArray(numCrossings);
 904 
 905                         // Get larger auxiliary storage:
 906                         aux_crossings_ref.putArray(_aux_crossings);
 907 
 908                         if (DO_STATS) {
 909                             rdrCtx.stats.stat_array_renderer_aux_crossings
 910                                 .add(numCrossings);
 911                         }
 912                         this.aux_crossings = _aux_crossings
 913                             = aux_crossings_ref.getArray(numCrossings);
 914 
 915                         crossingsLen = _crossings.length;
 916                     }
 917                     if (DO_STATS) {
 918                         // update max used mark
 919                         if (numCrossings > _arrayMaxUsed) {
 920                             _arrayMaxUsed = numCrossings;
 921                         }
 922                     }
 923                 } // ptrLen != 0
 924             } // bucketCount != 0
 925 
 926 
 927             if (numCrossings != 0) {
 928                 /*
 929                  * thresholds to switch to optimized merge sort
 930                  * for newly added edges + final merge pass.
 931                  */
 932                 if ((ptrLen < 10) || (numCrossings < 40)) {
 933                     if (DO_STATS) {
 934                         rdrCtx.stats.hist_rdr_crossings.add(numCrossings);
 935                         rdrCtx.stats.hist_rdr_crossings_adds.add(ptrLen);
 936                     }
 937 
 938                     /*
 939                      * threshold to use binary insertion sort instead of
 940                      * straight insertion sort (to reduce minimize comparisons).
 941                      */
 942                     useBinarySearch = (numCrossings >= 20);
 943 
 944                     // if small enough:
 945                     lastCross = _MIN_VALUE;
 946 
 947                     for (i = 0; i < numCrossings; i++) {
 948                         // get the pointer to the edge
 949                         ecur = _edgePtrs[i];
 950 
 951                         /* convert subpixel coordinates into pixel
 952                             positions for coming scanline */
 953                         /* note: it is faster to always update edges even
 954                            if it is removed from AEL for coming or last scanline */
 955 
 956                         // random access so use unsafe:
 957                         addr = addr0 + ecur; // ecur + OFF_F_CURX
 958 
 959                         // get current crossing:
 960                         curx = _unsafe.getInt(addr);
 961 
 962                         // update crossing with orientation at last bit:
 963                         cross = curx;
 964 
 965                         // Increment x using DDA (fixed point):
 966                         curx += _unsafe.getInt(addr + _OFF_BUMP_X);
 967 
 968                         // Increment error:
 969                         err  =  _unsafe.getInt(addr + _OFF_ERROR)
 970                               + _unsafe.getInt(addr + _OFF_BUMP_ERR);
 971 
 972                         // Manual carry handling:
 973                         // keep sign and carry bit only and ignore last bit (preserve orientation):
 974                         _unsafe.putInt(addr,               curx - ((err >> 30) & _ALL_BUT_LSB));
 975                         _unsafe.putInt(addr + _OFF_ERROR, (err & _ERR_STEP_MAX));
 976 
 977                         if (DO_STATS) {
 978                             rdrCtx.stats.stat_rdr_crossings_updates.add(numCrossings);
 979                         }
 980 
 981                         // insertion sort of crossings:
 982                         if (cross < lastCross) {
 983                             if (DO_STATS) {
 984                                 rdrCtx.stats.stat_rdr_crossings_sorts.add(i);
 985                             }
 986 
 987                             /* use binary search for newly added edges
 988                                in crossings if arrays are large enough */
 989                             if (useBinarySearch && (i >= prevNumCrossings)) {
 990                                 if (DO_STATS) {
 991                                     rdrCtx.stats.stat_rdr_crossings_bsearch.add(i);
 992                                 }
 993                                 low = 0;
 994                                 high = i - 1;
 995 
 996                                 do {
 997                                     // note: use signed shift (not >>>) for performance
 998                                     // as indices are small enough to exceed Integer.MAX_VALUE
 999                                     mid = (low + high) >> 1;
1000 
1001                                     if (_crossings[mid] < cross) {
1002                                         low = mid + 1;
1003                                     } else {
1004                                         high = mid - 1;
1005                                     }
1006                                 } while (low <= high);
1007 
1008                                 for (j = i - 1; j >= low; j--) {
1009                                     _crossings[j + 1] = _crossings[j];
1010                                     _edgePtrs [j + 1] = _edgePtrs[j];
1011                                 }
1012                                 _crossings[low] = cross;
1013                                 _edgePtrs [low] = ecur;
1014 
1015                             } else {
1016                                 j = i - 1;
1017                                 _crossings[i] = _crossings[j];
1018                                 _edgePtrs[i] = _edgePtrs[j];
1019 
1020                                 while ((--j >= 0) && (_crossings[j] > cross)) {
1021                                     _crossings[j + 1] = _crossings[j];
1022                                     _edgePtrs [j + 1] = _edgePtrs[j];
1023                                 }
1024                                 _crossings[j + 1] = cross;
1025                                 _edgePtrs [j + 1] = ecur;
1026                             }
1027 
1028                         } else {
1029                             _crossings[i] = lastCross = cross;
1030                         }
1031                     }
1032                 } else {
1033                     if (DO_STATS) {
1034                         rdrCtx.stats.stat_rdr_crossings_msorts.add(numCrossings);
1035                         rdrCtx.stats.hist_rdr_crossings_ratio
1036                             .add((1000 * ptrLen) / numCrossings);
1037                         rdrCtx.stats.hist_rdr_crossings_msorts.add(numCrossings);
1038                         rdrCtx.stats.hist_rdr_crossings_msorts_adds.add(ptrLen);
1039                     }
1040 
1041                     // Copy sorted data in auxiliary arrays
1042                     // and perform insertion sort on almost sorted data
1043                     // (ie i < prevNumCrossings):
1044 
1045                     lastCross = _MIN_VALUE;
1046 
1047                     for (i = 0; i < numCrossings; i++) {
1048                         // get the pointer to the edge
1049                         ecur = _edgePtrs[i];
1050 
1051                         /* convert subpixel coordinates into pixel
1052                             positions for coming scanline */
1053                         /* note: it is faster to always update edges even
1054                            if it is removed from AEL for coming or last scanline */
1055 
1056                         // random access so use unsafe:
1057                         addr = addr0 + ecur; // ecur + OFF_F_CURX
1058 
1059                         // get current crossing:
1060                         curx = _unsafe.getInt(addr);
1061 
1062                         // update crossing with orientation at last bit:
1063                         cross = curx;
1064 
1065                         // Increment x using DDA (fixed point):
1066                         curx += _unsafe.getInt(addr + _OFF_BUMP_X);
1067 
1068                         // Increment error:
1069                         err  =  _unsafe.getInt(addr + _OFF_ERROR)
1070                               + _unsafe.getInt(addr + _OFF_BUMP_ERR);
1071 
1072                         // Manual carry handling:
1073                         // keep sign and carry bit only and ignore last bit (preserve orientation):
1074                         _unsafe.putInt(addr,               curx - ((err >> 30) & _ALL_BUT_LSB));
1075                         _unsafe.putInt(addr + _OFF_ERROR, (err & _ERR_STEP_MAX));
1076 
1077                         if (DO_STATS) {
1078                             rdrCtx.stats.stat_rdr_crossings_updates.add(numCrossings);
1079                         }
1080 
1081                         if (i >= prevNumCrossings) {
1082                             // simply store crossing as edgePtrs is in-place:
1083                             // will be copied and sorted efficiently by mergesort later:
1084                             _crossings[i]     = cross;
1085 
1086                         } else if (cross < lastCross) {
1087                             if (DO_STATS) {
1088                                 rdrCtx.stats.stat_rdr_crossings_sorts.add(i);
1089                             }
1090 
1091                             // (straight) insertion sort of crossings:
1092                             j = i - 1;
1093                             _aux_crossings[i] = _aux_crossings[j];
1094                             _aux_edgePtrs[i] = _aux_edgePtrs[j];
1095 
1096                             while ((--j >= 0) && (_aux_crossings[j] > cross)) {
1097                                 _aux_crossings[j + 1] = _aux_crossings[j];
1098                                 _aux_edgePtrs [j + 1] = _aux_edgePtrs[j];
1099                             }
1100                             _aux_crossings[j + 1] = cross;
1101                             _aux_edgePtrs [j + 1] = ecur;
1102 
1103                         } else {
1104                             // auxiliary storage:
1105                             _aux_crossings[i] = lastCross = cross;
1106                             _aux_edgePtrs [i] = ecur;
1107                         }
1108                     }
1109 
1110                     // use Mergesort using auxiliary arrays (sort only right part)
1111                     MergeSort.mergeSortNoCopy(_crossings,     _edgePtrs,
1112                                               _aux_crossings, _aux_edgePtrs,
1113                                               numCrossings,   prevNumCrossings);
1114                 }
1115 
1116                 // reset ptrLen
1117                 ptrLen = 0;
1118                 // --- from former ScanLineIterator.next()
1119 
1120 
1121                 /* note: bboxx0 and bboxx1 must be pixel boundaries
1122                    to have correct coverage computation */
1123 
1124                 // right shift on crossings to get the x-coordinate:
1125                 curxo = _crossings[0];
1126                 x0    = curxo >> 1;
1127                 if (x0 < minX) {
1128                     minX = x0; // subpixel coordinate
1129                 }
1130 
1131                 x1 = _crossings[numCrossings - 1] >> 1;
1132                 if (x1 > maxX) {
1133                     maxX = x1; // subpixel coordinate
1134                 }
1135 
1136 
1137                 // compute pixel coverages
1138                 prev = curx = x0;
1139                 // to turn {0, 1} into {-1, 1}, multiply by 2 and subtract 1.
1140                 // last bit contains orientation (0 or 1)
1141                 crorientation = ((curxo & 0x1) << 1) - 1;
1142 
1143                 if (windingRuleEvenOdd) {
1144                     sum = crorientation;
1145 
1146                     // Even Odd winding rule: take care of mask ie sum(orientations)
1147                     for (i = 1; i < numCrossings; i++) {
1148                         curxo = _crossings[i];
1149                         curx  =  curxo >> 1;
1150                         // to turn {0, 1} into {-1, 1}, multiply by 2 and subtract 1.
1151                         // last bit contains orientation (0 or 1)
1152                         crorientation = ((curxo & 0x1) << 1) - 1;
1153 
1154                         if ((sum & 0x1) != 0) {
1155                             // TODO: perform line clipping on left-right sides
1156                             // to avoid such bound checks:
1157                             x0 = (prev > bboxx0) ? prev : bboxx0;
1158 
1159                             if (curx < bboxx1) {
1160                                 x1 = curx;
1161                             } else {
1162                                 x1 = bboxx1;
1163                                 // skip right side (fast exit loop):
1164                                 i = numCrossings;
1165                             }
1166 
1167                             if (x0 < x1) {
1168                                 x0 -= bboxx0; // turn x0, x1 from coords to indices
1169                                 x1 -= bboxx0; // in the alpha array.
1170 
1171                                 pix_x      =  x0      >> _SUBPIXEL_LG_POSITIONS_X;
1172                                 pix_xmaxm1 = (x1 - 1) >> _SUBPIXEL_LG_POSITIONS_X;
1173 
1174                                 if (pix_x == pix_xmaxm1) {
1175                                     // Start and end in same pixel
1176                                     tmp = (x1 - x0); // number of subpixels
1177                                     _alpha[pix_x    ] += tmp;
1178                                     _alpha[pix_x + 1] -= tmp;
1179 
1180                                     if (useBlkFlags) {
1181                                         // flag used blocks:
1182                                         // note: block processing handles extra pixel:
1183                                         _blkFlags[pix_x    >> _BLK_SIZE_LG] = 1;
1184                                     }
1185                                 } else {
1186                                     tmp = (x0 & _SUBPIXEL_MASK_X);
1187                                     _alpha[pix_x    ]
1188                                         += (_SUBPIXEL_POSITIONS_X - tmp);
1189                                     _alpha[pix_x + 1]
1190                                         += tmp;
1191 
1192                                     pix_xmax = x1 >> _SUBPIXEL_LG_POSITIONS_X;
1193 
1194                                     tmp = (x1 & _SUBPIXEL_MASK_X);
1195                                     _alpha[pix_xmax    ]
1196                                         -= (_SUBPIXEL_POSITIONS_X - tmp);
1197                                     _alpha[pix_xmax + 1]
1198                                         -= tmp;
1199 
1200                                     if (useBlkFlags) {
1201                                         // flag used blocks:
1202                                         // note: block processing handles extra pixel:
1203                                         _blkFlags[pix_x    >> _BLK_SIZE_LG] = 1;
1204                                         _blkFlags[pix_xmax >> _BLK_SIZE_LG] = 1;
1205                                     }
1206                                 }
1207                             }
1208                         }
1209 
1210                         sum += crorientation;
1211                         prev = curx;
1212                     }
1213                 } else {
1214                     // Non-zero winding rule: optimize that case (default)
1215                     // and avoid processing intermediate crossings
1216                     for (i = 1, sum = 0;; i++) {
1217                         sum += crorientation;
1218 
1219                         if (sum != 0) {
1220                             // prev = min(curx)
1221                             if (prev > curx) {
1222                                 prev = curx;
1223                             }
1224                         } else {
1225                             // TODO: perform line clipping on left-right sides
1226                             // to avoid such bound checks:
1227                             x0 = (prev > bboxx0) ? prev : bboxx0;
1228 
1229                             if (curx < bboxx1) {
1230                                 x1 = curx;
1231                             } else {
1232                                 x1 = bboxx1;
1233                                 // skip right side (fast exit loop):
1234                                 i = numCrossings;
1235                             }
1236 
1237                             if (x0 < x1) {
1238                                 x0 -= bboxx0; // turn x0, x1 from coords to indices
1239                                 x1 -= bboxx0; // in the alpha array.
1240 
1241                                 pix_x      =  x0      >> _SUBPIXEL_LG_POSITIONS_X;
1242                                 pix_xmaxm1 = (x1 - 1) >> _SUBPIXEL_LG_POSITIONS_X;
1243 
1244                                 if (pix_x == pix_xmaxm1) {
1245                                     // Start and end in same pixel
1246                                     tmp = (x1 - x0); // number of subpixels
1247                                     _alpha[pix_x    ] += tmp;
1248                                     _alpha[pix_x + 1] -= tmp;
1249 
1250                                     if (useBlkFlags) {
1251                                         // flag used blocks:
1252                                         // note: block processing handles extra pixel:
1253                                         _blkFlags[pix_x    >> _BLK_SIZE_LG] = 1;
1254                                     }
1255                                 } else {
1256                                     tmp = (x0 & _SUBPIXEL_MASK_X);
1257                                     _alpha[pix_x    ]
1258                                         += (_SUBPIXEL_POSITIONS_X - tmp);
1259                                     _alpha[pix_x + 1]
1260                                         += tmp;
1261 
1262                                     pix_xmax = x1 >> _SUBPIXEL_LG_POSITIONS_X;
1263 
1264                                     tmp = (x1 & _SUBPIXEL_MASK_X);
1265                                     _alpha[pix_xmax    ]
1266                                         -= (_SUBPIXEL_POSITIONS_X - tmp);
1267                                     _alpha[pix_xmax + 1]
1268                                         -= tmp;
1269 
1270                                     if (useBlkFlags) {
1271                                         // flag used blocks:
1272                                         // note: block processing handles extra pixel:
1273                                         _blkFlags[pix_x    >> _BLK_SIZE_LG] = 1;
1274                                         _blkFlags[pix_xmax >> _BLK_SIZE_LG] = 1;
1275                                     }
1276                                 }
1277                             }
1278                             prev = _MAX_VALUE;
1279                         }
1280 
1281                         if (i == numCrossings) {
1282                             break;
1283                         }
1284 
1285                         curxo = _crossings[i];
1286                         curx  =  curxo >> 1;
1287                         // to turn {0, 1} into {-1, 1}, multiply by 2 and subtract 1.
1288                         // last bit contains orientation (0 or 1)
1289                         crorientation = ((curxo & 0x1) << 1) - 1;
1290                     }
1291                 }
1292             } // numCrossings > 0
1293 
1294             // even if this last row had no crossings, alpha will be zeroed
1295             // from the last emitRow call. But this doesn't matter because
1296             // maxX < minX, so no row will be emitted to the AlphaConsumer.
1297             if ((y & _SUBPIXEL_MASK_Y) == _SUBPIXEL_MASK_Y) {
1298                 lastY = y >> _SUBPIXEL_LG_POSITIONS_Y;
1299 
1300                 // convert subpixel to pixel coordinate within boundaries:
1301                 minX = FloatMath.max(minX, bboxx0) >> _SUBPIXEL_LG_POSITIONS_X;
1302                 maxX = FloatMath.min(maxX, bboxx1) >> _SUBPIXEL_LG_POSITIONS_X;
1303 
1304                 if (maxX >= minX) {
1305                     // note: alpha array will be zeroed by copyAARow()
1306                     // +1 because alpha [pix_minX; pix_maxX[
1307                     // fix range [x0; x1[
1308                     // note: if x1=bboxx1, then alpha is written up to bboxx1+1
1309                     // inclusive: alpha[bboxx1] ignored, alpha[bboxx1+1] == 0
1310                     // (normally so never cleared below)
1311                     copyAARow(_alpha, lastY, minX, maxX + 1, useBlkFlags, ac);
1312 
1313                     // speculative for next pixel row (scanline coherence):
1314                     if (_enableBlkFlagsHeuristics) {
1315                         // Use block flags if large pixel span and few crossings:
1316                         // ie mean(distance between crossings) is larger than
1317                         // 1 block size;
1318 
1319                         // fast check width:
1320                         maxX -= minX;
1321 
1322                         // if stroking: numCrossings /= 2
1323                         // => shift numCrossings by 1
1324                         // condition = (width / (numCrossings - 1)) > blockSize
1325                         useBlkFlags = (maxX > _BLK_SIZE) && (maxX >
1326                             (((numCrossings >> stroking) - 1) << _BLK_SIZE_LG));
1327 
1328                         if (DO_STATS) {
1329                             tmp = FloatMath.max(1,
1330                                     ((numCrossings >> stroking) - 1));
1331                             rdrCtx.stats.hist_tile_generator_encoding_dist
1332                                 .add(maxX / tmp);
1333                         }
1334                     }
1335                 } else {
1336                     ac.clearAlphas(lastY);
1337                 }
1338                 minX = _MAX_VALUE;
1339                 maxX = _MIN_VALUE;
1340             }
1341         } // scan line iterator
1342 
1343         // Emit final row
1344         y--;
1345         y >>= _SUBPIXEL_LG_POSITIONS_Y;
1346 
1347         // convert subpixel to pixel coordinate within boundaries:
1348         minX = FloatMath.max(minX, bboxx0) >> _SUBPIXEL_LG_POSITIONS_X;
1349         maxX = FloatMath.min(maxX, bboxx1) >> _SUBPIXEL_LG_POSITIONS_X;
1350 
1351         if (maxX >= minX) {
1352             // note: alpha array will be zeroed by copyAARow()
1353             // +1 because alpha [pix_minX; pix_maxX[
1354             // fix range [x0; x1[
1355             // note: if x1=bboxx1, then alpha is written up to bboxx1+1
1356             // inclusive: alpha[bboxx1] ignored then cleared and
1357             // alpha[bboxx1+1] == 0 (normally so never cleared after)
1358             copyAARow(_alpha, y, minX, maxX + 1, useBlkFlags, ac);
1359         } else if (y != lastY) {
1360             ac.clearAlphas(y);
1361         }
1362 
1363         // update member:
1364         edgeCount = numCrossings;
1365         prevUseBlkFlags = useBlkFlags;
1366 
1367         if (DO_STATS) {
1368             // update max used mark
1369             activeEdgeMaxUsed = _arrayMaxUsed;
1370         }
1371     }
1372 
1373     void endRendering() {
1374         if (DO_MONITORS) {
1375             rdrCtx.stats.mon_rdr_endRendering.start();
1376         }
1377         if (edgeMinY == Integer.MAX_VALUE) {
1378             return; // undefined edges bounds
1379         }
1380 
1381         // bounds as half-open intervals
1382         final int spminX = FloatMath.max(FloatMath.ceil_int(edgeMinX - 0.5d), boundsMinX);
1383         final int spmaxX = FloatMath.min(FloatMath.ceil_int(edgeMaxX - 0.5d), boundsMaxX);
1384 
1385         // edge Min/Max Y are already rounded to subpixels within bounds:
1386         final int spminY = edgeMinY;
1387         final int spmaxY = edgeMaxY;
1388 
1389         buckets_minY = spminY - boundsMinY;
1390         buckets_maxY = spmaxY - boundsMinY;
1391 
1392         if (DO_LOG_BOUNDS) {
1393             MarlinUtils.logInfo("edgesXY = [" + edgeMinX + " ... " + edgeMaxX
1394                                 + "[ [" + edgeMinY + " ... " + edgeMaxY + "[");
1395             MarlinUtils.logInfo("spXY    = [" + spminX + " ... " + spmaxX
1396                                 + "[ [" + spminY + " ... " + spmaxY + "[");
1397         }
1398 
1399         // test clipping for shapes out of bounds
1400         if ((spminX >= spmaxX) || (spminY >= spmaxY)) {
1401             return;
1402         }
1403 
1404         // half open intervals
1405         // inclusive:
1406         final int pminX =  spminX                    >> SUBPIXEL_LG_POSITIONS_X;
1407         // exclusive:
1408         final int pmaxX = (spmaxX + SUBPIXEL_MASK_X) >> SUBPIXEL_LG_POSITIONS_X;
1409         // inclusive:
1410         final int pminY =  spminY                    >> SUBPIXEL_LG_POSITIONS_Y;
1411         // exclusive:
1412         final int pmaxY = (spmaxY + SUBPIXEL_MASK_Y) >> SUBPIXEL_LG_POSITIONS_Y;
1413 
1414         // store BBox to answer ptg.getBBox():
1415         initConsumer(pminX, pminY, pmaxX, pmaxY);
1416 
1417         // Heuristics for using block flags:
1418         if (ENABLE_BLOCK_FLAGS) {
1419             enableBlkFlags = this.useRLE;
1420             prevUseBlkFlags = enableBlkFlags && !ENABLE_BLOCK_FLAGS_HEURISTICS;
1421 
1422             if (enableBlkFlags) {
1423                 // ensure blockFlags array is large enough:
1424                 // note: +2 to ensure enough space left at end
1425                 final int blkLen = ((pmaxX - pminX) >> BLOCK_SIZE_LG) + 2;
1426                 if (blkLen > INITIAL_ARRAY) {
1427                     blkFlags = blkFlags_ref.getArray(blkLen);
1428                 }
1429             }
1430         }
1431 
1432         // memorize the rendering bounding box:
1433         /* note: bbox_spminX and bbox_spmaxX must be pixel boundaries
1434            to have correct coverage computation */
1435         // inclusive:
1436         bbox_spminX = pminX << SUBPIXEL_LG_POSITIONS_X;
1437         // exclusive:
1438         bbox_spmaxX = pmaxX << SUBPIXEL_LG_POSITIONS_X;
1439         // inclusive:
1440         bbox_spminY = spminY;
1441         // exclusive:
1442         bbox_spmaxY = spmaxY;
1443 
1444         if (DO_LOG_BOUNDS) {
1445             MarlinUtils.logInfo("pXY       = [" + pminX + " ... " + pmaxX
1446                                 + "[ [" + pminY + " ... " + pmaxY + "[");
1447             MarlinUtils.logInfo("bbox_spXY = [" + bbox_spminX + " ... "
1448                                 + bbox_spmaxX + "[ [" + bbox_spminY + " ... "
1449                                 + bbox_spmaxY + "[");
1450         }
1451 
1452         // Prepare alpha line:
1453         // add 2 to better deal with the last pixel in a pixel row.
1454         final int width = (pmaxX - pminX) + 2;
1455 
1456         // Useful when processing tile line by tile line
1457         if (width > INITIAL_AA_ARRAY) {
1458             if (DO_STATS) {
1459                 rdrCtx.stats.stat_array_renderer_alphaline.add(width);
1460             }
1461             alphaLine = alphaLine_ref.getArray(width);
1462         }
1463     }
1464 
1465     void initConsumer(int minx, int miny, int maxx, int maxy)
1466     {
1467         // assert maxy >= miny && maxx >= minx;
1468         bboxX0 = minx;
1469         bboxX1 = maxx;
1470         bboxY0 = miny;
1471         bboxY1 = maxy;
1472 
1473         final int width = (maxx - minx);
1474 
1475         if (FORCE_NO_RLE) {
1476             useRLE = false;
1477         } else if (FORCE_RLE) {
1478             useRLE = true;
1479         } else {
1480             // heuristics: use both bbox area and complexity
1481             // ie number of primitives:
1482 
1483             // fast check min width:
1484             useRLE = (width > RLE_MIN_WIDTH);
1485         }
1486     }
1487 
1488     private int bbox_spminX, bbox_spmaxX, bbox_spminY, bbox_spmaxY;
1489 
1490     public void produceAlphas(final MarlinAlphaConsumer ac) {
1491         ac.setMaxAlpha(MAX_AA_ALPHA);
1492 
1493         if (enableBlkFlags && !ac.supportBlockFlags()) {
1494             // consumer does not support block flag optimization:
1495             enableBlkFlags = false;
1496             prevUseBlkFlags = false;
1497         }
1498 
1499         if (DO_MONITORS) {
1500             rdrCtx.stats.mon_rdr_endRendering_Y.start();
1501         }
1502 
1503         // Process all scan lines:
1504         _endRendering(bbox_spminY, bbox_spmaxY, ac);
1505 
1506         if (DO_MONITORS) {
1507             rdrCtx.stats.mon_rdr_endRendering_Y.stop();
1508         }
1509     }
1510 
1511     void copyAARow(final int[] alphaRow,
1512                    final int pix_y, final int pix_from, final int pix_to,
1513                    final boolean useBlockFlags,
1514                    final MarlinAlphaConsumer ac)
1515     {
1516         if (DO_MONITORS) {
1517             rdrCtx.stats.mon_rdr_copyAARow.start();
1518         }
1519         if (DO_STATS) {
1520             rdrCtx.stats.stat_cache_rowAA.add(pix_to - pix_from);
1521         }
1522 
1523         if (useBlockFlags) {
1524             if (DO_STATS) {
1525                 rdrCtx.stats.hist_tile_generator_encoding.add(1);
1526             }
1527             ac.setAndClearRelativeAlphas(blkFlags, alphaRow, pix_y, pix_from, pix_to);
1528         } else {
1529             if (DO_STATS) {
1530                 rdrCtx.stats.hist_tile_generator_encoding.add(0);
1531             }
1532             ac.setAndClearRelativeAlphas(alphaRow, pix_y, pix_from, pix_to);
1533         }
1534         if (DO_MONITORS) {
1535             rdrCtx.stats.mon_rdr_copyAARow.stop();
1536         }
1537     }
1538 
1539     // output pixel bounding box:
1540     int bboxX0, bboxX1, bboxY0, bboxY1;
1541 
1542     @Override
1543     public int getOutpixMinX() {
1544         return bboxX0;
1545     }
1546 
1547     @Override
1548     public int getOutpixMaxX() {
1549         return bboxX1;
1550     }
1551 
1552     @Override
1553     public int getOutpixMinY() {
1554         return bboxY0;
1555     }
1556 
1557     @Override
1558     public int getOutpixMaxY() {
1559         return bboxY1;
1560     }
1561 
1562     @Override
1563     public double getOffsetX() {
1564         return RDR_OFFSET_X;
1565     }
1566 
1567     @Override
1568     public double getOffsetY() {
1569         return RDR_OFFSET_Y;
1570     }
1571 }