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