Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/java2d/pisces/PiscesRenderingEngine.java
38918 views
/*1* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.java2d.pisces;2627import java.awt.Shape;28import java.awt.BasicStroke;29import java.awt.geom.Path2D;30import java.awt.geom.AffineTransform;31import java.awt.geom.PathIterator;3233import sun.awt.geom.PathConsumer2D;34import sun.java2d.pipe.Region;35import sun.java2d.pipe.RenderingEngine;36import sun.java2d.pipe.AATileGenerator;3738public class PiscesRenderingEngine extends RenderingEngine {39private static enum NormMode {OFF, ON_NO_AA, ON_WITH_AA}4041/**42* Create a widened path as specified by the parameters.43* <p>44* The specified {@code src} {@link Shape} is widened according45* to the specified attribute parameters as per the46* {@link BasicStroke} specification.47*48* @param src the source path to be widened49* @param width the width of the widened path as per {@code BasicStroke}50* @param caps the end cap decorations as per {@code BasicStroke}51* @param join the segment join decorations as per {@code BasicStroke}52* @param miterlimit the miter limit as per {@code BasicStroke}53* @param dashes the dash length array as per {@code BasicStroke}54* @param dashphase the initial dash phase as per {@code BasicStroke}55* @return the widened path stored in a new {@code Shape} object56* @since 1.757*/58public Shape createStrokedShape(Shape src,59float width,60int caps,61int join,62float miterlimit,63float dashes[],64float dashphase)65{66final Path2D p2d = new Path2D.Float();6768strokeTo(src,69null,70width,71NormMode.OFF,72caps,73join,74miterlimit,75dashes,76dashphase,77new PathConsumer2D() {78public void moveTo(float x0, float y0) {79p2d.moveTo(x0, y0);80}81public void lineTo(float x1, float y1) {82p2d.lineTo(x1, y1);83}84public void closePath() {85p2d.closePath();86}87public void pathDone() {}88public void curveTo(float x1, float y1,89float x2, float y2,90float x3, float y3) {91p2d.curveTo(x1, y1, x2, y2, x3, y3);92}93public void quadTo(float x1, float y1, float x2, float y2) {94p2d.quadTo(x1, y1, x2, y2);95}96public long getNativeConsumer() {97throw new InternalError("Not using a native peer");98}99});100return p2d;101}102103/**104* Sends the geometry for a widened path as specified by the parameters105* to the specified consumer.106* <p>107* The specified {@code src} {@link Shape} is widened according108* to the parameters specified by the {@link BasicStroke} object.109* Adjustments are made to the path as appropriate for the110* {@link VALUE_STROKE_NORMALIZE} hint if the {@code normalize}111* boolean parameter is true.112* Adjustments are made to the path as appropriate for the113* {@link VALUE_ANTIALIAS_ON} hint if the {@code antialias}114* boolean parameter is true.115* <p>116* The geometry of the widened path is forwarded to the indicated117* {@link PathConsumer2D} object as it is calculated.118*119* @param src the source path to be widened120* @param bs the {@code BasicSroke} object specifying the121* decorations to be applied to the widened path122* @param normalize indicates whether stroke normalization should123* be applied124* @param antialias indicates whether or not adjustments appropriate125* to antialiased rendering should be applied126* @param consumer the {@code PathConsumer2D} instance to forward127* the widened geometry to128* @since 1.7129*/130public void strokeTo(Shape src,131AffineTransform at,132BasicStroke bs,133boolean thin,134boolean normalize,135boolean antialias,136final PathConsumer2D consumer)137{138NormMode norm = (normalize) ?139((antialias) ? NormMode.ON_WITH_AA : NormMode.ON_NO_AA)140: NormMode.OFF;141strokeTo(src, at, bs, thin, norm, antialias, consumer);142}143144void strokeTo(Shape src,145AffineTransform at,146BasicStroke bs,147boolean thin,148NormMode normalize,149boolean antialias,150PathConsumer2D pc2d)151{152float lw;153if (thin) {154if (antialias) {155lw = userSpaceLineWidth(at, 0.5f);156} else {157lw = userSpaceLineWidth(at, 1.0f);158}159} else {160lw = bs.getLineWidth();161}162strokeTo(src,163at,164lw,165normalize,166bs.getEndCap(),167bs.getLineJoin(),168bs.getMiterLimit(),169bs.getDashArray(),170bs.getDashPhase(),171pc2d);172}173174private float userSpaceLineWidth(AffineTransform at, float lw) {175176double widthScale;177178if ((at.getType() & (AffineTransform.TYPE_GENERAL_TRANSFORM |179AffineTransform.TYPE_GENERAL_SCALE)) != 0) {180widthScale = Math.sqrt(at.getDeterminant());181} else {182/* First calculate the "maximum scale" of this transform. */183double A = at.getScaleX(); // m00184double C = at.getShearX(); // m01185double B = at.getShearY(); // m10186double D = at.getScaleY(); // m11187188/*189* Given a 2 x 2 affine matrix [ A B ] such that190* [ C D ]191* v' = [x' y'] = [Ax + Cy, Bx + Dy], we want to192* find the maximum magnitude (norm) of the vector v'193* with the constraint (x^2 + y^2 = 1).194* The equation to maximize is195* |v'| = sqrt((Ax+Cy)^2+(Bx+Dy)^2)196* or |v'| = sqrt((AA+BB)x^2 + 2(AC+BD)xy + (CC+DD)y^2).197* Since sqrt is monotonic we can maximize |v'|^2198* instead and plug in the substitution y = sqrt(1 - x^2).199* Trigonometric equalities can then be used to get200* rid of most of the sqrt terms.201*/202203double EA = A*A + B*B; // x^2 coefficient204double EB = 2*(A*C + B*D); // xy coefficient205double EC = C*C + D*D; // y^2 coefficient206207/*208* There is a lot of calculus omitted here.209*210* Conceptually, in the interests of understanding the211* terms that the calculus produced we can consider212* that EA and EC end up providing the lengths along213* the major axes and the hypot term ends up being an214* adjustment for the additional length along the off-axis215* angle of rotated or sheared ellipses as well as an216* adjustment for the fact that the equation below217* averages the two major axis lengths. (Notice that218* the hypot term contains a part which resolves to the219* difference of these two axis lengths in the absence220* of rotation.)221*222* In the calculus, the ratio of the EB and (EA-EC) terms223* ends up being the tangent of 2*theta where theta is224* the angle that the long axis of the ellipse makes225* with the horizontal axis. Thus, this equation is226* calculating the length of the hypotenuse of a triangle227* along that axis.228*/229230double hypot = Math.sqrt(EB*EB + (EA-EC)*(EA-EC));231/* sqrt omitted, compare to squared limits below. */232double widthsquared = ((EA + EC + hypot)/2.0);233234widthScale = Math.sqrt(widthsquared);235}236237return (float) (lw / widthScale);238}239240void strokeTo(Shape src,241AffineTransform at,242float width,243NormMode normalize,244int caps,245int join,246float miterlimit,247float dashes[],248float dashphase,249PathConsumer2D pc2d)250{251// We use strokerat and outat so that in Stroker and Dasher we can work only252// with the pre-transformation coordinates. This will repeat a lot of253// computations done in the path iterator, but the alternative is to254// work with transformed paths and compute untransformed coordinates255// as needed. This would be faster but I do not think the complexity256// of working with both untransformed and transformed coordinates in257// the same code is worth it.258// However, if a path's width is constant after a transformation,259// we can skip all this untransforming.260261// If normalization is off we save some transformations by not262// transforming the input to pisces. Instead, we apply the263// transformation after the path processing has been done.264// We can't do this if normalization is on, because it isn't a good265// idea to normalize before the transformation is applied.266AffineTransform strokerat = null;267AffineTransform outat = null;268269PathIterator pi = null;270271if (at != null && !at.isIdentity()) {272final double a = at.getScaleX();273final double b = at.getShearX();274final double c = at.getShearY();275final double d = at.getScaleY();276final double det = a * d - c * b;277if (Math.abs(det) <= 2 * Float.MIN_VALUE) {278// this rendering engine takes one dimensional curves and turns279// them into 2D shapes by giving them width.280// However, if everything is to be passed through a singular281// transformation, these 2D shapes will be squashed down to 1D282// again so, nothing can be drawn.283284// Every path needs an initial moveTo and a pathDone. If these285// are not there this causes a SIGSEGV in libawt.so (at the time286// of writing of this comment (September 16, 2010)). Actually,287// I am not sure if the moveTo is necessary to avoid the SIGSEGV288// but the pathDone is definitely needed.289pc2d.moveTo(0, 0);290pc2d.pathDone();291return;292}293294// If the transform is a constant multiple of an orthogonal transformation295// then every length is just multiplied by a constant, so we just296// need to transform input paths to stroker and tell stroker297// the scaled width. This condition is satisfied if298// a*b == -c*d && a*a+c*c == b*b+d*d. In the actual check below, we299// leave a bit of room for error.300if (nearZero(a*b + c*d, 2) && nearZero(a*a+c*c - (b*b+d*d), 2)) {301double scale = Math.sqrt(a*a + c*c);302if (dashes != null) {303dashes = java.util.Arrays.copyOf(dashes, dashes.length);304for (int i = 0; i < dashes.length; i++) {305dashes[i] = (float)(scale * dashes[i]);306}307dashphase = (float)(scale * dashphase);308}309width = (float)(scale * width);310pi = src.getPathIterator(at);311if (normalize != NormMode.OFF) {312pi = new NormalizingPathIterator(pi, normalize);313}314// by now strokerat == null && outat == null. Input paths to315// stroker (and maybe dasher) will have the full transform at316// applied to them and nothing will happen to the output paths.317} else {318if (normalize != NormMode.OFF) {319strokerat = at;320pi = src.getPathIterator(at);321pi = new NormalizingPathIterator(pi, normalize);322// by now strokerat == at && outat == null. Input paths to323// stroker (and maybe dasher) will have the full transform at324// applied to them, then they will be normalized, and then325// the inverse of *only the non translation part of at* will326// be applied to the normalized paths. This won't cause problems327// in stroker, because, suppose at = T*A, where T is just the328// translation part of at, and A is the rest. T*A has already329// been applied to Stroker/Dasher's input. Then Ainv will be330// applied. Ainv*T*A is not equal to T, but it is a translation,331// which means that none of stroker's assumptions about its332// input will be violated. After all this, A will be applied333// to stroker's output.334} else {335outat = at;336pi = src.getPathIterator(null);337// outat == at && strokerat == null. This is because if no338// normalization is done, we can just apply all our339// transformations to stroker's output.340}341}342} else {343// either at is null or it's the identity. In either case344// we don't transform the path.345pi = src.getPathIterator(null);346if (normalize != NormMode.OFF) {347pi = new NormalizingPathIterator(pi, normalize);348}349}350351// by now, at least one of outat and strokerat will be null. Unless at is not352// a constant multiple of an orthogonal transformation, they will both be353// null. In other cases, outat == at if normalization is off, and if354// normalization is on, strokerat == at.355pc2d = TransformingPathConsumer2D.transformConsumer(pc2d, outat);356pc2d = TransformingPathConsumer2D.deltaTransformConsumer(pc2d, strokerat);357pc2d = new Stroker(pc2d, width, caps, join, miterlimit);358if (dashes != null) {359pc2d = new Dasher(pc2d, dashes, dashphase);360}361pc2d = TransformingPathConsumer2D.inverseDeltaTransformConsumer(pc2d, strokerat);362pathTo(pi, pc2d);363}364365private static boolean nearZero(double num, int nulps) {366return Math.abs(num) < nulps * Math.ulp(num);367}368369private static class NormalizingPathIterator implements PathIterator {370371private final PathIterator src;372373// the adjustment applied to the current position.374private float curx_adjust, cury_adjust;375// the adjustment applied to the last moveTo position.376private float movx_adjust, movy_adjust;377378// constants used in normalization computations379private final float lval, rval;380381NormalizingPathIterator(PathIterator src, NormMode mode) {382this.src = src;383switch (mode) {384case ON_NO_AA:385// round to nearest (0.25, 0.25) pixel386lval = rval = 0.25f;387break;388case ON_WITH_AA:389// round to nearest pixel center390lval = 0f;391rval = 0.5f;392break;393case OFF:394throw new InternalError("A NormalizingPathIterator should " +395"not be created if no normalization is being done");396default:397throw new InternalError("Unrecognized normalization mode");398}399}400401public int currentSegment(float[] coords) {402int type = src.currentSegment(coords);403404int lastCoord;405switch(type) {406case PathIterator.SEG_CUBICTO:407lastCoord = 4;408break;409case PathIterator.SEG_QUADTO:410lastCoord = 2;411break;412case PathIterator.SEG_LINETO:413case PathIterator.SEG_MOVETO:414lastCoord = 0;415break;416case PathIterator.SEG_CLOSE:417// we don't want to deal with this case later. We just exit now418curx_adjust = movx_adjust;419cury_adjust = movy_adjust;420return type;421default:422throw new InternalError("Unrecognized curve type");423}424425// normalize endpoint426float x_adjust = (float)Math.floor(coords[lastCoord] + lval) +427rval - coords[lastCoord];428float y_adjust = (float)Math.floor(coords[lastCoord+1] + lval) +429rval - coords[lastCoord + 1];430431coords[lastCoord ] += x_adjust;432coords[lastCoord + 1] += y_adjust;433434// now that the end points are done, normalize the control points435switch(type) {436case PathIterator.SEG_CUBICTO:437coords[0] += curx_adjust;438coords[1] += cury_adjust;439coords[2] += x_adjust;440coords[3] += y_adjust;441break;442case PathIterator.SEG_QUADTO:443coords[0] += (curx_adjust + x_adjust) / 2;444coords[1] += (cury_adjust + y_adjust) / 2;445break;446case PathIterator.SEG_LINETO:447break;448case PathIterator.SEG_MOVETO:449movx_adjust = x_adjust;450movy_adjust = y_adjust;451break;452case PathIterator.SEG_CLOSE:453throw new InternalError("This should be handled earlier.");454}455curx_adjust = x_adjust;456cury_adjust = y_adjust;457return type;458}459460public int currentSegment(double[] coords) {461float[] tmp = new float[6];462int type = this.currentSegment(tmp);463for (int i = 0; i < 6; i++) {464coords[i] = (float) tmp[i];465}466return type;467}468469public int getWindingRule() {470return src.getWindingRule();471}472473public boolean isDone() {474return src.isDone();475}476477public void next() {478src.next();479}480}481482static void pathTo(PathIterator pi, PathConsumer2D pc2d) {483RenderingEngine.feedConsumer(pi, pc2d);484pc2d.pathDone();485}486487/**488* Construct an antialiased tile generator for the given shape with489* the given rendering attributes and store the bounds of the tile490* iteration in the bbox parameter.491* The {@code at} parameter specifies a transform that should affect492* both the shape and the {@code BasicStroke} attributes.493* The {@code clip} parameter specifies the current clip in effect494* in device coordinates and can be used to prune the data for the495* operation, but the renderer is not required to perform any496* clipping.497* If the {@code BasicStroke} parameter is null then the shape498* should be filled as is, otherwise the attributes of the499* {@code BasicStroke} should be used to specify a draw operation.500* The {@code thin} parameter indicates whether or not the501* transformed {@code BasicStroke} represents coordinates smaller502* than the minimum resolution of the antialiasing rasterizer as503* specified by the {@code getMinimumAAPenWidth()} method.504* <p>505* Upon returning, this method will fill the {@code bbox} parameter506* with 4 values indicating the bounds of the iteration of the507* tile generator.508* The iteration order of the tiles will be as specified by the509* pseudo-code:510* <pre>511* for (y = bbox[1]; y < bbox[3]; y += tileheight) {512* for (x = bbox[0]; x < bbox[2]; x += tilewidth) {513* }514* }515* </pre>516* If there is no output to be rendered, this method may return517* null.518*519* @param s the shape to be rendered (fill or draw)520* @param at the transform to be applied to the shape and the521* stroke attributes522* @param clip the current clip in effect in device coordinates523* @param bs if non-null, a {@code BasicStroke} whose attributes524* should be applied to this operation525* @param thin true if the transformed stroke attributes are smaller526* than the minimum dropout pen width527* @param normalize true if the {@code VALUE_STROKE_NORMALIZE}528* {@code RenderingHint} is in effect529* @param bbox returns the bounds of the iteration530* @return the {@code AATileGenerator} instance to be consulted531* for tile coverages, or null if there is no output to render532* @since 1.7533*/534public AATileGenerator getAATileGenerator(Shape s,535AffineTransform at,536Region clip,537BasicStroke bs,538boolean thin,539boolean normalize,540int bbox[])541{542Renderer r;543NormMode norm = (normalize) ? NormMode.ON_WITH_AA : NormMode.OFF;544if (bs == null) {545PathIterator pi;546if (normalize) {547pi = new NormalizingPathIterator(s.getPathIterator(at), norm);548} else {549pi = s.getPathIterator(at);550}551r = new Renderer(3, 3,552clip.getLoX(), clip.getLoY(),553clip.getWidth(), clip.getHeight(),554pi.getWindingRule());555pathTo(pi, r);556} else {557r = new Renderer(3, 3,558clip.getLoX(), clip.getLoY(),559clip.getWidth(), clip.getHeight(),560PathIterator.WIND_NON_ZERO);561strokeTo(s, at, bs, thin, norm, true, r);562}563r.endRendering();564PiscesTileGenerator ptg = new PiscesTileGenerator(r, r.MAX_AA_ALPHA);565ptg.getBbox(bbox);566return ptg;567}568569public AATileGenerator getAATileGenerator(double x, double y,570double dx1, double dy1,571double dx2, double dy2,572double lw1, double lw2,573Region clip,574int bbox[])575{576// REMIND: Deal with large coordinates!577double ldx1, ldy1, ldx2, ldy2;578boolean innerpgram = (lw1 > 0 && lw2 > 0);579580if (innerpgram) {581ldx1 = dx1 * lw1;582ldy1 = dy1 * lw1;583ldx2 = dx2 * lw2;584ldy2 = dy2 * lw2;585x -= (ldx1 + ldx2) / 2.0;586y -= (ldy1 + ldy2) / 2.0;587dx1 += ldx1;588dy1 += ldy1;589dx2 += ldx2;590dy2 += ldy2;591if (lw1 > 1 && lw2 > 1) {592// Inner parallelogram was entirely consumed by stroke...593innerpgram = false;594}595} else {596ldx1 = ldy1 = ldx2 = ldy2 = 0;597}598599Renderer r = new Renderer(3, 3,600clip.getLoX(), clip.getLoY(),601clip.getWidth(), clip.getHeight(),602PathIterator.WIND_EVEN_ODD);603604r.moveTo((float) x, (float) y);605r.lineTo((float) (x+dx1), (float) (y+dy1));606r.lineTo((float) (x+dx1+dx2), (float) (y+dy1+dy2));607r.lineTo((float) (x+dx2), (float) (y+dy2));608r.closePath();609610if (innerpgram) {611x += ldx1 + ldx2;612y += ldy1 + ldy2;613dx1 -= 2.0 * ldx1;614dy1 -= 2.0 * ldy1;615dx2 -= 2.0 * ldx2;616dy2 -= 2.0 * ldy2;617r.moveTo((float) x, (float) y);618r.lineTo((float) (x+dx1), (float) (y+dy1));619r.lineTo((float) (x+dx1+dx2), (float) (y+dy1+dy2));620r.lineTo((float) (x+dx2), (float) (y+dy2));621r.closePath();622}623624r.pathDone();625626r.endRendering();627PiscesTileGenerator ptg = new PiscesTileGenerator(r, r.MAX_AA_ALPHA);628ptg.getBbox(bbox);629return ptg;630}631632/**633* Returns the minimum pen width that the antialiasing rasterizer634* can represent without dropouts occurring.635* @since 1.7636*/637public float getMinimumAAPenSize() {638return 0.5f;639}640641static {642if (PathIterator.WIND_NON_ZERO != Renderer.WIND_NON_ZERO ||643PathIterator.WIND_EVEN_ODD != Renderer.WIND_EVEN_ODD ||644BasicStroke.JOIN_MITER != Stroker.JOIN_MITER ||645BasicStroke.JOIN_ROUND != Stroker.JOIN_ROUND ||646BasicStroke.JOIN_BEVEL != Stroker.JOIN_BEVEL ||647BasicStroke.CAP_BUTT != Stroker.CAP_BUTT ||648BasicStroke.CAP_ROUND != Stroker.CAP_ROUND ||649BasicStroke.CAP_SQUARE != Stroker.CAP_SQUARE)650{651throw new InternalError("mismatched renderer constants");652}653}654}655656657658