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