Debian Codegraph @

src/com/github/weisj/jsvg/nodes/AbstractGradient.java

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 /*
2 * MIT License
3 *
4 * Copyright (c) 2021-2025 Jannis Weis
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
7 * associated documentation files (the "Software"), to deal in the Software without restriction,
8 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
9 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in all copies or
13 * substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
16 * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 *
21 */
22 package com.github.weisj.jsvg.nodes;
23
24 import java.awt.*;
25 import java.awt.geom.AffineTransform;
26 import java.awt.geom.Rectangle2D;
27 import java.util.ArrayList;
28 import java.util.Comparator;
29 import java.util.List;
30
31 import org.jetbrains.annotations.NotNull;
32 import org.jetbrains.annotations.Nullable;
33
34 import com.github.weisj.jsvg.attributes.SpreadMethod;
35 import com.github.weisj.jsvg.attributes.UnitType;
36 import com.github.weisj.jsvg.attributes.value.TransformValue;
37 import com.github.weisj.jsvg.geometry.size.Percentage;
38 import com.github.weisj.jsvg.nodes.container.ContainerNode;
39 import com.github.weisj.jsvg.paint.SVGPaint;
40 import com.github.weisj.jsvg.parser.PaintParser;
41 import com.github.weisj.jsvg.parser.impl.AttributeNode;
42 import com.github.weisj.jsvg.parser.impl.AttributeNode.ElementRelation;
43 import com.github.weisj.jsvg.renderer.MeasureContext;
44 import com.github.weisj.jsvg.renderer.RenderContext;
45 import com.github.weisj.jsvg.renderer.output.Output;
46
47 @SuppressWarnings("java:S119") // Generic name Self is intentional
48 abstract class AbstractGradient<Self extends AbstractGradient<Self>> extends ContainerNode implements SVGPaint {
49 protected TransformValue gradientTransform;
50 protected UnitType gradientUnits;
51 protected SpreadMethod spreadMethod;
52
53 private @NotNull Color[] colors;
54 private Percentage[] offsets;
55
56 private float[] tmpFractions;
57
58 public final Percentage[] offsets() {
59 return offsets;
60 }
61
62 public final @NotNull Color[] colors() {
63 return colors;
64 }
65
66 @Override
67 public final void build(@NotNull AttributeNode attributeNode) {
68 super.build(attributeNode);
69
70 AbstractGradient<?> template = parseTemplate(attributeNode);
71
72 gradientUnits = attributeNode.getEnum("gradientUnits",
73 template != null ? template.gradientUnits : UnitType.ObjectBoundingBox);
74 spreadMethod = attributeNode.getEnum("spreadMethod",
75 template != null ? template.spreadMethod : SpreadMethod.Pad);
76
77 gradientTransform = attributeNode.parseTransform("gradientTransform");
78 if (gradientTransform == null && template != null)
79 gradientTransform = template.gradientTransform;
80
81
82 List<Stop> stops = childrenOfType(Stop.class);
83 if (stops.isEmpty() && template != null) {
84 colors = template.colors();
85 offsets = template.offsets();
86 } else {
87 parseStops(stops);
88 }
89
90 // noinspection unchecked
91 Self selfTemplate = getClass().isInstance(template) ? (Self) template : null;
92 buildGradient(attributeNode, selfTemplate);
93 children().clear();
94 }
95
96 private void parseStops(@NotNull List<Stop> stops) {
97 stops.sort(Comparator.comparing(Stop::offset));
98 List<Color> colorsList = new ArrayList<>();
99 List<Percentage> offsetsList = new ArrayList<>();
100
101 boolean realGradient = false;
102 for (Stop stop : stops) {
103 // Clamp the offset
104 float stopOffset = Math.max(0, Math.min(1, stop.offset().value()));
105 Color stopColor = stop.color();
106
107 boolean isFirstStop = offsetsList.isEmpty();
108 boolean effectiveStop = isFirstStop
109 || isEffectiveStop(stopOffset, stopColor, offsetsList, colorsList);
110 realGradient = !isFirstStop && effectiveStop;
111
112 if (isFirstStop && stopOffset != 0) {
113 // If the first stop is not at 0, we need to add a transparent color at the beginning.
114 offsetsList.add(Percentage.ZERO);
115 colorsList.add(stopColor);
116 }
117
118 if (effectiveStop) {
119 offsetsList.add(new Percentage(stopOffset));
120 colorsList.add(stopColor);
121 }
122 }
123
124 if (!offsetsList.isEmpty() && offsetsList.get(offsetsList.size() - 1).value() != 1f) {
125 // If the last stop is not at 1, we need to add a transparent color at the end.
126 offsetsList.add(Percentage.ONE);
127 colorsList.add(colorsList.get(colorsList.size() - 1));
128 }
129
130 if (!realGradient && !colorsList.isEmpty()) {
131 // If all stops are equal, we can just use the first color.
132 // This never gets passed to the radial gradient hence we don't need to provide a second stop.
133 colors = new Color[] {colorsList.get(0)};
134 offsets = new Percentage[] {Percentage.ZERO};
135 } else {
136 colors = colorsList.toArray(new Color[0]);
137 offsets = offsetsList.toArray(new Percentage[0]);
138 makeStrictlyIncreasing(offsets);
139 }
140 }
141
142 private static void makeStrictlyIncreasing(@NotNull Percentage @NotNull [] offsets) {
143 // Round up equal values to the next float value.
144 for (int i = 1; i < offsets.length; i++) {
145 if (offsets[i].value() <= offsets[i - 1].value()) {
146 offsets[i] = new Percentage(Math.nextUp(offsets[i - 1].value()));
147 }
148 }
149
150 // Values have possibly exceeded 1 now. Clamp them back down.
151 for (int i = offsets.length - 1; i >= 0; i--) {
152 if (offsets[i].value() >= 1) {
153 offsets[i] = Percentage.ONE;
154 }
155 }
156
157 // Now round values down as in step one but from top to bottom.
158 // Note: As there are 126 x 2^23 + 1 floats between 0 and 1 and we don't expect input array to be
159 // that large we can safely assume that now all values are distinct (as there will be a gap with
160 // enough space to shift all offsets to).
161 for (int i = offsets.length - 2; i >= 0; i--) {
162 if (offsets[i].value() >= offsets[i + 1].value()) {
163 offsets[i] = new Percentage(Math.nextDown(offsets[i + 1].value()));
164 }
165 }
166 }
167
168 private static boolean isEffectiveStop(float stopOffset, @NotNull Color stopColor,
169 @NotNull List<@NotNull Percentage> offsetsList,
170 @NotNull List<@NotNull Color> colorsList) {
171 return stopOffset > offsetsList.get(offsetsList.size() - 1).value()
172 || !stopColor.equals(colorsList.get(colorsList.size() - 1));
173 }
174
175 private @Nullable AbstractGradient<?> parseTemplate(@NotNull AttributeNode attributeNode) {
176 AbstractGradient<?> template = attributeNode.getElementByHref(AbstractGradient.class, attributeNode.getHref(),
177 ElementRelation.TEMPLATE);
178 return template != this ? template : null;
179 }
180
181 protected abstract void buildGradient(@NotNull AttributeNode attributeNode, @Nullable Self template);
182
183 @Override
184 public void fillShape(@NotNull Output output, @NotNull RenderContext context, @NotNull Shape shape,
185 @Nullable Rectangle2D bounds) {
186 Rectangle2D b = bounds != null ? bounds : shape.getBounds2D();
187 output.setPaint(() -> paintForBounds(context.measureContext(), b));
188 output.fillShape(shape);
189 }
190
191 @Override
192 public void drawShape(@NotNull Output output, @NotNull RenderContext context, @NotNull Shape shape,
193 @Nullable Rectangle2D bounds) {
194 Rectangle2D b = bounds != null ? bounds : shape.getBounds2D();
195 output.setPaint(() -> paintForBounds(context.measureContext(), b));
196 output.drawShape(shape);
197 }
198
199 private @NotNull Paint paintForBounds(@NotNull MeasureContext context, @NotNull Rectangle2D bounds) {
200 Color[] gradColors = colors();
201 if (gradColors.length == 0) return PaintParser.DEFAULT_COLOR;
202 if (gradColors.length == 1) return gradColors[0];
203 return gradientForBounds(gradientUnits.deriveMeasure(context), bounds, offsets(), gradColors);
204 }
205
206 protected float[] offsetsToFractions(Percentage[] gradOffsets) {
207 // NOTE: We need to recompute the fractions if a stop is animated.
208 if (tmpFractions == null || tmpFractions.length != gradOffsets.length) {
209 tmpFractions = new float[gradOffsets.length];
210 for (int i = 0; i < tmpFractions.length; i++) {
211 tmpFractions[i] = gradOffsets[i].value();
212 }
213 }
214 return tmpFractions;
215 }
216
217 protected abstract @NotNull Paint gradientForBounds(@NotNull MeasureContext measure, @NotNull Rectangle2D bounds,
218 Percentage[] gradOffsets, @NotNull Color[] gradColors);
219
220 protected final @NotNull AffineTransform computeViewTransform(@NotNull MeasureContext measure,
221 @NotNull Rectangle2D bounds) {
222 AffineTransform viewTransform = gradientUnits.viewTransform(bounds);
223 if (gradientTransform != null) viewTransform.concatenate(gradientTransform.get(measure));
224 return viewTransform;
225 }
226 }